Ejemplo n.º 1
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Weight,Date,UserId")] WeightEntry weightEntry)
        {
            if (id != weightEntry.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(weightEntry);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!WeightEntryExists(weightEntry.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["UserId"] = new SelectList(_context.Users, "Id", "Id", weightEntry.UserId);
            return(View(weightEntry));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the weight lost in pounds of the current weight entry since the previous weight entry
        /// </summary>
        /// <param name="currentWeightEntry">Current weight entry</param>
        /// <param name="weightEntries">All weight entries in the system</param>
        /// <returns>Weight lost in pounds of the current weight entry since the previous weight entry</returns>
        public static double Convert(WeightEntry currentWeightEntry, IEnumerable <WeightEntry> weightEntries)
        {
            var previousEntry  = weightEntries.OrderBy(p => p.Date).LastOrDefault(p => p.Date < currentWeightEntry.Date);
            var previousWeight = (previousEntry == null ? Settings.Default.StartWeight : previousEntry.Value);

            return(previousWeight - currentWeightEntry.Value);
        }
Ejemplo n.º 3
0
        async void TestLargeDataSet()
        {
            if (!await ShowLoseDataWarning())
            {
                return;
            }

            try
            {
                IncrementPendingRequestCount();

                await ClearData();

                // set goal
                var goal = new WeightLossGoal(new DateTime(2017, 1, 1), 200, new DateTime(2017, 7, 1), 200, WeightUnitEnum.ImperialPounds);
                await DataService.SetGoal(goal);

                // add some weights
                DateTime date   = new DateTime(2017, 3, 29);
                TimeSpan day    = TimeSpan.FromDays(1);
                Random   random = new Random();
                for (int i = 0; i < 1000; i++)
                {
                    date = date - day;
                    var weightEntry = new WeightEntry(date, 200 + (decimal)(random.NextDouble() * 10) - 5, WeightUnitEnum.ImperialPounds);
                    await DataService.AddWeightEntry(weightEntry);
                }
            }
            finally
            {
                DecrementPendingRequestCount();
            }

            Close();
        }
Ejemplo n.º 4
0
        public async Task <bool> UpdateWeightEntryAsync(WeightEntry weightEntryToUpdate)
        {
            _dbContext.WeightEntries.Update(weightEntryToUpdate);
            var updated = await _dbContext.SaveChangesAsync();

            return(updated > 0);
        }
Ejemplo n.º 5
0
        private async void messagePrompt_Completed(object sender, PopUpEventArgs <string, PopUpResult> e)
        {
            if (e.PopUpResult == PopUpResult.Ok)
            {
                weights.clear();

                WeightEntry entry = new WeightEntry()
                {
                    weight = 0, entryNum = "0"
                };
                weights.weightList.Add(entry);
                await weights.writeJsonAsync();

                weight.Text = "";

                ToastPrompt toast = new ToastPrompt();
                toast.Title   = "Easy Weight";
                toast.Message = "Weights succesfully reset.";
                toast.MillisecondsUntilHidden = 2000;
                toast.ImageSource             = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));

                toast.Show();
            }
            else
            {
                ToastPrompt toast = new ToastPrompt();
                toast.Title   = "Easy Weight";
                toast.Message = "Weights not reset.";
                toast.MillisecondsUntilHidden = 2000;
                toast.ImageSource             = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));

                toast.Show();
            }
        }
Ejemplo n.º 6
0
        public async Task <string> CreateAsync(WeightEntry weightEntry)
        {
            weightEntry.Id = ObjectId.GenerateNewId().ToString();
            await _collection.InsertOneAsync(weightEntry);

            return(weightEntry.Id);
        }
        public static InfoForToday GetTodaysDisplayInfo(WeightLossGoal goal, WeightEntry todaysWeightEntry)
        {
            var infoForToday = new InfoForToday();

            infoForToday.TodaysDisplayWeight = (todaysWeightEntry != null) ? todaysWeightEntry.ToString() : Constants.Strings.DailyInfoPage_UnknownWeight;

            if (goal == null)
            {
                infoForToday.IsEnterWeightButtonVisible = false;
                infoForToday.IsSetGoalButtonVisible     = true;
            }
            else if (todaysWeightEntry == null)
            {
                infoForToday.IsEnterWeightButtonVisible = true;
                infoForToday.IsSetGoalButtonVisible     = false;
            }

            infoForToday.TodaysMessage = GetTodaysMessageFromWeight(todaysWeightEntry, goal); // ok that either may be null

            // if they haven't set a goal, or don't have a weight today, or today is the first day of the diet, then we don't
            // want to colorize the screen or show the HowToEat information below their weight
            if (goal != null && todaysWeightEntry != null && goal.StartDate.Date != DateTime.Today.Date)
            {
                // update the window color if we have a weight for today and know their goal
                decimal goalWeightForToday = GetGoalWeightForDate(goal, DateTime.Today.Date);
                bool    onADiet            = todaysWeightEntry.Weight > goalWeightForToday;
                infoForToday.ColorToShow     = onADiet ? BaseColorEnum.Red : BaseColorEnum.Green;
                infoForToday.HowToEatMessage = onADiet ? Constants.Strings.DailyInfoPage_HowToEat_OnDiet : Constants.Strings.DailyInfoPage_HowToEat_OffDiet;
            }

            return(infoForToday);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> Edit(int id,
                                               [Bind("WeightEntryId,WeightTime,MesuredWeight,PetId")] WeightEntry weightEntryToUpdate, int page = 1)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (id != weightEntryToUpdate.WeightEntryId)
                {
                    return(NotFound());
                }
                if (ModelState.IsValid)
                {
                    var updateStatus = await _weightEntryService.UpdateWeightEntryAsync(weightEntryToUpdate);

                    if (!updateStatus)
                    {
                        return(RedirectToAction("Index", "EditEntries", new { error = true, msgToDisplay = "An error has occured with the databse." }));
                    }
                    var goalReached = _weightEntryService.WeightGoalReached(weightEntryToUpdate);
                    return(RedirectToAction("Index", "EditEntries", new { id = page, updated = true, msgToDisplay = "Weight entry has been successfully updated." }));
                }
                ViewBag.Page = page;
                return(View(weightEntryToUpdate));
            }
            return(RedirectToAction("Index", "NotAuthorized"));
        }
Ejemplo n.º 9
0
        public async Task <bool> CreateWeightEntryAsync(WeightEntry weightEntry)
        {
            await _dbContext.WeightEntries.AddAsync(weightEntry);

            var created = await _dbContext.SaveChangesAsync();

            return(created > 0);
        }
Ejemplo n.º 10
0
        public string Create()
        {
            var weightEntry = new WeightEntry
            {
            };

            return(_weightsRepository.CreateResource(weightEntry));
        }
Ejemplo n.º 11
0
        public ActionResult DeleteConfirmed(int id)
        {
            WeightEntry weightEntry = db.WeightEntries.Find(id);

            db.WeightEntries.Remove(weightEntry);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 12
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            WeightEntry.ConvertPoundsToStones((double)value, out var stones, out var remainingPounds, out var negative);

            var parsed = $"{stones} st {remainingPounds:0.0} lbs";

            return((negative ? "-" : "") + parsed);
        }
Ejemplo n.º 13
0
 public Task <int> SaveWeightAsync(WeightEntry weight)
 {
     if (weight.ID != 0)
     {
         return(_database.UpdateAsync(weight));
     }
     return(_database.InsertAsync(weight));
 }
Ejemplo n.º 14
0
            public void PrepareTest()
            {
                //_createUtcTime = RandomData.GetDateTime().ToUniversalTime();
                //   SystemTime.UtcNow = () => _createUtcTime;

                _weightEntry = new WeightEntry
                {
                };
            }
        async void EditEntry(WeightEntry selectedItem)
        {
            AnalyticsService.TrackEvent(Constants.Analytics.GraphAndListCategory, Constants.Analytics.GraphList_LaunchedEditExistingWeight, 1);

            var navParams = new NavigationParameters();

            navParams.Add(nameof(WeightEntry), selectedItem);
            await NavigationService.NavigateAsync($"{nameof(NavigationPage)}/{nameof(WeightEntryPage)}", navParams, useModalNavigation : true);
        }
Ejemplo n.º 16
0
        public SplashScreenPageViewModel(INavigationService navigationService, IPageDialogService pageDialogService, IDeviceService deviceService)
            : base(navigationService)
        {
            _navigationService = navigationService;

            SettingVals       = new SettingVals();
            LatestWeightEntry = new WeightEntry();
            AllWeightEntries  = new List <WeightEntry>();
        }
Ejemplo n.º 17
0
 public ActionResult Edit([Bind(Include = "Id,Weight,Date")] WeightEntry weightEntry)
 {
     if (ModelState.IsValid)
     {
         db.Entry(weightEntry).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(weightEntry));
 }
Ejemplo n.º 18
0
        public async Task <bool> CreateWeightEntry(double weight, int petId)
        {
            var weightEntry = new WeightEntry
            {
                MesuredWeight = (float)weight,
                PetId         = petId,
                WeightTime    = DateTime.Now
            };

            return(await _weightEntryService.CreateWeightEntryAsync(weightEntry));
        }
Ejemplo n.º 19
0
        public ActionResult Create([Bind(Include = "Id,Weight,Date")] WeightEntry weightEntry)
        {
            if (ModelState.IsValid)
            {
                db.WeightEntries.Add(weightEntry);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(weightEntry));
        }
        public IActionResult PutEntry(WeightEntry entry)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            _repositoryWrapper.WeightEntries.Update(entry);

            return(Accepted());
        }
Ejemplo n.º 21
0
        public WeightEntryViewModel MapWeightEntry(WeightEntry weightEntry)
        {
            var weighEntryViewModel = new WeightEntryViewModel
            {
                WeightEntryId = weightEntry.WeightEntryId,
                WeightTime    = weightEntry.WeightTime,
                MesuredWeight = weightEntry.MesuredWeight,
                PetId         = weightEntry.PetId
            };

            return(weighEntryViewModel);
        }
Ejemplo n.º 22
0
 private void UnitEntry_Completed(object sender, EventArgs e)
 {
     if (UnitEntry.Text.ToString() != string.Empty)
     {
         // Go to Weight
         singleItem.Unit       = UnitEntry.Text.ToString();
         UnitEntry.IsEnabled   = false;
         UnitLabel.IsVisible   = false;
         WeightEntry.IsVisible = true;
         WeightEntry.Focus();
     }
 }
Ejemplo n.º 23
0
        public async Task <IActionResult> Create([Bind("Id,Weight,Date,UserId")] WeightEntry weightEntry)
        {
            if (ModelState.IsValid)
            {
                _context.Add(weightEntry);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["UserId"] = new SelectList(_context.Users, "Id", "Id", weightEntry.UserId);
            return(View(weightEntry));
        }
        // NOTE:: either of the parameters could be null if they are not yet entered
        static string GetTodaysMessageFromWeight(WeightEntry todaysEntry, WeightLossGoal goal)
        {
            // if they haven't set a goal
            if (goal == null)
            {
                return(Constants.Strings.DailyInfoPage_TodaysMessage_NoGoal);
            }

            // if they started the goal today
            if (goal.StartDate.Date == DateTime.Today.Date)
            {
                return(Constants.Strings.DailyInfoPage_TodaysMessage_NewGoal);
            }

            // if they haven't entered today's weight yet
            if (todaysEntry == null)
            {
                return(Constants.Strings.DailyInfoPage_TodaysMessage_NoWeightToday);
            }

            decimal todaysGoalWeight = GetGoalWeightForDate(goal, DateTime.Today.Date);
            int     daysToGo         = (int)(Math.Floor((goal.GoalDate.Date - DateTime.Today.Date).TotalDays));

            // they have reached their goal weight (could be before or after the goal date, we show same message either way)
            if (todaysEntry.Weight <= goal.GoalWeight)
            {
                return(Constants.Strings.DailyInfoPage_GoalEnd_Success);
            }

            // they've reached the goal date, show success/failure
            if (daysToGo <= 0)
            {
                return((todaysEntry.Weight <= todaysGoalWeight) ?
                       Constants.Strings.DailyInfoPage_GoalEnd_Success :
                       Constants.Strings.DailyInfoPage_GoalEnd_Failure);
            }

            // they are still working towards a goal, show a summary of their progress
            var amountLost      = goal.StartWeight - todaysEntry.Weight;
            var amountRemaining = Math.Max(todaysEntry.Weight - goal.GoalWeight, 0); // prevent from going negative
            int daysSinceStart  = (int)(Math.Floor((DateTime.Today.Date - goal.StartDate.Date).TotalDays));

            // ex: You have [lost/gained] [XX.X] [pounds/kilograms] since starting on your current goal [XX] days ago. You have [XX] days left to lose a remaining [XX.X] pounds. [You can do it!/Keep up the good work!]
            // NOTE: we don't want to say "-1.2 gained" so we always make sure what we display is positive
            string gainedLost = (amountLost < 0) ? Constants.Strings.DailyInfoPage_Summary_Gained : Constants.Strings.DailyInfoPage_Summary_Lost;
            string endingText = (todaysEntry.Weight <= todaysGoalWeight) ? Constants.Strings.DailyInfoPage_SummaryEnding_OnTrack : Constants.Strings.DailyInfoPage_SummaryEnding_OffTrack;

            return(string.Format(Constants.Strings.DailyInfoPage_ProgressSummary,
                                 gainedLost, Math.Abs(amountLost), Constants.Strings.Common_WeightUnit, daysSinceStart,
                                 daysToGo, amountRemaining, endingText));
        }
Ejemplo n.º 25
0
        // Delete... this gets the info for the edit view
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            WeightEntry weightEntry = db.WeightEntries.Find(id);

            if (weightEntry == null)
            {
                return(HttpNotFound());
            }
            return(View(weightEntry));
        }
        async void ConfirmDeleteItem(WeightEntry entry)
        {
            AnalyticsService.TrackEvent(Constants.Analytics.GraphAndListCategory, Constants.Analytics.GraphList_DeleteExistingWeight_Start, 1);

            // show warning that an entry will be deleted, allow them to cancel
            var result = await DialogService.DisplayAlertAsync(Constants.Strings.GraphPage_ConfirmDelete_Title,
                                                               string.Format(Constants.Strings.GraphPage_ConfirmDelete_Message, entry.Date),
                                                               Constants.Strings.GENERIC_OK,
                                                               Constants.Strings.GENERIC_CANCEL);

            if (!result)
            {
                AnalyticsService.TrackEvent(Constants.Analytics.GraphAndListCategory, Constants.Analytics.GraphList_DeleteExistingWeight_Cancelled, 1);
                return;
            }

            AnalyticsService.TrackEvent(Constants.Analytics.GraphAndListCategory, Constants.Analytics.GraphList_DeleteExistingWeight_Confirmed, 1);
            bool deleteSucceeded = true;

            try
            {
                IncrementPendingRequestCount(); // show loading
                deleteSucceeded = await DataService.RemoveWeightEntryForDate(entry.Date);

                if (!deleteSucceeded)
                {
                    AnalyticsService.TrackEvent(Constants.Analytics.GraphAndListCategory, Constants.Analytics.GraphList_DeleteExistingWeight_Failed, 1);
                }
            }
            catch (Exception ex)
            {
                AnalyticsService.TrackFatalError($"{nameof(ConfirmDeleteItem)} threw an exception", ex);
                AnalyticsService.TrackEvent(Constants.Analytics.GraphAndListCategory, Constants.Analytics.GraphList_DeleteExistingWeight_Exception, 1);

                deleteSucceeded = false; // handled with dialog below
            }
            finally
            {
                DecrementPendingRequestCount(); // hide loading
            }

            if (!deleteSucceeded)
            {
                await DialogService.DisplayAlertAsync(Constants.Strings.GraphPage_DeleteFailed_Title, Constants.Strings.GraphPage_DeleteFailed_Message, Constants.Strings.GENERIC_OK);

                this.RefreshFromUserDataAsync();
            }
        }
Ejemplo n.º 27
0
        public async Task <bool> AddWeightEntry(WeightEntry newEntry)
        {
#if DEBUG
            await SimulateSlowNetworkIfEnabled();
#endif

            if (await WeightEntryForDateExists(newEntry.Date))
            {
                return(false);
            }

            MockEntries.Add(newEntry);
            FireUserDataUpdated();

            return(true);
        }
Ejemplo n.º 28
0
        private async void AddPoint(object sender, EventArgs e)
        {
            if (float.TryParse(WeightEntry.Text, out float value))
            {
                var obj = new JObject
                {
                    ["value"] = value
                };
                await NetClient.PublishAsync($"scale/{RemoteScale.DeviceId}/weight/calibration/add", obj.ToString());

                await NetClient.PublishAsync($"scale/{RemoteScale.DeviceId}/weight/calibration/get");

                WeightEntry.Text = "";
                WeightEntry.Focus();
            }
        }
        public IActionResult PostEntry(WeightEntry entry)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var savedEntry = _repositoryWrapper.WeightEntries.Add(entry);

            //if add op is not success
            if (savedEntry == null)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, "Database Failure"));
            }

            return(Created("/", savedEntry));
        }
Ejemplo n.º 30
0
        /// <summary>
        ///     Tries to update the goal weight, which is sotred at index 0 of the weight list.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string currGoal = weights.weightList[0].weight.ToString();

            try
            {
                WeightEntry entry = new WeightEntry()
                {
                    weight = Convert.ToInt32(new_goal.Text.ToString()), entryNum = "0"
                };
                weights.weightList[0] = entry;
                Determine_Color();

                ToastPrompt toast = new ToastPrompt();
                toast.Title   = "Easy Weight";
                toast.Message = "New goal weight set.";
                toast.MillisecondsUntilHidden = 2000;
                toast.ImageSource             = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));

                toast.Show();
            }
            catch (System.FormatException f)
            {
                weights.weightList[0].weight = Convert.ToInt32(currGoal);

                ToastPrompt toast = new ToastPrompt();
                toast.Title   = "Easy Weight";
                toast.Message = "Please input a whole number.";
                toast.MillisecondsUntilHidden = 2000;
                toast.ImageSource             = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));

                toast.Show();
            }
            catch (System.ArgumentOutOfRangeException f)
            {
                weights.weightList[0].weight = Convert.ToInt32(new_goal.Text.ToString());
            }
            await weights.writeJsonAsync();
        }