public static async Task<UserAccounts> RegisterUser(ToracGolfContext dbContext, SignUpEnteredDataBase signUpModel)
        {
            //go either get the ref season record or add it
            var refSeasonRecord = await SeasonDataProvider.RefSeasonAddOrGet(dbContext, signUpModel.CurrentSeason).ConfigureAwait(false);

            //user to add
            var userToAdd = new UserAccounts
            {
                StateId = Convert.ToInt32(signUpModel.HomeState),
                CreatedDate = DateTime.Now,
                CurrentSeasonId = refSeasonRecord.SeasonId,
                EmailAddress = signUpModel.Email,
                FirstName = signUpModel.FirstName,
                LastName = signUpModel.LastName,
                Password = signUpModel.Password
            };

            //go try to add the user
            dbContext.Users.Add(userToAdd);

            //go save the changes
            await dbContext.SaveChangesAsync().ConfigureAwait(false);

            //add the user season now
            await SeasonDataProvider.UserSeasonAdd(dbContext, userToAdd.UserId, refSeasonRecord).ConfigureAwait(false);

            //return the user now
            return await dbContext.Users.AsNoTracking().FirstAsync(x => x.UserId == userToAdd.UserId).ConfigureAwait(false);
        }
        private static Task<Last20Rounds[]> HandicapCalculatorRoundSelectorHelper(ToracGolfContext dbContext, int userId, int? seasonId)
        {
            //go build the base query
            var query = (from myRounds in dbContext.Rounds.AsNoTracking()
                         join myTeeLocations in dbContext.CourseTeeLocations.AsNoTracking()
                         on new { myRounds.CourseId, myRounds.CourseTeeLocationId } equals new { myTeeLocations.CourseId, myTeeLocations.CourseTeeLocationId }
                         where myRounds.UserId == userId
                         orderby myRounds.RoundDate descending, myRounds.RoundId descending
                         select new
                         {
                             myRounds.RoundId,
                             myRounds.Score,
                             myRounds.SeasonId,
                             myTeeLocations.Rating,
                             myTeeLocations.Slope
                         }).Take(20).AsQueryable();

            //do we need to add the season?
            if (seasonId.HasValue)
            {
                //tack on the season
                query = query.Where(x => x.SeasonId == seasonId.Value);
            }

            //go grab the last 20 rounds class and return the task
            return query.Select(x => new Last20Rounds
            {
                RoundId = x.RoundId,
                RoundScore = x.Score,
                Rating = x.Rating,
                Slope = x.Slope
            }).ToArrayAsync();
        }
 public SecurityController(IMemoryCache cache, ICacheFactoryStore cacheFactoryStore, ToracGolfContext dbContext, IOptions<AppSettings> configuration, ILogger<SecurityController> logger)
 {
     DbContext = dbContext;
     Cache = cache;
     CacheFactory = cacheFactoryStore;
     Configuration = configuration;
     Logger = logger;
 }
        public static async Task ChangePassword(ToracGolfContext dbContext, int userId, string password)
        {
            var user = await dbContext.Users.FirstAsync(x => x.UserId == userId).ConfigureAwait(false);

            user.Password = password;

            await dbContext.SaveChangesAsync().ConfigureAwait(false);
        }
 public SettingsController(IMemoryCache cache, ICacheFactoryStore cacheFactoryStore, ToracGolfContext dbContext, IAntiforgery antiforgery, IOptions<AppSettings> configuration)
 {
     DbContext = dbContext;
     Cache = cache;
     CacheFactory = cacheFactoryStore;
     Antiforgery = antiforgery;
     Configuration = configuration;
 }
        public NewsFeedCommentRepository(ToracGolfContext dbContext)
        {
            DbContext = dbContext;

            //just set the method....we are doing this so the calling user doesn't have to populate it in a variable first
            SelectCommand = SelectCommentsBuilder();

            //UserProfileFinder = userProfileFinder;
        }
 public static async Task<IDictionary<int, string>> SeasonSelectForUser(ToracGolfContext dbContext, int userId)
 {
     return await (from mySeasons in dbContext.UserSeason.AsNoTracking()
                   join refSeasons in dbContext.Ref_Season.AsNoTracking()
                   on mySeasons.SeasonId equals refSeasons.SeasonId
                   where mySeasons.UserId == userId
                   orderby mySeasons.Rounds.Select(x => x.RoundDate).DefaultIfEmpty(DateTime.MaxValue).Min() descending
                   select refSeasons).ToDictionaryAsync(x => x.SeasonId, x => x.SeasonText).ConfigureAwait(false);
 }
 private static IQueryable<DashboardRoundDisplay> BuildSelectStatement(ToracGolfContext dbContext, IOrderedQueryable<Round> sortedQuery)
 {
     return sortedQuery.Take(5).Select(x => new DashboardRoundDisplay
     {
         CourseId = x.Course.CourseId,
         RoundDate = x.RoundDate,
         Score = x.Score,
         CourseName = x.Course.Name,
         TeeBoxLocation = dbContext.CourseTeeLocations.FirstOrDefault(y => y.CourseTeeLocationId == x.CourseTeeLocationId).Description
     });
 }
        public static async Task<int> CourseAdd(ToracGolfContext dbContext, int userId, CourseAddEnteredData CourseData, string courseSavePath)
        {
            //course record to add
            var courseToAdd = new Course
            {
                Name = CourseData.CourseName,
                Description = CourseData.Description,
                IsActive = true,
                Pending = true,
                City = CourseData.City,
                StateId = Convert.ToInt32(CourseData.StateListing),
                UserIdThatCreatedCourse = userId,
                OnlyAllow18Holes = CourseData.OnlyAllow18Holes,
                CreatedDate = DateTime.Now
            };

            courseToAdd.CourseTeeLocations = CourseData.TeeLocations.Select((x, i) => new CourseTeeLocations
            {
                CourseId = courseToAdd.CourseId,
                Description = x.Description,
                TeeLocationSortOrderId = i,
                Front9Par = x.Front9Par.Value,
                Back9Par = x.Back9Par.Value,
                Rating = x.Rating.Value,
                Slope = x.Slope.Value,
                Yardage = x.Yardage.Value,
                FairwaysOnCourse = 18 - x.NumberOfPar3s.Value
            }).ToArray();

            //add the course to the context
            dbContext.Course.Add(courseToAdd);

            //go save it
            await dbContext.SaveChangesAsync().ConfigureAwait(false);

            //do we have a course image?
            if (CourseData.CourseImage != null)
            {
                //grab the byte array for the file
                var fileToSave = ToracLibrary.Core.Graphics.GraphicsUtilities.ImageFromJsonBase64String(CourseData.CourseImage);

                //grab where we have the actual .jpg vs png
                var indexOfSlash = fileToSave.MimeType.IndexOf(@"/");

                //grab the file name to save
                var fileNameToSave = System.IO.Path.Combine(courseSavePath, string.Format("{0}.{1}", courseToAdd.CourseId, fileToSave.MimeType.Substring(indexOfSlash + 1, fileToSave.MimeType.Length - indexOfSlash - 1)));

                //go save the file
                System.IO.File.WriteAllBytes(fileNameToSave, fileToSave.FileBytes);
            }

            //return the course id
            return courseToAdd.CourseId;
        }
        public async Task<IEnumerable<NewsFeedCommentRow>> CommentSelect(ToracGolfContext dbContext, int userId, int id, NewsFeedItemModel.NewsFeedTypeId newsFeedTypeId, ImageFinder userImageFinder)
        {
            var data = await CommentRepository.GetComments().AsNoTracking()
                         .Where(x => x.AreaId == id && x.NewsFeedTypeId == (int)newsFeedTypeId)
                         .OrderByDescending(x => x.CreatedDate)
                         .Select(CommentRepository.SelectCommand).ToListAsync().ConfigureAwait(false);

            data.ForEach(x => x.UserProfileUrl = userImageFinder.FindImage(x.UserIdThatMadeComment));

            return data;
        }
 public static async Task<IEnumerable<CourseForRoundAddScreen>> ActiveCoursesSelectForState(ToracGolfContext dbContext, int stateId)
 {
     return await dbContext.Course.AsNoTracking()
                  .Where(x => x.StateId == stateId && x.IsActive)
                  .OrderBy(x => x.Name)
                .Select(x => new CourseForRoundAddScreen
                {
                    CourseId = x.CourseId,
                    Name = x.Name,
                }).ToArrayAsync();
 }
        private static IQueryable<Round> BuildBaseQuery(ToracGolfContext dbContext, int userId, int? seasonId)
        {
            var baseQuery = dbContext.Rounds.AsNoTracking().Where(x => x.UserId == userId);

            if (seasonId.HasValue)
            {
                baseQuery = baseQuery.Where(x => x.SeasonId == seasonId);
            }

            return baseQuery;
        }
 public RoundController(IMemoryCache cache,
                        ICacheFactoryStore cacheFactoryStore,
                        ToracGolfContext dbContext,
                        IAntiforgery antiforgery,
                        IOptions<AppSettings> configuration,
                        IListingFactory<RoundListingFactory.RoundListingSortEnum, Round, RoundListingData> roundListingFactory)
 {
     DbContext = dbContext;
     Cache = cache;
     CacheFactory = cacheFactoryStore;
     Antiforgery = antiforgery;
     Configuration = configuration;
     RoundListingFactory = roundListingFactory;
 }
 public CourseController(IMemoryCache cache,
                         ICacheFactoryStore cacheFactoryStore,
                         ToracGolfContext dbContext,
                         IAntiforgery antiforgery,
                         IOptions<AppSettings> configuration,
                         IListingFactory<CourseListingFactory.CourseListingSortEnum, Course, CourseListingData> courseListingFactory)
 {
     DbContext = dbContext;
     Cache = cache;
     CacheFactory = cacheFactoryStore;
     Antiforgery = antiforgery;
     Configuration = configuration;
     CourseListingFactory = courseListingFactory;
 }
        public static async Task<IEnumerable<KeyValuePair<string, int>>> RoundPieChart(ToracGolfContext dbContext, int userId, int? seasonId)
        {
            var baseQuery = BuildBaseQuery(dbContext, userId, seasonId);

            var lst = new List<KeyValuePair<string, int>>();

            lst.Add(new KeyValuePair<string, int>("70's", await baseQuery.CountAsync(x => x.Score < 80).ConfigureAwait(false)));
            lst.Add(new KeyValuePair<string, int>("80's", await baseQuery.CountAsync(x => x.Score >= 80 && x.Score <= 89).ConfigureAwait(false)));
            lst.Add(new KeyValuePair<string, int>("90's", await baseQuery.CountAsync(x => x.Score >= 90 && x.Score <= 99).ConfigureAwait(false)));
            lst.Add(new KeyValuePair<string, int>("100's", await baseQuery.CountAsync(x => x.Score >= 100 && x.Score <= 109).ConfigureAwait(false)));
            lst.Add(new KeyValuePair<string, int>("> 110", await baseQuery.CountAsync(x => x.Score >= 110).ConfigureAwait(false)));

            return lst.Where(x => x.Value > 0).ToArray();
        }
Exemple #16
0
 public HomeController(IMemoryCache cache,
                       ICacheFactoryStore cacheFactoryStore,
                       ToracGolfContext dbContext,
                       IAntiforgery antiforgery,
                       IOptions<AppSettings> configuration,
                       Lazy<NewsFeedDataProvider> newsFeedDataProvider)
 {
     DbContext = dbContext;
     Cache = cache;
     CacheFactory = cacheFactoryStore;
     Antiforgery = antiforgery;
     Configuration = configuration;
     NewsFeedDataProvider = newsFeedDataProvider;
 }
        public static async Task<IEnumerable<DashboardHandicapScoreSplitDisplay>> ScoreHandicapGraph(ToracGolfContext dbContext, int userId, int? seasonId)
        {
            //var minDateToGrab = DateTime.Now.AddYears(-1);

            //just grab the last year so we don't grab globs of data
            return await BuildBaseQuery(dbContext, userId, seasonId).OrderBy(x => x.RoundDate).Take(20)
                .Select(x => new DashboardHandicapScoreSplitDisplay
                {
                    Month = x.RoundDate.Month,
                    Day = x.RoundDate.Day,
                    Year = x.RoundDate.Year,
                    Score = x.Score,
                    Handicap = dbContext.Handicap.FirstOrDefault(y => y.RoundId == x.RoundId).HandicapAfterRound
                }).ToArrayAsync().ConfigureAwait(false);
        }
        public async Task<IEnumerable<NewsFeedCommentRow>> CommentAdd(ToracGolfContext dbContext, int userId, int id, NewsFeedItemModel.NewsFeedTypeId newsFeedTypeId, string commentToAdd, ImageFinder userImageFinder)
        {
            //lets go add the row
            await CommentRepository.Add(new NewsFeedComment
            {
                AreaId = id,
                NewsFeedTypeId = (int)newsFeedTypeId,
                UserIdThatCommented = userId,
                CreatedDate = DateTime.Now,
                Comment = commentToAdd
            });

            //go return this posts comment
            return await CommentSelect(dbContext, userId, id, newsFeedTypeId, userImageFinder);
        }
        public static async Task<HandicapProgression> HandicapProgression(ToracGolfContext dbContext, int userId, int? seasonId)
        {
            var query = dbContext.Rounds.Include(x => x.Handicap).AsNoTracking()
                        .Where(x => x.UserId == userId);

            if (seasonId.HasValue)
            {
                query = query.Where(x => x.SeasonId == seasonId.Value);
            }

            return await query.OrderByDescending(x => x.RoundDate).OrderByDescending(x => x.RoundId).Select(x => new HandicapProgression
            {
                HandicapBeforeRound = x.Handicap.HandicapBeforeRound,
                HandicapAfterRound = x.Handicap.HandicapAfterRound
            }).FirstOrDefaultAsync().ConfigureAwait(false);
        }
        public static IQueryable<Course> CourseSelectQueryBuilder(ToracGolfContext dbContext,
                                                                  IListingFactory<CourseListingFactory.CourseListingSortEnum, Course, CourseListingData> courseListingFactory,
                                                                  string courseNameFilter,
                                                                  int? stateFilter)
        {
            //build the queryable
            var queryable = dbContext.Course.AsNoTracking().Where(x => x.IsActive).AsQueryable();

            //go build the query
            queryable = FilterBuilder.BuildQueryFilter(dbContext, queryable, courseListingFactory,
                                    new KeyValuePair<string, object>(nameof(courseNameFilter), courseNameFilter),
                                    new KeyValuePair<string, object>(nameof(stateFilter), stateFilter));

            //return the queryable
            return queryable;
        }
 public static async Task<IEnumerable<SeasonListingData>> SeasonListingForGrid(ToracGolfContext dbContext, int userId)
 {
     return await (from mySeasons in dbContext.UserSeason.AsNoTracking()
                   join refSeasons in dbContext.Ref_Season.AsNoTracking()
                   on mySeasons.SeasonId equals refSeasons.SeasonId
                   where mySeasons.UserId == userId
                   orderby mySeasons.Rounds.Select(x => x.RoundDate).DefaultIfEmpty(DateTime.MaxValue).Min() descending
                   select new SeasonListingData
                   {
                       Description = refSeasons.SeasonText,
                       SeasonId = refSeasons.SeasonId,
                       NumberOfRounds = mySeasons.Rounds.Count(),
                       TopScore = mySeasons.Rounds.Min(x => x.Score),
                       WorseScore = mySeasons.Rounds.Max(x => x.Score),
                       AverageScore = mySeasons.Rounds.Average(x => x.Score),
                   }).ToArrayAsync().ConfigureAwait(false);
 }
        public static async Task<UserSeason> UserSeasonAdd(ToracGolfContext dbContext, int userId, Ref_Season refSeasonRecord)
        {
            //record to add
            var recordToAdd = new UserSeason
            {
                UserId = userId,
                SeasonId = refSeasonRecord.SeasonId,
                CreatedDate = DateTime.Now
            };

            //add the record
            dbContext.UserSeason.Add(recordToAdd);

            //go save the changes
            await dbContext.SaveChangesAsync().ConfigureAwait(false);

            //return the record now
            return recordToAdd;
        }
        public static async Task<Ref_Season> RefSeasonAddOrGet(ToracGolfContext dbContext, string seasonText)
        {
            //let's first try to find the season with the same name
            var seasonToAdd = await dbContext.Ref_Season.AsNoTracking().FirstOrDefaultAsync(x => x.SeasonText == seasonText).ConfigureAwait(false);

            //didn't find a season with this name
            if (seasonToAdd == null)
            {
                //create the new season
                seasonToAdd = new Ref_Season { SeasonText = seasonText, CreatedDate = DateTime.Now };

                //add the record
                dbContext.Ref_Season.Add(seasonToAdd);

                //we need to save it for foreign key 
                await dbContext.SaveChangesAsync().ConfigureAwait(false);
            }

            //return the record
            return seasonToAdd;
        }
        public static async Task<int> SaveRound(ToracGolfContext dbContext, int userId, int seasonId, RoundAddEnteredData roundData)
        {
            //build the round record
            var round = new Round
            {
                CourseId = roundData.CourseId,
                CourseTeeLocationId = roundData.TeeLocationId,
                RoundDate = roundData.RoundDate,
                Is9HoleScore = roundData.NineHoleScore,
                Score = roundData.Score.Value,
                UserId = userId,
                SeasonId = seasonId,
                GreensInRegulation = roundData.GreensInRegulation,
                Putts = roundData.Putts,
                FairwaysHit = roundData.FairwaysHit
            };

            //go grab the tee location 
            var teeLocation = await dbContext.CourseTeeLocations.AsNoTracking().FirstAsync(x => x.CourseTeeLocationId == roundData.TeeLocationId).ConfigureAwait(false);

            //add the round handicap now
            round.RoundHandicap = Handicapper.CalculateHandicap(new Last20Rounds[] { new Last20Rounds { Rating = teeLocation.Rating, Slope = teeLocation.Slope, RoundScore = round.Score } }).Value;

            //add the round
            dbContext.Rounds.Add(round);

            //save the round
            //await dbContext.SaveChangesAsync();
            dbContext.SaveChanges();

            //we need to go add the handicap records
            await RefreshHandicapRecords(dbContext, userId);

            //return the round id
            return round.RoundId;
        }
        public static async Task<IEnumerable<TeeBoxSelectForCourseSelect>> TeeBoxSelectForCourse(ToracGolfContext dbContext, int courseId, double? currentHandicap)
        {
            var dbResults = await dbContext.CourseTeeLocations.AsNoTracking()
                                   .Where(x => x.CourseId == courseId).ToArrayAsync();


            var lst = new List<TeeBoxSelectForCourseSelect>();

            foreach (var teeBox in dbResults)
            {
                var teeBoxModel = new TeeBoxSelectForCourseSelect
                {
                    Back9Par = teeBox.Back9Par,
                    Front9Par = teeBox.Front9Par,
                    CourseId = teeBox.CourseId,
                    CourseTeeLocationId = teeBox.CourseTeeLocationId,
                    Description = teeBox.Description,
                    Rating = teeBox.Rating,
                    Slope = teeBox.Slope,
                    Yardage = teeBox.Yardage,
                    TeeLocationSortOrderId = teeBox.TeeLocationSortOrderId
                };

                //now add the course handicap and the max score
                teeBoxModel.CourseTeeBoxHandicap = Handicapper.CalculateCourseHandicap(currentHandicap, teeBoxModel.Slope);

                //now calculate the score
                teeBoxModel.MaxScorePerHole = Handicapper.MaxScorePerHole(teeBoxModel.CourseTeeBoxHandicap);

                //add the tee box score
                lst.Add(teeBoxModel);
            }

            //return the list
            return lst;
        }
        public static async Task<bool> DeleteARound(ToracGolfContext dbContext, int roundIdToDelete)
        {
            //grab the round
            var roundToDelete = await dbContext.Rounds.FirstOrDefaultAsync(x => x.RoundId == roundIdToDelete);

            //remove the round
            dbContext.Rounds.Remove(roundToDelete);

            //save the changes
            await dbContext.SaveChangesAsync().ConfigureAwait(false);

            //return a true result
            return true;
        }
 public static async Task<int> TotalNumberOfRounds(ToracGolfContext dbContext, IListingFactory<RoundListingFactory.RoundListingSortEnum, Round, RoundListingData> roundListingFactory, int userId, string roundNameFilter, int? StateFilter, DateTime? roundDateStartFilter, DateTime? roundDateEndFilter, bool onlyHandicappedRounds)
 {
     return await RoundSelectQueryBuilder(dbContext, roundListingFactory, userId, roundNameFilter, StateFilter, roundDateStartFilter, roundDateEndFilter, onlyHandicappedRounds).CountAsync().ConfigureAwait(false);
 }
        public static async Task<RoundSelectModel> RoundSelect(IListingFactory<RoundListingFactory.RoundListingSortEnum, Round, RoundListingData> roundListingFactory,
                                                               ToracGolfContext dbContext,
                                                               int userId,
                                                               int pageId,
                                                               RoundListingFactory.RoundListingSortEnum sortBy,
                                                               string courseNameFilter,
                                                               int? seasonFilter,
                                                               int recordsPerPage,
                                                               DateTime? roundDateStartFilter,
                                                               DateTime? roundDateEndFilter,
                                                               ImageFinder courseImageFinder,
                                                               bool handicappedRoundOnly)
        {
            //go grab the query
            var queryable = RoundSelectQueryBuilder(dbContext, roundListingFactory, userId, courseNameFilter, seasonFilter, roundDateStartFilter, roundDateEndFilter, handicappedRoundOnly);

            //go sort the data
            var sortedQueryable = roundListingFactory.SortByConfiguration[sortBy](queryable, new ListingFactoryParameters(dbContext, userId)).ThenBy(x => x.RoundId);

            //go return the queryable
            var selectableQuery = sortedQueryable.Select(x => new RoundListingData
            {
                RoundId = x.RoundId,
                CourseId = x.CourseId,
                CourseName = x.Course.Name,
                RoundDate = x.RoundDate,
                Score = x.Score,
                SeasonId = x.SeasonId,
                TeeBoxLocation = x.CourseTeeLocation,
                HandicapBeforeRound = x.Handicap.HandicapBeforeRound,

                Putts = x.Putts,
                FairwaysHit = x.FairwaysHit,
                GreensInRegulation = x.GreensInRegulation,

                RoundHandicap = x.RoundHandicap
            });

            //go run the query now
            var dataSet = await EFPaging.PageEfQuery(selectableQuery, pageId, recordsPerPage).ToListAsync().ConfigureAwait(false);

            //let's loop through the rounds and display the starts
            foreach (var round in dataSet)
            {
                //calculate the adjusted score
                round.AdjustedScore = Convert.ToInt32(Math.Round(round.Score - round.HandicapBeforeRound, 0));

                //go calculate the round performance
                round.RoundPerformance = (int)RoundPerformance.CalculateRoundPerformance(round.TeeBoxLocation.Front9Par + round.TeeBoxLocation.Back9Par, round.AdjustedScore);

                //set the image path
                round.CourseImagePath = courseImageFinder.FindImage(round.CourseId);
            }

            //go return the lookup now
            return new RoundSelectModel(dataSet);
        }
        public static IQueryable<Round> RoundSelectQueryBuilder(ToracGolfContext dbContext,
                                                                IListingFactory<RoundListingFactory.RoundListingSortEnum, Round, RoundListingData> roundListingFactory,
                                                                int userId,
                                                                string courseNameFilter,
                                                                int? seasonFilter,
                                                                DateTime? roundDateStartFilter,
                                                                DateTime? roundDateEndFilter,
                                                                bool handicappedRoundsOnly)
        {
            //build the queryable
            var queryable = dbContext.Rounds.AsNoTracking().Where(x => x.UserId == userId).AsQueryable();

            //go build the query filters
            queryable = FilterBuilder.BuildQueryFilter(dbContext, queryable, roundListingFactory,
                                    new KeyValuePair<string, object>(nameof(courseNameFilter), courseNameFilter),
                                    new KeyValuePair<string, object>(nameof(seasonFilter), seasonFilter),
                                    new KeyValuePair<string, object>(nameof(roundDateStartFilter), roundDateStartFilter),
                                    new KeyValuePair<string, object>(nameof(roundDateStartFilter), roundDateStartFilter),
                                    new KeyValuePair<string, object>(nameof(handicappedRoundsOnly), handicappedRoundsOnly));

            //if (handicappedRoundsOnly)
            //{
            //    //how many rounds do we have?
            //    int roundsWeHaveInQuery = queryable.Count();

            //    //now check how many are in the calculation
            //    var howManyToCalculateWith = Handicapper.HowManyRoundsToUseInFormula(roundsWeHaveInQuery > 20 ? 20 : roundsWeHaveInQuery);

            //    //now just grab the last 20
            //    var last20RoundIds = queryable.OrderByDescending(x => x.RoundDate)
            //                                  .ThenByDescending(x => x.RoundId)
            //                                  .Take(20) //we only ever get the last 20...
            //                                  .OrderBy(x => x.RoundHandicap) //now grab the lowest rated rounds of how many we are going to calculate with
            //                                  .Take(howManyToCalculateWith) //then grab just those
            //                                  .Select(x => x.RoundId).ToArray();

            //    //add the round id's to the query
            //    queryable = queryable.Where(x => last20RoundIds.Contains(x.RoundId));
            //}

            //return the query
            return queryable;
        }
        public static async Task<bool> RefreshHandicapRecords(ToracGolfContext dbContext, int userId)
        {
            //let's go delete all the handicap records
            var roundsToDelete = await (from myData in dbContext.Rounds
                                        join myHandicaps in dbContext.Handicap
                                        on myData.RoundId equals myHandicaps.RoundId
                                        where myData.UserId == userId
                                        select myHandicaps).ToArrayAsync();

            //delete all handicap records
            dbContext.Handicap.RemoveRange(roundsToDelete);

            //save the deletions
            await dbContext.SaveChangesAsync();

            //5. let's go rebuild all the handicap records
            var roundsForUser = await dbContext.Rounds.Include(x => x.CourseTeeLocation).Where(x => x.UserId == userId)
                                .OrderBy(x => x.RoundDate).ThenBy(x => x.RoundId)
                                .Select(x => x).ToArrayAsync();

            //func to go from rounds to last 20 rounds
            Func<Round, Last20Rounds> roundToLast20 = x => new Last20Rounds
            {
                RoundId = x.RoundId,
                RoundScore = x.Score,
                Rating = x.CourseTeeLocation.Rating,
                Slope = x.CourseTeeLocation.Slope
            };

            //lets loop through those rounds for the user
            foreach (var roundToCalculate in roundsForUser)
            {
                //grab the 20 rounds before this round
                var roundsToUse = roundsForUser
                    .Where(x => x.RoundDate < roundToCalculate.RoundDate)
                    .OrderByDescending(x => x.RoundDate)
                    .ThenByDescending(x => x.RoundId)
                    .Take(20)
                    .Select(roundToLast20).ToArray();

                //current round we are up too
                var currentRoundInArrayFormat = new Last20Rounds[] { roundToLast20(roundToCalculate) };

                //rounds for the "After round handicap"
                ICollection<Last20Rounds> roundsToCalculateAfterRoundHandicap;

                //if we have 0 rounds, then use the round we are looking through
                if (!roundsToUse.Any())
                {
                    //set the current rounds to just this one guy
                    roundsToUse = currentRoundInArrayFormat;

                    //set it to just this round
                    roundsToCalculateAfterRoundHandicap = roundsToUse;
                }
                else
                {
                    roundsToCalculateAfterRoundHandicap = roundsToUse.Concat(currentRoundInArrayFormat).ToArray();
                }

                //add the record to the context
                dbContext.Handicap.Add(new Handicap
                {
                    RoundId = roundToCalculate.RoundId,
                    HandicapBeforeRound = Handicapper.CalculateHandicap(roundsToUse).Value,
                    HandicapAfterRound = Handicapper.CalculateHandicap(roundsToCalculateAfterRoundHandicap).Value
                });
            }

            //go save the changes for the course handicap
            await dbContext.SaveChangesAsync();

            //return a postive result
            return true;
        }