public async Task <IActionResult> Edit(int?id, FoodViewModel viewModel) { if (id == null) { id = 0; } try { if (ModelState.IsValid) { var saving1 = await _foodRepository.SaveFoodAsync(viewModel, (int)id); if (saving1 != null) { return(RedirectToAction("Index")); } } } catch (DbUpdateException /* ex */) { //Log the error (uncomment ex variable name and write a log. ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator."); } return(View(viewModel)); }
public void Given_basket_item_list_and_quantity_of_items_should_be_sum_if_order_food_is_same_as_previus( FoodViewModel food) { // given var publisher = new Subject <IBasketItemViewModel>(); var viewModel = ClassUnderTest; var firstBasketItem = new BasketItemViewModel(food) { Quantity = 2 }; var secondBasketItem = new BasketItemViewModel(food) { Quantity = 3 }; // when publisher.OnNext(firstBasketItem); publisher.OnNext(secondBasketItem); // then Assert.That(firstBasketItem.TotalPrice, Is.EqualTo(5 * food.Price)); Assert.That(viewModel.Items.Count, Is.EqualTo(1)); Assert.That(viewModel.Items, Is.Not.Null); // ReSharper disable once PossibleNullReferenceException Assert.That(viewModel.Items.FirstOrDefault().Quantity, Is.EqualTo(5)); }
public ActionResult Edit(FoodViewModel model) { // Check if model state is valid if (ModelState.IsValid) { using (var database = new BlogDbContext()) { // Get salat from database var salat = database.Foods .FirstOrDefault(a => a.Id == model.Id); // Set salat properties salat.Title = model.Title; salat.Content = model.Content; // salat.CategoryId = model.CategoryId; // this.SetsalatTags(salat, model, database); // Save salat state in database database.Entry(salat).State = EntityState.Modified; database.SaveChanges(); // Redirect to the index page return(RedirectToAction("List")); } } // If model state is invalid, return the same view return(View(model)); }
/// <summary> /// save food item details /// </summary> /// <param name="foodViewModel">food view model</param> /// <returns>Return medicine detail</returns> public FoodViewModel SaveFoodItemDetails(FoodViewModel foodViewModel) { Food foodInstance; if (foodViewModel.FoodID == 0) { foodInstance = new Food(); foodInstance.CreatedDate = DateTime.Now; } else { foodInstance = this.unitOfWork.FoodRepository.GetByID(foodViewModel.FoodID); } foodInstance.FoodName = foodViewModel.FoodName; foodInstance.Price = foodViewModel.Price; foodInstance.Quantity = foodViewModel.Quantity; //medicineInstance.IssueDate = DateTime.Parse(medicineViewModel.IssueDate.Replace("/","-")); foodInstance.IssueDate = DateTime.ParseExact(foodViewModel.IssueDate, "mm/dd/yyyy", CultureInfo.InvariantCulture); if (foodViewModel.FoodID == 0) { this.unitOfWork.FoodRepository.Insert(foodInstance); } else { this.unitOfWork.FoodRepository.Update(foodInstance); } this.unitOfWork.Save(); return(foodViewModel); }
public async Task <IActionResult> Insert(FoodViewModel vm) { if (ModelState.IsValid) { if (User.IsInRole("Admin")) { vm.IsGlobal = true; } else if (User.IsInRole("User")) { vm.IsGlobal = false; } vm.Calories = 0; vm.ProfileId = (await _uManager.FindByNameAsync(User.Identity.Name)).ProfileId; var f = vm.ToFood(); var createOperation = await _fbo.CreateAsync(f); if (!createOperation.Success) { return(View("Error", new ErrorViewModel() { RequestId = createOperation.Exception.Message })); } return(RedirectToAction(nameof(Index))); } return(RedirectToAction("Index")); }
// GET: User/Foods public async Task <IActionResult> Index() { var oldDate = DateTime.Now.AddDays(-12); var dates = _context.Foods.Where(l => l.CreationDate < oldDate); _context.Foods.RemoveRange(dates); _context.SaveChanges(); var userLoggedIn = await GetCurrentUserAsync(); var model = new List <FoodViewModel>(); foreach (var food in _context.Foods) { var foodviewmodel = new FoodViewModel { FoodId = food.FoodId, FoodName = food.FoodName, VoteCount = food.VoteCount }; if (await UsersVote(userLoggedIn.Id, food.FoodId)) { foodviewmodel.IsThumbsUp = true; } else { foodviewmodel.IsThumbsUp = false; } model.Add(foodviewmodel); } return(View(model)); }
public IActionResult ShowFoods() { List <FoodItemViewModel> topOrders = db.OrderItemOrders. GroupBy(o => o.OrderItem). OrderByDescending(o => o.Count()). Select(o => new FoodItemViewModel { OrderItem = o.Key, TotalCount = o.Count(), TotalAmountSum = o.Sum(p => p.CurrentPrice) }).Take(10).ToList(); List <FoodItemViewModel> unordered = db.OrderItemOrders. GroupBy(o => o.OrderItem). OrderBy(o => o.Count()). Select(o => new FoodItemViewModel { OrderItem = o.Key, TotalCount = o.Count(), TotalAmountSum = o.Sum(p => p.CurrentPrice) }).Take(10).ToList(); FoodViewModel foodViewModel = new FoodViewModel() { TopOrders = topOrders, Unordered = unordered }; return(PartialView(foodViewModel)); }
private FoodDTO Create(FoodViewModel viewModel) { try { log.Debug(FoodViewModel.FormatFoodViewModel(viewModel)); FoodDTO food = new FoodDTO(); // copy values viewModel.UpdateDTO(food, null); //RequestContext.Principal.Identity.GetUserId()); // audit food.CreateBy = null; //RequestContext.Principal.Identity.GetUserId(); food.CreateOn = DateTime.UtcNow; // add log.Debug("_foodService.AddFood - " + FoodDTO.FormatFoodDTO(food)); int id = _foodService.AddFood(food); food.FoodId = id; log.Debug("result: 'success', id: " + id); return(food); } catch (Exception e) { // error log.Error(e.ToString()); throw; } }
public ActionResult Edit(int FoodId, FoodViewModel editedFood) { try { // TODO: Add update logic here //var food = foods.First(f => f.FoodId == FoodId); using (var db = new FoodLogContext()) { var food = db.Foods.First(f => f.FoodId == FoodId); food.Name = editedFood.Food.Name; food.Calories = editedFood.Food.Calories; food.GramsOfCarb = editedFood.Food.GramsOfCarb; food.GramsOfFat = editedFood.Food.GramsOfFat; food.GramsOfProtein = editedFood.Food.GramsOfProtein; food.FoodType = food.FoodType.FoodTypes.First(t => t.Name == editedFood.SelectedFoodType); db.SaveChanges(); } return(RedirectToAction("Index")); } catch { return(View()); } }
public ActionResult Create(FoodViewModel newFood) { try { // TODO: Add insert logic here var food = new FoodModel() { Name = newFood.Food.Name, Calories = newFood.Food.Calories, GramsOfCarb = newFood.Food.GramsOfCarb, GramsOfFat = newFood.Food.GramsOfFat, GramsOfProtein = newFood.Food.GramsOfProtein }; food.FoodType = food.FoodType.FoodTypes.First(t => t.Name == newFood.SelectedFoodType); using (var db = new FoodLogContext()) { db.Foods.Add(food); db.SaveChanges(); } return(RedirectToAction("Index")); } catch { return(View()); } }
public ActionResult Update([FromBody] FoodViewModel fvm) { var currentRes = _bo.Read(fvm.Id); if (!currentRes.Success) { return(StatusCode((int)HttpStatusCode.InternalServerError)); } var current = currentRes.Result; if (current == null) { return(NotFound()); } if (SupportMethods.SupportMethods.Equals(fvm, current)) { return(base.StatusCode((int)HttpStatusCode.NotModified)); } current = SupportMethods.SupportMethods.Update(fvm, current); var updateResult = _bo.Update(current); if (!updateResult.Success) { return(StatusCode((int)HttpStatusCode.InternalServerError)); } return(Ok()); }
public ActionResult Create([FromBody] FoodViewModel fvm) { var f = fvm.ToFood(); var res = _bo.Create(f); return(StatusCode(res.Success ? (int)HttpStatusCode.OK : (int)HttpStatusCode.InternalServerError)); }
protected override void OnAppearing() { base.OnAppearing(); FoodViewModel FVM = (FoodViewModel)foodtable.BindingContext; FVM.loadFood(App.Instance.date); }
protected override void OnDisappearing() { base.OnDisappearing(); FoodViewModel FVM = (FoodViewModel)foodtable.BindingContext; FVM.saveFood(); }
private bool IsCollisionWithFood(SnakeViewModel snakeVM, FoodViewModel foodVM) { return(snakeVM.HeadX + snakeVM.Width > foodVM.X && snakeVM.HeadX < foodVM.X + foodVM.Width && snakeVM.HeadY < foodVM.Y + foodVM.Height && snakeVM.HeadY + snakeVM.Height > foodVM.Y); }
public ActionResult Index(FoodViewModel foodViewModel) { int foodId = foodRepository.GetFoodId(foodViewModel); Food food = foodRepository.GetFood(foodId); if (Session["Orders"] == null) { Session["Orders"] = new Order(); } Order order = (Order)Session["Orders"]; OrderRecord orderRecord = new OrderRecord(); if (order.OrderRecords == null) { order.OrderRecords = new List <OrderRecord>(); } orderRecord.Event = food; orderRecord.RecordAmount = foodViewModel.Quantity; orderRecord.RecordAmountForKids = 0; if (foodViewModel.QuantityForKids != null) { orderRecord.RecordAmountForKids = (int)foodViewModel.QuantityForKids; } order.OrderRecords.Add(orderRecord); Session["Orders"] = order; return(RedirectToAction("Index", "Order")); }
// GET: Food/Edit/10 public ActionResult Edit(int?id) { // Check the id if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } // Get food item Food food = db.Items.Find(id) as Food; // check the food if (food == null) { return(HttpNotFound()); } // Create View Model Object FoodViewModel vm = new FoodViewModel(); vm.Name = food.Name; vm.Cost = food.Cost; vm.Description = food.Description; vm.Ingredients = food.Ingredients; vm.MenuSection = db.MenuSections.Find(food.MenuSectionId); vm.Size = food.Size; vm.AddedDate = food.AddedDate; vm.PhotoPath = food.ItemImage; return(View(vm)); }
/// <summary> /// Get Food by id /// </summary> /// <param name="id">Food id</param> /// <returns>Food json view model</returns> public IHttpActionResult Get(int id) { try { // get log.Debug("_foodService.GetFood - foodId: " + id + " "); var food = new FoodViewModel(_foodService.GetFood(id)); log.Debug("_foodService.GetFood - " + FoodViewModel.FormatFoodViewModel(food)); log.Debug("result: 'success'"); //return Json(food, JsonRequestBehavior.AllowGet); //return Content(JsonConvert.SerializeObject(food), "application/json"); //return food; //return JsonConvert.SerializeObject(food); return(Ok(food)); } catch (Exception e) { // error log.Error(e.ToString()); throw; } }
public JsonResult Post([FromBody] FoodViewModel vm) { try { if (ModelState.IsValid) { var newFood = Mapper.Map <Food>(vm); // Save to database after mapping the view model _logger.LogInformation("Attempting to save new food..."); _repository.AddFood(newFood); if (_repository.SaveAll()) { var lastId = newFood.Id; Response.StatusCode = (int)HttpStatusCode.Created; return(Json(lastId)); } } } catch (Exception ex) { _logger.LogError("Failed to save new food to the database", ex); Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new { Message = ex.Message })); } Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new { Message = "Failed", ModelState = ModelState })); }
public async Task <IActionResult> Details(Guid?id) { if (id == null) { return(NotFound()); } var getOperation = await _fbo.ReadAsync((Guid)id); if (!getOperation.Success) { return(View("Error", new ErrorViewModel() { RequestId = getOperation.Exception.Message })); } if (getOperation.Result == null) { return(NotFound()); } var catOperation = await _cbo.ReadAsync(getOperation.Result.CategoryId); var fvm = FoodViewModel.Parse(getOperation.Result); fvm.Fats = Math.Round(fvm.Fats, 2); fvm.Carbohydrates = Math.Round(fvm.Carbohydrates, 2); fvm.Protein = Math.Round(fvm.Protein, 2); fvm.Alcohol = Math.Round(fvm.Alcohol, 2); fvm.Calories = Math.Round(fvm.Calories, 2); var cvm = CategoryViewModel.Parse(catOperation.Result); var dic = new Dictionary <FoodViewModel, CategoryViewModel>(); dic.Add(fvm, cvm); return(View(dic)); }
// POST: api/Foods public async Task Post([FromBody] FoodViewModel m) { if (await this.db.Foods.Where(x => x.FoodName.ToLower() == m.FoodName).AnyAsync()) { throw new InvalidOperationException("Food with that name already exists"); } this.db.Foods.Add(new Food { FoodId = Guid.NewGuid(), Calories = m.Calories, Carbs = m.Carb, Fat = m.Fat, Fiber = m.Fiber, FoodName = m.FoodName, Protein = m.Protein, ServingSize = m.ServingSize, ServingSizeUnits = m.ServingSizeUnits }); try { await this.db.SaveChangesAsync(); } catch (Exception e) { throw e; } }
/// <summary> /// Handles the retrieval of <see cref="Nutrient"/> data for all selected food items in the meal to be logged /// </summary> /// <remarks> /// Makes use of the <see cref="SearchHandler"/> class for organizing API request and storing nutrient data. /// Nutrient data isn't stored originally because food search API responses don't include these details /// </remarks> /// <param name="ndbnos">A list of all food identifiers to be included in nutritional data API queries</param> /// <returns>A populated <see cref="FoodViewModel"/></returns> public FoodViewModel AddNutrientData(List <string> ndbnos) { SearchHandler handler = new SearchHandler(); var client = HttpClientAccessor.HttpClient; List <Food> foodItems = new List <Food>(); foreach (string n in ndbnos) { HttpResponseMessage response = client.GetAsync(handler.OrganizeReportQ(n)).Result; if (response.IsSuccessStatusCode) { JObject dataObject = JObject.Parse(response.Content.ReadAsStringAsync().Result); Food f = new Food(); foodItems.Add(handler.StoreMealNutrientDetails(f, dataObject, "full")); } else { // handle failure } } FoodViewModel fvm = new FoodViewModel() { Foods = foodItems }; return(fvm); }
public async Task <IActionResult> Index(FoodViewModel foodViewModel) { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var homeCook = _context.HomeCook.Where(c => c.IdentityUserId == userId).SingleOrDefault(); var meals = await _recipeByIngredientAndCuisineRequest.GetRecipesByIngredientAndCuisine(foodViewModel.SelectedIngredient, foodViewModel.SelectedCuisine); List <SelectListItem> ingredients = new List <SelectListItem>(); var _ingredients = _context.Ingredients.Select(a => new SelectListItem() { Text = a.Name, Value = a.Name }); ingredients = _ingredients.OrderBy(a => a.Text).ToList(); List <SelectListItem> cuisines = new List <SelectListItem>(); var _cuisines = _context.Cuisines.Select(a => new SelectListItem() { Text = a.Name, Value = a.Name }); cuisines = _cuisines.OrderBy(a => a.Text).ToList(); foodViewModel.HomeCook = homeCook; foodViewModel.Meals = meals; foodViewModel.Ingredients = ingredients; foodViewModel.Cuisines = cuisines; return(View(foodViewModel)); }
/// <summary> /// Add or Edit Food details /// </summary> /// <param name="model">Food View Model</param> /// <returns>food item list view</returns> public ActionResult SaveFoodItemDetails(FoodViewModel model) { if (model != null) { var foodDetails = this._manageClient.SaveFoodItemDetails(model); if (foodDetails.FoodID == 0) { this.TempData["SucessAlert"] = "1"; } else { this.TempData["SucessAlert"] = "2"; } if (this.Session["UserType"] != null) { if (this.Session["UserType"].ToString() != "ADMN") { return(this.RedirectToAction("ClientDashboard", "ClientDashboard", new { Area = "Client", userStatus = this.Session["UserStatus"].ToString() })); } else { return(this.RedirectToAction("AdminDashboard", "AdminDashboard", new { Area = "Admin" })); } } } return(this.RedirectToAction("AdminDashboard", "AdminDashboard", new { Area = "Admin" })); }
public async Task <dynamic> UpdateFood(FoodViewModel model) { return(await ExecuteInMonitoring(async() => { return await service.UpdateFoodAsync(model); })); }
public bool CreateRest(FoodViewModel model) { try { FoodModel rest = new FoodModel(); rest.Address = new AddressModel(); rest.Name = model.Name; rest.Category = model.Category; rest.PriceMin = model.PriceMin; rest.PriceMax = model.PriceMax; rest.Address.Street = model.Street; rest.Address.City = model.City; rest.Address.PostalCode = model.PostalCode; rest.CreatedAt = model.CreatedAt; rest.CreatedBy = model.CreatedBy; rests.Add(rest); return(true); } catch (Exception e) { throw e; } }
// GET: Foods public async Task<IActionResult> Index(string searchString) { var s = await _context.Foods.OrderBy(x => x.FoodClass.Name).ToArrayAsync(); List<FoodViewModel> fm = new List<FoodViewModel>(); foreach (var f in s) { Guid guid = f.FoodClassId; var st = _context.FoodClass.Single(x => x.Id == guid); var tt = new FoodViewModel { Id=f.Id, Name = f.Name, Detail = f.Detail, picture = f.picture, Price = f.Price, ClassName = st.Name }; fm.Add(tt); } if (!String.IsNullOrEmpty(searchString)) { s = await _context.Foods.Where(x=>x.Name==searchString).OrderBy(x => x.FoodClass.Name).ToArrayAsync(); fm = new List<FoodViewModel>(); foreach (var f in s) { Guid guid = f.FoodClassId; var st = _context.FoodClass.Single(x => x.Id == guid); var tt = new FoodViewModel { Id = f.Id, Name = f.Name, Detail = f.Detail, picture = f.picture, Price = f.Price, ClassName = st.Name }; fm.Add(tt); } } return View(fm); }
public int GetFoodId(FoodViewModel food) { Food foodEvent = db.Foods.Where(ev => ev.Restaurant.Id == food.Restaurant_Id && ev.StartTime == food.StartTime).FirstOrDefault(); int eventId = foodEvent.Id; return(eventId); }
public FoodPage() { InitializeComponent(); var vm = new FoodViewModel(); this.DataContext = vm; }
public DetailFoodPage(FoodViewModel f) { var pageService = new PageService(); var dataAccess = new SQLiteFoodStore(DependencyService.Get <ISQLite>()); ViewModel = new DetailFoodPageViewModel(pageService, dataAccess, f); InitializeComponent(); }