public RecipeEditViewModel EntityToViewModel(RecipeEntity entity)
        {
            var editModel = new RecipeEditViewModel();

            var styles = this._styleRepository.GetStyles();

            editModel.StyleList = new SelectList(
                styles,
                "StyleId",
                "Name",
                0);

            if (entity != null)
            {
                editModel.FinalGravity = entity.FinalGravity;
                editModel.GrainBill = entity.GrainBill;
                editModel.Instructions = entity.Instructions;
                editModel.Name = entity.Name;
                editModel.OriginalGravity = entity.OriginalGravity;
                editModel.RecipeId = entity.RecipeId;
                editModel.StyleId = entity.Style.StyleId;
                editModel.Slug = entity.Slug;
            }

            return editModel;
        }
        public RecipeEntity ViewModelToEntity(RecipeEditViewModel viewModel)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException(
                          "viewModel",
                          "Must have something to convert to an entity.");
            }

            var style =
                this
                ._styleRepository
                .GetStyle(viewModel.StyleId);

            return(new RecipeEntity
            {
                FinalGravity = viewModel.FinalGravity,
                GrainBill = viewModel.GrainBill,
                Instructions = viewModel.Instructions,
                Name = viewModel.Name,
                OriginalGravity = viewModel.OriginalGravity,
                RecipeId = viewModel.RecipeId,
                Slug = viewModel.Slug,
                Style = style,
                Contributor = this._userProfileFactory.Create()
            });
        }
        public RecipeEditViewModel EntityToViewModel(RecipeEntity entity)
        {
            var editModel = new RecipeEditViewModel();

            var styles = this._styleRepository.GetStyles();


            editModel.StyleList = new SelectList(
                styles,
                "StyleId",
                "Name",
                0);

            if (entity != null)
            {
                editModel.FinalGravity    = entity.FinalGravity;
                editModel.GrainBill       = entity.GrainBill;
                editModel.Instructions    = entity.Instructions;
                editModel.Name            = entity.Name;
                editModel.OriginalGravity = entity.OriginalGravity;
                editModel.RecipeId        = entity.RecipeId;
                editModel.StyleId         = entity.Style.StyleId;
                editModel.Slug            = entity.Slug;
            }

            return(editModel);
        }
Ejemplo n.º 4
0
        public ActionResult Create(RecipeEditViewModel recipe)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var recipeEntity =
                        this._editViewModelMapper.ViewModelToEntity(recipe);

                    this._recipeRepository.Save(recipeEntity);

                    var context = Microsoft.AspNet.SignalR.
                                  GlobalHost
                                  .ConnectionManager
                                  .GetHubContext <RecipeHub>();
                    context
                    .Clients
                    .All
                    .recipeAdded(
                        _displayViewModelMapper
                        .EntityToViewModel(recipeEntity)
                        );

                    return(RedirectToAction("Index"));
                }
            }
            catch
            {
            }

            return(View(recipe));
        }
Ejemplo n.º 5
0
        public IActionResult Edit(RecipeEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                int    recipeId = Convert.ToInt32(_protector.Unprotect(model.EncryptedId));
                Recipe recipe   = _recipeRepository.GetRecipe(recipeId);
                recipe.Name        = model.Name;
                recipe.Description = model.Description;
                recipe.AuthorId    = model.AuthorId;
                recipe.AddedTime   = model.AddedTime;
                recipe.Hint        = model.Hint;
                recipe.Ingridients = model.Ingridients.SerializeListToString();
                recipe.Tags        = model.Tags.SerializeListToString();
                recipe.Time        = model.Time;

                if (model.Photo != null)
                {
                    if (model.ExistingPhotoPath != null)
                    {
                        string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "images",
                                                       model.ExistingPhotoPath);
                        System.IO.File.Delete(filePath);
                    }
                    recipe.PhotoPatch = ProcessUploadedFile(model, "images");
                }

                _recipeRepository.Update(recipe);

                recipe.EncryptedId = _protector.Protect(recipe.Id.ToString());

                return(RedirectToAction("details", new { id = recipe.EncryptedId }));
            }
            return(View());
        }
Ejemplo n.º 6
0
        public ActionResult Edit(RecipeEditViewModel recipe)
        {
            try
            {
                // Yes, it's a bit chatty, but we need to
                // validate the entity from the database.
                var recipeEntity =
                    this._recipeRepository.GetRecipe(recipe.RecipeId);

                if (!CanEdit(recipeEntity))
                {
                    // Simply return the user to the detail view.
                    // Not too worried about the throw.
                    return(RedirectToAction("Details", new { id = recipe.RecipeId }));
                }

                var entityToSave = this
                                   ._editViewModelMapper
                                   .ViewModelToEntity(recipe);

                this._recipeRepository.Save(entityToSave);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Ejemplo n.º 7
0
        public ActionResult Edit(RecipeEditViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                using (var context = new ApplicationDbContext())
                {
                    var recipeService = new RecipeService(context, HttpContext);
                    recipeService.Edit(model);
                    context.SaveChanges();

                    var recipe = recipeService.GetRecipe(model.Id);

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

                    return(RedirectToAction("Details", new { id = model.Id }));
                }
            }
            catch
            {
                return(View(model));
            }
        }
Ejemplo n.º 8
0
        public ActionResult Edit(int id)
        {
            var model = new RecipeEditViewModel(unitOfWork, id);

            TempData["editRecipe"] = model;
            return(View("MainEdit", model));
        }
Ejemplo n.º 9
0
        internal void Edit(RecipeEditViewModel model)
        {
            var userService   = new UserService(_context, _httpContext);
            var cleranceLevel = userService.GetCurrentUserCleranceLevel();

            var recipe = GetById(model.Id);

            if (cleranceLevel.Level < recipe.ClassificationLevel.Level)
            {
                return;
            }

            var controlLevelService   = new ControlLevelService(_context);
            var classificationLevelId = controlLevelService.GetIdByLevel(model.ClassificationLevel);

            var authorId = userService.GetCurrentUserId();

            recipe.Id   = model.Id;
            recipe.Name = model.Name;
            recipe.Text = model.Text;
            recipe.ClassificationLevelId = classificationLevelId;
            recipe.AuthorId = authorId;

            _context.Entry(recipe).State = EntityState.Modified;
        }
        public RecipeEntity ViewModelToEntity(RecipeEditViewModel viewModel)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException(
                    "viewModel",
                    "Must have something to convert to an entity.");
            }

            var style =
                this
                ._styleRepository
                .GetStyle(viewModel.StyleId);

            return new RecipeEntity
            {
                FinalGravity = viewModel.FinalGravity,
                GrainBill = viewModel.GrainBill,
                Instructions = viewModel.Instructions,
                Name = viewModel.Name,
                OriginalGravity = viewModel.OriginalGravity,
                RecipeId = viewModel.RecipeId,
                Slug = viewModel.Slug,
                Style = style,
                Contributor = this._userProfileFactory.Create()
            };
        }
Ejemplo n.º 11
0
 public static Recipe FromRecipeEdit(this RecipeEditViewModel recipe)
 {
     return(new Recipe
     {
         Id = recipe.Id,
         Title = recipe.Title,
         Description = recipe.Description,
         Preparation = recipe.Preparation
     });
 }
Ejemplo n.º 12
0
        public async Task ApplyEditRecipe(RecipeEditViewModel recipeEditViewModel)
        {
            var recipe = this.db.Recipes.FirstOrDefault(X => X.Id == recipeEditViewModel.Id);

            recipe.Name         = recipeEditViewModel.Name;
            recipe.ImageUrl     = recipeEditViewModel.ImageUrl;
            recipe.CookingTime  = recipeEditViewModel.CookingTime;
            recipe.Instructions = recipeEditViewModel.Instructions;
            await this.db.SaveChangesAsync();
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> Edit(RecipeEditViewModel recipeEditViewModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(recipeEditViewModel));
            }
            await this.recipeService.ApplyEditRecipe(recipeEditViewModel);

            return(this.Redirect($"/Recipes/Details/{recipeEditViewModel.Id}"));
        }
        public async Task <IActionResult> Edit(RecipeEditViewModel recipeEditViewModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(recipeEditViewModel));
            }

            await this.recipesService.EditAsync(recipeEditViewModel);

            return(this.RedirectToAction("GetAll", "Recipes", new { area = "Administration" }));
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> Edit(string hashtag, string name)
        {
            Guid recipeGuid = await this.GetRecipeGuid(name);

            var repository = new RecipeRepository(_settings.AzureStorageConnectionString);
            var item       = await repository.GetAsync(recipeGuid);

            item.ProcessRecipe();

            var viewModel = new RecipeEditViewModel(hashtag, item);

            return(View(viewModel));
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> UpdateEditedRecipe(RecipeEditViewModel model)
        {
            var userId = this.userManager.GetUserId(this.User);

            if (!this.ModelState.IsValid)
            {
                return(this.View(model.Id));
            }

            await this.recipesService.EditRecipe(model, userId);

            return(this.RedirectToAction(nameof(this.Index)));
        }
Ejemplo n.º 17
0
        public async Task EditShouldChangeRecipe()
        {
            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 RecipeEditViewModel
            {
                Id            = recipeResult,
                CategoryId    = 5,
                CookProcedure = "five",
                CookTime      = 5,
                Photo         = "fifthPhoto",
                Serving       = 5,
                Title         = "fifthEdit",
            };

            await service.EditRecipe(model, userId);

            Assert.Equal(5, dbContext.Recipes.FirstOrDefault(x => x.Id == recipeResult).CategoryId);
        }
Ejemplo n.º 18
0
        public async Task DoesRecipeEditAsyncThrowsNullReferenceExceptionWhenNoSuchCookingVessel()
        {
            var recipeList = new List <Recipe>
            {
                new Recipe
                {
                    Id              = TestRecipeId,
                    Name            = TestRecipeName,
                    CookingVesselId = TestCookingVesselId,
                },
            };

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

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

            var recipeToEdit = new RecipeEditViewModel
            {
                Id              = TestRecipeId,
                Name            = TestRecipeName,
                Portions        = TestPortionsCount,
                PreparationTime = TestPreparationTime,
                CookingTime     = TestCookingTime,
                Preparation     = TestPreparation,
                Notes           = TestNotes,
                CookingVesselId = TestCookingVesselId2,
            };

            await Assert.ThrowsAsync <NullReferenceException>(async() => await service.EditAsync(recipeToEdit, string.Empty));
        }
Ejemplo n.º 19
0
 public int UpdateRecipe([FromBody] RecipeEditViewModel model)
 {
     if (!ModelState.IsValid)
     {
         return(0);
     }
     try
     {
         _recipeService.SaveRecipeEditViewModel(model);
         return(model.Id);
     }
     catch (Exception ex)
     {
         return(0);
     }
 }
        //public async Task<IActionResult> Edit(int id, [Bind("RecipeId,Title,Instructions,RecipeItem,RecipeItems")] RecipeEditViewModel recipeEditViewModel)
        public async Task <IActionResult> Edit(int id, [Bind("RecipeId,Title,Instructions,RecipeItem,RecipeItems")] RecipeEditViewModel recipeEditViewModel)
        {
            if (id != recipeEditViewModel.RecipeId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var recipe = _context.Recipes.Find(id);
                    recipe.Title        = recipeEditViewModel.Title;
                    recipe.Instructions = recipeEditViewModel.Instructions;

                    //Explicit loading voor RecipeItems https://entityframeworkcore.com/querying-data-loading-eager-lazy
                    // Dan met loop door properties recipeitem heen om te kijken of ze zijn aangepast of niet.

                    _context.Entry(recipe)
                    .Collection(c => c.RecipeItems)
                    .Load();

                    for (int i = 0; i < recipe.RecipeItems.Count; i++)
                    {
                        recipe.RecipeItems[i].Name     = recipeEditViewModel.RecipeItems[i].Name;
                        recipe.RecipeItems[i].Quantity = recipeEditViewModel.RecipeItems[i].Quantity;
                        recipe.RecipeItems[i].Unit     = recipeEditViewModel.RecipeItems[i].Unit;
                    }

                    _context.Update(recipe);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!RecipeExists(recipeEditViewModel.RecipeId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(recipeEditViewModel));
        }
Ejemplo n.º 21
0
        public ActionResult Edit(int id)
        {
            using (var context = new ApplicationDbContext())
            {
                var recipeService = new RecipeService(context, HttpContext);
                var recipe        = recipeService.GetRecipe(id);

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

                var userService          = new UserService(context, HttpContext);
                var classificationLevels = userService.GetAvailableClassificationLevels();
                var viewModel            = new RecipeEditViewModel(recipe, classificationLevels);
                return(View(viewModel));
            }
        }
        public JsonResult Edit(int?id)
        {
            var result = new RecipeEditViewModel();

            if (id.HasValue)
            {
                result.Recipe = _recipeManager.GetRecipe(id.Value);
            }
            else
            {
                result.Recipe = new Recipe();
            }
            result.Effects     = _ingredientManager.GetAllEffects();
            result.Moods       = _ingredientManager.GetAllMoods();
            result.Ingredients = _ingredientManager.GetAllIngredients();

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 23
0
        // Only the creator can edit his recipe.
        public async Task EditRecipe(RecipeEditViewModel model, string userId)
        {
            var recipe = await this.recipeRepository.All().FirstOrDefaultAsync(x => x.Id == model.Id);

            if (recipe.UserId == userId)
            {
                recipe.CategoryId    = model.CategoryId;
                recipe.CookProcedure = model.SanitizedCookProcedure;
                recipe.Title         = model.Title;
                recipe.CookTime      = model.CookTime;
                recipe.Photo         = model.Photo;
                recipe.Serving       = model.Serving;
                recipe.ModifiedOn    = DateTime.UtcNow;
                this.recipeRepository.Update(recipe);
            }

            await this.recipeRepository.SaveChangesAsync();
        }
Ejemplo n.º 24
0
        public IActionResult EditRecipe(string id)
        {
            var userId     = this.userManager.GetUserId(this.User);
            var recipe     = this.recipesService.GetAll <RecipeEditViewModel>().FirstOrDefault(x => x.Id == id);
            var categories = this.categoriesService.GetAll <CategoryDropdownViewModel>();
            var viewModel  = new RecipeEditViewModel()
            {
                Id            = recipe.Id,
                Categories    = categories,
                Photo         = recipe.Photo,
                Title         = recipe.Title,
                CookProcedure = recipe.CookProcedure,
                CookTime      = recipe.CookTime,
                Serving       = recipe.Serving,
                CategoryId    = recipe.CategoryId,
            };

            return(this.View(viewModel));
        }
        public async Task TestIfRecipeEditAsyncWorks()
        {
            this.SeedDatabase();

            var path = "Test.jpg";

            using (var img = File.OpenRead(path))
            {
                var testImage = new FormFile(img, 0, img.Length, "Test.jpg", img.Name)
                {
                    Headers     = new HeaderDictionary(),
                    ContentType = "image/jpeg",
                };

                var model = new RecipeEditViewModel
                {
                    Id              = 1,
                    Name            = this.firstRecipe.Name,
                    Description     = this.firstRecipe.Description,
                    Ingredients     = this.firstRecipe.Ingredients,
                    PreparationTime = this.firstRecipe.PreparationTime,
                    CookingTime     = this.firstRecipe.CookingTime,
                    PortionsNumber  = this.firstRecipe.PortionsNumber,
                    Difficulty      = "Medium",
                    Image           = testImage,
                    CategoryId      = 1,
                };

                await this.recipesService.EditAsync(model);
            }

            var count = await this.recipesRepository.All().CountAsync();

            var result = await this.recipesRepository
                         .All()
                         .Where(x => x.Id == 1)
                         .Select(o => o.Difficulty.ToString())
                         .FirstOrDefaultAsync();

            Assert.Equal(1, count);
            Assert.Equal("Medium", result);
        }
Ejemplo n.º 26
0
        public IActionResult Edit(string id)
        {
            int    recipeId = Convert.ToInt32(_protector.Unprotect(id));
            Recipe recipe   = _recipeRepository.GetRecipe(recipeId);
            RecipeEditViewModel recipeEditViewModel = new RecipeEditViewModel
            {
                Id                = recipe.Id,
                Name              = recipe.Name,
                Description       = recipe.Description,
                ExistingPhotoPath = recipe.PhotoPatch,
                EncryptedId       = _protector.Protect(recipe.Id.ToString()),
                AuthorId          = recipe.AuthorId,
                Hint              = recipe.Hint,
                Ingridients       = recipe.Ingridients.DeserializeStringToList(),
                Tags              = recipe.Tags.DeserializeStringToList(),
                Time              = recipe.Time
            };

            return(View(recipeEditViewModel));
        }
Ejemplo n.º 27
0
        public async Task <IActionResult> DeleteIngredient(int id, RecipeEditViewModel viewModel)
        {
            //Get current user
            var currentUser = await GetCurrentUserAsync();

            //Create instances of view model
            var recipeObj = viewModel.Recipe;

            //Check to see if the viewmodel is null
            if (viewModel == null)
            {
                return(NotFound());
            }

            var ingredList = await _context.IngredientList.FindAsync(id);

            _context.IngredientList.Remove(ingredList);
            await _context.SaveChangesAsync();

            return(RedirectToAction("Edit", new { id = recipeObj.RecipeId }));
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> Edit(RecipeEditViewModel viewModel)
        {
            if (!this.ModelState.IsValid)
            {
                viewModel.CategoriesCategoryId = await this.categoryRecipeService.GetAllCategoriesForRecipeAsync(viewModel.Id);

                viewModel.CategoriesToSelect = await this.categoriesService.GetAllCategoriesSelectListAsync();

                viewModel.IngredientsToSelect = await this.ingredientsService.GetAllIngredientsSelectListAsync();

                viewModel.CookingVesselsToSelect = await this.cookingVesselsService.GetAllCookingVesselsSelectListAsync();

                return(this.View(viewModel));
            }

            var rootPath = this.webHostEnvironment.WebRootPath;

            await this.recipesService.EditAsync(viewModel, rootPath);

            return(this.RedirectToAction(nameof(Web.Controllers.RecipesController.Details), new { id = viewModel.Id }));
        }
Ejemplo n.º 29
0
        public async Task <IActionResult> Edit(RecipeEditViewModel viewModel)
        {
            Recipe item;

            var repository = new RecipeRepository(_settings.AzureStorageConnectionString);

            if (viewModel.IsNew())
            {
                item = new Recipe();
            }
            else
            {
                item = await repository.GetAsync(viewModel.Guid);
            }

            viewModel.FillModel(item);

            await repository.SaveAsync(item);

            return(RedirectToAction("Details", "Recipes", new { hashtag = viewModel.Hashtag, name = item.Name }));
        }
        public async Task EditAsync(RecipeEditViewModel recipeEditViewModel)
        {
            if (!Enum.TryParse(recipeEditViewModel.Difficulty, true, out Difficulty difficulty))
            {
                throw new ArgumentException(
                          string.Format(ExceptionMessages.DifficultyInvalidType, recipeEditViewModel.Difficulty));
            }

            var recipe = await this.recipesRepository
                         .All()
                         .FirstOrDefaultAsync(r => r.Id == recipeEditViewModel.Id);

            if (recipe == null)
            {
                throw new NullReferenceException(
                          string.Format(ExceptionMessages.RecipeNotFound, recipeEditViewModel.Id));
            }

            if (recipeEditViewModel.Image != null)
            {
                var newImageUrl = await this.cloudinaryService
                                  .UploadAsync(recipeEditViewModel.Image, recipeEditViewModel.Name + Suffixes.RecipeSuffix);

                recipe.ImagePath = newImageUrl;
            }

            recipe.Name            = recipeEditViewModel.Name;
            recipe.Description     = recipeEditViewModel.Description;
            recipe.Ingredients     = recipeEditViewModel.Ingredients;
            recipe.PreparationTime = recipeEditViewModel.PreparationTime;
            recipe.CookingTime     = recipeEditViewModel.CookingTime;
            recipe.PortionsNumber  = recipeEditViewModel.PortionsNumber;
            recipe.Difficulty      = difficulty;
            recipe.CategoryId      = recipeEditViewModel.CategoryId;

            this.recipesRepository.Update(recipe);
            await this.recipesRepository.SaveChangesAsync();
        }
        public async Task TestEditingRecipeWithMissingRecipe()
        {
            await this.SeedUsers();

            await this.SeedCategories();

            var path = "Test.jpg";

            RecipeEditViewModel model;

            using (var img = File.OpenRead(path))
            {
                var testImage = new FormFile(img, 0, img.Length, "Test.jpg", img.Name)
                {
                    Headers     = new HeaderDictionary(),
                    ContentType = "image/jpeg",
                };

                model = new RecipeEditViewModel
                {
                    Id              = 1,
                    Name            = this.firstRecipe.Name,
                    Description     = this.firstRecipe.Description,
                    Ingredients     = this.firstRecipe.Ingredients,
                    PreparationTime = this.firstRecipe.PreparationTime,
                    CookingTime     = this.firstRecipe.CookingTime,
                    PortionsNumber  = this.firstRecipe.PortionsNumber,
                    Difficulty      = "Easy",
                    Image           = testImage,
                    CategoryId      = 1,
                };
            }

            var exception = await Assert
                            .ThrowsAsync <NullReferenceException>(async() => await this.recipesService.EditAsync(model));

            Assert.Equal(string.Format(ExceptionMessages.RecipeNotFound, model.Id), exception.Message);
        }
Ejemplo n.º 32
0
        public RecipeEditViewModel GetRecipeEditViewModel(int recipeId)
        {
            RecipeEditViewModel vm = new RecipeEditViewModel();

            IDbConnection conn;

            conn      = new MySql.Data.MySqlClient.MySqlConnection(ConnectionString);
            vm.Recipe = conn.Query <Recipe>("SELECT * FROM Recipe WHERE Id = " + recipeId).ToList().FirstOrDefault();
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("SELECT * FROM recipe_ingredient AS A LEFT JOIN ingredient AS B ON A.IngredientId = B.Id " +
                            "LEFT JOIN quantity_unit AS C ON A.QuantityUnitId = C.Id WHERE RecipeId = {0}", recipeId);
            vm.Recipe.RecipeIngredients = conn.Query <RecipeIngredient, Ingredient, QuantityUnit, RecipeIngredient>(sb.ToString(),
                                                                                                                    (component, ingredient, quantityUnit) =>
            {
                component.Ingredient   = ingredient;
                component.QuantityUnit = quantityUnit;
                return(component);
            }, splitOn: "Id").ToList();
            vm.IngredientsList   = conn.Query <Ingredient>("SELECT * FROM ingredient").ToList();
            vm.QuantityUnitsList = conn.Query <QuantityUnit>("SELECT * FROM quantity_unit").ToList();
            return(vm);
        }