Ejemplo n.º 1
0
        public async Task <IActionResult> Create(CreateMealInputModel inputModel)
        {
            var viewModel = new CreateMealViewModel();

            if (!this.ModelState.IsValid)
            {
                viewModel.CategoriesItems = this.categoriesService.GetAllCategories();

                return(this.View(viewModel));
            }

            var user = await this.userManager.GetUserAsync(this.User);

            try
            {
                await this.mealService.CreateAsync(inputModel, user.Id, $"{this.environment.WebRootPath}/images");
            }
            catch (Exception exception)
            {
                this.ModelState.AddModelError(string.Empty, exception.Message);

                viewModel.CategoriesItems = this.categoriesService.GetAllCategories();

                return(this.View(viewModel));
            }

            return(this.RedirectToAction(nameof(this.All)));
        }
Ejemplo n.º 2
0
        public async Task CheckCreatingMealAsync()
        {
            ApplicationDbContext db = GetDb();

            var mealRepository        = new EfDeletableEntityRepository <Meal>(db);
            var ingredientRepository  = new EfDeletableEntityRepository <Ingredient>(db);
            var subCategoryRepository = new EfDeletableEntityRepository <SubCategory>(db);

            var service = new MealService(
                mealRepository, ingredientRepository, subCategoryRepository);

            var list = new List <MealIngredientInputModel>()
            {
                new MealIngredientInputModel {
                    NameAndQuantity = "XD?"
                },
            };

            var fileMock = new Mock <IFormFile>();

            // Setup mock file using a memory stream
            var content  = "Hello World from a Fake File";
            var fileName = "test.png";
            var ms       = new MemoryStream();
            var writer   = new StreamWriter(ms);

            writer.Write(content);
            writer.Flush();
            ms.Position = 0;
            fileMock.Setup(_ => _.OpenReadStream()).Returns(ms);
            fileMock.Setup(_ => _.FileName).Returns(fileName);
            fileMock.Setup(_ => _.Length).Returns(ms.Length);

            var file = fileMock.Object;

            var meal = new CreateMealInputModel
            {
                Name                = "TestName",
                PreparationTime     = "10 mins",
                CookingTime         = "10 mins",
                SkillLevel          = SkillLevel.Easy,
                PortionCount        = "6-8",
                KCal                = 100,
                Fat                 = 10,
                Saturates           = 10,
                Carbs               = 10,
                Sugars              = 10,
                Fibre               = 10,
                Protein             = 10,
                Salt                = 10,
                Description         = "Some text for description",
                MethodOfPreparation = "Some text for methodOfPreparation",
                CategoryId          = 1,
                Ingredients         = list,
                Images              = new List <IFormFile> {
                    file
                },
            };

            await service.CreateAsync(meal, "userId", "wwwroot/images/meals");

            Assert.Single(db.Meals.Where(x => x.Name == "TestName"));
        }
Ejemplo n.º 3
0
        public async Task CreateAsync(CreateMealInputModel inputModel, string userId, string imagePath)
        {
            var subCategoryId = this.subCategoryRepository.AllAsNoTracking().Where(x => x.Name == inputModel.SubCategory).Select(x => x.Id).FirstOrDefault();

            var meal = new Meal
            {
                Name                = inputModel.Name,
                PreparationTime     = inputModel.PreparationTime,
                CookingTime         = inputModel.CookingTime,
                SkillLevel          = inputModel.SkillLevel,
                PortionCount        = inputModel.PortionCount,
                KCal                = inputModel.KCal,
                Fat                 = inputModel.Fat,
                Saturates           = inputModel.Saturates,
                Carbs               = inputModel.Carbs,
                Sugars              = inputModel.Sugars,
                Fibre               = inputModel.Fibre,
                Protein             = inputModel.Protein,
                Salt                = inputModel.Salt,
                Description         = inputModel.Description,
                MethodOfPreparation = inputModel.MethodOfPreparation,
                CategoryId          = inputModel.CategoryId,
                SubCategoryId       = subCategoryId,
                AddedByUserId       = userId,
            };

            foreach (var inputIngredient in inputModel.Ingredients)
            {
                var ingredient = this.ingredientRepository.All().FirstOrDefault(x => x.NameAndQuantity == inputIngredient.NameAndQuantity);

                if (ingredient == null)
                {
                    ingredient = new Ingredient
                    {
                        NameAndQuantity = inputIngredient.NameAndQuantity,
                    };
                }

                meal.Ingredients.Add(new MealIngredient
                {
                    Ingredient = ingredient,
                });
            }

            Directory.CreateDirectory($"{imagePath}/meals/");

            foreach (var image in inputModel.Images)
            {
                var extension = Path.GetExtension(image.FileName).TrimStart('.');

                if (!this.allowedExtensions.Any(x => extension.EndsWith(x)))
                {
                    throw new Exception($"Invalid image extension {extension}");
                }

                var newImage = new Image
                {
                    AddedByUserId = userId,
                    Extension     = extension,
                };

                meal.Images.Add(newImage);
                var physicalPath = $"{imagePath}/meals/{newImage.Id}.{extension}";
                using var fileStream = new FileStream(physicalPath, FileMode.Create);
                await image.CopyToAsync(fileStream);
            }

            await this.mealRepository.AddAsync(meal);

            await this.mealRepository.SaveChangesAsync();
        }