public override void Delete(LeagueDbContext dbContext)
 {
     SessionResult?.Delete(dbContext);
     Scorings?.ToList().ForEach(x => x.Sessions.Remove(this));
     Reviews?.ToList().ForEach(x => x.Delete(dbContext));
     base.Delete(dbContext);
 }
Exemplo n.º 2
0
 public override void Delete(LeagueDbContext dbContext)
 {
     IRSimSessionDetails?.Delete(dbContext);
     RawResults?.ToList().ForEach(x => x.Delete(dbContext));
     ScoredResults?.ToList().ForEach(x => x.Delete(dbContext));
     base.Delete(dbContext);
 }
        /// <summary>
        /// <para>Load all data required for calculating the statistics from the database.</para>
        /// <para>Must be called prior to <see cref="Calculate"/> if lazy loading is disabled!</para>
        /// </summary>
        /// <param name="dbContext">Database context from EntityFramework.</param>
        /// <param name="force">Force loading data again even if IsDataLoaded is true.</param>
        public virtual async Task LoadRequiredDataAsync(LeagueDbContext dbContext, bool force = false)
        {
            if (DriverStatistic == null || DriverStatistic.Count == 0)
            {
                await dbContext.Entry(this)
                .Collection(x => x.DriverStatistic)
                .LoadAsync();

                var memberIds  = DriverStatistic.Select(x => x.MemberId);
                var sessionIds = DriverStatistic
                                 .SelectMany(x => new long?[] { x.FirstSessionId, x.LastSessionId, x.FirstRaceId, x.LastRaceId })
                                 .Where(x => x != null)
                                 .Select(x => x.Value);
                var resultRowIds = DriverStatistic
                                   .SelectMany(x => new long?[] { x.FirstResultRowId, x.LastResultRowId })
                                   .Where(x => x != null)
                                   .Select(x => x.Value);

                await dbContext.Set <LeagueMemberEntity>()
                .Where(x => memberIds.Contains(x.MemberId))
                .LoadAsync();

                await dbContext.Set <SessionBaseEntity>()
                .Where(x => sessionIds.Contains(x.SessionId))
                .LoadAsync();

                await dbContext.Set <ResultRowEntity>()
                .Where(x => resultRowIds.Contains(x.ResultRowId))
                .LoadAsync();

                dbContext.ChangeTracker.DetectChanges();
            }
        }
Exemplo n.º 4
0
        public StandingsEntity GetSeasonStandings(SessionBaseEntity currentSession, LeagueDbContext dbContext, int maxRacesCount = -1)
        {
            StandingsEntity standings = new StandingsEntity()
            {
                ScoringTable = this,
                SessionId    = (currentSession?.SessionId).GetValueOrDefault()
            };

            if (currentSession == null)
            {
                return(standings);
            }

            if (maxRacesCount == -1)
            {
                maxRacesCount = Sessions.Count() - DropWeeks;
            }

            if (ScoringKind == ScoringKindEnum.Team)
            {
                return(GetSeasonTeamStandings(currentSession, dbContext, maxRacesCount));
            }

            var allScoredResults      = Scorings?.SelectMany(x => x.ScoredResults).ToList();
            var previousScoredResults = allScoredResults.Where(x => x.Result.Session.Date < currentSession.Date).ToList();

            var currentResult       = currentSession.SessionResult;
            var currentScoredResult = allScoredResults.SingleOrDefault(x => x.Result.Session == currentSession);

            var previousScoredRows    = previousScoredResults.SelectMany(x => x.FinalResults).ToList();
            var previousStandingsRows = previousScoredRows
                                        .AggregateByDriver(maxRacesCount, true)
                                        .OrderBy(x => - x.TotalPoints)
                                        .ThenBy(x => x.PenaltyPoints)
                                        .ThenBy(x => - x.Wins);

            previousStandingsRows.Select((value, index) => new { index, value }).ToList().ForEach(x => x.value.Position = x.index + 1);

            allScoredResults = previousScoredResults.ToList();
            allScoredResults.Add(currentScoredResult);
            var currentStandingsRows = allScoredResults
                                       .SelectMany(x => x.FinalResults)
                                       .AggregateByDriver(maxRacesCount, true)
                                       .OrderBy(x => - x.TotalPoints)
                                       .ThenBy(x => x.PenaltyPoints)
                                       .ThenBy(x => - x.Wins);

            currentStandingsRows.Select((value, index) => new { index, value }).ToList().ForEach(x => x.value.Position = x.index + 1);

            standings.StandingsRows = currentStandingsRows
                                      .Diff(previousStandingsRows)
                                      .OrderBy(x => - x.TotalPoints)
                                      .ThenBy(x => x.PenaltyPoints)
                                      .ThenBy(x => - x.Wins)
                                      .ToList();
            standings.StandingsRows.ForEach(x => x.ScoringTable = this);
            standings.Calculate();

            return(standings);
        }
Exemplo n.º 5
0
        private static async Task Tick(string leagueDbName)
        {
            // Load statistic sets and check for recalculation interval
            using (var dbContext = new LeagueDbContext(leagueDbName))
            {
                var statisticSets      = dbContext.Set <StatisticSetEntity>().ToList();
                var checkStatisticSets = statisticSets.Where(x => IsDueTick(x.UpdateTime, TimeSpanConverter.Convert(x.UpdateInterval))).OrderBy(x => GetTypePriority(x));


                dbContext.Configuration.LazyLoadingEnabled = false;
                foreach (var statisticSet in checkStatisticSets)
                {
                    await statisticSet.CheckRequireRecalculationAsync(dbContext);

                    if (statisticSet.RequiresRecalculation)
                    {
                        await statisticSet.LoadRequiredDataAsync(dbContext);

                        statisticSet.Calculate(dbContext);
                    }
                }
                dbContext.Configuration.LazyLoadingEnabled = true;
                dbContext.SaveChanges();
            }
            GC.Collect();
        }
 public override void Delete(LeagueDbContext dbContext)
 {
     InvolvedMembers?.Clear();
     Comments?.ToList().ForEach(x => x.Delete(dbContext));
     AcceptedReviewVotes?.ToList().ForEach(x => x.Delete(dbContext));
     base.Delete(dbContext);
 }
        public IHttpActionResult PutModels([FromBody] MappableDTO[] data, [FromUri] string requestType, [FromUri] string leagueName)
        {
            try
            {
                logger.Info($"Put Models request || type: {requestType} - league: {leagueName} - data: {string.Join("/", (object[])data)}");
                CheckLeagueRole(User, leagueName);

                if (leagueName == null)
                {
                    return(BadRequest("Parameter leagueName can not be null"));
                }

                if (data == null)
                {
                    return(Ok(data));
                }

                //return Ok();

                if (data.Count() == 0)
                {
                    return(Ok(new MappableDTO[0]));
                }

                Type requestTypeType;
                if (requestType == null)
                {
                    requestTypeType = data.GetType();
                }
                else
                {
                    requestTypeType = GetRequestType(requestType);
                }

                if (requestTypeType == null)
                {
                    return(BadRequest("Could not identify request type"));
                }

                var databaseName = GetDatabaseNameFromLeagueName(leagueName);

                using (var dbContext = new LeagueDbContext(databaseName))
                    using (IModelDataProvider modelDataProvider = new ModelDataProvider(dbContext, User.Identity.Name, User.Identity.GetUserId()))
                    {
                        data = modelDataProvider.PutArray(requestTypeType, data);
                        if (dbContext.DbChanged)
                        {
                            UpdateLeague(leagueName, User);
                        }
                    }
                //GC.Collect();
                logger.Info($"Put Models request || send data: {string.Join("/", (object[])data)}");
                return(Ok(data));
            }
            catch (Exception e)
            {
                logger.Error("Error in PutModels", e);
                throw;
            }
        }
 public override void Delete(LeagueDbContext dbContext)
 {
     FinalResults?.ToList().ForEach(x => x.Delete(dbContext));
     HardChargers.Clear();
     CleanestDrivers.Clear();
     base.Delete(dbContext);
 }
        static void Main(string[] args)
        {
            // Create season statistic set
            //using (var dbContext = new LeagueDbContext("SkippyCup_leagueDb"))
            //{
            //    var season = dbContext.Seasons.Find(1);

            //    var seasonStatistics = new SeasonStatisticSetEntity();
            //    season.SeasonStatistics.Add(seasonStatistics);

            //    var sprintScoring = dbContext.Set<ScoringEntity>().Find(7);
            //    var enduranceScoring = dbContext.Set<ScoringEntity>().Find(8);

            //    seasonStatistics.Scorings.Add(sprintScoring);
            //    seasonStatistics.Scorings.Add(enduranceScoring);

            //    dbContext.SaveChanges();
            //}

            // Calculate season statistics
            using (var dbContext = new LeagueDbContext("SkippyCup_leagueDb"))
            {
                var seasonStatistics = dbContext.Set <SeasonStatisticSetEntity>().ToList();

                dbContext.Configuration.LazyLoadingEnabled = false;

                seasonStatistics.ForEach(x => x.LoadRequiredDataAsync(dbContext).Wait());
                seasonStatistics.ForEach(x => x.Calculate(dbContext));

                dbContext.SaveChanges();
            }

            // Create league statistic set
            //using (var dbContext = new LeagueDbContext("SkippyCup_leagueDb"))
            //{
            //    var leagueStatistic = new LeagueStatisticSetEntity();
            //    dbContext.LeagueStatistics.Add(leagueStatistic);

            //    leagueStatistic.StatisticSets.Add(dbContext.Seasons.First().SeasonStatistics.First());
            //    leagueStatistic.StatisticSets.Add(dbContext.Seasons.First().SeasonStatistics.Last());

            //    dbContext.SaveChanges();
            //}

            // Calculate league statistics
            using (var dbContext = new LeagueDbContext("SkippyCup_leagueDb"))
            {
                var leagueStatistic = dbContext.Set <LeagueStatisticSetEntity>().First();

                dbContext.Configuration.LazyLoadingEnabled = false;

                leagueStatistic.LoadRequiredDataAsync(dbContext).Wait();
                leagueStatistic.Calculate(dbContext);

                dbContext.SaveChanges();
            }

            //Console.Read();
        }
 public void Init()
 {
     _context = new LeagueDbContext
     {
         Players = MockDbSet(FakePlayersCollection[0], FakePlayersCollection[1]),
         Teams   = MockDbSet(FakePlayersCollection[0].Team, FakePlayersCollection[1].Team)
     };
 }
Exemplo n.º 11
0
 public override void Delete(LeagueDbContext dbContext)
 {
     if (ScoredResultRow?.ScoredResult?.Result != null)
     {
         ScoredResultRow.ScoredResult.Result.RequiresRecalculation = true;
     }
     base.Delete(dbContext);
 }
 public override void Delete(LeagueDbContext dbContext)
 {
     ScoredResultRows.ToList().ForEach(x => x.Delete(dbContext));
     if (Result != null)
     {
         Result.RequiresRecalculation = true;
     }
     base.Delete(dbContext);
 }
Exemplo n.º 13
0
        public IHttpActionResult PostLeague([FromUri] string leagueName, [FromUri] string fullName = "")
        {
            // check for empty body and invalid data
            if (string.IsNullOrEmpty(leagueName))
            {
                return(BadRequestEmptyParameter(nameof(leagueName)));
            }
            if (string.IsNullOrEmpty(fullName))
            {
                fullName = leagueName;
            }
            base.CheckLeagueRole(User, leagueName);

            var dbName   = GetDatabaseNameFromLeagueName(leagueName);
            var register = LeagueRegister.Get();

            var league = register.GetLeague(leagueName);

            if (league == null)
            {
                // check current number of leagues for that user
                string userId      = User.Identity.GetUserId();
                var    leagueCount = register.Leagues.Count(x => x.CreatorId.ToString() == userId);
                var    maxLeagues  = 3;
                if (leagueCount >= maxLeagues)
                {
                    return(BadRequest($"Create league failed. Maximum numbers of {maxLeagues} leagues per user reached."));
                }

                using (var dbContext = new LeagueDbContext(dbName, createDb: true))
                {
                    var seasons = dbContext.Seasons;
                    if (seasons == null || seasons.Count() == 0)
                    {
                        seasons.Add(new iRLeagueDatabase.Entities.SeasonEntity()
                        {
                            SeasonName             = "First Season",
                            CreatedByUserName      = User.Identity.Name,
                            CreatedByUserId        = User.Identity.GetUserId(),
                            LastModifiedByUserName = User.Identity.Name,
                            LastModifiedByUserId   = User.Identity.GetUserId()
                        });
                        dbContext.SaveChanges();
                        // Create new entry in league register
                        return(Ok($"New League {leagueName} with database {dbName} created!"));
                    }
                    UpdateLeague(leagueName, User);
                    return(BadRequest($"League {leagueName} already exists!"));
                }
            }

            // if league exists just update fullname
            league.PrettyName = fullName;
            register.Save();
            return(Ok("League information updated"));
        }
        public override void Delete(LeagueDbContext dbContext)
        {
            AddPenalty?.Delete(dbContext);
            ReviewPenalties?.ToList().ForEach(x => x.Delete(dbContext));
            dbContext.Set <DriverStatisticRowEntity>()
            .Where(x => x.LastResultRowId == ScoredResultRowId || x.FirstResultRowId == ScoredResultRowId)
            .Load();

            base.Delete(dbContext);
        }
Exemplo n.º 15
0
 public override void Delete(LeagueDbContext dbContext)
 {
     IncidentReview?.AcceptedReviewVotes?.Remove(this);
     ReviewPenalties?.ForEach(x => x.ReviewVote = null);
     if (IncidentReview?.Session?.SessionResult != null)
     {
         IncidentReview.Session.SessionResult.RequiresRecalculation = true;
     }
     base.Delete(dbContext);
 }
Exemplo n.º 16
0
        public SessionService(IHttpContextAccessor httpContextAccessor, LeagueDbContext dbContext)
        {
            _dal = dbContext;

            string userId = httpContextAccessor.HttpContext?.User.Identity?.Name;

            if (userId != null)
            {
                initialize(userId);
            }
        }
Exemplo n.º 17
0
        protected override async Task <IReadOnlyDictionary <int, Item> > LoadBatchAsync(
            IReadOnlyList <int> keys,
            CancellationToken cancellationToken)
        {
            await using LeagueDbContext dbContext =
                            _dbContextFactory.CreateDbContext();

            return(await dbContext.Items
                   .Where(i => keys.Contains(i.Id))
                   .ToDictionaryAsync(t => t.Id, cancellationToken));
        }
 public override void Delete(LeagueDbContext dbContext)
 {
     if (Scoring != null)
     {
         var results = Scoring.GetAllSessions().Where(x => x.SessionResult != null).Select(x => x.SessionResult);
         foreach (var result in results)
         {
             result.RequiresRecalculation = true;
         }
     }
     base.Delete(dbContext);
 }
Exemplo n.º 19
0
        public static IMapper GetEntityMapper(LeagueDbContext dbContext)
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <IncidentReviewDataDTO, IncidentReview>()
                .MapOnlyIfChanged();
                //.ForMember(dest => dest.InvolvedMembers, opt => opt.Ignore());
                cfg.CreateMap <LeagueMemberDataDTO, LeagueMember>()
                .ConstructUsing(source => GetMapping(source, dbContext.Members))
                .MapOnlyIfChanged();
                cfg.CreateMap <SeasonDataDTO, Season>()
                .ConstructUsing(source => GetMapping(source, dbContext.Seasons))
                .MapOnlyIfChanged();
                cfg.CreateMap <CommentDataDTO, CommentBase>()
                .ConstructUsing(source => GetMapping(source, dbContext.Comments))
                .MapOnlyIfChanged();
                cfg.CreateMap <ResultDataDTO, Result>()
                .ConstructUsing(source => GetMapping(source, dbContext.Results))
                .MapOnlyIfChanged();
                cfg.CreateMap <ScoringDataDTO, Scoring>()
                .ConstructUsing(source => GetMapping(source, dbContext.Scorings))
                .MapOnlyIfChanged();
                cfg.CreateMap <ResultRowDataDTO, ResultRow>()
                .ConstructUsing(source => GetMapping(source, dbContext.ResultRows))
                .MapOnlyIfChanged();
                cfg.CreateMap <ReviewCommentDataDTO, ReviewComment>()
                .ConstructUsing(source => GetMapping(source, dbContext.ReviewComments))
                .MapOnlyIfChanged();
                cfg.CreateMap <SessionDataDTO, SessionBase>()
                .ConstructUsing(source => GetMapping(source, dbContext.Sessions))
                .MapOnlyIfChanged();
                cfg.CreateMap <SessionDataDTO, RaceSession>()
                .ConstructUsing(source => GetMapping(source, dbContext.RaceSessions))
                .MapOnlyIfChanged();
                cfg.CreateMap <ScheduleDataDTO, Schedule>()
                .ConstructUsing(source => GetMapping(source, dbContext.Schedules))
                .MapOnlyIfChanged();

                cfg.CreateMap <LeagueMemberInfoDTO, LeagueMember>().ConvertUsing((source, dest) => GetMapping(source, dest, dbContext.Members));
                cfg.CreateMap <IncidentReviewInfoDTO, IncidentReview>().ConvertUsing((source, dest) => GetMapping(source, dest, dbContext.Reviews));
                cfg.CreateMap <SeasonInfoDTO, Season>().ConvertUsing((source, dest) => GetMapping(source, dest, dbContext.Seasons));
                cfg.CreateMap <CommentInfoDTO, CommentBase>().ConvertUsing((source, dest) => GetMapping(source, dest, dbContext.Comments));
                cfg.CreateMap <ResultInfoDTO, Result>().ConvertUsing((source, dest) => GetMapping(source, dest, dbContext.Results));
                cfg.CreateMap <ScoringInfoDTO, Scoring>().ConvertUsing((source, dest) => GetMapping(source, dest, dbContext.Scorings));
                cfg.CreateMap <SessionInfoDTO, SessionBase>().ConvertUsing((source, dest) => GetMapping(source, dest, dbContext.Sessions));
                cfg.CreateMap <SessionInfoDTO, RaceSession>().ConvertUsing((source, dest) => GetMapping(source, dest, dbContext.RaceSessions));
                cfg.CreateMap <ScheduleInfoDTO, Schedule>().ConvertUsing((source, dest) => GetMapping(source, dest, dbContext.Schedules));
            });


            return(config.CreateMapper());
        }
Exemplo n.º 20
0
            public async Task <IEnumerable <Item> > GetItemsAsync(
                Build build,
                [ScopedService] LeagueDbContext dbContext,
                ItemByIdDataLoader itemById,
                CancellationToken cancellationToken)
            {
                int[] itemIds = await dbContext.BuildItems
                                .Where(bi => bi.BuildId == build.Id)
                                .Select(t => t.ItemId)
                                .ToArrayAsync();

                return(await itemById.LoadAsync(itemIds, cancellationToken));
            }
Exemplo n.º 21
0
            public async Task <IEnumerable <Skill> > GetSkillsAsync(
                Page page,
                [ScopedService] LeagueDbContext dbContext,
                SkillByIdDataLoader skillById,
                CancellationToken cancellationToken)
            {
                int[] skillIds = await dbContext.PageSkills
                                 .Where(p => p.PageId == page.Id)
                                 .Select(r => r.SkillId)
                                 .ToArrayAsync();

                return(await skillById.LoadAsync(skillIds, cancellationToken));
            }
Exemplo n.º 22
0
        public async Task <AddUserPayload> AddUserAsync(AddUserInput input, [ScopedService] LeagueDbContext context)
        {
            User user = new User
            {
                Username = input.Username,
                Password = input.Password
            };

            context.Users.Add(user);
            await context.SaveChangesAsync();

            return(new AddUserPayload(user));
        }
        public IHttpActionResult DeleteModels([FromUri] string[] requestIds, string requestType, string leagueName)
        {
            try
            {
                logger.Info($"Delete Models request || type: {requestType} - league: {leagueName} - ids: {string.Join("/", requestIds.Select(x => $"[{x}]"))}");
                CheckLeagueRole(User, leagueName);

                if (requestIds == null || requestType == null || leagueName == null)
                {
                    return(BadRequest("Parameters can not be null!"));
                }

                if (requestIds.Count() == 0)
                {
                    return(BadRequest("Request ids can not be empty"));
                }

                long[][] requestIdValues;
                if (requestIds != null && requestIds.Count() > 0)
                {
                    requestIdValues = requestIds.Select(x => GetIdFromString(x)).ToArray();
                }
                else
                {
                    requestIdValues = null;
                }

                Type requestTypeType = GetRequestType(requestType);

                var databaseName = GetDatabaseNameFromLeagueName(leagueName);

                bool data;
                using (var dbContext = new LeagueDbContext(databaseName))
                    using (IModelDataProvider modelDataProvider = new ModelDataProvider(dbContext))
                    {
                        data = modelDataProvider.DeleteArray(requestTypeType, requestIdValues);
                        if (dbContext.DbChanged)
                        {
                            UpdateLeague(leagueName, User);
                        }
                    }
                //GC.Collect();
                logger.Info($"Delete Models request || send answer: {data}");
                return(Ok(data));
            }
            catch (Exception e)
            {
                logger.Error("Error in PostModels", e);
                throw;
            }
        }
        public IHttpActionResult GetModel(string requestId, string requestType, string leagueName, string fields, bool excludeFields = false)
        {
            try
            {
                logger.Info($"Get Model Fields request || type: {requestType} - league: {leagueName} - id: [{requestId}] - fields: {fields}");
                CheckLeagueRole(User, leagueName);

                if (requestId == null || requestType == null || leagueName == null)
                {
                    return(BadRequest("Parameter requestType or leagueName can not be null!"));
                }

                string[] fieldValues = new string[0];
                try
                {
                    fieldValues = fields?.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) ?? fieldValues;
                }
                catch (Exception e)
                {
                    throw new ArgumentException("Invalid field names", e);
                }

                long[] requestIdValue = GetIdFromString(requestId);

                Type requestTypeType = GetRequestType(requestType);

                var databaseName = GetDatabaseNameFromLeagueName(leagueName);

                MappableDTO data;
                using (var dbContext = new LeagueDbContext(databaseName))
                    using (IModelDataProvider modelDataProvider = new ModelDataProvider(dbContext))
                    {
                        data = modelDataProvider.Get(requestTypeType, requestIdValue);
                    }
                //GC.Collect();

                data.SetSerializableProperties(fieldValues, excludeFields);

                var response = SelectFieldsHelper.GetSelectedFieldObject(data);

                logger.Info($"Get Model Fields request || send data: {data} - fields: {string.Join(",", fieldValues)}");

                return(Json(response));
            }
            catch (Exception e)
            {
                logger.Error("Error in GetModel Fields", e);
                throw;
            }
        }
        public IHttpActionResult GetModels([FromUri] string[] requestIds, string requestType, string leagueName)
        {
            try
            {
                logger.Info($"Get Models request || type: {requestType} - league: {leagueName} - ids: {string.Join("/", requestIds.Select(x => $"[{string.Join(",", x)}]"))}");

                CheckLeagueRole(User, leagueName);

                if (requestType == null || leagueName == null)
                {
                    return(BadRequest("Parameter requestType or leagueName can not be null!"));
                }

                long[][] requestIdValues;
                if (requestIds != null && requestIds.Count() > 0)
                {
                    requestIdValues = requestIds.Select(x => GetIdFromString(x)).ToArray();
                }
                else
                {
                    requestIdValues = null;
                }

                Type requestTypeType = GetRequestType(requestType);

                var databaseName = GetDatabaseNameFromLeagueName(leagueName);

                MappableDTO[] data;
                using (var dbContext = new LeagueDbContext(databaseName))
                    using (IModelDataProvider modelDataProvider = new ModelDataProvider(dbContext))
                    {
                        data = modelDataProvider.GetArray(requestTypeType, requestIdValues);
                    }
                //GC.Collect();

                logger.Info($"Get Models request || send data: {string.Join("/", (object[])data)}");

                return(Ok(data));
            }
            catch (Exception e)
            {
                logger.Error("Error in GetModels", e);
                throw;
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Perform a check if recalculation is required based on the current data set.
        /// <para>Calling this function will also set the value of <see cref="StatisticSetEntity.RequiresRecalculation"/></para>
        /// </summary>
        /// <param name="dbContext">Database context from EntityFramework</param>
        /// <returns><see langword="true"/> if calculation is required</returns>
        public override async Task <bool> CheckRequireRecalculationAsync(LeagueDbContext dbContext)
        {
            if (RequiresRecalculation)
            {
                return(true);
            }

            if (dbContext.Configuration.LazyLoadingEnabled == false)
            {
                await LoadRequiredDataAsync(dbContext);
            }

            var Scorings = ScoringTable?.Scorings;

            RequiresRecalculation = (Scorings
                                     ?.SelectMany(x => x.Sessions.Where(y => y.SessionResult != null).Select(y => y.SessionResult))
                                     ?.Any(x => x.Season.Finished == false && (x.RequiresRecalculation || x.LastModifiedOn > LastModifiedOn))).GetValueOrDefault();

            return(RequiresRecalculation);
        }
Exemplo n.º 27
0
        /// <summary>
        /// <para>Load all data required for calculating the statistics from the database.</para>
        /// <para>Must be called prior to <see cref="Calculate"/> if lazy loading is disabled!</para>
        /// </summary>
        /// <param name="dbContext">Database context from EntityFramework.</param>
        /// <param name="force">Force loading data again even if IsDataLoaded is true.</param>
        /// <returns></returns>
        public override async Task LoadRequiredDataAsync(LeagueDbContext dbContext, bool force = false)
        {
            if (IsDataLoaded && force == false)
            {
                return;
            }

            await base.LoadRequiredDataAsync(dbContext, force);

            // Load season statistic sets
            await dbContext.Entry(this).Collection(x => x.StatisticSets).LoadAsync();

            // Load data for each SeasonStatisticSet
            foreach (var statisticSet in StatisticSets)
            {
                await statisticSet.LoadRequiredDataAsync(dbContext);
            }

            IsDataLoaded = true;
        }
Exemplo n.º 28
0
        /// <summary>
        /// Perform a check if recalculation is required based on the current data set.
        /// <para>Calling this function will also set the value of <see cref="StatisticSetEntity.RequiresRecalculation"/></para>
        /// </summary>
        /// <param name="dbContext">Database context from EntityFramework</param>
        /// <returns><see langword="true"/> if calculation is required</returns>
        public override async Task <bool> CheckRequireRecalculationAsync(LeagueDbContext dbContext)
        {
            if (RequiresRecalculation)
            {
                return(true);
            }

            if (dbContext.Configuration.LazyLoadingEnabled == false)
            {
                await LoadRequiredDataAsync(dbContext);
            }

            RequiresRecalculation |= StatisticSets.Any(x => x.LastModifiedOn > LastModifiedOn);
            if (RequiresRecalculation)
            {
                return(true);
            }

            RequiresRecalculation |= (await Task.WhenAll(StatisticSets.Select(async x => await x.CheckRequireRecalculationAsync(dbContext)))).Any(x => x);

            return(RequiresRecalculation);
        }
Exemplo n.º 29
0
        public StandingsEntity GetSeasonStandings(LeagueDbContext dbContext)
        {
            var allSessions = GetAllSessions();

            //if (Scorings != null && Scorings.Count > 0)
            //{
            //    foreach (var msc in Scorings)
            //    {
            //        var addSessions = msc.Sessions.Except(allSessions);
            //        allSessions.AddRange(addSessions);
            //    }
            //}

            var session = allSessions.Where(x => x.SessionResult != null).OrderBy(x => x.Date).LastOrDefault();

            if (session == null)
            {
                return(null);
            }

            return(GetSeasonStandings(session, dbContext, allSessions.Count - DropWeeks));
        }
        public IHttpActionResult GetModel(string requestId, string requestType, string leagueName)
        {
            try
            {
                logger.Info($"Get Model request || type: {requestType} - league: {leagueName} - id: [{requestId}]");
                CheckLeagueRole(User, leagueName);

                if (requestId == null || requestType == null || leagueName == null)
                {
                    return(BadRequest("Parameter requestType or leagueName can not be null!"));
                }

                long[] requestIdValue = GetIdFromString(requestId);

                Type requestTypeType = GetRequestType(requestType);

                var databaseName = GetDatabaseNameFromLeagueName(leagueName);

                MappableDTO data;
                using (var dbContext = new LeagueDbContext(databaseName))
                    using (IModelDataProvider modelDataProvider = new ModelDataProvider(dbContext))
                    {
                        data = modelDataProvider.Get(requestTypeType, requestIdValue);
                    }
                //GC.Collect();

                logger.Info($"Get Model request || send data: {data?.ToString()}");

                return(Ok(data));
            }
            catch (Exception e)
            {
                logger.Error("Error in GetModel", e);
                throw;
            }
        }