public ActionResult Create(RecipeCreateViewModel model) { Recipe newRecipe = new Recipe(); newRecipe.Name = model.Name; newRecipe.Description = model.Description; newRecipe.Products = model.Products; unitOfWork.RecipeRep.Add(newRecipe); try { unitOfWork.Save(); } catch (DbEntityValidationException ex) { foreach (DbEntityValidationResult validationError in ex.EntityValidationErrors) { Response.Write("Object: " + validationError.Entry.Entity.ToString()); Response.Write(""); foreach (DbValidationError err in validationError.ValidationErrors) { Response.Write(err.ErrorMessage + ""); } } } return(RedirectToAction("Index")); }
private void CreateRecipeFromButton() { var recipeCreateViewModel = new RecipeCreateViewModel(); var recipe = new Recipe() { Id = recipeCreateViewModel.Id, Title = recipeCreateViewModel.Title }; }
public async Task <string> CreateAsync(RecipeCreateViewModel model, string userId, StringValues sessionKeysList, StringValues sessionValuesList) { var id = Guid.NewGuid().ToString(); await this.recipeRepository.AddAsync(new Recipe { Id = id, CategoryId = model.CategoryId, Title = model.SanitizedTitle, CookProcedure = model.SanitizedCookProcedure, CookTime = model.CookTime, Serving = model.Serving, Photo = model.Photo, NutritionValueId = id, UserId = userId, CreatedOn = DateTime.UtcNow, }); bool isCorrectlyParsed = false; for (int i = 0; i < sessionKeysList.Count; i++) { isCorrectlyParsed = decimal.TryParse(sessionValuesList[i], NumberStyles.Number, CultureInfo.InvariantCulture, out var parsed); await this.productRepository.AddAsync(new Product { Id = Guid.NewGuid().ToString(), RecipeId = id, Name = sessionKeysList[i].ToString(), Quantity = parsed, }); } await this.nutritionRepository.AddAsync(new NutritionValue { Id = Guid.NewGuid().ToString(), RecipeId = id, Calories = model.NutritionValue.Calories, Carbohydrates = model.NutritionValue.Carbohydrates, Fats = model.NutritionValue.Fats, Fiber = model.NutritionValue.Fiber, Protein = model.NutritionValue.Protein, Salt = model.NutritionValue.Salt, Sugar = model.NutritionValue.Sugar, CreatedOn = DateTime.UtcNow, }); if (isCorrectlyParsed) { await this.recipeRepository.SaveChangesAsync(); await this.productRepository.SaveChangesAsync(); await this.nutritionRepository.SaveChangesAsync(); } return(id); }
public ActionResult Create() { using (var context = new ApplicationDbContext()) { var userService = new UserService(context, HttpContext); var classificationLevels = userService.GetAvailableClassificationLevels(); var viewModel = new RecipeCreateViewModel(classificationLevels); return(View(viewModel)); } }
// GET: Recipes/Create public IActionResult Create() { RecipeCreateViewModel recipeCreateViewModel = new RecipeCreateViewModel { Categories = _categoryService.GetAll(), Complexities = _complexityService.GetAll() }; return(View(recipeCreateViewModel)); }
public IActionResult Create() { var id = Guid.NewGuid().ToString(); var categories = this.categoriesService.GetAll <CategoryDropdownViewModel>(); var viewModel = new RecipeCreateViewModel { Categories = categories, }; return(this.View(viewModel)); }
public async Task <IActionResult> Create(RecipeCreateViewModel model) { if (ModelState.IsValid) { await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(model)); }
public async Task <IActionResult> Create( [Bind("RecipeName", "RecipeDescription", "Servings", "PrepareTime", "UserID", "Image", "Ingredients", "RecipeSteps")] RecipeCreateViewModel model) { Recipe recipe = new Recipe(); recipe.Ingredients = await MatchRecipeProduct(model.Ingredients); if (counter >= recipe.Ingredients.Count) { ModelState.AddModelError("", "Recipe is Required to Have Minimum of 1 Ingredient"); } else if (invalidProducts.Count > 0) { foreach (string invalidProduct in invalidProducts) { ModelState.AddModelError("", "Unable to find matched product for " + invalidProduct); } } if (ModelState.IsValid) { string uniqueFileName = ProcessUploadedFile(model.Image); ApplicationUser user = await _UserManager.FindByIdAsync(model.UserID); recipe.RecipeApprovalStatus = RecipeApprovalStatus.Approved; recipe.AddedDate = DateTime.Now; recipe.RecipeName = model.RecipeName; recipe.UserID = model.UserID; recipe.PrepareTime = model.PrepareTime; recipe.Servings = model.Servings; recipe.RecipeDescription = model.RecipeDescription; recipe.RecipeSteps = model.RecipeSteps; recipe.ImageUrl = uniqueFileName; if (model.PrepareTime.Any(char.IsDigit)) { Regex regex = new Regex(@"^(?<NUMVALUE>\d+.?\d*)\s*(?<STRVALUE>[A-Za-z]*)$", RegexOptions.Singleline); Match match = regex.Match(recipe.PrepareTime); recipe.PrepareTimeDuration = match.Groups["NUMVALUE"].Value; recipe.PrepareTimeMeasurement = match.Groups["STRVALUE"].Value; } _context.Add(recipe); await _context.SaveChangesAsync(); //Change the return URL LATER return(RedirectToAction(nameof(Index))); } return(View(model)); }
public async Task <IActionResult> Create() { RecipeCreateViewModel model = new RecipeCreateViewModel(); ApplicationUser user = await _SignInManager.UserManager.GetUserAsync(User); model.UserID = user.Id; model.FirstName = user.FirstName; model.Ingredients.Add(new IngredientViewModel()); model.RecipeSteps.Add(new RecipeSteps()); ViewData["IngredientServingTypeID"] = new SelectList(_context.Set <ProductServingType>(), "ProductServingTypeID", "ServingType"); return(View(model)); }
public async Task <IActionResult> GroceryListCreate() { var vm = new RecipeCreateViewModel(); vm.Recipes = await _context.Recipes.Select(p => new SelectListItem { Value = p.Id.ToString(), Text = p.Title, Selected = false }).ToListAsync(); return(View(vm)); }
// GET: Recipes/Create public async Task <IActionResult> Create() { //Get current user's UserId. var currentUser = await GetCurrentUserAsync(); var viewModel = new RecipeCreateViewModel { AvailableTech = await _context.Technique.Where(t => t.User.Id == currentUser.Id).ToListAsync(), AvailableIngredients = await _context.Ingredient.Where(i => i.User.Id == currentUser.Id).ToListAsync(), }; return(View(viewModel)); }
public async Task AddReviewShouldCreateANewReviewToRecipe() { var options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options; AutoMapperConfig.RegisterMappings(Assembly.Load("CookingBook.Web.ViewModels")); var dbContext = new ApplicationDbContext(options); var recipeRepo = new EfDeletableEntityRepository <Recipe>(dbContext); var nutritionRepo = new EfDeletableEntityRepository <NutritionValue>(dbContext); var productRepo = new EfDeletableEntityRepository <Product>(dbContext); var userRepo = new EfDeletableEntityRepository <ApplicationUser>(dbContext); var service = new RecipesService(recipeRepo, nutritionRepo, productRepo, userRepo); var category = new Category(); var nutrValue = new NutritionValue(); var user = new ApplicationUser(); var prod = new Collection <RecipeByIdProductsViewModel>(); var recipeCreateViewModel = new RecipeCreateViewModel { CategoryId = 1, CookProcedure = "cookProc", Photo = "photo", Serving = 1, Title = "addNew", CookTime = 2, NutritionValue = new RecipeCreateNutritionValuesViewModel { Calories = 1, Carbohydrates = 1, Fats = 1, Fiber = 1, Protein = 1, Salt = 1, Sugar = 1, }, Products = new List <RecipeCreateProductsViewModel>(), }; string userId = "trayan"; StringValues sv = new StringValues("one"); StringValues sk = new StringValues("1"); var recipeResult = await service.CreateAsync(recipeCreateViewModel, userId, sv, sk); var model = new ReviewForRecipeViewModel { Comment = "commentOne", RecipeId = recipeResult, Score = 5, UserId = "trayan", CreatedOn = DateTime.Now, }; var reviewResult = await service.AddReview(model); Assert.IsType <string>(reviewResult); Assert.NotEmpty(reviewResult); Assert.NotNull(reviewResult); Assert.True(dbContext.Reviews.Any()); }
public async Task EditByAdminShouldChangeRecipe() { var options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options; AutoMapperConfig.RegisterMappings(Assembly.Load("CookingBook.Web.ViewModels")); var dbContext = new ApplicationDbContext(options); var recipeRepo = new EfDeletableEntityRepository <Recipe>(dbContext); var nutritionRepo = new EfDeletableEntityRepository <NutritionValue>(dbContext); var productRepo = new EfDeletableEntityRepository <Product>(dbContext); var userRepo = new EfDeletableEntityRepository <ApplicationUser>(dbContext); var service = new RecipesService(recipeRepo, nutritionRepo, productRepo, userRepo); var category = new Category(); var nutrValue = new NutritionValue(); var user = new ApplicationUser(); var prod = new Collection <RecipeByIdProductsViewModel>(); var recipeCreateViewModel = new RecipeCreateViewModel { CategoryId = 1, CookProcedure = "cookProc", Photo = "photo", Serving = 1, Title = "addNew", CookTime = 2, NutritionValue = new RecipeCreateNutritionValuesViewModel { Calories = 1, Carbohydrates = 1, Fats = 1, Fiber = 1, Protein = 1, Salt = 1, Sugar = 1 }, Products = new List <RecipeCreateProductsViewModel>(), }; string userId = "trayan"; StringValues sv = new StringValues("one"); StringValues sk = new StringValues("1"); var recipeResult = await service.CreateAsync(recipeCreateViewModel, userId, sv, sk); var model = new AdminRecipeViewModel { Id = recipeResult, CategoryId = 5, CookProcedure = "five", CookTime = 5, Photo = "fifthPhoto", Serving = 5, Title = "fifthEdit", }; await service.EditByAdmin(model); Assert.Equal(5, dbContext.Recipes.FirstOrDefault(x => x.Id == recipeResult).CategoryId); }
public ActionResult Create(RecipeCreateViewModel model) { if (model.Tags == null) { this.ModelState.AddModelError(string.Empty, "The recipe must contain at least " + ModelConstants.TagsMinCount + " tag!"); } if (this.ModelState.IsValid) { string userId = this.User.Identity.GetUserId(); this.recipes.Add(model.Title, model.Preparation, model.CategoryId, userId, model.Ingredients, model.RecipeImages, model.Tags); return(this.RedirectToAction("All")); } return(this.View(model)); }
// GET: Recipes/Edit/5 public async Task <IActionResult> Edit(int?id) { RecipeCreateViewModel recipeCreateViewModel = new RecipeCreateViewModel { Categories = _categoryService.GetAll(), Complexities = _complexityService.GetAll(), Recipe = _recipeService.GetEdit(id) }; if (recipeCreateViewModel == null) { return(NotFound()); } return(View(recipeCreateViewModel)); }
public IActionResult GroceryListCreate(RecipeCreateViewModel recipeViewModel) { var RecipeList = new List <Recipe>(); foreach (var recipe in recipeViewModel.Recipes) { if (recipe.Selected) { var recipeId = int.Parse(recipe.Value); RecipeList.Add(_context.Recipes.FirstOrDefault(p => p.Id == recipeId)); } } //await _context.SaveChangesAsync(); return(RedirectToAction(nameof(GroceryListDetails), new { recipeList = RecipeList })); }
// https://www.pluralsight.com/guides/asp-net-mvc-using-multiple-submit-buttons-with-default-model-binding-and-controller-actions public async Task <IActionResult> addRecipe([Bind("Id,Title,Instructions")] RecipeCreateViewModel recipeViewModel) { if (ModelState.IsValid) { var recipe = new Recipe() { Id = recipeViewModel.Id, Title = recipeViewModel.Title, Instructions = recipeViewModel.Instructions }; _context.Add(recipe); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(addIngredient), new { RecipeId = recipe.Id })); } return(View(nameof(Create))); }
public void Add(RecipeCreateViewModel model) { var controlLevelService = new ControlLevelService(_context); var classificationLevelId = controlLevelService.GetIdByLevel(model.ClassificationLevel); var userService = new UserService(_context, _httpContext); var authorId = userService.GetCurrentUserId(); var recipe = new Recipe { Name = model.Name, Text = model.Text, ClassificationLevelId = classificationLevelId, AuthorId = authorId }; _context.Recipes.Add(recipe); }
public async Task <IActionResult> Create(RecipeCreateViewModel viewModel) { //This block of code will join the ingredient table with the recipe table //Check for current user var currentUser = await GetCurrentUserAsync(); //Instantiate instances for recipe, ingredient, and ingredient list var recipe = viewModel.Recipe; var ingredient = viewModel.Ingredient; var ingredList = viewModel.IngredientLists; IngredientList newList = new IngredientList(); ModelState.Remove("Recipe.User"); ModelState.Remove("Recipe.UserId"); ModelState.Remove("Ingredient.Name"); ModelState.Remove("Ingredient.User"); ModelState.Remove("IngredientLists.IngredientId"); if (ModelState.IsValid) { recipe.UserId = currentUser.Id; _context.Add(recipe); newList.RecipeId = recipe.RecipeId; newList.IngredientId = ingredient.IngredientId; newList.Quantity = ingredList.Quantity; newList.Measurement = ingredList.Measurement; _context.Add(newList); await _context.SaveChangesAsync(); return(RedirectToAction("Build", new { id = recipe.RecipeId, Recipe = viewModel })); } //Adds a technique to the recipe viewModel.AvailableTech = await _context.Technique.ToListAsync(); //Add an ingredient to the ingredient list viewModel.AvailableIngredients = await _context.Ingredient.ToListAsync(); return(View(viewModel)); }
// GET: Recipes/Build/5 public async Task <IActionResult> Build(int?id) { //Get current user var currentUser = await GetCurrentUserAsync(); //instantiate an instance of viewmodel. RecipeCreateViewModel viewModel = new RecipeCreateViewModel(); //Check to see if id is null if (id == null) { return(NotFound()); } //Get the context of Recipe var recipe = await _context.Recipe .Include(r => r.Technique) .Include(r => r.User) .Include(r => r.IngredientLists) .ThenInclude(il => il.Ingredient) .FirstOrDefaultAsync(il => il.RecipeId == id); viewModel.Recipe = recipe; /*recipe = await _context.Recipe.FindAsync(id);*/ if (recipe == null) { return(NotFound()); } var ingredList = await _context.IngredientList .Include(i => i.Ingredient) .FirstOrDefaultAsync(il => il.RecipeId == id); viewModel.IngredientLists = ingredList; //Add an ingredient to the ingredient list viewModel.AvailableIngredients = await _context.Ingredient.Where(i => i.User.Id == currentUser.Id).ToListAsync(); viewModel.AvailableTech = await _context.Technique.Where(t => t.User.Id == currentUser.Id).ToListAsync(); return(View(viewModel)); }
public ActionResult Create(RecipeCreateViewModel model) { if (!ModelState.IsValid) { return(View(model)); } try { using (var context = new ApplicationDbContext()) { var recipeService = new RecipeService(context, HttpContext); recipeService.Add(model); context.SaveChanges(); return(RedirectToAction("Index")); } } catch { return(View(model)); } }
public async Task <IActionResult> CreateAsync(RecipeCreateViewModel model) { var userId = this.userManager.GetUserId(this.User); var sessionKeys = this.HttpContext.Request.Form.TryGetValue("Name", out var sessionKeysList); var sessionValues = this.HttpContext.Request.Form.TryGetValue("Quantity", out var sessionValuesList); if (!(this.ModelState.IsValid || sessionKeys || sessionValues)) { return(this.Content("Something went wrong!")); } if (sessionKeysList.Count != sessionValuesList.Count) { return(this.Content("All products should have values!")); } var recipeId = await this.recipesService.CreateAsync(model, userId, sessionKeysList, sessionValuesList); return(this.RedirectToAction(nameof(this.ById), new { id = recipeId })); }
public ActionResult Create() { RecipeCreateViewModel model = new RecipeCreateViewModel(unitOfWork); return(View("Create", model)); }
public async Task <IActionResult> Build(int?id, RecipeCreateViewModel viewModel) { //Get current user var currentUser = await GetCurrentUserAsync(); //Create instances of view model var ingredient = viewModel.Ingredient; var ingredientListObj = viewModel.IngredientLists; var recipeObj = viewModel.Recipe; //Instantiate a new list for storage of recipeId and IngredientId IngredientList newList = new IngredientList(); //Get the context of ingredientlist from the database var ingredList = await _context.IngredientList .Include(i => i.Ingredient) .FirstOrDefaultAsync(il => il.RecipeId == id); viewModel.IngredientLists = ingredList; //Get the context of the recipe from database var recipe = await _context.Recipe .Include(r => r.Technique) .Include(r => r.User) .Include(r => r.IngredientLists) .ThenInclude(il => il.Ingredient) .FirstOrDefaultAsync(il => il.RecipeId == id); viewModel.Recipe = recipe; //Get the dropdowns for ingredients and available techniques viewModel.AvailableIngredients = await _context.Ingredient.Where(i => i.User.Id == currentUser.Id).ToListAsync(); viewModel.AvailableTech = await _context.Technique.Where(t => t.User.Id == currentUser.Id).ToListAsync(); //Check to se if the recipe id is the same as the id passed into the method if (id != recipe.RecipeId) { return(NotFound()); } //Made ModelState valid by removing invalid values ModelState.Remove("Recipe.User"); ModelState.Remove("Recipe.UserId"); ModelState.Remove("Recipe.Description"); ModelState.Remove("Recipe.Directions"); ModelState.Remove("Ingredient.Name"); ModelState.Remove("Ingredient.User"); ModelState.Remove("Ingredient.IngredientId"); ModelState.Remove("IngredientLists.IngredientId"); //check to see if the ModelState is valid if (ModelState.IsValid) { //Check to see if the ingredientId is valid. 0 is an invalid value for the ingredientId, if so, prompt a message to alert the user. if (ingredient.IngredientId == 0) { ModelState.AddModelError("", "You must select an ingredient."); } //Check to see if the ingredient already exists on the ingredient list, if so, prompt a message to alert the user. else if (viewModel.IngredientLists.IngredientId == ingredient.IngredientId && viewModel.IngredientLists.RecipeId == recipe.RecipeId) { ModelState.AddModelError("", "This ingredient is already in the recipe."); } //If both conditions have been passed make all the necessary changes that the user has made to the fields. else { newList.RecipeId = recipe.RecipeId; newList.IngredientId = ingredient.IngredientId; newList.Quantity = ingredientListObj.Quantity; newList.Measurement = ingredientListObj.Measurement; recipe.Title = recipeObj.Title; recipe.Description = recipeObj.Description; recipe.UserId = currentUser.Id; recipe.TechniqueId = recipeObj.TechniqueId; recipe.Directions = recipeObj.Directions; recipe.Comment = recipeObj.Comment; _context.Update(recipe); _context.Add(newList); await _context.SaveChangesAsync(); return(RedirectToAction("Build", new { id = recipe.RecipeId })); } } //Check to see if the viewmodel is null if (viewModel == null) { return(NotFound()); } return(View(viewModel)); }
public async Task <IActionResult> Create( [Bind("RecipeName", "RecipeDescription", "Servings", "PrepareTime", "UserID", "Image", "Ingredients", "RecipeSteps")] RecipeCreateViewModel model) { Recipe recipe = new Recipe(); int counter = 0; foreach (IngredientViewModel ingredient in model.Ingredients) { if (string.IsNullOrEmpty(ingredient.IngredientName) || string.IsNullOrEmpty(ingredient.ServingContent)) { counter++; continue; } Category category = _context.Category.Where(c => c.CategoryName.ToLower().Contains(ingredient.IngredientName.ToLower())).FirstOrDefault(); Product product = null; if (category != null) { product = await _context.Product.Include(p => p.ServingType).Include(p => p.Category) .Where(p => p.Category.CategoryName == category.CategoryName).OrderByDescending(p => p.ProductStock).FirstOrDefaultAsync(); } else { product = await _context.Product.Include(p => p.ServingType).Where(p => p.ProductName.ToLower().Contains(ingredient.IngredientName.ToLower())) .OrderByDescending(p => p.ProductStock) .FirstOrDefaultAsync(); } if (product == null) { ModelState.AddModelError("", "Unable to find matched product for " + ingredient.IngredientName); } else { //MIGHT NEED CHANGE COMPARE SERVING CONTENT Ingredient ingredientModel = new Ingredient() { ProductID = product.ProductID, ServingContent = ingredient.ServingContent, IngredientName = ingredient.IngredientName, Quantity = 1 }; recipe.Ingredients.Add(ingredientModel); } } if (counter == model.Ingredients.Count) { ModelState.AddModelError("", "Recipe is Required to Have Minimum of 1 Ingredient"); } if (ModelState.IsValid) { string uniqueFileName = ProcessUploadedFile(model.Image); ApplicationUser user = await _UserManager.FindByIdAsync(model.UserID); bool isAdmin = await _UserManager.IsInRoleAsync(user, "ADMIN"); recipe.RecipeApprovalStatus = isAdmin? RecipeApprovalStatus.Approved : RecipeApprovalStatus.Pending; recipe.AddedDate = DateTime.Now; if (isAdmin) { recipe.ApprovedDate = DateTime.Now; } recipe.RecipeName = model.RecipeName; recipe.UserID = model.UserID; recipe.PrepareTime = model.PrepareTime; recipe.Servings = model.Servings; recipe.RecipeDescription = model.RecipeDescription; recipe.RecipeSteps = model.RecipeSteps; recipe.ImageUrl = uniqueFileName; if (model.PrepareTime.Any(char.IsDigit)) { Regex regex = new Regex(@"^(?<NUMVALUE>\d+.?\d*)\s*(?<STRVALUE>[A-Za-z]*)$", RegexOptions.Singleline); Match match = regex.Match(recipe.PrepareTime); recipe.PrepareTimeDuration = match.Groups["NUMVALUE"].Value; recipe.PrepareTimeMeasurement = match.Groups["STRVALUE"].Value; } _context.Add(recipe); await _context.SaveChangesAsync(); //Change the return URL LATER if (isAdmin) { return(RedirectToAction("Index", "AdminRecipes")); } else { return(RedirectToAction("Index", "Manage", new { pageName = "MyRecipes" })); } } return(View(model)); }