protected override void ExecuteRequest(HttpContext context) { (bool isOk, User user) = CheckClaimsForUser(Request, context, _userRepository); if (!isOk || user == null) { return; } FoodEntry foodEntry = new FoodEntry() { Id = Request.Id, Datetime = Request.DateTime, OpenFoodFactsDataId = Request.OFFDataId, UserId = user.Id }; foodEntry = _foodEntryRepository.Update(foodEntry).GetAwaiter().GetResult(); if (foodEntry == null) { context.Response.StatusCode = StatusCodes.Status400BadRequest; context.Response.WriteAsync("Could not update the given food entry, please check body data sanity"); } else { context.Response.StatusCode = StatusCodes.Status200OK; } }
public List <FoodEntry> GetAllFoodEntries(string tablename) { if (!PersistentDataProvider.Current.allTableNames.Contains(tablename)) { MessageBox.Show($"Table {tablename} not found"); } try { using var con = new SQLiteConnection("Data Source=" + directory + databaseName); con.Open(); string stm = "SELECT * FROM " + tablename; using var cmd = new SQLiteCommand(stm, con); using SQLiteDataReader rdr = cmd.ExecuteReader(); List <FoodEntry> result = new List <FoodEntry>(); while (rdr.Read()) { FoodEntry b = new FoodEntry(PersistentDataProvider.Current.AllFoods.Where(x => x.Name == rdr.GetString(1)).FirstOrDefault(), rdr.GetDouble(2), rdr.GetString(3)); b.ID = rdr.GetInt32(0); result.Add(b); } return(result.OrderBy(x => x.Date).ToList()); } catch (System.Data.SQLite.SQLiteException) { MessageBox.Show("Table " + tablename + " not found!"); return(null); } }
protected override void ExecuteRequest(HttpContext context) { (bool isOk, User user) = CheckClaimsForUser(Request, context, _userRepository); if (!isOk || user == null) { return; } FoodEntry foodEntry = _foodEntryRepository.GetFoodEntryById(Request.Id); if (foodEntry == null) { context.Response.StatusCode = StatusCodes.Status400BadRequest; context.Response.WriteAsync("Could not find the food entry, please check body data sanity"); return; } if (!_foodEntryRepository.Delete(Request.Id).GetAwaiter().GetResult()) { context.Response.StatusCode = StatusCodes.Status400BadRequest; context.Response.WriteAsync("Could not remove the food entry"); } else { context.Response.StatusCode = StatusCodes.Status200OK; } }
public void DeleteFoodEntry() // Deletes anything related to the FoodEntry. See Stored Procedure. { dbClass.DeleteFoodEntryFromDB_AtFoodEntryID(SelectedFoodEntryListItem.FoodEntryID.Value); FoodEntry currentFoodEntry = FoodEntryList.Where(tag => SelectedFoodEntryListItem.FoodEntryID.Value == tag.FoodEntryID).FirstOrDefault(); FoodEntryList.Remove(currentFoodEntry); }
protected override void ExecuteRequest(HttpContext context) { (bool isOk, User user) = CheckClaimsForUser(Request, context, _userRepository); if (!isOk || user == null) { return; } OpenFoodFactsData offData = _oFFDataRepository.Insert(new OpenFoodFactsData() { Name = Request.Name, IsCustom = true, // 100g Energy100g = Request.Energy100g, Proteins100g = Request.Proteins100g, Sodium100g = Request.Sodium100g, Fat100g = Request.Fat100g, Salt100g = Request.Salt100g, SaturatedFat100g = Request.SaturatedFat100g, Sugars100g = Request.Sugars100g, // Serving EnergyServing = Request.EnergyServing, ProteinsServing = Request.ProteinsServing, SodiumServing = Request.SodiumServing, FatServing = Request.FatServing, SaltServing = Request.SaltServing, SaturatedFatServing = Request.SaturatedFatServing, SugarsServing = Request.SugarsServing, }).GetAwaiter().GetResult(); FoodEntry foodEntryData = _foodEntryRepository.Insert(new FoodEntry() { Datetime = DateTime.Now, UserId = user.Id, OpenFoodFactsDataId = offData.Id }).GetAwaiter().GetResult(); if (foodEntryData != null) { // update all quests based on datas var quests = _questRepository.Get(user, _questTypeRepository, QuestState.InProgress).GetAwaiter().GetResult(); foreach (var quest in quests) { var questHandler = QuestHandlers.Create(quest, user, _questTypeRepository); questHandler.Update("Calories", (foodEntryData.Servings * offData.EnergyServing).ToString()); _questRepository.Update(quest).GetAwaiter().GetResult(); } string foodEntryJson = JsonSerializer.Serialize(foodEntryData); context.Response.StatusCode = StatusCodes.Status200OK; context.Response.WriteAsync(foodEntryJson).GetAwaiter().GetResult(); } else { context.Response.StatusCode = StatusCodes.Status204NoContent; } }
public void AddFoodEntry_Tag() { FoodEntry currentFoodEntry = FoodEntryList.Where(tag => SelectedFoodEntryListItem.FoodEntryID.Value == tag.FoodEntryID).FirstOrDefault(); Tag currentTag = null;//TagViewModel.SubcategoryTagList.Where(tag => TagViewModel.SelectedTagListItem.TagID.Value == tag.TagID).FirstOrDefault(); dbClass.InsertFoodEntry_TagToDB((int)currentFoodEntry.FoodEntryID, (int)currentTag.TagID.Value); currentFoodEntry.FoodEntry_TagList.Add(currentTag); }
public void DeleteFoodEntry_Tag() { FoodEntry currentFoodEntry = FoodEntryList.Where(tag => SelectedFoodEntryListItem.FoodEntryID.Value == tag.FoodEntryID).FirstOrDefault(); Tag currentTag = null; // TagViewModel.SubcategoryTagList.Where(tag => SelectedFoodEntry_TagListItem.TagID.Value == tag.TagID).FirstOrDefault(); dbClass.DeleteFoodEntry_TagFromDB_AtTagID((int)currentFoodEntry.FoodEntryID.Value, (int)currentTag.TagID.Value); currentFoodEntry.FoodEntry_TagList.Remove(currentTag); }
public void AddFoodEntry() { FoodEntry.Food = AllFoodItems.FirstOrDefault(f => f.Name.Equals(Name)); FoodEntry.Calories = CalculateCalories(FoodEntry); FoodToday.TotalCalories.Add(FoodEntry); FoodEntry = new FoodEntry() { Amount = 0, Food = new Food() }; StateHasChanged(); }
public List <FoodEntry> GetFoodEntriesOfToday(string tablename) { if (!PersistentDataProvider.Current.allTableNames.Contains(tablename)) { MessageBox.Show($"Table {tablename} not found"); } try { List <Food> FoodHelperListe = GetAllFoods("Foods"); List <FoodEntry> result = new List <FoodEntry>(); using var con = new SQLiteConnection("Data Source=" + directory + databaseName); con.Open(); string stm = "SELECT * FROM " + tablename; using var cmd = new SQLiteCommand(stm, con); using SQLiteDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { //string u = rdr.GetString(1); Food helper = (from p in FoodHelperListe where p.Name == rdr.GetString(1) select p).FirstOrDefault(); FoodEntry c = new FoodEntry(helper, rdr.GetDouble(2), rdr.GetString(3)); c.ID = rdr.GetInt32(0); result.Add(c); } var helper2 = result.AsEnumerable().Where(x => Convert.ToDateTime(x.Date) == DateTime.Today).OrderBy(x => x.Food).GroupBy(x => x.Food).ToList(); List <FoodEntry> endresult = new List <FoodEntry>(); foreach (var x in helper2) { Food h = (from p in PersistentDataProvider.Current.AllFoods where p.Name == x.First().Food select p).FirstOrDefault(); double gewicht = x.Sum(x => x.Weight); endresult.Add(new FoodEntry(h, gewicht, DateTime.Today.ToString())); } return(endresult); } catch (System.Data.SQLite.SQLiteException) { return(null); } }
public FoodViewModel(FoodEntry food) { Title = AppResource.EditFood; IsEditView = true; Food = food; Name = Food.Name; Calories = Food.Calories; Carbs = Food.Carbs; Protein = Food.Protein; Fat = Food.Fat; Fiber = Food.Fiber; Salt = Food.Salt; }
public ActionResult AddEntry(string date, string title, float calories) { FlabberUser user = FlabberContext.CurrentUser; if (user == null) { return(RedirectToAction("Index", "Home")); } // Get the date. Force to UTC. DateTime userDate = DateTime.Parse(date); userDate = DateTime.SpecifyKind(userDate, DateTimeKind.Local); // Add the entry FoodEntry entry = new FoodEntry(); entry.Calories = calories; entry.Title = title; entry.Date = userDate; entry.User = user; entry.Id = Guid.NewGuid(); FoodEntry.Repository.SaveOrUpdate(entry); // Add to the autocomplete list title = title.Trim(); FoodItem item = FoodItem.Repository.First("@Title", title); if (item == null) { item = new FoodItem(); item.Title = title; item.User = user; item.Brand = "Notset"; item.Calories = calories; item.Id = Guid.NewGuid(); FoodItem.Repository.SaveOrUpdate(item); // Update the cache if it exists string cacheKey = string.Format("FoodItems{0}", user.Id); if (HttpContext.Cache[cacheKey] != null) { List <FoodItem> list = (List <FoodItem>)HttpContext.Cache[cacheKey]; list.Add(item); HttpContext.Cache[cacheKey] = list; } } return(RedirectToAction("Index", "Food")); }
public async Task <IActionResult> NewFood(FoodEntry foodEntry) { if (foodEntry != null) { _context.FoodEntry.Add(foodEntry); await _context.SaveChangesAsync(); return(Ok()); } else { return(BadRequest()); } }
//====================== private void LoadData() { DataTable dt1 = dbClass.Execute_Proc("dbo.GetTags"); foreach (DataRow Row1 in dt1.Rows) { Tag tag = new Tag ( Row1.Field <int?>("TagID"), Row1.Field <int?>("ParentCategoryID"), Row1.Field <string>("Name"), Row1.Field <string>("ColorID"), Row1.Field <bool?>("IsUserCreated"), Row1.Field <bool?>("IsFeelingGoodBad") ); if (tag.ParentCategoryID == null) { TagViewModel.CategoryTagList.Add(tag); } else { TagViewModel.SubcategoryTagList.Add(tag); } } DataTable dt2 = dbClass.Execute_Proc("dbo.GetFoodEntrys"); foreach (DataRow Row2 in dt2.Rows) { FoodEntry foodEntry = new FoodEntry ( Row2.Field <int?>("FoodEntryId"), Row2.Field <string>("Picture"), Row2.Field <DateTime>("DateTime"), Row2.Field <string>("Description"), Row2.Field <bool?>("IsFeelingGoodBad") ); DataTable dt3 = dbClass.GetFoodEntry_Tags("dbo.GetFoodEntry_Tags", (int)foodEntry.FoodEntryID); foreach (DataRow Row3 in dt3.Rows) { int TagID = Row3.Field <int>("TagID"); Tag foundTag = TagViewModel.SubcategoryTagList.Where(tag => TagID == tag.TagID).FirstOrDefault(); foodEntry.FoodEntry_TagList.Add(foundTag); } EntryViewModel.FoodEntryList.Add(foodEntry); } }
public async Task <IActionResult> OnGetAsync(int?id) { if (id == null) { return(NotFound()); } FoodEntry = await _context.FoodEntry.FirstOrDefaultAsync(m => m.Id == id); if (FoodEntry == null) { return(NotFound()); } return(Page()); }
public async Task <IActionResult> UpdateEntry(FoodEntry foodEntry) { try { //foodEntry.ModifiedDate = DateTime.Now; _ctx.FoodEntries.Update(foodEntry); await _ctx.SaveChangesAsync(); return(Accepted()); } catch (Exception e) { _logger.LogError(e, "error in " + e.TargetSite); return(StatusCode(500)); } }
public async Task <IActionResult> OnPostAsync(int?id) { if (id == null) { return(NotFound()); } FoodEntry = await _context.FoodEntry.FindAsync(id); if (FoodEntry != null) { _context.FoodEntry.Remove(FoodEntry); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index")); }
public FoodDetailPage() { InitializeComponent(); var item = new FoodEntry { Id = 0, Name = "Apple", Calories = 100, Carbs = 50, Date = DateTime.Now, Username = App.User.UserName }; viewModel = new FoodDetailViewModel(item); BindingContext = viewModel; }
public ActionResult Delete(Guid id) { FlabberUser user = FlabberContext.CurrentUser; if (user == null) { return(RedirectToAction("Index", "Home")); } if (id != Guid.Empty) { FoodEntry entry = FoodEntry.Repository.Read(id); FoodEntry.Repository.Delete(entry); } return(RedirectToAction("Index", "Food")); }
public ActionResult AddEntry(string date,string title,float calories) { FlabberUser user = FlabberContext.CurrentUser; if (user == null) return RedirectToAction("Index", "Home"); // Get the date. Force to UTC. DateTime userDate = DateTime.Parse(date); userDate = DateTime.SpecifyKind(userDate, DateTimeKind.Local); // Add the entry FoodEntry entry = new FoodEntry(); entry.Calories = calories; entry.Title = title; entry.Date = userDate; entry.User = user; entry.Id = Guid.NewGuid(); FoodEntry.Repository.SaveOrUpdate(entry); // Add to the autocomplete list title = title.Trim(); FoodItem item = FoodItem.Repository.First("@Title", title); if (item == null) { item = new FoodItem(); item.Title = title; item.User = user; item.Brand = "Notset"; item.Calories = calories; item.Id = Guid.NewGuid(); FoodItem.Repository.SaveOrUpdate(item); // Update the cache if it exists string cacheKey = string.Format("FoodItems{0}", user.Id); if (HttpContext.Cache[cacheKey] != null) { List<FoodItem> list = (List<FoodItem>)HttpContext.Cache[cacheKey]; list.Add(item); HttpContext.Cache[cacheKey] = list; } } return RedirectToAction("Index", "Food"); }
public void AddNewFoodEntry() { DateTime dateTime = new DateTime(); dateTime = DateTime.Now; int newFoodEntryID = dbClass.InsertFoodEntryToDB(dateTime, NewEntryDescription, NewEntryIsFeelingGoodBad); FoodEntry newFoodEntry = new FoodEntry { FoodEntryID = newFoodEntryID, DateTime = dateTime, Description = NewEntryDescription, IsFeelingGoodBad = NewEntryIsFeelingGoodBad }; FoodEntryList.Add(newFoodEntry); }
protected override void OnInitialized() { AllFoodItems = _FoodService.GetAllFood(); if (AllFoodItems.Any()) { Name = AllFoodItems.ElementAt(0)?.Name; } FoodToday = _CalorieService.GetFoodOfDay(DateTime.Now) ?? new FoodInDay() { Day = DateTime.Now, TotalCalories = new List <FoodEntry>() }; FoodEntry = new FoodEntry() { Amount = 0, Food = new Food() }; CurrentDate = DateTime.Now.ToShortDateString(); base.OnInitialized(); }
public async Task <IActionResult> AddEntry(FoodEntryRequest entry) { try { var food = await _ctx.Foods.Where(f => f.Id == entry.FoodId).FirstOrDefaultAsync(); var foodEntry = new FoodEntry { Food = food, Timestamp = DateTime.Now, Amount = entry.Amount, UserId = Guid.Parse(GetUserId()) }; _ctx.FoodEntries.Add(foodEntry); await _ctx.SaveChangesAsync(); return(Created("api/foodentry", foodEntry)); } catch (Exception e) { _logger.LogError(e, "error in " + e.TargetSite); return(StatusCode(500)); } }
private void DialogHost_DialogClosing(object sender, DialogClosingEventArgs eventArgs) { try { //Get Parameter and check for type var input = eventArgs.Parameter; //To do: Make Insertion possible for any datetime #region Insert Food Entry if (input.GetType() == typeof(FoodEntryView)) { try { //Insert Food Entry into DB FoodEntryView helper = (FoodEntryView)input; if (helper.SelectedFood != null && helper.Weight != 0) { Food lebensmittelHinzugefuegt = helper.SelectedFood; FoodEntry eintrag = new FoodEntry(lebensmittelHinzugefuegt, helper.Weight, helper.SelectedDate.ToString()); PersistentDataProvider.Current.databaseService.InsertValues("Foodentries", typeof(FoodEntry), eintrag); } else { MessageBox.Show("Eintrag unvollständig, bitte erneut versuchen."); } } catch (System.InvalidOperationException) { MessageBox.Show("Datum auswählen!"); } } #endregion } catch (System.NullReferenceException) { } }
private async void GetFood(int fdcId) { int carbs, calories; string apiURL = $"https://api.nal.usda.gov/fdc/v1/{fdcId}?api_key={apiKey}"; FoodObject = JsonConvert.DeserializeObject <FoodObject>(await _client.GetStringAsync(apiURL)); Name = FoodObject.Description; foreach (FoodNutrient nutrient in FoodObject.FoodNutrients) { if (nutrient.Nutrient.Name.ToLower().Contains("carbohydrate") || nutrient.Nutrient.Name.ToLower().Contains("carbs")) { Int32.TryParse(nutrient.Nutrient.Number, out carbs); Carbs = carbs; } if (nutrient.Nutrient.Name.ToLower().Contains("energy")) { Int32.TryParse(nutrient.Nutrient.Number, out calories); Calories = calories; } } Food = new FoodEntry() { Name = Name, Calories = Calories, Carbs = Carbs, Username = App.User.UserName, Date = DateTime.Now }; FoodNameEntry.Text = Food.Name; FoodCarbEntry.Text = $"{Food.Carbs}"; FoodCalEntry.Text = $"{Food.Calories}"; }
protected override void ExecuteRequest(HttpContext context) { (bool isOk, User user) = CheckClaimsForUser(Request, context, _userRepository); if (!isOk || user == null) { return; } FoodEntry foodEntryData = _foodEntryRepository.Insert(new FoodEntry() { UserId = user.Id, OpenFoodFactsDataId = Request.OFFDataId, Datetime = DateTime.Now }).GetAwaiter().GetResult(); if (foodEntryData != null) { var offData = _offDataRepository.Get(foodEntryData.OpenFoodFactsDataId).GetAwaiter().GetResult().FirstOrDefault(); // update all quests based on datas var quests = _questRepository.Get(user, _questTypeRepository, InProgress).GetAwaiter().GetResult(); foreach (var quest in quests) { var questHandler = QuestHandlers.Create(quest, user, _questTypeRepository); questHandler.Update("Calories", (foodEntryData.Servings * offData.EnergyServing).ToString()); _questRepository.Update(quest).GetAwaiter().GetResult(); } string foodEntryJson = JsonSerializer.Serialize(foodEntryData); context.Response.StatusCode = StatusCodes.Status200OK; context.Response.WriteAsync(foodEntryJson).GetAwaiter().GetResult(); } else { context.Response.StatusCode = StatusCodes.Status204NoContent; } }
private FoodEntryModel CreateEntryModel(FoodEntry foodEntry) { var profileSettings = CurrentProfileSettings; var model = new FoodEntryModel { Id = foodEntry.Id, Title = foodEntry.Title, Description = foodEntry.Description, ConsumedDate = foodEntry.EntryDate, FoodEntryType = foodEntry.MealType.ToString(), Calories = foodEntry.Calories.HasValue ? foodEntry.Calories.Value : 0, Carbs = foodEntry.Carbs.HasValue ? foodEntry.Carbs.Value : 0, Fat = foodEntry.Fat.HasValue ? foodEntry.Fat.Value : 0, Protein = foodEntry.Protein.HasValue ? foodEntry.Protein.Value : 0 }; SetFoodEntryProfileSettings(model); return model; }
public JsonResult Entry(FoodEntryModel model) { if (ModelState.IsValid) { using (var entities = new DietJournalEntities()) { FoodEntry foodEntry = null; if (model.Id > 0) foodEntry = entities.FoodEntries.FirstOrDefault(e => e.Id == model.Id); if (foodEntry == null) { foodEntry = new FoodEntry(); entities.FoodEntries.AddObject(foodEntry); } foodEntry.UserId = CurrentUserId.Value; foodEntry.Title = model.Title; foodEntry.Description = model.Description; foodEntry.Calories = model.Calories; foodEntry.Carbs = model.Carbs; foodEntry.EntryDate = model.ConsumedDate; foodEntry.Fat = model.Fat; foodEntry.Protein = model.Protein; foodEntry.SavedDate = DateTime.Now; foodEntry.MealType = !String.IsNullOrEmpty(model.FoodEntryType) ? int.Parse(model.FoodEntryType) : 0; if (model.Favorite) { var favorite = new FoodFavorite { UserId = CurrentUserId, MealType = foodEntry.MealType, Title = foodEntry.Title, Description = foodEntry.Description, Calories = foodEntry.Calories, Carbs = foodEntry.Carbs, Protein = foodEntry.Protein, Fat = foodEntry.Fat }; entities.FoodFavorites.AddObject(favorite); } entities.SaveChanges(); if (model.EntryValues != null && model.EntryValues.Count > 0) { foreach (var entryValue in model.EntryValues) { FoodEntryMealTypeValue value = null; if (!String.IsNullOrEmpty(entryValue.Id)) { var entryValueId = int.Parse(entryValue.Id); value = entities.FoodEntryMealTypeValues.FirstOrDefault(v => v.Id == entryValueId); } if (value == null) { value = new FoodEntryMealTypeValue { MealTypeValueId = int.Parse(entryValue.EntryTypeValueId), FoodEntryId = foodEntry.Id }; entities.FoodEntryMealTypeValues.AddObject(value); } value.Value = entryValue.Value; } entities.SaveChanges(); } } return Json(new { IsValid = true }); } return Json(new { IsValid = false, ErrorMessage = "" }); }
private void EditNameButton_Clicked(object sender, EventArgs e) { FoodName.IsVisible = false; FoodEntry.IsVisible = true; FoodEntry.Focus(); }
public FoodDetailViewModel(FoodEntry entry = null) { Title = entry?.Name; Food = entry; }
public void AddFoodEntry(FoodEntry entry) { throw new NotImplementedException(); }
public static void AddCommand() { bool isTypeValid = false; bool isEntryValid = false; int command = 1; string entry = ""; DateTime today = DateTime.Now; // show commands. check command is valid while (!isTypeValid) { Console.WriteLine(string.Empty); HelpAddCommand(); string line = Console.ReadLine(); isTypeValid = CheckTypeValid(line); if (isTypeValid) { command = int.Parse(line); } else { Console.WriteLine("Error. Command not valid."); } } // the command was valid. now request entry value while (!isEntryValid) { Console.WriteLine(string.Empty); Console.WriteLine("Enter the diary text:"); string line = Console.ReadLine(); if (line.Length > 0) { entry = line; isEntryValid = true; } else { Console.WriteLine("Error. Please enter diary text."); } } DiaryEntry diaryEntry = null; switch (command) { case 1: diaryEntry = new GeneralEntry(today, entry); break; case 2: diaryEntry = new GratitudeEntry(today, entry); break; case 3: diaryEntry = new FoodEntry(today, entry); break; case 4: diaryEntry = new FitnessEntry(today, entry); break; default: break; } diary.AddEntry(diaryEntry); Console.WriteLine(string.Empty); Console.WriteLine("---------------------------------------------------------------------------"); Console.WriteLine(string.Empty); Console.WriteLine("Success. Created entry: '{0}'", entry); Console.WriteLine(string.Empty); Console.WriteLine("---------------------------------------------------------------------------"); Console.WriteLine(string.Empty); Console.WriteLine("Press any key to continue."); Console.ReadKey(); //GradeBookUserInterface.CommandLoop(gradeBook); }
private int CalculateCalories(FoodEntry foodEntry) { var relative = foodEntry.Amount / 100.0f; return((int)(relative * (foodEntry.Food?.CaloriesPer100g ?? 0.0f))); }
public FoodViewModel() { Title = AppResource.NewFood; IsEditView = false; Food = new FoodEntry(); }