コード例 #1
0
        public async Task <ActionResult> PostRecipe(RecipeInputModel input)
        {
            var user = this.currentUser.UserId;

            var category = await this.categories.Find(input.Category);

            if (category == null)
            {
                return(BadRequest(Result.Failure("Category does not exist.")));
            }

            var recipe = new Recipe
            {
                Name            = input.Name,
                ImageUrl        = input.ImageUrl,
                Protein         = input.Protein,
                Carbs           = input.Carbs,
                Fat             = input.Fat,
                Price           = input.Price,
                PreparationTime = input.PreparationTime,
                User            = user,
                Category        = category,
                Micronutrients  = new Micronutrients
                {
                    Salt      = input.Salt,
                    Potassium = input.Potassium
                },
                Instructions = input.Instructions
            };

            await this.recipes.Save(recipe);

            return(Result.Success);
        }
コード例 #2
0
        public ActionResult Create(RecipeInputModel recipe)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.PartialView(recipe));
            }

            var newRecipe = this.recipes.Create(
                this.sanitizer.Sanitize(recipe.Title),
                this.sanitizer.Sanitize(recipe.Description),
                this.sanitizer.Sanitize(recipe.CookingTime),
                this.sanitizer.Sanitize(recipe.RecipeImage));

            if (this.User.Identity.IsAuthenticated)
            {
                newRecipe.AuthorId = this.User.Identity.GetUserId();
            }

            newRecipe.CreatedOn = DateTime.UtcNow;

            this.recipes.Add(newRecipe);

            var resultRecipe = this.Mapper.Map <RecipeInputModel>(newRecipe);

            this.TempData["Notification"] = "Recipe was successfully added!";

            return(this.PartialView(resultRecipe));
        }
コード例 #3
0
        public async Task <ActionResult> Create([FromBody] RecipeInputModel input)
        {
            var isTitleAlreadyExisting = await this.recipesService.IsTitleAlreadyExistingAsync(input.Title);

            if (isTitleAlreadyExisting)
            {
                return(this.BadRequest(new BadRequestViewModel
                {
                    Message = Messages.AlreadyExistsRecipe,
                }));
            }

            try
            {
                var user = await this.userManager.FindByNameAsync(this.User.Identity.Name);

                await this.recipesService.CreateAsync(input.Title, input.Content, input.Portions, input.PreparationTime, input.CookingTime, input.CategoryName, input.Picture, input.Ingredients, user.Id);

                return(this.Ok(new
                {
                    Message = Messages.SuccessfullyAdded,
                }));
            }
            catch (Exception)
            {
                return(this.BadRequest(new BadRequestViewModel
                {
                    Message = Messages.UnknownError,
                }));
            }
        }
コード例 #4
0
        public async Task DoesRecipeCreateAsyncThrowsNullReferenceExceptionWhenNoSuchCookingVessel()
        {
            var recipesList = new List <Recipe>();

            var service = this.CreateMockAndConfigureService(
                recipesList,
                new List <Category>(),
                new List <CategoryRecipe>(),
                new List <Ingredient>(),
                new List <Nutrition>(),
                new List <RecipeIngredient>(),
                new List <RecipeImage>(),
                new List <CookingVessel>(),
                new List <UserRecipe>(),
                new List <ApplicationUser>());

            var recipeToCreate = new RecipeInputModel
            {
                Name            = TestRecipeName,
                CookingVesselId = TestCookingVesselId,
            };

            await Assert.ThrowsAsync <NullReferenceException>(async() =>
                                                              await service.CreateAsync(TestUserId, recipeToCreate, TestRootPath));
        }
コード例 #5
0
        public async Task DoesRecipeCreateAsyncThrowsArgumentExceptionWhenRecipeWithSuchNameAlreadyExists()
        {
            var recipesList = new List <Recipe>
            {
                new Recipe
                {
                    Name = TestRecipeName,
                },
            };

            var service = this.CreateMockAndConfigureService(
                recipesList,
                new List <Category>(),
                new List <CategoryRecipe>(),
                new List <Ingredient>(),
                new List <Nutrition>(),
                new List <RecipeIngredient>(),
                new List <RecipeImage>(),
                new List <CookingVessel>(),
                new List <UserRecipe>(),
                new List <ApplicationUser>());

            var recipeToCreate = new RecipeInputModel
            {
                Name = TestRecipeName,
            };

            await Assert.ThrowsAsync <ArgumentException>(async() =>
                                                         await service.CreateAsync(TestUserId, recipeToCreate, TestRootPath));
        }
コード例 #6
0
        public async Task <IActionResult> Create()
        {
            var recipe = new RecipeInputModel
            {
                Categories     = await this.categoriesService.GetAllCategoriesSelectListAsync(),
                Ingredients    = await this.ingredientsService.GetAllIngredientsSelectListAsync(),
                CookingVessels = await this.cookingVesselsService.GetAllCookingVesselsSelectListAsync(),
            };

            return(this.View(recipe));
        }
コード例 #7
0
        public ActionResult Create(RecipeInputModel model)
        {
            if (model != null && this.ModelState.IsValid)
            {
                var recipe = Mapper.Map <Recipe>(model);
                this.Data.Recipes.Add(recipe);
                this.Data.SaveChanges();

                return(this.RedirectToAction(x => x.Details(recipe.Id)));
            }

            this.LoadCategories();
            return(this.View(model));
        }
コード例 #8
0
        public async Task <IActionResult> Post(RecipeInputModel inputModel)
        {
            var userId = this.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
            var user   = await this.userManager.FindByIdAsync(userId);

            var recipeId = await this.recipeService.PostAsync(inputModel.Title, inputModel.Description, inputModel.ImageURL, user);

            foreach (var ingredient in inputModel.Ingredients)
            {
                await this.ingredientService.Create(ingredient.IngredientName, ingredient.Amount, ingredient.Type, recipeId);
            }

            return(this.Created("recipe", new { id = recipeId }));
        }
コード例 #9
0
        public IActionResult Create(RecipeInputModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View());
            }

            var userId = this.userManager.GetUserId(this.HttpContext.User);
            var recipe = this.mapper.Map <Recipe>(model);

            recipe.Level  = Enum.Parse <DifficultyLevel>(model.Level);
            recipe.Date   = DateTime.Now;
            recipe.UserId = userId;

            this.recipes.Create(recipe);

            return(this.RedirectToAction("All", "Recipes"));
        }
コード例 #10
0
        public async Task <IActionResult> Create(RecipeInputModel inputModel)
        {
            if (!this.ModelState.IsValid)
            {
                inputModel.Categories = await this.categoriesService.GetAllCategoriesSelectListAsync();

                inputModel.Ingredients = await this.ingredientsService.GetAllIngredientsSelectListAsync();

                inputModel.CookingVessels = await this.cookingVesselsService.GetAllCookingVesselsSelectListAsync();

                return(this.View(inputModel));
            }

            var rootPath = this.webHostEnvironment.WebRootPath;
            var userId   = this.userManager.GetUserId(this.User);

            await this.recipesService.CreateAsync(userId, inputModel, rootPath);

            return(this.RedirectToAction(nameof(this.All)));
        }
コード例 #11
0
        public async Task <ActionResult <bool> > AddRecipe([FromBody] RecipeInputModel model)
        {
            if (ModelState.IsValid)
            {
                var recipe = new Recipe
                {
                    Name = model.Name,
                    DurationInMinutes = model.DurationInMinutes,
                    HealthyStatus     = model.HealthyStatus,
                    CreatedOn         = DateTime.UtcNow
                };
                _context.Recipes.Add(recipe);

                foreach (var ingredient in model.Ingredients)
                {
                    var ing = new Ingredient
                    {
                        Recipe         = recipe,
                        Name           = ingredient.Name,
                        Quantity       = ingredient.Quantity,
                        UnityOfMeasure = ingredient.UnityOfMeasure,
                        CreatedOn      = DateTime.UtcNow
                    };
                    _context.Ingredients.Add(ing);

                    // Add relation
                    _context.RecipeIngredients.Add(new RecipeIngredient
                    {
                        Recipe     = recipe,
                        Ingredient = ing
                    });
                }

                return(await _context.SaveChangesAsync() > 0);
            }

            return(false);
        }
コード例 #12
0
        public IActionResult Process(RecipeInputModel model)
        {
            var sessionUId = HttpContext.Session.GetInt32("_Userid");

            // controller action method to process new recipes
            if (!ModelState.IsValid || model.Ingredients == null)
            {
                var user = _db.Users.FirstOrDefault(u => u.Id == sessionUId);

                // this block will grab the recipe items, only this user has entered before
                if (user != null)
                {
                    var userRecipesIds       = _db.Recipes.Where(r => r.UploaderId == user.Id).Select(r => r.Id).ToList();
                    var recipeIngredientsIds =
                        _db.RecipeIngredients.Where(ri => userRecipesIds.Contains(ri.RecipeId))
                        .Select(ri => ri.IngredientId).ToList();
                    var ingredients = _db.Ingredients.Where(i => recipeIngredientsIds.Contains(i.Id)).ToList();
                    ViewData["ingredients"] = ingredients;
                }

                var dbCategories = _db.Categories.OrderBy(s => s.Name).ToList();
                ViewData["categories"] = dbCategories;
                if (model.Ingredients == null)
                {
                    ModelState.AddModelError("ingDiv", "Ingredients are required");
                }

                return(View("New"));
            }

            var catId  = _db.Categories.First(u => u.Name == model.Category).Id;
            var recipe = new Recipe();

            if (model.Photo != null) // user provided photo
            {
                var size   = model.Photo.Length;
                var stream = new MemoryStream();
                if (size > 0)
                {
                    using (stream)
                    {
                        model.Photo.CopyTo(stream);
                    }
                }

                recipe = new Recipe
                {
                    Name        = model.Name,
                    Description = model.Description,
                    Instruction = model.Instruction,
                    CategoryId  = catId,
                    Photo       = stream.ToArray(),
                    UploaderId  = sessionUId.Value,
                    CreatedAt   = DateTime.Now
                };
                _db.Recipes.Add(recipe);
            }
            else // user did not provide photo
            {
                recipe = new Recipe
                {
                    Name        = model.Name,
                    Description = model.Description,
                    Instruction = model.Instruction,
                    CategoryId  = catId,
                    UploaderId  = sessionUId.Value,
                    CreatedAt   = DateTime.Now
                };
                _db.Recipes.Add(recipe);
            }

            _db.SaveChanges();

            foreach (var ingredientItem in model.Ingredients)
            {
                var ingredient   = new Ingredient.Ingredient();
                var dbIngredient = _db.Ingredients.SingleOrDefault(i => i.Name == ingredientItem.Ingredient);
                if (dbIngredient == null)
                {
                    ingredient = new Ingredient.Ingredient
                    {
                        Name      = ingredientItem.Ingredient,
                        CreatedAt = DateTime.Now
                    };
                    _db.Ingredients.Add(ingredient);
                    _db.SaveChanges();
                }
                else
                {
                    ingredient = dbIngredient;
                }

                // checking for duplicate recipe ingredients
                var dupe = _db.RecipeIngredients.FirstOrDefault(ri =>
                                                                ri.RecipeId == recipe.Id && ri.IngredientId == ingredient.Id);
                if (dupe == null)
                {
                    var recipeIngredient = new RecipeIngredients
                    {
                        IngredientId = ingredient.Id,
                        RecipeId     = recipe.Id,
                        Amount       = ingredientItem.Amount,
                        AmountType   = ingredientItem.AmountType
                    };
                    _db.RecipeIngredients.Add(recipeIngredient);
                    _db.SaveChanges();
                }
            }

            return(RedirectToAction("Page", new { recipeId = recipe.Id }));
        }
コード例 #13
0
        public IActionResult Update(RecipeInputModel model)
        {
            if (!ModelState.IsValid || model.Ingredients == null)
            {
                return(RedirectToAction("Edit", new { recipeId = model.RecipeId }));
            }

            var category = _db.Categories.SingleOrDefault(c => c.Name == model.Category);
            int categoryId;

            var dbRecipe = _db.Recipes.SingleOrDefault(r => r.Id == model.RecipeId);

            if (dbRecipe == null)
            {
                return(RedirectToAction("Index"));
            }

            // checking if the user specified a category
            if (category == null)
            {
                categoryId = dbRecipe.CategoryId;
            }
            else
            {
                categoryId = category.Id;
            }

            // updating selected recipe
            dbRecipe.Name        = model.Name;
            dbRecipe.Description = model.Description;
            dbRecipe.Instruction = model.Instruction;
            dbRecipe.CategoryId  = categoryId;
            dbRecipe.UpdatedAt   = DateTime.Now;
            if (model.Photo != null)
            {
                var stream = new MemoryStream();
                if (model.Photo.Length > 0)
                {
                    using (stream)
                    {
                        model.Photo.CopyTo(stream);
                    }

                    dbRecipe.Photo = stream.ToArray();
                }
            }

            _db.SaveChanges();

            // removing ingredients have been removed
            var deleteIngredients =
                from recipeIngredients in _db.RecipeIngredients
                where recipeIngredients.RecipeId == model.RecipeId
                select recipeIngredients;

            foreach (var ingredient in deleteIngredients)
            {
                _db.RecipeIngredients.Remove(ingredient);
            }

            _db.SaveChanges();

            // adding back ingredients that are still there, checking for duplicates
            foreach (var ingredientItem in model.Ingredients)
            {
                var ingredient   = new Ingredient.Ingredient();
                var dbIngredient = _db.Ingredients.SingleOrDefault(i => i.Name == ingredientItem.Ingredient);
                if (dbIngredient == null)
                {
                    ingredient = new Ingredient.Ingredient
                    {
                        Name      = ingredientItem.Ingredient,
                        CreatedAt = DateTime.Now
                    };
                    _db.Ingredients.Add(ingredient);
                    _db.SaveChanges();
                }
                else
                {
                    ingredient = dbIngredient;
                }

                var dupe = _db.RecipeIngredients.FirstOrDefault(ri =>
                                                                ri.RecipeId == dbRecipe.Id && ri.IngredientId == ingredient.Id);
                if (dupe == null)
                {
                    var recipeIngredient = new RecipeIngredients
                    {
                        IngredientId = ingredient.Id,
                        RecipeId     = dbRecipe.Id,
                        Amount       = ingredientItem.Amount,
                        AmountType   = ingredientItem.AmountType
                    };
                    _db.RecipeIngredients.Add(recipeIngredient);
                    _db.SaveChanges();
                }
            }

            return(RedirectToAction("Page", new { recipeId = dbRecipe.Id }));
        }
コード例 #14
0
        public async Task <string> CreateAsync(string userId, RecipeInputModel inputModel, string rootPath)
        {
            if (this.recipesRepository.All().Any(x => x.Name == inputModel.Name))
            {
                throw new ArgumentException(ExceptionMessages.RecipeAlreadyExists, inputModel.Name);
            }

            var cookingVessel = this.cookingVesselRepository.All()
                                .FirstOrDefault(x => x.Id == inputModel.CookingVesselId);

            if (cookingVessel == null)
            {
                throw new NullReferenceException(
                          string.Format(ExceptionMessages.CookingVesselMissing, inputModel.CookingVesselId));
            }

            var recipe = new Recipe
            {
                Name            = inputModel.Name,
                PreparationTime = TimeSpan.FromMinutes(inputModel.PreparationTime),
                CookingTime     = TimeSpan.FromMinutes(inputModel.CookingTime),
                Preparation     = inputModel.Preparation,
                Notes           = inputModel.Notes,
                Portions        = inputModel.Portions,
                CreatorId       = userId,
                CookingVesselId = inputModel.CookingVesselId,
            };

            cookingVessel.Recipes.Add(recipe);

            var user = this.userRepository.All()
                       .FirstOrDefault(x => x.Id == userId);

            user.CreatedRecipes.Add(recipe);

            foreach (var imageFile in inputModel.Images)
            {
                var image = new RecipeImage();
                image.ImageUrl = $"/assets/img/recipes/{image.Id}.jpg";
                image.RecipeId = recipe.Id;

                string imagePath = rootPath + image.ImageUrl;

                using (FileStream stream = new FileStream(imagePath, FileMode.Create))
                {
                    await imageFile.CopyToAsync(stream);
                }

                recipe.Images.Add(image);
            }

            foreach (var categoryId in inputModel.SelectedCategories)
            {
                var category = this.categoryRepository.All()
                               .FirstOrDefault(x => x.Id == categoryId);

                if (category == null)
                {
                    throw new NullReferenceException(
                              string.Format(ExceptionMessages.CategoryMissing, categoryId));
                }

                var categoryRecipe = new CategoryRecipe
                {
                    CategoryId = categoryId,
                    RecipeId   = recipe.Id,
                };

                recipe.Categories.Add(categoryRecipe);
                category.Recipes.Add(categoryRecipe);
            }

            foreach (var ingredientInputModel in inputModel.SelectedIngredients)
            {
                var ingredient = this.ingredientRepository.All()
                                 .FirstOrDefault(x => x.Id == ingredientInputModel.IngredientId);

                if (ingredient == null)
                {
                    throw new NullReferenceException(
                              string.Format(ExceptionMessages.IngredientMissing, ingredientInputModel.IngredientId));
                }

                var ingredientRecipe = new RecipeIngredient
                {
                    IngredientId  = ingredientInputModel.IngredientId,
                    WeightInGrams = ingredientInputModel.WeightInGrams,
                    PartOfRecipe  = ingredientInputModel.PartOfRecipe,
                    RecipeId      = recipe.Id,
                };

                recipe.Ingredients.Add(ingredientRecipe);
                ingredient.Recipies.Add(ingredientRecipe);
            }

            await this.recipesRepository.AddAsync(recipe);

            await this.recipesRepository.SaveChangesAsync();

            await this.recipeImageRepository.SaveChangesAsync();

            await this.categoryRecipesRepository.SaveChangesAsync();

            await this.ingredientRecipeRepository.SaveChangesAsync();

            var recipeWithNutrition = this.recipesRepository.All()
                                      .Where(x => x.Name == inputModel.Name)
                                      .FirstOrDefault();

            var recipeIngredients = await this.ingredientRecipeRepository.All()
                                    .Where(x => x.RecipeId == recipeWithNutrition.Id)
                                    .ToListAsync();

            if (recipeWithNutrition.Ingredients.Count > 0)
            {
                var nutritions = this.nutritionRepository.All()
                                 .ToList()
                                 .Where(x => recipeIngredients.Any(y => y.IngredientId == x.IngredientId))
                                 .ToList();

                if (nutritions.All(x => x != null) && nutritions.Count() > 0)
                {
                    await this.nutritionsService.CalculateNutritionForRecipeAsync(recipeWithNutrition.Id);
                }
                else
                {
                    recipeWithNutrition.Nutrition = null;
                }
            }

            return(recipeWithNutrition.Id);
        }
コード例 #15
0
        public async Task DoesRecipeCreateAsyncWorkCorrectly()
        {
            var recipesList = new List <Recipe>();

            var cookingVesselList = new List <CookingVessel>
            {
                new CookingVessel
                {
                    Id     = TestCookingVesselId,
                    Name   = TestCookingVesselName,
                    Height = TestCookingVesselHeight,
                    Area   = TestCookingVesselArea,
                    Volume = TestCookingVesselVolume,
                },
            };

            var userList = new List <ApplicationUser>
            {
                new ApplicationUser
                {
                    Id       = TestUserId,
                    UserName = TestUserUsername,
                },
            };

            var categoryList = new List <Category>
            {
                new Category
                {
                    Id   = TestCategoryId,
                    Name = TestCategoryName,
                },
            };

            var recipeIngredientsList = new List <RecipeIngredient>
            {
                new RecipeIngredient
                {
                    RecipeId      = TestRecipeId,
                    IngredientId  = TestIngredientId,
                    PartOfRecipe  = TestPartOfRecipeIngredient,
                    WeightInGrams = TestWeightIngredient,
                },
            };

            var ingredientList = new List <Ingredient>
            {
                new Ingredient
                {
                    Id   = TestIngredientId,
                    Name = TestIngredientName,
                },
            };

            var nutritionList = new List <Nutrition>
            {
                new Nutrition
                {
                    Id            = TestNutritionId,
                    Calories      = 100,
                    Carbohydrates = 100,
                    Fats          = 100,
                    Proteins      = 100,
                    Fibres        = 100,
                    IngredientId  = TestIngredientId,
                },
            };

            var service = this.CreateMockAndConfigureService(
                recipesList,
                categoryList,
                new List <CategoryRecipe>(),
                ingredientList,
                nutritionList,
                recipeIngredientsList,
                new List <RecipeImage>(),
                cookingVesselList,
                new List <UserRecipe>(),
                userList);

            using FileStream stream = File.OpenRead(TestImageName);
            var file = new FormFile(stream, 0, stream.Length, null, stream.Name)
            {
                Headers     = new HeaderDictionary(),
                ContentType = TestImageContentType,
            };

            var recipeToCreate = new RecipeInputModel
            {
                Name            = TestRecipeName,
                CookingTime     = TestCookingTime,
                CookingVesselId = TestCookingVesselId,
                Notes           = TestNotes,
                Preparation     = TestPreparation,
                PreparationTime = TestPreparationTime,
                Portions        = TestPortionsCount,
                Images          = new List <IFormFile>
                {
                    file,
                },
                SelectedCategories = new List <int>
                {
                    TestCategoryId,
                },
                SelectedIngredients = new List <RecipeIngredientInputModel>
                {
                    new RecipeIngredientInputModel
                    {
                        IngredientId  = TestIngredientId,
                        PartOfRecipe  = TestPartOfRecipeIngredient,
                        WeightInGrams = TestWeightIngredient,
                    },
                },
            };

            await service.CreateAsync(TestUserId, recipeToCreate, TestRootPath);

            var count = recipesList.Count();

            Assert.Equal(1, count);
        }
コード例 #16
0
        public async Task DoesRecipeCreateAsyncThrowsNullReferenceExceptionWhenNoSuchIngredient()
        {
            var recipesList       = new List <Recipe>();
            var cookingVesselList = new List <CookingVessel>
            {
                new CookingVessel
                {
                    Id     = TestCookingVesselId,
                    Name   = TestCookingVesselName,
                    Height = TestCookingVesselHeight,
                    Area   = TestCookingVesselArea,
                    Volume = TestCookingVesselVolume,
                },
            };

            var userList = new List <ApplicationUser>
            {
                new ApplicationUser
                {
                    Id       = TestUserId,
                    UserName = TestUserUsername,
                },
            };

            var categoryList = new List <Category>
            {
                new Category
                {
                    Id   = TestCategoryId,
                    Name = TestCategoryName,
                },
            };

            var service = this.CreateMockAndConfigureService(
                recipesList,
                categoryList,
                new List <CategoryRecipe>(),
                new List <Ingredient>(),
                new List <Nutrition>(),
                new List <RecipeIngredient>(),
                new List <RecipeImage>(),
                cookingVesselList,
                new List <UserRecipe>(),
                userList);

            using FileStream stream = File.OpenRead(TestImageName);
            var file = new FormFile(stream, 0, stream.Length, null, stream.Name)
            {
                Headers     = new HeaderDictionary(),
                ContentType = TestImageContentType,
            };

            var recipeToCreate = new RecipeInputModel
            {
                Name            = TestRecipeName,
                CookingTime     = TestCookingTime,
                CookingVesselId = TestCookingVesselId,
                Notes           = TestNotes,
                Preparation     = TestPreparation,
                PreparationTime = TestPreparationTime,
                Portions        = TestPortionsCount,
                Images          = new List <IFormFile>
                {
                    file,
                },
                SelectedCategories = new List <int>
                {
                    TestCategoryId,
                },
                SelectedIngredients = new List <RecipeIngredientInputModel>
                {
                    new RecipeIngredientInputModel
                    {
                        IngredientId  = TestIngredientId,
                        PartOfRecipe  = TestPartOfRecipeIngredient,
                        WeightInGrams = TestWeightIngredient,
                    },
                },
            };

            await Assert.ThrowsAsync <NullReferenceException>(async() =>
                                                              await service.CreateAsync(TestUserId, recipeToCreate, TestRootPath));
        }