public void TestGetAllCategoryRecipe() { var repository = new Mock <IRepository <CategoryRecipe> >(); var categoryRecipes = new List <CategoryRecipe>(); var r1 = new CategoryRecipe() { categoryId = 1, name = "fromage" }; var r2 = new CategoryRecipe() { categoryId = 2, name = "fruit" }; var r3 = new CategoryRecipe() { categoryId = 3, name = "poisson" }; categoryRecipes.Add(r1); categoryRecipes.Add(r2); categoryRecipes.Add(r3); repository.Setup(x => x.GetAll()).Returns(categoryRecipes.AsQueryable()).Verifiable(); var controller = new CategoryRecipesController(repository.Object); controller.Request = new HttpRequestMessage(); controller.Configuration = new HttpConfiguration(); var response = controller.Get(); IQueryable <CategoryRecipe> s; Assert.IsTrue(response.TryGetContentValue <IQueryable <CategoryRecipe> >(out s)); Assert.AreEqual(categoryRecipes.AsQueryable().Count(), s.Count()); Assert.AreEqual(categoryRecipes.AsQueryable().First(), s.First()); }
public HttpResponseMessage Post(CategoryRecipe entity) { var res = _repo.Add(entity); if (!res) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } return(Request.CreateResponse(HttpStatusCode.Created, entity)); }
public HttpResponseMessage Get(int id) { CategoryRecipe res = _repo.Get(id); if (res == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } return(Request.CreateResponse(res)); }
public void TestPostCategoryRecipe() { var repository = new Mock <IRepository <CategoryRecipe> >(); var categoryRecipe = new CategoryRecipe() { categoryId = 1, name = "fromage" }; repository.Setup(x => x.Add(categoryRecipe)).Returns(true).Verifiable(); var controller = new CategoryRecipesController(repository.Object); controller.Request = new HttpRequestMessage(); controller.Configuration = new HttpConfiguration(); var response = controller.Post(categoryRecipe); CategoryRecipe s; Assert.IsTrue(response.TryGetContentValue <CategoryRecipe>(out s)); Assert.AreEqual(categoryRecipe, s); Assert.AreNotEqual(10, s.categoryId); }
public static void Seed(RecipeBookContext recipeBookContext, ILoggerFactory loggerFactory, IWebHostEnvironment hostingEnv) { var logger = loggerFactory.CreateLogger(typeof(RecipeBookContextSeed)); try { if (recipeBookContext.Authors.Any()) { logger.LogInformation("The database has already been seeded"); return; } var author = new Author { IdentityUsername = AuthorizationConstants.DEFAULT_USER_USERNAME }; recipeBookContext.Authors.Add(author); recipeBookContext.SaveChanges(); var recipe = new Recipe { Name = "Sesame seed burger buns", Description = "Homemade Hamburger Buns", DatePosted = DateTime.Today, // TODO: Implement photo saving Photo = "", Rating = 4.5f, Course = Course.Mains, Author = author, AuthorId = author.Id }; recipeBookContext.Recipes.Add(recipe); recipeBookContext.SaveChanges(); var instructions = GetSeedDataFromJson <Instruction>(hostingEnv, path: "Data/SeedData/recipeInstructions.json", logger); foreach (var instruction in instructions) { instruction.RecipeId = recipe.Id; } recipeBookContext.Instructions.AddRange(instructions); recipeBookContext.SaveChanges(); var ingredients = GetSeedDataFromJson <Ingredient>(hostingEnv, path: "Data/SeedData/recipeIngredients.json", logger); foreach (var ingredient in ingredients) { ingredient.RecipeId = recipe.Id; } recipeBookContext.Ingredients.AddRange(ingredients); recipeBookContext.SaveChanges(); var comments = GetSeedDataFromJson <Comment>(hostingEnv, path: "Data/SeedData/recipeComments.json", logger); foreach (var comment in comments) { comment.RecipeId = recipe.Id; comment.AuthorId = author.Id; comment.DatePosted = DateTime.Today; } recipeBookContext.Comments.AddRange(comments); recipeBookContext.SaveChanges(); var categories = new List <Category>() { new Category { CategoryName = "Healthy" }, new Category { CategoryName = "Cakes and baking" }, new Category { CategoryName = "Cheap and healthy" } }; recipeBookContext.Categories.AddRange(categories); recipeBookContext.SaveChanges(); var categoryRecipe = new CategoryRecipe() { CategoryId = categories.Single(category => category.CategoryName == "Cakes and baking").Id, RecipeId = recipe.Id }; recipeBookContext.CategoryRecipe.AddRange(categoryRecipe); recipeBookContext.SaveChanges(); } catch (Exception exception) { logger.LogError($"Failed to seed RecipeBookDb {exception.Message}"); throw; } }
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); }
public async Task EditAsync(RecipeEditViewModel viewModel, string rootPath) { var recipe = this.recipesRepository.All() .FirstOrDefault(x => x.Id == viewModel.Id); if (recipe == null) { throw new NullReferenceException(string.Format(ExceptionMessages.RecipeMissing, viewModel.Id)); } if (this.recipesRepository.All().Any(x => x.Name == viewModel.Name && x.Id != viewModel.Id)) { throw new ArgumentException(ExceptionMessages.RecipeAlreadyExists, viewModel.Name); } recipe.Name = viewModel.Name; recipe.PreparationTime = TimeSpan.FromMinutes(viewModel.PreparationTime); recipe.CookingTime = TimeSpan.FromMinutes(viewModel.CookingTime); recipe.Portions = viewModel.Portions; recipe.Preparation = viewModel.Preparation; recipe.Notes = viewModel.Notes; recipe.ModifiedOn = DateTime.UtcNow; var cookingVesselBeforeEdit = this.cookingVesselRepository.All() .FirstOrDefault(x => x.Id == recipe.CookingVesselId); if (cookingVesselBeforeEdit.Id != viewModel.CookingVesselId) { var cookingVessel = this.cookingVesselRepository.All() .FirstOrDefault(x => x.Id == viewModel.CookingVesselId); if (cookingVessel == null) { throw new NullReferenceException( string.Format(ExceptionMessages.CookingVesselMissing, viewModel.CookingVesselId)); } recipe.CookingVesselId = viewModel.CookingVesselId; cookingVessel.Recipes.Add(recipe); cookingVesselBeforeEdit.Recipes.Remove(recipe); } var recipesCategoriesBeforeEdit = await this.categoryRecipesRepository.All() .Where(x => x.RecipeId == recipe.Id) .ToListAsync(); foreach (var recipesCategory in recipesCategoriesBeforeEdit) { this.categoryRecipesRepository.HardDelete(recipesCategory); } await this.categoryRecipesRepository.SaveChangesAsync(); foreach (var categoryId in viewModel.CategoriesCategoryId) { 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); } var recipeIngredientsBeforeEdit = await this.ingredientRecipeRepository.All() .Where(x => x.RecipeId == recipe.Id) .ToListAsync(); foreach (var recipeIngredient in recipeIngredientsBeforeEdit) { this.ingredientRecipeRepository.HardDelete(recipeIngredient); } await this.ingredientRecipeRepository.SaveChangesAsync(); foreach (var recipeIngredient in viewModel.Ingredients) { var ingredient = this.ingredientRepository.All() .FirstOrDefault(x => x.Id == recipeIngredient.IngredientId); if (ingredient == null) { throw new NullReferenceException( string.Format(ExceptionMessages.IngredientMissing, recipeIngredient.IngredientId)); } var ingredientRecipe = new RecipeIngredient { IngredientId = recipeIngredient.IngredientId, WeightInGrams = recipeIngredient.WeightInGrams, PartOfRecipe = recipeIngredient.PartOfRecipe, RecipeId = recipe.Id, }; recipe.Ingredients.Add(ingredientRecipe); ingredient.Recipies.Add(ingredientRecipe); } if (viewModel.ImagesToSelect != null) { var imagesBeforeEdit = await this.recipeImageRepository.All() .Where(x => x.RecipeId == recipe.Id) .ToListAsync(); foreach (var image in imagesBeforeEdit) { this.recipeImageRepository.HardDelete(image); } await this.recipeImageRepository.SaveChangesAsync(); foreach (var fileImage in viewModel.ImagesToSelect) { 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 fileImage.CopyToAsync(stream); } recipe.Images.Add(image); } await this.recipeImageRepository.SaveChangesAsync(); } this.recipesRepository.Update(recipe); await this.recipesRepository.SaveChangesAsync(); await this.cookingVesselRepository.SaveChangesAsync(); await this.categoryRecipesRepository.SaveChangesAsync(); await this.categoryRepository.SaveChangesAsync(); await this.ingredientRecipeRepository.SaveChangesAsync(); await this.ingredientRepository.SaveChangesAsync(); var nutrition = this.nutritionRepository.All() .FirstOrDefault(x => x.RecipeId == recipe.Id); if (nutrition != null) { this.nutritionRepository.HardDelete(nutrition); } await this.nutritionsService.CalculateNutritionForRecipeAsync(recipe.Id); }