Beispiel #1
0
    /*
     * private IList<WorkoutSample> DeviceSamplesForWorkout(WorkoutExtended workoutExted)
     * {
     *      IList<WorkoutSample> workoutSamples = new List<WorkoutSample>();
     *      int sequenceNum = 0;
     *      double minLat = double.MaxValue;
     *      double maxLat = double.MinValue;
     *      double minLng = double.MaxValue;
     *      double maxLng = double.MinValue;
     *      foreach (XElement sample in samples)
     *      {
     *          WorkoutSample workoutSample = DeviceSampleToWorkoutSampleAdaptor(sample);
     *          if (workoutSample.Lat != null && workoutSample.Lng != null)
     *          {
     *              double lat = Convert.ToDouble(workoutSample.Lat);
     *              double lng = Convert.ToDouble(workoutSample.Lng);
     *              if (lat < minLat)
     *              {
     *                  minLat = lat;
     *              }
     *              if (lat > maxLat)
     *              {
     *                  maxLat = lat;
     *              }
     *              if (lng < minLng)
     *              {
     *                  minLng = lng;
     *              }
     *              if (lng > maxLng)
     *              {
     *                  maxLng = lng;
     *              }
     *          }
     *          workoutSample.SampleNumber = sequenceNum++;
     *          workoutSample.WorkoutExtended = workoutExted;
     *          workoutSamples.Add(workoutSample);
     *      }
     *      workoutExted.LatMin = minLat;
     *      workoutExted.LatMax = maxLat;
     *      workoutExted.LngMin = minLng;
     *      workoutExted.LngMax = maxLng;
     *
     *      return workoutSamples;
     *
     * }
     */

    private void ParseFitnessHistoryDetail(string xml)
    {
        XElement doc      = XElement.Parse(xml);
        XElement activity = doc.Descendants().FirstOrDefault(n => n.Name.LocalName == "Activity");

        aqufitEntities entities = new aqufitEntities();
        User           user     = entities.UserSettings.OfType <User>().FirstOrDefault(u => u.UserKey == PortalSettings.UserId && u.PortalKey == PortalSettings.PortalId);

        Affine.Utils.WorkoutUtil.WorkoutType workoutType = Affine.Utils.WorkoutUtil.WorkoutType.RUNNING;
        string atype = (activity.Attribute("Sport").Value).ToLower();
        string title = string.Empty;

        switch (atype)
        {
        case "walking":
            workoutType = Affine.Utils.WorkoutUtil.WorkoutType.WALKING;
            title       = "Walking ";
            break;

        case "cycling":
            workoutType = Affine.Utils.WorkoutUtil.WorkoutType.CYCLING;
            title       = "Cycling ";
            break;

        case "swimming":
            workoutType = Affine.Utils.WorkoutUtil.WorkoutType.SWIMMING;
            title       = "Swimming ";
            break;

        case "running":
        default:
            title       = "Running ";
            workoutType = Affine.Utils.WorkoutUtil.WorkoutType.RUNNING;
            break;
        }
        string activityId  = activity.Descendants().FirstOrDefault(n => n.Name.LocalName == "Id").Value;
        long   thirdParyId = GetNumberFromStr(activityId);

        IEnumerable <XElement> laps = activity.Descendants().Where(n => n.Name.LocalName == "Lap");

        if (laps.Count() > 0)
        {   // we must have a lap
            // get the start time.
            XElement lap1      = laps.ElementAt(0);
            DateTime startTime = Convert.ToDateTime(lap1.Attribute("StartTime").Value);

            // total time
            double[] timesInSec = activity.Descendants().Where(n => n.Name.LocalName == "TotalTimeSeconds").Select(n => Convert.ToDouble(n.Value)).ToArray();
            double   totalSec   = 0.0;
            foreach (double t in timesInSec)
            {
                totalSec += t;
            }
            long duration = (long)Affine.Utils.UnitsUtil.unitsToSystemDefualt(totalSec, Affine.Utils.UnitsUtil.MeasureUnit.UNIT_SEC);

            // total cal
            double[] calArray = activity.Descendants().Where(n => n.Name.LocalName == "Calories").Select(n => Convert.ToDouble(n.Value)).ToArray();
            double   totalCal = 0.0;
            foreach (double c in calArray)
            {
                totalCal += c;
            }

            // total dist
            double[] distArray = activity.Descendants().Where(n => n.Name.LocalName == "DistanceMeters").Where(n => n.Parent.Name.LocalName == "Lap").Select(n => Convert.ToDouble(n.Value)).ToArray();
            double   totalDist = 0.0;
            foreach (double d in distArray)
            {
                totalDist += d;
            }

            Workout workout = new Workout()
            {
                Date           = startTime.ToUniversalTime(),
                TimeStamp      = DateTime.Now,
                Calories       = totalCal,
                AccoutType     = (short)Affine.Services.ThirdParty.AccountTypes.GARMIN,
                Description    = "",
                Distance       = Affine.Utils.UnitsUtil.unitsToSystemDefualt(totalDist, Affine.Utils.UnitsUtil.MeasureUnit.UNIT_M),
                Duration       = duration,
                Emotion        = null,
                PortalKey      = (int)PortalSettings.PortalId,
                UserSetting    = user,
                Terrain        = null,
                ThirdPartyId   = thirdParyId,
                Title          = title,
                Weather        = null,
                DataSrc        = (int)Affine.Utils.WorkoutUtil.DataSrc.GARMIN,
                WorkoutTypeKey = (long)workoutType
            };
            // now we need to add the extended data ...

            // get all the track points
            XElement[] trackpoints = activity.Descendants().Where(n => n.Name.LocalName == "Trackpoint").ToArray();
            //  IList<WorkoutSample> workoutSamples = new List<WorkoutSample>();
            WorkoutExtended extended = new WorkoutExtended()
            {
                UserStream = workout
            };
            entities.AddToWorkoutExtendeds(extended);
            int    sequenceNum = 0;
            double minLat      = double.MaxValue;
            double maxLat      = double.MinValue;
            double minLng      = double.MaxValue;
            double maxLng      = double.MinValue;
            foreach (XElement point in trackpoints)
            {
                try
                {
                    double   lat      = Convert.ToDouble(point.Descendants().FirstOrDefault(n => n.Name.LocalName == "LatitudeDegrees").Value);
                    double   lng      = Convert.ToDouble(point.Descendants().FirstOrDefault(n => n.Name.LocalName == "LongitudeDegrees").Value);
                    DateTime time     = Convert.ToDateTime(point.Descendants().FirstOrDefault(n => n.Name.LocalName == "Time").Value);
                    double   distance = Convert.ToDouble(point.Descendants().FirstOrDefault(n => n.Name.LocalName == "DistanceMeters").Value);
                    distance = Affine.Utils.UnitsUtil.unitsToSystemDefualt(distance, Affine.Utils.UnitsUtil.MeasureUnit.UNIT_M);
                    XElement el        = point.Descendants().FirstOrDefault(n => n.Name.LocalName == "AltitudeMeters");
                    double?  elivation = null;
                    if (el != null)
                    {
                        elivation = Convert.ToDouble(el.Value);
                        elivation = Affine.Utils.UnitsUtil.unitsToSystemDefualt(elivation.Value, Affine.Utils.UnitsUtil.MeasureUnit.UNIT_M);
                    }
                    if (lat < minLat)
                    {
                        minLat = lat;
                    }
                    if (lat > maxLat)
                    {
                        maxLat = lat;
                    }
                    if (lng < minLng)
                    {
                        minLng = lng;
                    }
                    if (lng > maxLng)
                    {
                        maxLng = lng;
                    }
                    WorkoutSample sample = new WorkoutSample()
                    {
                        Lat             = lat,
                        Lng             = lng,
                        SampleNumber    = sequenceNum++,
                        WorkoutExtended = extended,
                        Date            = time,
                        Elevation       = elivation,
                        Distance        = distance
                    };
                    entities.AddToWorkoutSamples(sample);
                }
                catch (NullReferenceException ex) { }   // just goto the next full sample
            }
            extended.LatMax = maxLat;
            extended.LatMin = minLat;
            extended.LngMax = maxLng;
            extended.LngMin = minLng;
            Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
            dataMan.SaveWorkout(entities, workout);
        }
    }
Beispiel #2
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                service.InlineScript = true;
                ScriptManager.GetCurrent(Page).Services.Add(service);
                imgAd.Src = ResolveUrl("~/images/iphoneAd.png");

                Affine.Utils.WorkoutUtil.WorkoutType workoutType = Affine.Utils.WorkoutUtil.WorkoutType.RUNNING;
                if (Request["wt"] != null)
                {
                    workoutType = Affine.Utils.WorkoutUtil.IntToWorkoutType(Convert.ToInt32(Request["wt"]));
                }
                atiWorkoutTypes.SelectedType = workoutType;
                aqufitEntities entities     = new aqufitEntities();
                WorkoutType    selectedType = entities.WorkoutType.First(w => w.Id == (int)workoutType);
                userQuery             = entities.UserSettings.OfType <User>().Where(u => u.PortalKey == this.PortalId && !u.User2WorkoutType.Select(wt => wt.WorkoutType.Id).Contains(selectedType.Id)).OrderBy(u => u.Id).AsQueryable();
                userQueryRecentActive = userQuery.OrderByDescending(w => w.LastLoginDate);
                if (this.UserSettings != null)
                {
                    userQueryLiveNear = userQuery.Where(u => u.LngHome.HasValue && u.LngHome.HasValue).OrderBy(u => Math.Abs(u.LatHome.Value - UserSettings.LatHome.Value) + Math.Abs(u.LngHome.Value - UserSettings.LngHome.Value));
                }
                userQueryMostWatched = userQuery.Where(u => u.Metrics.FirstOrDefault(m => m.MetricType == (int)Affine.Utils.MetricUtil.MetricType.NUM_FOLLOWERS) != null).OrderByDescending(u => u.Metrics.FirstOrDefault(m => m.MetricType == (int)Affine.Utils.MetricUtil.MetricType.NUM_FOLLOWERS).MetricValue);
                IQueryable <Workout> fastWorkoutQuery = entities.UserStreamSet.Include("UserSettings").OfType <Workout>().Where(w => w.WorkoutTypeKey.HasValue && w.WorkoutTypeKey.Value == (int)workoutType && w.Duration.HasValue && w.Duration.Value > 0);
                if (workoutType == Utils.WorkoutUtil.WorkoutType.RUNNING)
                {
                    // metrics will be 1 mile, 5km and 10km
                    hFastTime1.InnerText = "Fastest 1 mile";
                    double mile = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.MILE_1);
                    workoutQueryFastest1 = fastWorkoutQuery.Where(w => w.Distance >= mile).OrderBy(w => w.Duration);

                    hFastTime2.InnerText = "Fastest 5 km";
                    double km5 = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.KM_5);
                    workoutQueryFastest2 = fastWorkoutQuery.Where(w => w.Distance >= km5).OrderBy(w => w.Duration);
                }
                else if (workoutType == Utils.WorkoutUtil.WorkoutType.ROW)
                {
                    // row metrics will be fastest 500 M and 1 Km
                    hFastTime1.InnerText = "Fastest 500 M";
                    double m500 = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.M_500);
                    workoutQueryFastest1 = fastWorkoutQuery.Where(w => w.Distance >= m500).OrderBy(w => w.Duration);

                    hFastTime2.InnerText = "Fastest 1 km";
                    double km1 = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.KM_1);
                    workoutQueryFastest2 = fastWorkoutQuery.Where(w => w.Distance >= km1).OrderBy(w => w.Duration);
                }
                else if (workoutType == Utils.WorkoutUtil.WorkoutType.CROSSFIT)
                {
                    hFastTime1.InnerText = "Fran";
                    workoutQueryFastest1 = fastWorkoutQuery.Where(w => w.WOD.Standard > 0 && w.WOD.Name == "Fran" && w.RxD.HasValue && w.RxD.Value).OrderBy(w => w.Duration);

                    hFastTime2.InnerText = "Helen";
                    workoutQueryFastest2 = fastWorkoutQuery.Where(w => w.WOD.Standard > 0 && w.WOD.Name == "Helen" && w.RxD.HasValue && w.RxD.Value).OrderBy(w => w.Duration);
                }

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    if (ProfileSettings != null)
                    {
                        liFindFriends.Visible       = false;
                        pageViewFindFriends.Visible = false;
                        atiProfileImg.Settings      = ProfileSettings;
                        atiProfileImg.IsOwner       = base.Permissions == AqufitPermission.OWNER;
                        atiPeoplePanel.Visible      = false;
                        atiPeopleViewer.Visible     = true;
                        peopleTabTitle.Text         = ProfileSettings.UserName + " Achievements";
                        litUserName.Text            = "<a class=\"midBlue\" href=\"" + ResolveUrl("~") + ProfileSettings.UserName + "\">" + ProfileSettings.UserName + "</a> <span> (" + ProfileSettings.UserFirstName + " " + ProfileSettings.UserLastName + ")</span>";
                        atiShareLink.ShareLink      = Request.Url.AbsoluteUri;
                        atiShareLink.ShareTitle     = ProfileSettings.UserName + " Achievements";

                        if (ProfileSettings is Group)
                        {
                            Affine.Utils.ConstsUtil.Relationships memberType = Utils.ConstsUtil.Relationships.NONE;
                            if (UserSettings != null)
                            {
                                UserFriends uf = entities.UserFriends.FirstOrDefault(f => f.SrcUserSettingKey == UserSettings.Id && f.DestUserSettingKey == ProfileSettings.Id);
                                if (uf != null)
                                {
                                    memberType = Utils.ConstsUtil.IntToRelationship(uf.Relationship);
                                }
                            }
                            Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
                            atiWorkoutTotals.Visible = false;
                            nvgCrossfit.Visible      = false;
                            liConfig.Visible         = (memberType == Utils.ConstsUtil.Relationships.GROUP_ADMIN || memberType == Utils.ConstsUtil.Relationships.GROUP_OWNER);
                            if ((memberType == Utils.ConstsUtil.Relationships.GROUP_ADMIN || memberType == Utils.ConstsUtil.Relationships.GROUP_OWNER) && Request["c"] != null)
                            {
                                atiPeopleViewer.Visible      = false;
                                atiLeaderBoardConfig.Visible = true;
                                bool hasCustom = entities.LeaderBoard2WOD.FirstOrDefault(lb => lb.UserSetting.Id == GroupSettings.Id) != null;
                                if (hasCustom)
                                {
                                    Affine.Data.json.LeaderBoardWOD[] all = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id);
                                    System.Web.Script.Serialization.JavaScriptSerializer jsSerial = new System.Web.Script.Serialization.JavaScriptSerializer();
                                    RadAjaxManager1.ResponseScripts.Add("$(function(){ Aqufit.Page." + atiLeaderBoard2Config.ID + ".loadLeaderBoardFromJson('" + jsSerial.Serialize(all) + "'); });");
                                }
                            }
                            else
                            {
                                Affine.Data.json.LeaderBoardWOD[] all = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id);
                                System.Web.Script.Serialization.JavaScriptSerializer jsSerial = new System.Web.Script.Serialization.JavaScriptSerializer();
                                RadAjaxManager1.ResponseScripts.Add("$(function(){ Aqufit.Page." + atiLeaderBoard2.ID + ".loadLeaderBoardFromJson('" + jsSerial.Serialize(all) + "'); });");
                            }
                        }
                        else
                        {
                            atiWorkoutTotals.Cols = 3;
                            // get number of workouts for each workout type
                            WorkoutType[]        wtypes       = entities.WorkoutType.ToArray();
                            IQueryable <Workout> workoutQuery = entities.UserStreamSet.OfType <Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id);
                            foreach (WorkoutType wt in wtypes)
                            {
                                atiWorkoutTotals.Totals.Add(new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                                {
                                    Name  = wt.Name,
                                    Icon  = wt.Icon,
                                    Total = "" + workoutQuery.Where(w => w.WorkoutTypeKey == wt.Id).Count()
                                });
                            }
                            IQueryable <Workout> crossfitWorkouts = entities.UserStreamSet.OfType <Workout>().Include("WOD").Where(w => w.UserSetting.Id == ProfileSettings.Id && w.IsBest == true);
                            int numDistinct = crossfitWorkouts.Select(w => w.WOD).Distinct().Count();
                            IQueryable <Workout> wodsToDisplay = null;
                            wodsToDisplay = crossfitWorkouts.OrderByDescending(w => w.Id);
                            string baseUrl = ResolveUrl("~") + "workout/";
                            // We need to split up into WOD types now...
                            Workout[] timedWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.TIMED).OrderBy(w => w.Duration).ToArray();
                            IList <DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem> cfTotals = timedWods.Select(w => new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                            {
                                Name = w.Title, Total = Affine.Utils.UnitsUtil.durationToTimeString(Convert.ToInt64(w.Duration)), Link = baseUrl + w.WOD.Id
                            }).ToList();
                            // Now all the scored ones...
                            Workout[] scoredWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.SCORE || w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.AMRAP).ToArray();
                            cfTotals = cfTotals.Concat(scoredWods.Select(w => new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                            {
                                Name = w.Title, Total = Convert.ToString(w.Score), Link = baseUrl + w.WOD.Id
                            }).ToList()).ToList();
                            Workout[] maxWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT).ToArray();
                            cfTotals = cfTotals.Concat(maxWods.Select(w => new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                            {
                                Name = w.Title, Total = Affine.Utils.UnitsUtil.systemDefaultToUnits(w.Max.Value, WeightUnits) + " " + Affine.Utils.UnitsUtil.unitToStringName(WeightUnits), Link = baseUrl + w.WOD.Id
                            }).ToList()).ToList();
                            // TODO: we should have workout names link to that workout (a you vs. them kinda deal)
                            nvgCrossfit.Totals = cfTotals.OrderBy(t => t.Name).ToArray();

                            #region Achievments

                            Affine.WebService.StreamService ss = new WebService.StreamService();
                            string js = string.Empty;

                            Affine.Utils.WorkoutUtil.WorkoutType running = Utils.WorkoutUtil.WorkoutType.RUNNING;
                            Achievement[] runningAchievements            = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)running && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in runningAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedRunning.addItem('" + json + "','" + a.AchievementType.Name + "'); ";
                            }
                            Affine.Utils.WorkoutUtil.WorkoutType rowing = Utils.WorkoutUtil.WorkoutType.ROW;
                            Achievement[] rowingAchievements            = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)rowing && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in rowingAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedRowing.addItem('" + json + "','" + a.AchievementType.Name + "'); ";
                            }
                            Affine.Utils.WorkoutUtil.WorkoutType cycling = Utils.WorkoutUtil.WorkoutType.CYCLING;
                            Achievement[] cyclingAchievements            = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)cycling && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in cyclingAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedCycling.addItem('" + json + "','" + a.AchievementType.Name + "'); ";
                            }
                            Affine.Utils.WorkoutUtil.WorkoutType swimming = Utils.WorkoutUtil.WorkoutType.SWIMMING;
                            Achievement[] swimmingAchievements            = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)swimming && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in swimmingAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedSwimming.addItem('" + json + "','" + a.AchievementType.Name + "'); ";
                            }

                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "Achievements", "$(function(){" + js + " });", true);
                            #endregion
                        }
                    }
                    else
                    {
                        peopleTabTitle.Text     = "Athletes";
                        atiPeoplePanel.Visible  = true;
                        atiPeopleViewer.Visible = false;
                        SetupPage();        // do normal page setup
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }