public static IWorkout CovertTPWorkoutToInternal(Workout tpWorkout) { IWorkout internalWorkout; switch (tpWorkout.WorkoutTypeDescription) { case "Swim": { internalWorkout = MapSwimWorkout(tpWorkout); break; } case "Bike": { internalWorkout = MapCycleWorkout(tpWorkout); break; } case "Run": { internalWorkout = MapRunWorkout(tpWorkout); break; } case "Custom": { internalWorkout = MapCustomWorkout(tpWorkout); break; } default: { internalWorkout = new CustomWorkout(); break; } } return internalWorkout; }
public async Task<IHttpActionResult> PutWorkout(int id, Workout workout) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != workout.WorkoutID) { return BadRequest(); } db.Entry(workout).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WorkoutExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
public void UpdateWorkout(Workout workout) { //Todo test this well var workoutToUpdate = _context.Workouts.Find(workout.WorkoutId); if (workoutToUpdate != null) { _context.Entry(workoutToUpdate).CurrentValues.SetValues(workout); } }
public async Task<IHttpActionResult> PostWorkout(Workout workout) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Workouts.Add(workout); await db.SaveChangesAsync(); return CreatedAtRoute("DefaultApi", new { id = workout.WorkoutID }, workout); }
public void TheStrengthActivityIsAddedToTheCurrentWorkout() { var workOut = new Workout(new WorkoutDocument()); var repo = new Mock<IExerciseRepository>(); var ws = new Mock<IWorkoutService>(); var handler = new AddStrengthCommandHandler(ws.Object, repo.Object); var command = new AddStrengthCommand { Weight = 20, ExerciseId = 1, Repetitions= 99, Notes = "foo" }; ws.Setup(x => x.CurrentWorkout()).Returns(workOut); repo.Setup(x => x.Load(1)).Returns(new Exercise(new ExerciseDocument { Description = "exer" })); handler.Handle(command); workOut.StrengthSegments.Count().ShouldEqual(1); }
public static IWorkout MapCycleWorkout(Workout tpWorkout) { ICycleWorkout cycleWorkout = new CycleWorkout(); cycleWorkout.TPWorkoutID = tpWorkout.WorkoutId; cycleWorkout.CadenceAverage = tpWorkout.CadenceAverage; cycleWorkout.CadenceMaximum = tpWorkout.CadenceMaximum; cycleWorkout.PowerAverage = tpWorkout.PowerAverage; cycleWorkout.PowerMaximum = tpWorkout.PowerMaximum; cycleWorkout.StartDate = tpWorkout.WorkoutDay; cycleWorkout.StartTime = tpWorkout.StartTime; if (tpWorkout.TimeTotalInSeconds.HasValue) cycleWorkout.Duration = new TimeSpan(0, 0, (int) tpWorkout.TimeTotalInSeconds); cycleWorkout.DistanceInMeters = tpWorkout.DistanceInMeters; cycleWorkout.VelocityAverage = tpWorkout.VelocityAverage; cycleWorkout.VelocityMaximum = tpWorkout.VelocityMaximum; cycleWorkout.HeartRateAverage = tpWorkout.HeartRateAverage; cycleWorkout.HeartRateMaximum = tpWorkout.HeartRateMaximum; cycleWorkout.HeartRateMinimum = tpWorkout.HeartRateMinimum; //cycleWorkout.TrainingStressScore = tpWorkout. return cycleWorkout; }
public void Update(Workout workout) { workoutRepository.Delete(workout.Id); workoutRepository.Create(workout); }
private WorkoutDTO MapWorkout(Workout model) { var modelDTO = new WorkoutDTO { Id = model.Id, WorkoutDate = model.WorkoutDate, Exercises = new List<Exercise>(model.Exercises), ApplicationUser = model.ApplicationUser }; return modelDTO; }
/* 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); } }
public static IWorkout MapSwimWorkout(Workout tpWorkout) { ISwimWorkout swimWorkout = new SwimWorkout(); swimWorkout.TPWorkoutID = tpWorkout.WorkoutId; swimWorkout.StartDate = tpWorkout.WorkoutDay; swimWorkout.StartTime = tpWorkout.StartTime; if (tpWorkout.TimeTotalInSeconds.HasValue) swimWorkout.Duration = new TimeSpan(0, 0, (int)tpWorkout.TimeTotalInSeconds); swimWorkout.DistanceInMeters = tpWorkout.DistanceInMeters; return swimWorkout; }
private void DeleteWorkout(Workout workout) { _gasContext.Workouts.Remove(workout); _gasContext.SaveChanges(); }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // CA - this will need to be cleaned up a lot.. but here is the iteration one version // ** People can view workouts in 4 modes (everyone, watchlist, friends, just them) // -In the case of running, cycling, swimming, and STANDARD crossfit Wods... we are going to // be storing peoples best times for (distance rnages) and standard wods... so in these cases // we can shorted the query time when we do an "everyone" query // -Watch list and friends we do the work of getting every time that person did the workout.. not just // there best times. // -Same for the (you only) view // private void LoadFlexDataForWorkout(Workout workout, Affine.Utils.ConstsUtil.GraphContext context) { Affine.Data.Managers.IDataManager dataManager = Affine.Data.Managers.LINQ.DataManager.Instance; JavaScriptSerializer serializer = new JavaScriptSerializer(); // onload we send friend, watch, and group member data that is needed to the app aqufitEntities entities = new aqufitEntities(); IList<long> friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == ProfileSettings.Id || f.DestUserSettingKey == ProfileSettings.Id)).Select(f => (f.SrcUserSettingKey == ProfileSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToList(); friendIds.Add(ProfileSettings.Id); // send the persons profile through var profile = new { UserName = ProfileSettings.UserName, Id = ProfileSettings.Id, FirstName = ProfileSettings.UserFirstName, LastName= ProfileSettings.UserLastName }; hiddenProfileJson.Value = serializer.Serialize(profile); var friends = entities.UserSettings.OfType<User>().Where(LinqUtils.BuildContainsExpression<User, long>(s => s.Id, friendIds)).Select(u => new { Id = u.Id, Un = u.UserName, Fn = u.UserFirstName, Ln = u.UserLastName }).ToArray(); hiddenFriendJson.Value = serializer.Serialize(friends); // get groups long[] groupIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == ProfileSettings.Id || f.DestUserSettingKey == ProfileSettings.Id) && f.Relationship > 0).Select(f => f.SrcUserSettingKey == ProfileSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey).ToArray(); UserSettings[] groupList = entities.UserSettings.OfType<Group>().Where(LinqUtils.BuildContainsExpression<UserSettings, long>(us => us.Id, groupIds)).OrderBy(f => f.UserName).ToArray(); var groups = entities.UserSettings.OfType<Group>().Where(LinqUtils.BuildContainsExpression<Group, long>(s => s.Id, groupIds)).Select(u => new { Id = u.Id, Un = u.UserName }).ToArray(); hiddenGroupJson.Value = serializer.Serialize(groups); // next we load the workout compare to all (friends) Affine.WebService.StreamService ss = new WebService.StreamService(); //hiddenWorkout.Value = ss.getWorkout(workout.Id); Affine.Data.json.Workout jsonWorkout = dataManager.workoutToJsonWorkout(workout); Affine.Data.json.WOD wod = null; Affine.Data.json.WorkoutData[] jsonWorkoutData = null; //var workoutJson = new { Id = workout.Id, WorkoutTypeKey = workout.WorkoutTypeKey, Title = workout.Title, Date = workout.Date.ToLocalTime().ToShortDateString(), DataSrc = workout.DataSrc }; Affine.Utils.UnitsUtil.MeasureUnit weight = base.WeightUnits; if (workout.WorkoutTypeKey == (int)Affine.Utils.WorkoutUtil.WorkoutType.CROSSFIT) { if (context == Utils.ConstsUtil.GraphContext.DEFAULT) { // default context for crossfit is the watchlist context = Utils.ConstsUtil.GraphContext.WATCHLIST; } // if this is a crossfit workout // we want to get ALL the same WoDs for you and your friends IQueryable<Workout> workoutDataQuery = context == Utils.ConstsUtil.GraphContext.EVERYONE ? entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id).AsQueryable() : context == Utils.ConstsUtil.GraphContext.WATCHLIST ? entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression<Workout, long>(w => w.UserSetting.Id, friendIds)).AsQueryable() : context == Utils.ConstsUtil.GraphContext.FRIENDS ? entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression<Workout, long>(w => w.UserSetting.Id, friendIds)).AsQueryable() : entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id && w.UserSetting.Id == ProfileSettings.Id ).AsQueryable(); var workoutData = workoutDataQuery.Select(w => new { Id = w.Id, UsKey = w.UserSetting.Id, Un = w.UserSetting.UserName, T = w.Duration, S = w.Score, M = w.Max, Rx = w.RxD, D = w.Date }).ToArray(); wod = new Affine.Data.json.WOD (){ Id = workout.WOD.Id, Standard = workout.WOD.Standard, Type = workout.WOD.WODType.Id, Name = workout.WOD.Name, Description = workout.WOD.Description }; if (wod.Type == (int)Affine.Utils.WorkoutUtil.WodType.TIMED) { // time in sec jsonWorkoutData = workoutData.OrderByDescending(w => w.T).Select(w => new Affine.Data.json.WorkoutData() { UId = w.Un + "_" + w.Id, Id = w.Id, S = (double)w.T, Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false) }).ToArray(); } else if (wod.Type == (int)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT) { jsonWorkoutData = workoutData.OrderByDescending(w => w.M).Select(w => new Affine.Data.json.WorkoutData() { UId = w.Un + "_" + w.Id, Id = w.Id, S = Math.Round(Affine.Utils.UnitsUtil.systemDefaultToUnits(Convert.ToDouble(w.M), weight), 2), Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false) }).ToArray(); } else { jsonWorkoutData = workoutData.OrderByDescending(w => w.S).Select(w => new Affine.Data.json.WorkoutData() { UId = w.Un + "_" + w.Id , Id = w.Id, S = Math.Round(Convert.ToDouble(w.S), 2), Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false) }).ToArray(); } } else { // for now this will handle "running, swimming, walking, cycling" if (context == Utils.ConstsUtil.GraphContext.DEFAULT) { if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_NO_MAP || workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_WITH_MAP) { context = Utils.ConstsUtil.GraphContext.EVERYONE; } else if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.NIKE_NO_MAP) { context = Utils.ConstsUtil.GraphContext.WATCHLIST; } // TODO: not sure about this one.... /* else if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_WITH_MAP) { // TODO: ?? this is a special case that we want to compare all the times of people that have logged a run for the route. long mapRouteKey = entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id).Select(w => w.WorkoutExtendeds.FirstOrDefault().MapRoute.Id).FirstOrDefault(); IQueryable<Workout> workoutQuery = entities.WorkoutExtendeds.Include("UserStream").Where(we => we.MapRoute != null && we.MapRoute.Id == mapRouteKey).Select(we => we.UserStream).OfType<Workout>().OrderBy(w => w.Duration).Take(5000); workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here. Workout[] data = workoutQuery.ToArray(); var wd = data.OrderByDescending(w => w.Duration).Select(w => new { UId = w.UserSetting.UserName + "_" + w.Id, Id = w.Id, S = w.Duration, Un = w.UserSetting.UserName, D = w.Date.ToLocalTime().ToShortDateString() }).ToArray(); var ret = new { WOD = new { }, WorkoutData = wd, Workout = workoutJson, Context = (int)context }; hiddenWorkoutData.Value = serializer.Serialize(ret); }*/ else { context = Utils.ConstsUtil.GraphContext.ME; } } if (context == Utils.ConstsUtil.GraphContext.EVERYONE) { // we want to compare achievments... IQueryable<Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a => a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey && workout.Distance >= a.AchievementType.DistanceRangeA && workout.Distance < a.AchievementType.DistanceRangeB).Take(5000).Select(a => a.UserStream).OfType<Workout>().AsQueryable(); workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id)); workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here. Workout[] data = workoutQuery.ToArray(); jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData() { UId = w.UserSetting.UserName + "_" + w.Id, Id = w.Id, S = w.Duration.Value, Un = w.UserSetting.UserName, D = w.Date.ToLocalTime().ToShortDateString() }).ToArray(); } else if (context == Utils.ConstsUtil.GraphContext.WATCHLIST || context == Utils.ConstsUtil.GraphContext.FRIENDS) { IQueryable<Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a => a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey && workout.Distance >= a.AchievementType.DistanceRangeA && workout.Distance < a.AchievementType.DistanceRangeB). Where(LinqUtils.BuildContainsExpression<Achievement, long>(a => a.UserSetting.Id, friendIds)).Take(5000).Select(a => a.UserStream).OfType<Workout>().AsQueryable(); workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id)); workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here. Workout[] data = workoutQuery.ToArray(); jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData() { UId = w.UserSetting.UserName + "_" + w.Id, Id = w.Id, S = w.Duration.Value, Un = w.UserSetting.UserName, D = w.Date.ToLocalTime().ToShortDateString() }).ToArray(); } else if (context == Utils.ConstsUtil.GraphContext.ME) // this is just you for the ranges.. since no map data { IQueryable<Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a => a.UserSetting.Id == ProfileSettings.Id && a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey && workout.Distance >= a.AchievementType.DistanceRangeA && workout.Distance < a.AchievementType.DistanceRangeB). Take(5000).Select(a => a.UserStream).OfType<Workout>().AsQueryable(); workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id)); workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here. Workout[] data = workoutQuery.ToArray(); jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData() { UId = w.UserSetting.UserName + "_" + w.Id, Id = w.Id, S = w.Duration.Value, Un = w.UserSetting.UserName, D = w.Date.ToLocalTime().ToShortDateString() }).ToArray(); } } var retWorkout = new { WOD = wod, WorkoutData = jsonWorkoutData, Workout = jsonWorkout, Context = (int)context }; hiddenWorkoutData.Value = serializer.Serialize(retWorkout); }
public void Initialize() { _model = new Workout(); _mapper = new MapperService.Implementations.WorkoutMapper(); }
protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request["w"])) { aqufitEntities entities = new aqufitEntities(); long wid = Convert.ToInt64(Request["w"]); // TODO: need security Workout workout = entities.UserStreamSet.Include("WorkoutExtendeds").Include("UserSetting").OfType <Workout>().FirstOrDefault(w => w.Id == wid); if (workout != null) { Affine.Data.json.Workout json = new Affine.Data.json.Workout() { Calories = workout.Calories, Date = workout.Date.ToShortDateString(), Description = workout.Description, Distance = workout.Distance, Duration = workout.Duration, Emotion = workout.Emotion, Id = workout.Id, Title = workout.Title, PortalKey = workout.PortalKey, UserKey = workout.UserSetting.UserKey, Weather = workout.Weather, }; if (workout.WorkoutExtendeds.FirstOrDefault() != null) { WorkoutExtended ext = workout.WorkoutExtendeds.First(); Affine.Data.json.WorkoutExtended jsonWorkoutExtended = new Affine.Data.json.WorkoutExtended() { Id = ext.Id, LatMax = ext.LatMax, LatMin = ext.LatMin, LngMax = ext.LngMax, LngMin = ext.LngMin }; Affine.Data.json.WorkoutSample[] samples = entities.WorkoutSamples.Where(s => s.WorkoutExtended.Id == ext.Id).OrderBy(s => s.SampleNumber) .Select(s => new Affine.Data.json.WorkoutSample() { Date = s.Date, Time = 0, Distance = s.Distance, Elevation = s.Elevation, HeartRate = s.HeartRate, Id = s.Id, Lat = s.Lat, Lng = s.Lng, SampleNumber = s.SampleNumber }).ToArray(); foreach (Affine.Data.json.WorkoutSample s in samples) { s.Time = s.Date.Ticks; } jsonWorkoutExtended.WorkoutSamples = samples; json.WorkoutExtended = jsonWorkoutExtended; } JavaScriptSerializer jserializer = new JavaScriptSerializer(); Response.Write(jserializer.Serialize(json)); } } else if (Request["ed"] != null && Request["u"] != null && Request["sd"] != null) { long uid = Convert.ToInt64(Request["u"]); DateTime endDate = DateTime.Parse(Request["ed"]); DateTime startDate = DateTime.Parse(Request["sd"]).ToUniversalTime(); endDate = endDate.AddDays(1).ToUniversalTime(); aqufitEntities entities = new aqufitEntities(); IList <Affine.Data.json.Workout> ret = new List <Affine.Data.json.Workout>(); IList <Workout> workoutList = entities.UserStreamSet.Include("UserSetting").OfType <Workout>(). Where(w => w.UserSetting.UserKey == uid && w.Date.CompareTo(endDate) <= 0 && w.Date.CompareTo(startDate) >= 0).OrderByDescending(w => w.Date).ToList(); workoutList = workoutList.Reverse().ToList(); foreach (Workout workout in workoutList) { Affine.Data.json.Workout json = new Affine.Data.json.Workout() { Calories = workout.Calories, TimeStamp = workout.TimeStamp, Date = workout.Date.ToShortDateString(), Description = workout.Description, Distance = workout.Distance, Duration = workout.Duration, Emotion = workout.Emotion, Id = workout.Id, Title = workout.Title, PortalKey = workout.PortalKey, UserKey = workout.UserSetting.UserKey, Weather = workout.Weather, DataSrc = workout.DataSrc }; ret.Add(json); } // TODO: need a case for empty data JavaScriptSerializer jserializer = new JavaScriptSerializer(); Response.Write(jserializer.Serialize(ret.ToArray())); } else { Response.Write("{ERROR:'invalid request'}"); } }
public static string GetUniqueTitle(Workout workout) { return($"{workout.Id}_{GetTitle(workout)}"); }
private void InsertExampleLoggedEntries() { if (conn.Table <Log_Set_Entry>().Count() == 0) { Log_Set_Entry log_set = new Log_Set_Entry(); log_set.Date = DateTime.Today; log_set.Reps = 8; log_set.Min_reps = 6; log_set.Max_reps = 10; log_set.Weight = 50; log_set.ExerciseId = 1; conn.Insert(log_set); log_set = new Log_Set_Entry(); log_set.Date = DateTime.Today; log_set.Reps = 8; log_set.Min_reps = 6; log_set.Max_reps = 10; log_set.Weight = 50; log_set.ExerciseId = 1; conn.Insert(log_set); log_set = new Log_Set_Entry(); log_set.Date = DateTime.Today; log_set.Reps = 8; log_set.Min_reps = 6; log_set.Max_reps = 10; log_set.Weight = 50; log_set.ExerciseId = 1; conn.Insert(log_set); log_set = new Log_Set_Entry(); log_set.Date = DateTime.Today; log_set.Reps = 7; log_set.Min_reps = 6; log_set.Max_reps = 10; log_set.Weight = 60; log_set.ExerciseId = 2; conn.Insert(log_set); } if (conn.Table <Log_Cardio_Set_Entry>().Count() == 0) { Log_Cardio_Set_Entry log_set = new Log_Cardio_Set_Entry(); log_set.Date = DateTime.Today; log_set.Type = "m"; log_set.Distance = 100; log_set.Minutes = 10; log_set.Seconds = 50; log_set.ExerciseId = 2; conn.Insert(log_set); log_set = new Log_Cardio_Set_Entry(); log_set.Date = DateTime.Today.AddDays(5); log_set.Type = "km"; log_set.Distance = 2; log_set.Hours = 1; log_set.Minutes = 0; log_set.Seconds = 50; log_set.ExerciseId = 2; conn.Insert(log_set); } if (conn.Table <Workout>().Count() == 0) { Workout work = new Workout(); work.Name = "monday"; work.RoutinesId = 1; conn.Insert(work); Workout_Exercise exer = new Workout_Exercise(); exer.WorkoutId = work.Id; exer.ExerciseId = 1; conn.Insert(exer); exer = new Workout_Exercise(); exer.WorkoutId = work.Id; exer.ExerciseId = 2; conn.Insert(exer); Target_Set targ_set = new Target_Set(); targ_set.Workout_ExerciseId = 1; targ_set.Min_reps = 5; targ_set.Max_reps = 5; conn.Insert(targ_set); targ_set = new Target_Set(); targ_set.Workout_ExerciseId = 1; targ_set.Min_reps = 5; targ_set.Max_reps = 5; conn.Insert(targ_set); targ_set = new Target_Set(); targ_set.Workout_ExerciseId = 1; targ_set.Min_reps = 5; targ_set.Max_reps = 5; conn.Insert(targ_set); targ_set = new Target_Set(); targ_set.Workout_ExerciseId = 1; targ_set.Min_reps = 5; targ_set.Max_reps = 5; conn.Insert(targ_set); targ_set = new Target_Set(); targ_set.Workout_ExerciseId = 2; targ_set.Min_reps = 5; targ_set.Max_reps = 5; conn.Insert(targ_set); targ_set = new Target_Set(); targ_set.Workout_ExerciseId = 2; targ_set.Min_reps = 5; targ_set.Max_reps = 5; conn.Insert(targ_set); Workout_Exercise_Trainingmax exer_max = new Workout_Exercise_Trainingmax(); exer_max.Workouts_ExercisesId = exer.Id; exer_max.TrainingMax = 80; conn.Insert(exer_max); Target_Set_Trainingmax set = new Target_Set_Trainingmax(); set.Min_reps = 8; set.Max_reps = 8; set.Percent = 60; set.Round = 0; conn.Insert(set); Target_Set_Trainingmax set2 = new Target_Set_Trainingmax(); set2.Min_reps = 3; set2.Max_reps = 3; set2.Percent = 90; set2.Round = 0; conn.Insert(set2); Log_Set_Entry log = new Log_Set_Entry(); log.Date = DateTime.Today.AddDays(-5); log.Reps = set.Min_reps; log.Weight = exer_max.TrainingMax * (set.Percent / 100); conn.Insert(log); log = new Log_Set_Entry(); log.Date = DateTime.Today.AddDays(-5); log.Reps = set2.Min_reps; log.Weight = exer_max.TrainingMax * (set2.Percent / 100); conn.Insert(log); } }
private async void LoadTableContentAsync(List <WorkoutCategoryDetailDTO> wcList, List <ActivityLevelDetailDTO> alList) { this.Parent.Parent.Parent.Parent.Enabled = false; List <Task> tasks = new List <Task>(); Dictionary <String, List <string> > keywords = new Dictionary <String, List <string> >(); foreach (var item in wBll.GetWorkoutByWCAL(-1, -1)) { string kw = wBll.ToPlacesKeyword(item.Name); if (kw == null) { kw = ""; } if (keywords.ContainsKey(kw)) { keywords[kw].Add(item.Name); } else { keywords.Add(kw, new List <string> { item.Name }); Task <PlacesNearbySearchResponse> task = wBll.GetWorkoutPlaces(kw, coord); tasks.Add(task); } } while (tasks.Count > 0) { Task finishedTask = await Task.WhenAny(tasks); int index = tasks.IndexOf(finishedTask); List <String> places = keywords.ElementAt(index).Value; Task <PlacesNearbySearchResponse> task = finishedTask as Task <PlacesNearbySearchResponse>; PlacesNearbySearchResponse response = task.Result; if (response.Results.Count() > 0) { for (int k = 0; k < places.Count; k++) { Workout w = wBll.GetWorkout(places[k]); Label lbl = new Label(); lbl.Text = places[k]; lbl.Font = new Font(lbl.Font.Name, 12f); lbl.Height = (int)(lbl.Font.Size * 2.5); lbl.Margin = new Padding(2); lbl.Paint += FrmAddWorkoutPreferences.LblWorkout_Paint; lbl.Click += lblWorkout_Click; int yIndex = wcList.IndexOf(wcList.SingleOrDefault(wc => wc.ID == w.WorkoutCategoryID)); int xIndex = alList.IndexOf(alList.SingleOrDefault(al => al.ID == w.ActivityLevelID)); panelList[yIndex][xIndex].Controls.Add(lbl); } } keywords.Remove(keywords.ElementAt(index).Key); tasks.Remove(finishedTask); } MessageBox.Show("load success"); this.Parent.Parent.Parent.Parent.Enabled = true; }
protected override XElement Convert(Workout workout, WorkoutSamples samples) { XNamespace ns1 = "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"; XNamespace activityExtensions = "http://www.garmin.com/xmlschemas/ActivityExtension/v2"; XNamespace trackPointExtensions = "http://www.garmin.com/xmlschemas/TrackPointExtension/v2"; XNamespace profileExtension = "http://www.garmin.com/xmlschemas/ProfileExtension/v1"; var sport = GetSport(workout); var subSport = GetSubSport(workout); var startTime = GetStartTimeUtc(workout); var outputSummary = GetOutputSummary(samples); var hrSummary = GetHeartRateSummary(samples); var cadenceSummary = GetCadenceSummary(samples); var resistanceSummary = GetResistanceSummary(samples); var lx = new XElement(activityExtensions + "TPX"); lx.Add(new XElement(activityExtensions + "TotalPower", workout?.Total_Work)); lx.Add(new XElement(activityExtensions + "MaximumCadence", cadenceSummary?.Max_Value)); lx.Add(new XElement(activityExtensions + "AverageCadence", cadenceSummary?.Average_Value)); lx.Add(new XElement(activityExtensions + "AverageWatts", outputSummary?.Average_Value)); lx.Add(new XElement(activityExtensions + "MaximumWatts", outputSummary?.Max_Value)); lx.Add(new XElement(activityExtensions + "AverageResistance", resistanceSummary?.Average_Value)); lx.Add(new XElement(activityExtensions + "MaximumResistance", resistanceSummary?.Max_Value)); var extensions = new XElement("Extensions"); extensions.Add(lx); var track = new XElement("Track"); var allMetrics = samples.Metrics; var hrMetrics = allMetrics.FirstOrDefault(m => m.Slug == "heart_rate"); var outputMetrics = allMetrics.FirstOrDefault(m => m.Slug == "output"); var cadenceMetrics = allMetrics.FirstOrDefault(m => m.Slug == "cadence"); var speedMetrics = GetSpeedSummary(samples); var resistanceMetrics = allMetrics.FirstOrDefault(m => m.Slug == "resistance"); var locationMetrics = samples.Location_Data?.SelectMany(x => x.Coordinates).ToArray(); var altitudeMetrics = allMetrics.FirstOrDefault(m => m.Slug == "altitude"); for (var i = 0; i < samples.Seconds_Since_Pedaling_Start.Count; i++) { var trackPoint = new XElement("TrackPoint"); if (locationMetrics is object && i < locationMetrics.Length) { var trackPosition = new XElement("Position"); trackPosition.Add(new XElement("LatitudeDegrees", locationMetrics[i].Latitude)); trackPosition.Add(new XElement("LongitudeDegrees", locationMetrics[i].Longitude)); if (altitudeMetrics is object && i < altitudeMetrics.Values.Length) { trackPosition.Add(new XElement("AltitudeMeters", ConvertDistanceToMeters(altitudeMetrics.GetValue(i), altitudeMetrics.Display_Unit))); } trackPoint.Add(trackPosition); } if (hrMetrics is object && i < hrMetrics.Values.Length) { var hr = new XElement("HeartRateBpm"); hr.Add(new XElement("Value", hrMetrics.Values[i])); trackPoint.Add(hr); } if (cadenceMetrics is object && i < cadenceMetrics.Values.Length) { trackPoint.Add(new XElement("Cadence", cadenceMetrics.Values[i])); } var tpx = new XElement(activityExtensions + "TPX"); if (speedMetrics is object && i < speedMetrics.Values.Length) { tpx.Add(new XElement(activityExtensions + "Speed", ConvertToMetersPerSecond(speedMetrics.GetValue(i), samples))); } if (outputMetrics is object && i < outputMetrics.Values.Length) { tpx.Add(new XElement(activityExtensions + "Watts", outputMetrics.Values[i])); } if (resistanceMetrics is object && i < resistanceMetrics.Values.Length) { tpx.Add(new XElement(activityExtensions + "Resistance", resistanceMetrics.Values[i])); } var trackPointExtension = new XElement("Extensions"); trackPointExtension.Add(tpx); trackPoint.Add(trackPointExtension); trackPoint.Add(new XElement("Time", GetTimeStamp(startTime, i))); track.Add(trackPoint); } var lap = new XElement("Lap"); lap.SetAttributeValue("StartTime", GetTimeStamp(startTime)); lap.Add(new XElement("TotalTimeSeconds", workout.Ride.Duration)); lap.Add(new XElement("Intensity", "Active")); lap.Add(new XElement("Triggermethod", "Manual")); lap.Add(new XElement("DistanceMeters", GetTotalDistance(samples))); lap.Add(new XElement("MaximumSpeed", GetMaxSpeedMetersPerSecond(samples))); lap.Add(new XElement("Calories", GetCalorieSummary(samples)?.Value)); lap.Add(new XElement("AverageHeartRateBpm", new XElement("Value", hrSummary?.Average_Value))); lap.Add(new XElement("MaximumHeartRateBpm", new XElement("Value", hrSummary?.Max_Value))); lap.Add(lx); lap.Add(track); var activity = new XElement("Activity"); activity.SetAttributeValue("Sport", sport); activity.Add(new XElement("Id", GetTimeStamp(startTime))); activity.Add(lap); var activities = new XElement("Activities"); activities.Add(activity); var root = new XElement("TrainingCenterDatabase", //new XAttribute("xsi:" + "schemaLocation", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd"), new XAttribute(XNamespace.Xmlns + nameof(ns1), ns1.NamespaceName), new XAttribute(XNamespace.Xmlns + nameof(activityExtensions), activityExtensions.NamespaceName), new XAttribute(XNamespace.Xmlns + nameof(trackPointExtensions), trackPointExtensions.NamespaceName), new XAttribute(XNamespace.Xmlns + nameof(profileExtension), profileExtension.NamespaceName)); root.Add(activities); return(root); }
public void AddWorkoutToHistory(Workout workout, string duration, string date, int caloriesBurned, IWorkoutRepository workoutRepository, List <int> reps, List <int> weights) { workoutRepository.AddWorkoutToHistory(workout, duration, date, caloriesBurned, reps, weights); }
private void InsertWorkout(Workout workout) { _gasContext.Workouts.Add(workout); _gasContext.SaveChanges(); }
public void StartWorkout(IStartWorkoutView form, Workout workout, IWorkoutRepository workoutRepository, IMainController mainController) { form.ShowWorkoutSession(mainController, workout); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here try { SetContentView(Resource.Layout.WorkoutSelecterLayout); ActionBar.Hide(); //Create Database db = new Database(); db.createDatabaseInfo(); db.createDatabaseWorkout(); //Load Data LoadData(); var create = FindViewById <Button>(Resource.Id.create); var PPLPPL = FindViewById <Button>(Resource.Id.PPLPPL); create.Click += async delegate { try { var intent = new Intent(this, typeof(WorkoutCreator)); this.StartActivity(intent); } catch (Exception e) { System.Exception myException = e; Toast error = Toast.MakeText(this, e.Message, ToastLength.Short); error.Show(); } }; PPLPPL.Click += async delegate { try { Info info = new Info() { Id = listSource[0].Id, Name = listSource[0].Name, Sex = listSource[0].Sex, Weight = listSource[0].Weight, Username = listSource[0].Name, Password = listSource[0].Password, Bench = "0", Squat = "0", Dead = "0", Ohp = "0", BenchActual = "0", SquatActual = "0", DeadActual = "0", OhpActual = "0", Unit = "", Month = "", x = "", Lower = "", Upper = "", Week = "", Workout = "PPLPPL", Days = 5 }; db.updateTableInfo(info); try { var test = listSourceWorkout[0].Day; Toast toast = Toast.MakeText(this, "before " + listSourceWorkout[0].Id + " " + test, ToastLength.Short); toast.Show(); Workout workout = new Workout() { Id = listSourceWorkout[0].Id, Day = "Push" }; db.updateTableWorkout(workout); LoadData(); Toast toast2 = Toast.MakeText(this, "after " + listSourceWorkout[0].Id + " " + listSourceWorkout[0].Day, ToastLength.Short); toast2.Show(); } catch { Workout workout = new Workout() { Id = 0, Day = "Push" }; db.insertIntoTableWorkout(workout); } try { var test = listSourceWorkout[1].Day; Workout workout2 = new Workout() { Id = listSourceWorkout[1].Id, Day = "Pull" }; db.updateTableWorkout(workout2); } catch { Workout workout2 = new Workout() { Id = 1, Day = "Pull" }; db.insertIntoTableWorkout(workout2); } try { var test = listSourceWorkout[2].Day; Workout workout3 = new Workout() { Id = listSourceWorkout[2].Id, Day = "Push2" }; db.updateTableWorkout(workout3); } catch { Workout workout3 = new Workout() { Id = 2, Day = "Push2" }; db.insertIntoTableWorkout(workout3); } try { var test = listSourceWorkout[3].Day; Workout workout4 = new Workout() { Id = listSourceWorkout[3].Id, Day = "Pull2" }; db.updateTableWorkout(workout4); } catch { Workout workout4 = new Workout() { Id = 3, Day = "Pull2" }; db.insertIntoTableWorkout(workout4); } try { var test = listSourceWorkout[4].Day; Workout workout5 = new Workout() { Id = listSourceWorkout[4].Id, Day = "Legs" }; db.updateTableWorkout(workout5); } catch { Workout workout5 = new Workout() { Id = 4, Day = "Legs" }; db.insertIntoTableWorkout(workout5); } LoadData(); Toast resp = Toast.MakeText(this, "Workout " + listSource[0].Workout + " Saved", ToastLength.Short); resp.Show(); var intent = new Intent(this, typeof(ProgramHome)); this.StartActivity(intent); } catch (Exception e) { System.Exception myException = e; Toast error = Toast.MakeText(this, e.Message, ToastLength.Short); error.Show(); } }; } catch (Exception e) { System.Exception myException = e; Toast error = Toast.MakeText(this, e.Message, ToastLength.Short); error.Show(); } }
private string GetFlexEmbed(Workout workout) { string ret = "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" id=\"ATI_Aqufit\" width=\"100%\" height=\"100%\" codebase=\"http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab\">"; ret += "<param name=\"movie\" value=\"" + ResolveUrl("~/DesktopModules/ATI_Base/resources/flex/Scratch.swf") + "\" />"; ret += "<param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#FFFFFF\" />"; ret += "<param name=\"flashvars\" value=\"u=" + ProfileSettings.UserKey + "&w="+workout.Id + "&url=http://flexfwd.com/\" />"; ret += "<param name=\"allowScriptAccess\" value=\"sameDomain\" />"; ret += "<param name=\"wmode\" VALUE=\"transparent\">"; ret += "<embed src=\"" + ResolveUrl("~/DesktopModules/ATI_Base/resources/flex/Scratch.swf") + "\" wmode=\"transparent\" quality=\"high\" bgcolor=\"#FFFFFF\" width=\"100%\" height=\"100%\" name=\"ATI_Aqufit\" align=\"middle\" play=\"true\" loop=\"false\" quality=\"high\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\""; ret += " flashvars=\"u=" + ProfileSettings.UserKey + "&w=" + workout.Id + "&url=http://flexfwd.com/\""; ret += " pluginspage=\"http://www.adobe.com/go/getflashplayer\"></embed></object>"; return ret; }
public void CreateWorkout([FromForm] Workout model) { _db.Workout.CreateWorkout(model); _db.Save(); }
public static IWorkout MapRunWorkout(Workout tpWorkout) { IRunWorkout runWorkout = new RunWorkout(); runWorkout.CadenceAverage = tpWorkout.CadenceAverage; runWorkout.CadenceMaximum = tpWorkout.CadenceMaximum; runWorkout.PowerAverage = tpWorkout.PowerAverage; runWorkout.PowerMaximum = tpWorkout.PowerMaximum; runWorkout.StartDate = tpWorkout.WorkoutDay; runWorkout.StartTime = tpWorkout.StartTime; if (tpWorkout.TimeTotalInSeconds.HasValue) runWorkout.Duration = new TimeSpan(0, 0, (int)tpWorkout.TimeTotalInSeconds); runWorkout.DistanceInMeters = tpWorkout.DistanceInMeters; runWorkout.VelocityAverage = tpWorkout.VelocityAverage; runWorkout.VelocityMaximum = tpWorkout.VelocityMaximum; runWorkout.HeartRateAverage = tpWorkout.HeartRateAverage; runWorkout.HeartRateMaximum = tpWorkout.HeartRateMaximum; runWorkout.HeartRateMinimum = tpWorkout.HeartRateMinimum; runWorkout.TPWorkoutID = tpWorkout.WorkoutId; return runWorkout; }
public IActionResult UpdateWorkout(int id, [FromBody] Workout model) { _db.Workout.UpdateWorkout(id, model); _db.Save(); return(Ok()); }
public async Task <Workout> Update(long id, int uId, Workout model) { if (model.Exercises.Count() < 1) { throw new Exception("Workout must include at least 1 exercise."); } if (model.Exercises == null) { throw new Exception("Exercises cannot be null."); } StringBuilder response = new StringBuilder(); if (string.IsNullOrWhiteSpace(model.Name)) { response.Append("Workout: Name cannot be null or empty."); } Workout workoutEntity = await _context.Workouts.Include(x => x.Exercises).SingleOrDefaultAsync(x => x.UserId == uId && x.WorkoutId == id); if (workoutEntity == null) { throw new Exception("Workout could not be found."); } workoutEntity.Name = model.Name; workoutEntity.Notes = model.Notes; List <Exercise> remove = new List <Exercise>(); foreach (Exercise exerciseEntity in workoutEntity.Exercises) { var exerciseMatch = model.Exercises.SingleOrDefault(x => x.ExerciseId == exerciseEntity.ExerciseId); if (exerciseMatch == null) { _context.Exercises.Remove(exerciseEntity); } else { exerciseEntity.Reps = exerciseMatch.Reps; exerciseEntity.Sets = exerciseMatch.Sets; exerciseEntity.UserId = exerciseMatch.UserId; exerciseEntity.ExerciseId = exerciseMatch.ExerciseId; exerciseEntity.Weight = exerciseMatch.Weight; _context.Exercises.Update(exerciseEntity); } } for (int i = 0; i < model.Exercises.Count(); i++) { Exercise exercise = model.Exercises[i]; StringBuilder exerciseSb = new StringBuilder(); string exerciseString = $"Exercise {i}: "; if (exercise.Reps < 0 || exercise.Reps > 255) { exerciseSb.Append($"Reps must be between 0 and 255. "); } if (exercise.Sets < 0 || exercise.Sets > 255) { exerciseSb.Append("Sets must be between 0 and 255. "); } if (exercise.Weight < 0 || exercise.Weight > 32767) { exerciseSb.Append("Weight must be between 0 and 32767. "); } if (exerciseSb.Length > 0) { throw new Exception(exerciseSb.Insert(0, exerciseString).ToString()); } exercise.WorkoutId = workoutEntity.WorkoutId; exercise.UserId = uId; if (exercise.ExerciseId == 0) { await _context.Exercises.AddAsync(exercise); } } await _context.SaveChangesAsync(); return(workoutEntity); }
public Task <int> SaveItemAsync(Workout item) { return(database.InsertOrReplaceAsync(item)); }
public static IWorkout MapCustomWorkout(Workout tpWorkout) { ICustomWorkout customWorkout = new CustomWorkout(); customWorkout.TPWorkoutID = tpWorkout.WorkoutId; customWorkout.StartDate = tpWorkout.WorkoutDay; customWorkout.StartTime = tpWorkout.StartTime; if (tpWorkout.TimeTotalInSeconds.HasValue) customWorkout.Duration = new TimeSpan(0, 0, (int)tpWorkout.TimeTotalInSeconds); return customWorkout; }
public Task <int> DeleteItemAsync(Workout item) { return(database.DeleteAsync(item)); }
public string getWokoutStreamData(long userSettingsKey, Workout workout) { aqufitEntities entities = new aqufitEntities(); //UserSettings settings = gid > 0 ? entities.UserSettings.FirstOrDefault(s => s.Id == gid) : entities.UserSettings.FirstOrDefault(s => s.UserKey == uid && s.PortalKey == pid); //IList<long> friendIds = new List<long>(); /* if (mode == 0) // NORMAL MODE { friendIds = ((perm == Convert.ToInt32(Affine.Dnn.Modules.ATI_PermissionPageBase.AqufitPermission.PUBLIC)) ? new List<long>() : entities.UserFriends.Where(f => (f.SrcUserSettingKey == profileSettings.Id || f.DestUserSettingKey == profileSettings.Id) && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FRIEND ).Select(f => (f.SrcUserSettingKey == profileSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToList()); friendIds.Add(profileSettings.Id); // PERMISSIONS: add the users own stream (we always show the users stream unless they change settings ) TODO: permissions user settings } else if (mode == 1) // FOLOW MODE { friendIds = entities.UserFriends.Where(f => f.SrcUserSettingKey == profileSettings.Id && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW ).Select(f => f.DestUserSettingKey).ToList(); friendIds.Add(profileSettings.Id); // PERMISSIONS: add the users own stream (we always show the users stream unless they change settings ) TODO: permissions user settings } else if (mode == 3) // Just "My" stream { friendIds.Add(profileSettings.Id); // PERMISSIONS: add the users own stream (we always show the users stream unless they change settings ) TODO: permissions user settings } IQueryable<UserStream> stream = null; if (mode == 2) // Favorites { stream = entities.User2StreamFavorites.Include("UserStreamSet").Where(f => f.UserKey == profile && f.PortalKey == pid).Select(s => s.UserStream).OrderByDescending(s => s.TimeStamp).ThenByDescending(s => s.Date).Skip(skip).Take(take); // hydrate the usersettings stream.Select(s => s.UserSetting).ToArray(); } else { stream = entities.UserStreamSet.Include("UserSetting").Where(LinqUtils.BuildContainsExpression<UserStream, long>(s => s.UserSetting.Id, friendIds)).Where(s => s.PortalKey == pid && (s.GroupKey == null || s.GroupKey == gid)) .Where(s => (s.PublishSettings == 0) || (s.PublishSettings == 1 && s.UserSetting.UserKey == profile) || (s.PublishSettings == 2 && s.UserSetting.UserKey != profile)) // This statment takes out publishing to a firends stream (PublishSettings == 1) byt leaves it in your own .OrderByDescending(s => s.TimeStamp).ThenByDescending(s => s.Date).Skip(skip).Take(take); // TODO: check that this operation is deffered and we are not querying the whole stream (profiling) } */ IQueryable<Workout> stream = null; // TODO: this sux harsh... but all my Garmin/Nike workouts come in as "Untitled" ... so lets ignore garmin if (workout.DataSrc == (int)Affine.Utils.WorkoutUtil.DataSrc.GARMIN || workout.DataSrc == (int)Affine.Utils.WorkoutUtil.DataSrc.NIKE_NO_MAP) { stream = entities.UserStreamSet.OfType<Workout>().Include("WOD").Include("UserSetting").Where(w => w.Id == workout.Id) .OrderByDescending(s => s.TimeStamp).ThenByDescending(s => s.Date); } else { stream = entities.UserStreamSet.OfType<Workout>().Include("WOD").Include("UserSetting").Where(w => w.UserSetting.Id == userSettingsKey && w.WorkoutTypeKey == workout.WorkoutTypeKey && w.Title == workout.Title) .OrderByDescending(s => s.TimeStamp).ThenByDescending(s => s.Date); } // TODO: this is the only way i can hydrate the Metrics.. stream.Select(m => m.UserSetting.Metrics).ToArray(); UserComment[] comments = entities.UserComment.Include("UserSetting").Where(LinqUtils.BuildContainsExpression<UserComment, long>(c => c.UserStream.Id, stream.Select(s => s.Id))).ToArray(); string json = _jserializer.Serialize(_IStreamManager.UserStreamArrayToStreamDataArray(stream.ToArray(), comments)); return json; }
private void DisplayWorkoutStatistics(Workout workout) { string html = string.Empty; string title = string.Empty; string statUrl = string.Empty; hiddenWorkoutKey.Value = "" + workout.Id; aqufitEntities entities = new aqufitEntities(); // First lets find out "How" we want to compare/display the workout based on the type that it is Affine.Utils.WorkoutUtil.WorkoutType wt = WorkoutUtil.IntToWorkoutType( (int)workout.WorkoutTypeKey ); html += "<ul>"; if (wt == WorkoutUtil.WorkoutType.CROSSFIT) { WOD wod = entities.WODs.Include("WODType").First(w => w.Id == workout.WOD.Id); // crossfit stats are going to be a bit different... we want to do things like this.. // say you just did Fran .. // 1) how many times have you done it... was it your best time? // 2) If it was a group posted workout.. how many people have also posted it so far.. // 3) How many people in your group did you do better than? // 4) If not a group post... how many friends/compare pallet people did you do better then? IList<long> friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == this.ProfileSettings.Id || f.DestUserSettingKey == this.ProfileSettings.Id) && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FRIEND ).Select(f => (f.SrcUserSettingKey == this.ProfileSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToList(); friendIds.Add(workout.UserSetting.Id); // add you into the list IQueryable<Workout> allFriendsWorkouts = entities.UserStreamSet.OfType<Workout>().Where(w => w.WOD != null && w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression<Workout, long>(w => w.UserSetting.Id, friendIds)); IQueryable<Workout> doneBeforeQuery = allFriendsWorkouts.Where(w => w.UserSetting.Id == workout.UserSetting.Id); int doneBeforeCount = doneBeforeQuery.Count(); title = workout.Title; statUrl = ResolveUrl("~/") + UserSettings.UserName + "/workout/" + workout.Id; html += "<li>This is the " + UnitsUtil.numberToNumberPlaceString(doneBeforeCount) + " time you have done this workout.</li>"; if (doneBeforeCount > 1) { // need to know if this is timed or scored ect .. if (wod.WODType.Id == (long)WorkoutUtil.WodType.TIMED) { int place = doneBeforeQuery.OrderBy(w => w.Duration).Where(w => w.Duration < workout.Duration).Count() + 1; html += "<li>This is the " + UnitsUtil.numberToNumberPlaceString(place) + " best time for this workout.</li>"; } else if (wod.WODType.Id == (long)WorkoutUtil.WodType.AMRAP || wod.WODType.Id == (long)WorkoutUtil.WodType.SCORE ) { int place = doneBeforeQuery.OrderBy(w => w.Score).Where(w => w.Score > workout.Score).Count() + 1; html += "<li>This is the " + UnitsUtil.numberToNumberPlaceString(place) + " best score for this workout.</li>"; } else if (wod.WODType.Id == (long)WorkoutUtil.WodType.MAX_WEIGHT) { int place = doneBeforeQuery.OrderBy(w => w.Max).Where(w => w.Max >= workout.Max).Count(); html += "<li>This is the " + UnitsUtil.numberToNumberPlaceString(place) + " highest weight for this workout.</li>"; } } // 2) If it was a group posted workout.. how many people have also posted it so far.. // check if this is a group workout.. if (wod.UserSettingsKey != 1) { Group group = entities.UserSettings.OfType<Group>().FirstOrDefault(u => u.Id == wod.UserSettingsKey); if (group != null) { // we need to get all the member ids... long[] groupFriendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == group.Id || f.DestUserSettingKey == group.Id) && f.Relationship >= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER ).Select(f => (f.SrcUserSettingKey == group.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToArray(); IQueryable<Workout> allGroupEntries = entities.UserStreamSet.OfType<Workout>().Where(w => w.WOD != null && w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression<Workout, long>(w => w.UserSetting.Id, groupFriendIds)); int gcount = allGroupEntries.Count(); html += "<li>So far " + UnitsUtil.numberToNumberPlaceString(gcount) + " members of " + group.UserName + " have posted this workout.</li>"; // TODO: how well are you doing in the group.. } } // next we report on friends stats // TODO: we really only want to count peoples best times... right now 1 person could be in the query having done the workout 5 times.. IQueryable<Workout> justFriends = allFriendsWorkouts.Where(w => w.UserSetting.Id != workout.UserSetting.Id); int friendsCount = justFriends.Count(); html += "<li>"+friendsCount + " of your friends have post results for the workout.<br />"; if (friendsCount > 0) { if (wod.WODType.Id == (long)WorkoutUtil.WodType.TIMED) { int place = allFriendsWorkouts.OrderBy(w => w.Duration).Where(w => w.Duration < workout.Duration).Count() + 1; html += "This is the " + UnitsUtil.numberToNumberPlaceString(place) + " best time out of your firends.<br />"; } else if (wod.WODType.Id == (long)WorkoutUtil.WodType.AMRAP || wod.WODType.Id == (long)WorkoutUtil.WodType.SCORE) { int place = allFriendsWorkouts.OrderBy(w => w.Score).Where(w => w.Score > workout.Score).Count() + 1; html += "This is the " + UnitsUtil.numberToNumberPlaceString(place) + " best score out of your friends.<br />"; } else if (wod.WODType.Id == (long)WorkoutUtil.WodType.MAX_WEIGHT) { int place = allFriendsWorkouts.OrderBy(w => w.Max).Where(w => w.Max >= workout.Max).Count(); html += "This is the " + UnitsUtil.numberToNumberPlaceString(place) + " highest weight out of your friends.<br />"; } } html += "</li>"; List<long> watchIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == this.ProfileSettings.Id ) && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW).Select(f => f.DestUserSettingKey).ToList(); watchIds.Add(workout.UserSetting.Id); // add you into the list IQueryable<Workout> allWatchListWorkouts = entities.UserStreamSet.OfType<Workout>().Where(w => w.WOD != null && w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression<Workout, long>(w => w.UserSetting.Id, watchIds)); IQueryable<Workout> justWatchList = allWatchListWorkouts.Where(u => u.UserSetting.Id != UserSettings.Id); int watchListCount = justWatchList.Count(); html += "<li>"+watchListCount + " of the athletes in your Compare Pallet have results for this workout.<br />"; if (watchListCount > 0) { if (wod.WODType.Id == (long)WorkoutUtil.WodType.TIMED) { int place = allWatchListWorkouts.OrderBy(w => w.Duration).Where(w => w.Duration < workout.Duration).Count() + 1; html += "This is the " + UnitsUtil.numberToNumberPlaceString(place) + " best time out of your Compare Pallet.<br />"; } else if (wod.WODType.Id == (long)WorkoutUtil.WodType.AMRAP || wod.WODType.Id == (long)WorkoutUtil.WodType.SCORE) { int place = allWatchListWorkouts.OrderBy(w => w.Score).Where(w => w.Score > workout.Score).Count() + 1; html += "This is the " + UnitsUtil.numberToNumberPlaceString(place) + " best score out of your Compare Pallet.<br />"; } else if (wod.WODType.Id == (long)WorkoutUtil.WodType.MAX_WEIGHT) { int place = allWatchListWorkouts.OrderBy(w => w.Max).Where(w => w.Max >= workout.Max).Count(); html += "This is the " + UnitsUtil.numberToNumberPlaceString(place) + " highest weight out of your Compare Pallet.<br />"; } } html += "</li>"; // report on stats if it is a "standard workout" (report the levels) if (wod.Standard > 0) { // need to know if this is timed or scored ect .. /* if (wod.WODType.Id == (long)WorkoutUtil.WodType.TIMED) { int place = doneBeforeQuery.OrderBy(w => w.Duration).Where(w => w.Duration < workout.Duration).Count() + 1; litDebug.Text += "This is the " + UnitsUtil.numberToNumberPlaceString(place) + " best time for this workout.<br />"; } else if (wod.WODType.Id == (long)WorkoutUtil.WodType.AMRAP || wod.WODType.Id == (long)WorkoutUtil.WodType.SCORE) { int place = doneBeforeQuery.OrderBy(w => w.Score).Where(w => w.Score < workout.Score).Count() + 1; litDebug.Text += "This is the " + UnitsUtil.numberToNumberPlaceString(place) + " best score for this workout.<br />"; } else if (wod.WODType.Id == (long)WorkoutUtil.WodType.MAX_WEIGHT) { int place = doneBeforeQuery.OrderBy(w => w.Max).Where(w => w.Max < workout.Max).Count() + 1; litDebug.Text += "This is the " + UnitsUtil.numberToNumberPlaceString(place) + " highest weight for this workout.<br />"; } */ } } else if (wt == WorkoutUtil.WorkoutType.WEIGHTS) { // TODO: this section needs a lot of work... } else { // TODO: we will want to break these appart.. but for now all cardio has the "same" stats // get all workouts of that type ... say "running" IQueryable<Workout> allWorkouts = entities.UserStreamSet.OfType<Workout>().Where(w => w.UserSetting.Id == UserSettings.Id && w.WorkoutTypeKey == workout.WorkoutTypeKey); // 1) Get some distance metrics IQueryable<Workout> allByDist = allWorkouts.Where(w => w.Distance.HasValue ).OrderBy(w => w.Distance); int longestRank = allByDist.Where(w => w.Distance >= workout.Distance).Count(); // get the distance metric (5K, 10K, 15K, Half, Full) UnitsUtil.DistanceMetric dmet = UnitsUtil.distanceMetricRounder(workout.Distance.Value, Utils.WorkoutUtil.IntToWorkoutType( (int)workout.WorkoutTypeKey )); double lowBound = UnitsUtil.distanceMetricToDistance(dmet); double hightBound = UnitsUtil.distanceMetricToDistance(UnitsUtil.ToDistanceMetric((int)dmet - 1)); IQueryable<Workout> allInRange = allByDist.Where(w => (w.Distance < hightBound && w.Distance >= lowBound)); int rangeSize = allInRange.Count(); int fastest = allInRange.Where(w => (w.Duration.HasValue && w.Duration <= workout.Duration)).Count(); title = workout.Title + (workout.AvrPace.HasValue ? " ("+Utils.UnitsUtil.durationToTimeString( (long)workout.AvrPace.Value ) +")" : ""); statUrl = ResolveUrl("~/") + UserSettings.UserName + "/workout/" + workout.Id; DateTime weekAgo = DateTime.Today.AddDays(-7); string wtName = Utils.WorkoutUtil.WorkoutTypeKeyToString((int)wt, false); if (workout.Date.CompareTo(weekAgo) >= 0) { int thisWeek = allByDist.Where(w => w.Date.CompareTo(weekAgo) >= 0).Count(); html += "<li>This was your " + UnitsUtil.numberToNumberPlaceString(thisWeek) + " " + wtName + " in the last <span class=\\\"calendar\\\"> 7</span> days</li>"; } DateTime monthAgo = DateTime.Today.AddDays(-30); if (workout.Date.CompareTo(monthAgo) >= 0) { int thisMonth = allByDist.Where(w => w.Date.CompareTo(monthAgo) >= 0).Count(); html += "<li>This was your " + UnitsUtil.numberToNumberPlaceString(thisMonth) + " " + wtName + " in the last <span class=\\\"calendar\\\">30</span> days</li>"; } // need to do pace info (pace for 5m, 10km, ect.. ) // IQueryable<Workout> allByPace = allInRange.Where(w => w.AvrPace.HasValue).OrderBy(w => w.AvrPace); // int paceRank = allInRange.Where(w => w.AvrPace < workout.AvrPace).Count(); // TODO: award badges based on when a person first gets to the above (1Mile, 5K, 10K, 15K, Half, Full) html += "<li>This was your " + UnitsUtil.numberToNumberPlaceString(longestRank) + " longest " + wtName + "</li>"; html += "<li>This was your " + UnitsUtil.numberToNumberPlaceString(fastest) + " fastest time out of " + rangeSize + " " + wtName + "<br /> between range of " + UnitsUtil.DistanceMetricToString(dmet) + " and " + UnitsUtil.DistanceMetricToString(UnitsUtil.ToDistanceMetric((int)dmet - 1)) + ".</li>"; // html += "Your pace of " + workout.AvrPace + " was " + UnitsUtil.numberToNumberPlaceString(paceRank) + "<br />"; // TODO: compare with some friends.. } html += "</ul>"; // TODO: this is temp var json = new { html = html, title = title, statUrl = statUrl }; JavaScriptSerializer serial = new JavaScriptSerializer(); RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.WorkoutStatsDialog.open('" + serial.Serialize(json) + "'); "); }
public void Create(Workout workout) { workoutRepository.Create(workout); }
public void UpdateWorkout(Workout workout) { workout.EndDateTime = GetEndDateTime(workout); _workoutRepository.Save(workout); }
public static Workout WorkoutToWorkoutVM(WorkoutVM workoutVM) { var workout = new Workout() { WorkoutId = workoutVM.WorkoutId, Distance = workoutVM.Distance, TotalTime = workoutVM.TotalTime, Notes = workoutVM.Notes, DiaryFeelingId = workoutVM.DiaryFeelingId, WorkoutTypeId = workoutVM.WorkoutTypeId }; return workout; }
public void DeleteWorkout(Workout workout) { DeleteWorkout(workout.WorkoutId); }
public void CreateWorkout(Workout workout) { _context.Workouts.Add(workout); }
public void DeleteWorkout(Workout workout, IWorkoutRepository workoutRepository) { workoutRepository.DeleteWorkout(workout); }
private Workout MapWorkoutViewModel(WorkoutViewModel model) { var exercises = new List<Exercise>(); foreach (var exercise in model.Exercises) { exercises.Add(MapExerciseViewModel(exercise)); } var workout = new Workout { Id = model.Id, WorkoutDate = model.WorkoutDate, Exercises = exercises }; return workout; }
public ActionResult <Workout> Create(Workout workout) { _workoutService.Create(workout); return(CreatedAtRoute("GetWorkout", new { id = workout.Id.ToString() }, workout)); }