public async Task <IActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var food = await db.FoodItems.FindAsync(id);

            var foodViewModel = new FoodItemViewModel()
            {
                Id              = food.Id,
                FoodName        = food.FoodName,
                Quality         = food.Quality,
                Quantity        = food.Quantity,
                PurchasesDate   = food.PurchasesDate,
                PurchasesTime   = food.PurchasesTime,
                Place           = food.Place,
                Password        = food.Password,
                ConfirmPassword = food.ConfirmPassword,

                ExistingImage = food.Image
            };

            if (food == null)
            {
                return(NotFound());
            }
            return(View(foodViewModel));
        }
Example #2
0
        public IActionResult UpdateFoodInList(int foodItemId, [FromBody] FoodItemViewModel viewModel)
        {
            if (viewModel == null)
            {
                return(HttpBadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(HttpBadRequest(ModelState));
            }


            FoodItem singleById = _foodRepository.GetSingle(foodItemId);

            if (singleById == null)
            {
                return(HttpNotFound());
            }

            singleById.ItemName = viewModel.ItemName;

            FoodItem newFoodItem = _foodRepository.Update(singleById);

            _coolMessageHubContext.Clients.All.FoodUpdated(newFoodItem);
            return(Ok(Mapper.Map <FoodItemViewModel>(newFoodItem)));
        }
        public IActionResult Update(int id, [FromBody] FoodItemViewModel foodItem)
        {
            var foodItemToCheck = _foodRepository.GetSingle(id);

            if (foodItemToCheck == null)
            {
                return(NotFound());
            }

            if (id != foodItem.Id)
            {
                return(BadRequest("Ids do not match"));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            FoodItem update = _foodRepository.Update(id, Mapper.Map <FoodItem>(foodItem));

            if (!_foodRepository.Save())
            {
                throw new Exception("Updating a fooditem failed on save.");
            }

            return(Ok(Mapper.Map <FoodItemViewModel>(update)));
        }
        public IHttpActionResult AddFoodToList([FromBody] FoodItemViewModel viewModel)
        {
            try
            {
                if (viewModel == null)
                {
                    return(BadRequest());
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                FoodList singleFoodList = _foodListRepository.GetSingle(x => x.Id == viewModel.FoodListId, "Foods");
                FoodItem item           = Mapper.Map <FoodItem>(viewModel);
                item.Created     = DateTime.Now;
                item.ImageString = CurrentAppSettings.DummyImageName;
                singleFoodList.Foods.Add(item);
                _foodListRepository.Update(singleFoodList);

                int save = _foodListRepository.Save();

                if (save > 0)
                {
                    return(CreatedAtRoute("GetSingleFood", new { foodItemId = item.Id }, Mapper.Map <FoodItemViewModel>(item)));
                }

                return(BadRequest());
            }
            catch (Exception exception)
            {
                return(InternalServerError(exception));
            }
        }
        public IActionResult PartiallyUpdate(int id, [FromBody] JsonPatchDocument <FoodItemViewModel> patchDoc)
        {
            if (patchDoc == null)
            {
                return(BadRequest());
            }

            FoodItem existingEntity = _foodRepository.GetSingle(id);

            if (existingEntity == null)
            {
                return(NotFound());
            }

            FoodItemViewModel foodItemViewModel = Mapper.Map <FoodItemViewModel>(existingEntity);

            patchDoc.ApplyTo(foodItemViewModel, ModelState);

            TryValidateModel(foodItemViewModel);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            FoodItem updated = _foodRepository.Update(id, Mapper.Map <FoodItem>(foodItemViewModel));

            if (!_foodRepository.Save())
            {
                throw new Exception("Updating a fooditem failed on save.");
            }

            return(Ok(Mapper.Map <FoodItemViewModel>(updated)));
        }
 public ActionResult ManageFoodItems(FoodItemViewModel obj)
 {
     try
     {
         FoodItem food = new FoodItem();
         food.Name     = obj.Name;
         food.Price    = obj.Price;
         food.Category = obj.Category;
         db.FoodItems.Add(food);
         db.SaveChanges();
         return(RedirectToAction("ManageFoodItems"));
     }
     catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
     {
         Exception raise = dbEx;
         foreach (var validationErrors in dbEx.EntityValidationErrors)
         {
             foreach (var validationError in validationErrors.ValidationErrors)
             {
                 string message = string.Format("{0}:{1}",
                                                validationErrors.Entry.Entity.ToString(),
                                                validationError.ErrorMessage);
                 raise = new InvalidOperationException(message, raise);
             }
         }
         throw raise;
     }
 }
        public IActionResult Add([FromBody] FoodItemViewModel foodItemViewModel)
        {
            if (foodItemViewModel == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            FoodItem toAdd = Mapper.Map <FoodItem>(foodItemViewModel);

            _foodRepository.Add(toAdd);

            if (!_foodRepository.Save())
            {
                throw new Exception("Creating a fooditem failed on save.");
            }

            FoodItem newFoodItem = _foodRepository.GetSingle(toAdd.Id);

            return(CreatedAtRoute("GetSingleFood", new { id = newFoodItem.Id },
                                  Mapper.Map <FoodItemViewModel>(newFoodItem)));
        }
        public async Task <IActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var food = await db.FoodItems
                       .FirstOrDefaultAsync(f => f.Id == id);

            var foodViewModel = new FoodItemViewModel()
            {
                Id            = food.Id,
                FoodName      = food.FoodName,
                Quality       = food.Quality,
                Quantity      = food.Quantity,
                PurchasesDate = food.PurchasesDate,
                PurchasesTime = food.PurchasesTime,
                Place         = food.Place,
                ExistingImage = food.Image
            };

            if (food == null)
            {
                return(NotFound());
            }

            return(View(food));
        }
        public IActionResult Update(int id, [FromBody] FoodItemViewModel foodItem)
        {
            try
            {
                var foodItemToCheck = _foodRepository.GetSingle(id);

                if (foodItemToCheck == null)
                {
                    return(NotFound());
                }

                if (id != foodItem.Id)
                {
                    return(BadRequest("Ids do not match"));
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                FoodItem update = _foodRepository.Update(id, Mapper.Map <FoodItem>(foodItem));

                return(Ok(Mapper.Map <FoodItemViewModel>(update)));
            }
            catch (Exception exception)
            {
                _logger.LogCritical("Error", exception);
                return(new StatusCodeResult(500));
            }
        }
        public IActionResult PartiallyUpdate(int id, [FromBody] JsonPatchDocument <FoodItemViewModel> patchDoc)
        {
            try
            {
                if (patchDoc == null)
                {
                    return(BadRequest());
                }

                FoodItem existingEntity = _foodRepository.GetSingle(id);

                if (existingEntity == null)
                {
                    return(NotFound());
                }

                FoodItemViewModel foodItemViewModel = Mapper.Map <FoodItemViewModel>(existingEntity);
                patchDoc.ApplyTo(foodItemViewModel, ModelState);

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                FoodItem updated = _foodRepository.Update(id, Mapper.Map <FoodItem>(foodItemViewModel));

                return(Ok(Mapper.Map <FoodItemViewModel>(updated)));
            }
            catch (Exception exception)
            {
                _logger.LogCritical("Error", exception);
                return(new StatusCodeResult(500));
            }
        }
        public async Task <IActionResult> Edit(int id, FoodItemViewModel model)
        {
            if (ModelState.IsValid)
            {
                var food = await db.FoodItems.FindAsync(model.Id);

                food.FoodName        = model.FoodName;
                food.Quality         = model.Quality;
                food.Quantity        = model.Quantity;
                food.PurchasesDate   = model.PurchasesDate;
                food.PurchasesTime   = model.PurchasesTime;
                food.Place           = model.Place;
                food.Password        = model.Password;
                food.ConfirmPassword = model.ConfirmPassword;

                if (model.Image != null)    ///////
                {
                    if (model.ExistingImage != null)
                    {
                        string filePath = Path.Combine(webHostEnvironment.WebRootPath, "Uploads", model.ExistingImage);
                        System.IO.File.Delete(filePath);
                    }

                    food.Image = ProcessUploadedFile(model);
                }
                db.Update(food);
                await db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View());
        }
        public async Task <IActionResult> Create(FoodItemViewModel model)
        {
            if (ModelState.IsValid)
            {
                string   uniqueFileName = ProcessUploadedFile(model);
                FoodItem food           = new FoodItem
                {
                    FoodName        = model.FoodName,
                    Quality         = model.Quality,
                    Quantity        = model.Quantity,
                    PurchasesDate   = model.PurchasesDate,
                    PurchasesTime   = model.PurchasesTime,
                    Place           = model.Place,
                    Password        = model.Password,
                    ConfirmPassword = model.ConfirmPassword,
                    Image           = uniqueFileName
                };

                db.Add(food);
                await db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(model));
        }
Example #13
0
        public IActionResult Pantry()
        {
            FoodItemRepository foodRepo  = new FoodItemRepository();
            FoodItemViewModel  viewModel = new FoodItemViewModel();

            viewModel.foodItems = foodRepo.GetAllFoods();
            return(View(viewModel));
        }
Example #14
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     if (e.Parameter != null)
     {
         var foodModel = e.Parameter as FoodItemViewModel;
         ItemViewModel = foodModel;
     }
 }
        // GET: FoodItems/Create
        public ActionResult Create()
        {
            var model = new FoodItemViewModel(new FoodItem());

            model.FoodItemTypes = db.FoodItemTypes.ToList();

            return(View(model));
        }
Example #16
0
        public async Task <IActionResult> SubmitFoodItem([FromBody] FoodItemViewModel model)
        {
            Dish dish = model.GetDbModel();

            cateringDbContext.Add(dish);
            await cateringDbContext.SaveChangesAsync();

            return(Ok());
        }
Example #17
0
        public async Task <IActionResult> UpdateFoodItem([FromRoute] int itemId, [FromBody] FoodItemViewModel model)
        {
            Dish dish = model.GetDbModel();

            cateringDbContext.Update(dish);
            await cateringDbContext.SaveChangesAsync();

            return(Ok());
        }
Example #18
0
        public ActionResult Update(FoodItemViewModel model)
        {
            if (ModelState.IsValid)
            {
                model.FoodItem.SetAsOriginal();


                if (string.IsNullOrEmpty(model.NewFoodItemType))
                {
                    model.FoodItem.SetFoodItemType(model.SelectedFoodItemType);
                    model.FoodItem.GlycemicIndex = model.FoodItem.GetFoodItemType().GlycemicIndex;
                }
                else
                {
                    FoodItemType fit = new FoodItemType()
                    {
                        TypeName      = model.NewFoodItemType.Trim(),
                        Unit          = model.FoodItem.Unit,
                        Calories      = model.FoodItem.Calories,
                        Carbs         = model.FoodItem.Carbs,
                        Fats          = model.FoodItem.Fats,
                        Protein       = model.FoodItem.Protein,
                        Fibre         = model.FoodItem.Fibre,
                        GlycemicIndex = model.FoodItem.GlycemicIndex
                    };
                    db.FoodItemTypes.Add(fit);
                    db.SaveChanges();
                    model.FoodItem.FoodItemType_Id = fit.Id;
                }
                if (string.IsNullOrEmpty(model.NewCategory))
                {
                    model.FoodItem.SetCategory(model.SelectedCategory);
                }
                else
                {
                    Category cat = new Category()
                    {
                        FoodCategory     = model.NewCategory,
                        FoodItemTypesIds = model.FoodItem.GetFoodItemType().Id.ToString()
                    };

                    db.Categories.Add(cat);
                    db.SaveChanges();

                    model.FoodItem.SetCategory(cat);
                }
                db.FoodItems.Add(model.FoodItem);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            TempData["Model"] = model;
            TempData.Keep();
            return(View("Update", model));
        }
Example #19
0
        public static FoodItemViewModel Convert(IPublishedContent source)
        {
            var destination = new FoodItemViewModel(
                System.Convert.ToString(source.GetProperty("photoOfTheFood").Value),
                System.Convert.ToString(source.GetProperty("foodName").DataValue),
                System.Convert.ToString(source.GetProperty("cuisine").DataValue),
                System.Convert.ToString(source.GetProperty("description").DataValue),
                source.Url,
                source.CreateDate
                );

            return(destination);
        }
 public ActionResult Index(FoodItemViewModel model)
 {
     //model.FoodItem.Category = db.Categories.FirstOrDefault(x => x.Id == model.SelectedCategory);
     //model.FoodItem.FoodItemType = db.FoodItemTypes.FirstOrDefault(x => x.Id == model.SelectedFoodItemType);
     model.FoodItem.SetCategory(model.SelectedCategory);
     model.FoodItem.SetFoodItemType(model.SelectedFoodItemType);
     if (ModelState.IsValid)
     {
         db.FoodItems.Add(model.FoodItem);
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View("Update", model));
 }
Example #21
0
        public async Task<IActionResult> EditFoodItem(FoodItemViewModel model)
        {
            if (!ModelState.IsValid)
            {
                throw new ArgumentException("Model wrong", nameof(model));
            }

            var mappedModel = Mapper.Map<FoodItem>(model);

            if (await FoodItemService.EditFoodItemAsync(mappedModel))
            {
                Response.StatusCode = (int)HttpStatusCode.OK;
                return RedirectToAction("Index");
            }
            return Json(new { success = false });
        }
Example #22
0
        public IActionResult Add([FromBody] FoodItemViewModel foodItemViewModel)
        {
            if (foodItemViewModel == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            FoodItem newFoodItem = _foodRepository.Add(Mapper.Map <FoodItem>(foodItemViewModel));

            return(CreatedAtRoute("GetSingleFood", new { id = newFoodItem.Id }, Mapper.Map <FoodItemViewModel>(newFoodItem)));
        }
        // GET: FoodItems/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(RedirectToAction("FoodItems"));
            }
            FoodItem foodItem = db.FoodItems.Find(id);

            if (foodItem == null)
            {
                return(HttpNotFound());
            }
            FoodItemViewModel model = new FoodItemViewModel(foodItem);

            return(View(model));
        }
        private string ProcessUploadedFile(FoodItemViewModel model)
        {
            string uniqueFileName = null;

            if (model.Image != null)    /////
            {
                string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Uploads");
                uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Image.FileName;    //////
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    model.Image.CopyTo(fileStream); ////////
                }
            }

            return(uniqueFileName);
        }
Example #25
0
        private IEnumerable <FoodItemViewModel> GetFoodItems(MySqlDataReader reader, IEnumerable <FoodItemIngredientViewModel> ingredients)
        {
            while (reader.Read())
            {
                var categoryId = reader.GetInt32("CategoryId");
                var foodItem   = new FoodItemViewModel
                {
                    FoodIngredients = ingredients.Where(x => x.CategoryId == categoryId).ToList(),
                    CategoryId      = categoryId,
                    ItemId          = reader.GetInt32("ItemId"),
                    ItemName        = reader.GetString("ItemName"),
                    Price           = reader.GetDouble("Price")
                };

                yield return(foodItem);
            }
        }
        public IHttpActionResult UpdateFoodInList(int foodItemId, [FromBody] FoodItemViewModel viewModel)
        {
            try
            {
                if (viewModel == null)
                {
                    return(BadRequest());
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                FoodItem singleById = _foodRepository.GetSingleById(foodItemId);

                if (singleById == null)
                {
                    return(NotFound());
                }

                singleById.ItemName = viewModel.ItemName;
                singleById.IsPublic = viewModel.IsPublic;


                if (ImageIsNewImage(viewModel))
                {
                    HandleImage(viewModel, singleById);
                }

                _foodRepository.Update(singleById);

                int save = _foodRepository.Save();

                if (save > 0)
                {
                    return(Ok(Mapper.Map <FoodItemViewModel>(singleById)));
                }

                return(BadRequest());
            }
            catch (Exception exception)
            {
                return(InternalServerError(exception));
            }
        }
        private string SaveImage(FoodItemViewModel viewModel)
        {
            if (String.IsNullOrEmpty(viewModel.ImageString))
            {
                return(String.Empty);
            }

            // Get Filename of new image
            var newFileName = Guid.NewGuid() + ".png";

            Image image = Base64ToImage(viewModel.ImageString.Split(',')[1]);

            string filePath = HttpContext.Current.Server.MapPath(CurrentAppSettings.ImageSaveFolder + newFileName);

            image.Save(filePath);

            return(newFileName);
        }
Example #28
0
        public IHttpActionResult GetRandomImageStringFromList(int id)
        {
            try
            {
                FoodList singleFoodList = _foodListRepository.GetSingle(x => x.Id == id, "Foods");

                if (singleFoodList == null)
                {
                    return(NotFound());
                }

                if (singleFoodList.UserId != CurrentUserId)
                {
                    return(StatusCode(HttpStatusCode.Forbidden));
                }

                if (!singleFoodList.Foods.Any())
                {
                    string imagePath = VirtualPathUtility.ToAbsolute(CurrentAppSettings.ImageSaveFolder + CurrentAppSettings.DummyImageName).TrimStart('/');
                    return(Ok(imagePath));
                }

                Random   random   = new Random();
                int      index    = random.Next(0, singleFoodList.Foods.Count);
                FoodItem foodItem = singleFoodList.Foods.ToList()[index];

                if (String.IsNullOrEmpty(foodItem.ImageString))
                {
                    string imagePath = VirtualPathUtility.ToAbsolute(CurrentAppSettings.ImageSaveFolder + CurrentAppSettings.DummyImageName).TrimStart('/');
                    return(Ok(imagePath));
                }

                FoodItemViewModel foodItemViewModel = Mapper.Map <FoodItemViewModel>(foodItem);
                return(Ok(foodItemViewModel.ImageString));
            }
            catch (Exception exception)
            {
                return(InternalServerError(exception));
            }
        }
        private void HandleImage(FoodItemViewModel viewModel, FoodItem singleById)
        {
            // save new image
            var newFileName = SaveImage(viewModel);

            if (!String.IsNullOrEmpty(newFileName))
            {
                if (singleById.ImageString != CurrentAppSettings.DummyImageName)
                {
                    // if old image is there
                    var oldimagePath = HttpContext.Current.Server.MapPath(CurrentAppSettings.ImageSaveFolder + singleById.ImageString);

                    // delete old image
                    if (File.Exists(oldimagePath))
                    {
                        File.Delete(oldimagePath);
                    }
                }

                // save db entry
                singleById.ImageString = newFileName;
            }
        }
        public IActionResult Add([FromBody] FoodItemViewModel foodItemViewModel)
        {
            try
            {
                if (foodItemViewModel == null)
                {
                    return(BadRequest());
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                FoodItem newFoodItem = _foodRepository.Add(Mapper.Map <FoodItem>(foodItemViewModel));

                return(CreatedAtRoute("GetSingleFood", new { id = newFoodItem.Id }, Mapper.Map <FoodItemViewModel>(newFoodItem)));
            }
            catch (Exception exception)
            {
                _logger.LogCritical("Error", exception);
                return(new StatusCodeResult(500));
            }
        }