Example #1
0
        private IEnumerable <MonthSummaryActivity> getUserMonthlyActivities(string accessToken, int id, DateTime today)
        {
            var user = context.GetUserById(id);

            if (user == null || user.MonthSummaries == null || user.MonthSummaries.Count == 0)
            {
                var allUserActivities     = stravaClient.getAllUserActivities(accessToken, id);
                var monthSummaryActivites = convertToMonthSummaryActivities(allUserActivities);

                user = new User()
                {
                    UserId         = id,
                    LastDownload   = DateTime.Now.Date,
                    MonthSummaries = monthSummaryActivites.ToList(),
                };
                context.Add(user);
                context.SaveChanges();
            }
            else
            {
                var userActivities        = stravaClient.getUserActivitiesByIdAfter(accessToken, user, user.LastDownload);
                var monthSummaryActivites = convertToMonthSummaryActivities(userActivities);

                if (monthSummaryActivites != null)
                {
                    user.LastDownload = DateTime.Now.Date;
                    foreach (var activity in monthSummaryActivites)
                    {
                        if (!context.Contains(activity))
                        {
                            context.Add(activity);
                            user.MonthSummaries.Add(activity);
                        }
                    }
                    context.SaveChanges();
                }
            }

            var activitiesThisMonth = from activity in user.MonthSummaries
                                      where activity.StartDate.Value.Month == today.Month &&
                                      activity.StartDate.Value.Year == today.Year
                                      select activity;

            if (activitiesThisMonth == null || activitiesThisMonth.ToList().Count == 0)
            {
                return(null);
            }

            return(activitiesThisMonth);
        }