Exemplo n.º 1
0
 public IActionResult Update(Recipe recipe)
 {
     if (ModelState.IsValid)
     {
         repository.AddRecipe(recipe);
         TempData["message"] = $"{recipe.Title} has been updated!";
         return(RedirectToAction("../Home/RecipeList"));
     }
     else
     {
         return(View(recipe));
     }
 }
Exemplo n.º 2
0
        public ActionResult Create(RecipeAddModel model)
        {
            if (ModelState.IsValid)
            {
                Recipe recipe = new Recipe
                {
                    Id         = model.Id,
                    Name       = model.Name,
                    Text       = model.Text,
                    CreateDate = DateTime.Now,
                    Tags       = model.IngridietsString,
                    UserId     = User.Identity.GetUserId(),
                };
                string imagePath = UploadFile(model.ImageFile, "images/thumbnails");
                recipe.ImageUrl = imagePath;

                db.AddRecipe(recipe);
                db.Save();

                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(View());
            }
        }
        public MensagemDto AddRecipe(RecipeDto recipe)
        {
            var RecipeToAdd = ConvertRecipeDto(recipe);
            var status      = _recipeRepository.AddRecipe(RecipeToAdd);

            return(MensagemToResponse(1, "Recipe Add"));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> AddNewRecipe([FromBody] NewRecipeDto recipeToAdd)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userRepo.GetUserByUserId(recipeToAdd.UserId);

            Recipe recipe = new Recipe()
            {
                User        = user,
                UserId      = recipeToAdd.UserId,
                Title       = recipeToAdd.Title,
                Description = recipeToAdd.Description,
                DateCreated = DateTime.Now,
                Steps       = recipeToAdd.Steps
            };

            var successful = await _recipeRepo.AddRecipe(recipe);

            if (successful)
            {
                return(Ok());
            }

            return(StatusCode(500));
        }
Exemplo n.º 5
0
        public ViewResult InsertPage(RecipeFormViewModelData recipe)
        {
            if (ModelState.IsValid)
            {
                RecipeItem newRecipe = new RecipeItem();
                newRecipe.RecipeName  = recipe.RecipeName;
                newRecipe.ServingSize = recipe.ServingSize;
                newRecipe.Description = recipe.Description;
                Ingredient newIngredient = new Ingredient();
                newIngredient.IngredientName = recipe.Ingredient;
                Equipment newEquipment = new Equipment();
                newEquipment.EquipmentName = recipe.Equipment;
                newRecipe.Instructions     = recipe.Instructions;

                repository.AddRecipe(newRecipe);
                repository.AddIngredient(newIngredient);
                repository.AddEquipment(newEquipment);
                repository.AddReview(new Review());
                return(View("DataPage", repository.Recipes));
            }
            else
            {
                return(View());
            }
        }
Exemplo n.º 6
0
        public ActionResult AddRecipe(RecipeModel objRecipe)
        {
            objRecipe.RecipeId = Guid.NewGuid();

            recipeRepository.AddRecipe(objRecipe);
            return(RedirectToAction("GetAllRecipe"));
        }
Exemplo n.º 7
0
        public async Task HandleAsync(SaveRecipeCommand command)
        {
            Recipe recipe = await _recipeRepository.GetRecipeAsync(command.Id);

            if (recipe == null)
            {
                recipe = new Recipe();
                _recipeRepository.AddRecipe(recipe);
            }

            recipe.Name        = command.Name;
            recipe.Ingredients = command.Ingredients;
            recipe.Preparation = command.Preparation;

            recipe.RecipeCategories.Clear();

            foreach (int categoryId in command.Categories)
            {
                Category category = await _categoryRepository.GetCategoryAsync(categoryId);

                recipe.RecipeCategories.Add(new RecipeCategory(recipe, category));
            }

            await _recipeRepository.UnitOfWork.SaveChangesAsync();
        }
 public void AddRecipeShouldAddNewRecipeWhenDoesNotExist()
 {
     _recipeRepository.AddRecipe(new Recipe
     {
         recipe_name = "Pavlova cake", cooking_time = new TimeSpan(00, 10, 00), ingredients = "Cake",
         description = "Freeze", is_favorite = false
     });
     Assert.AreEqual(4, _recipeRepository.GetAllRecipes().Count);
 }
Exemplo n.º 9
0
        public IHttpActionResult AddRecipe(RecipeDto request)
        {
            var activeUser = ActiveUser;

            request.UserId = activeUser.Id;
            var id = _recipeRepository.AddRecipe(request);

            return(Ok(id));
        }
Exemplo n.º 10
0
        public IActionResult Create(CreateRecipeViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            _repository.AddRecipe(viewModel);
            return(RedirectToAction("published", "Recipes"));
        }
Exemplo n.º 11
0
 public ActionResult <Recipe> addRecipe(Recipe recipe)
 {
     try
     {
         _recipeRepository.AddRecipe(recipe);
     }
     catch (Exception)
     {
         throw;
     }
     return(recipe);
 }
Exemplo n.º 12
0
        public IActionResult Create(CreateRecipeViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userId = _userManager.GetUserId(HttpContext.User);

                string uniqueFileName = null;
                if (model.Image != null)
                {
                    string uploadFolder = Path.Combine("wwwroot", "images");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Image.FileName;
                    string filePath = Path.Combine(uploadFolder, uniqueFileName);
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        model.Image.CopyTo(fileStream);
                    }
                }

                Recipe newRecipe = new Recipe
                {
                    Title             = model.Title,
                    Description       = model.Description,
                    Instructions      = model.Instructions,
                    MealType          = model.MealType,
                    Servings          = model.Servings,
                    PrepTime          = model.PrepTime,
                    CookTime          = model.CookTime,
                    Category          = model.Category,
                    SpiceLevel        = model.SpiceLevel,
                    ApplicationUserId = userId,
                    ImagePath         = uniqueFileName
                };

                _recipeRepository.AddRecipe(newRecipe);

                foreach (var item in model.Ingredients)
                {
                    Ingredient ingredient = new Ingredient
                    {
                        RecipeId = newRecipe.Id,
                        Measure  = item.Measure,
                        Unit     = item.Unit,
                        Name     = item.Name
                    };

                    _ingredientRepository.AddIngredient(ingredient);
                }

                return(RedirectToAction("index", "home"));
            }
            return(View());
        }
Exemplo n.º 13
0
        public IActionResult AddRecipe(RecipeDto newRecipe)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var recipe = _mapper.Map <Recipe>(newRecipe);

            recipe.UserId = userId;
            var addedRecipe = _recipeRepo.AddRecipe(recipe);

            _userActivityLoggerGateway.PostUserActivity(new UserActivity {
                Activity = "Add recipe", UserId = userId, Timestamp = DateTime.Now
            });
            return(Ok());
        }
Exemplo n.º 14
0
        public ActionResult <RecipeDto> AddRecipe(RecipeForCreationDto recipeForCreation)
        {
            var recipe = _mapper.Map <Recipe>(recipeForCreation);

            _recipeRepository.AddRecipe(recipe);
            _recipeRepository.Save();

            var recipeDto = _mapper.Map <RecipeDto>(recipe);

            return(CreatedAtRoute("GetRecipe",
                                  new { recipeDto.RecipeId },
                                  recipeDto));
        }
Exemplo n.º 15
0
        public async Task <ActionResult> AddRecipe(RecipeDto recipeDto)
        {
            if (recipeDto.ConsultationId <= 0 || recipeDto.PacientId <= 0)
            {
                return(BadRequest("Invalid data!"));
            }

            if (await _recipeRepository.AddRecipe(recipeDto))
            {
                return(Ok());
            }

            return(BadRequest("Upps..ceva nu a mers!"));
        }
Exemplo n.º 16
0
        public RedirectToActionResult AddRecipe(string name, string servings, string instructions, List <Ingredient> ingredients)
        {
            Recipe recipe = new Recipe();

            recipe.Name         = name;
            recipe.Servings     = Convert.ToInt32(servings);
            recipe.Instructions = instructions;
            recipe.Date         = DateTime.Now;
            foreach (Ingredient i in ingredients)
            {
                recipe.AddIngredient(i);
            }
            repo.AddRecipe(recipe);


            return(RedirectToAction("RecipeDetail", new { id = recipe.RecipeID }));
        }
Exemplo n.º 17
0
        public Recipe AddRecipe(Recipe recipe)
        {
            ValidateRecipe(recipe);

            // Parse ingredients list and add new items to the pantry (if they don't already exist)
            //foreach (var item in recipe.Ingredients)
            //{
            //    if (!pantryService.ItemExists(item.Id))
            //    {
            //        var newItem = pantryService.AddItem(item);
            //        item.Id = newItem.Id;
            //    }
            //}

            // Add recipe
            return(repository.AddRecipe(recipe));
        }
Exemplo n.º 18
0
        public async Task <RecipeResponse> AddAsync(Recipe recipe)
        {
            var checkCategory = await _categoryRepository.FindById(recipe.CategoryId);

            if (checkCategory == null)
            {
                return(new RecipeResponse($"Category could not be found"));
            }
            try
            {
                await _recipeRepository.AddRecipe(recipe);

                await _unitOfWork.SaveChanges();

                return(new RecipeResponse(recipe));
            }
            catch (Exception ex)
            {
                return(new RecipeResponse($"An unexpected error occured: {ex.Message}"));
            }
        }
Exemplo n.º 19
0
 public IActionResult EditRecipe(Recipe recipe)
 {
     if (ModelState.IsValid)
     {
         if (recipe.RecipeId == 0)
         {
             repo.AddRecipe(recipe);
         }
         else
         {
             recipe.OverallRating = recipe.UserRating;
             recipe.LastUpdated   = DateTime.Now;
             repo.UpdateRecipe(recipe);
         }
         return(RedirectToAction("Index", "Recipe"));
     }
     else
     {
         ViewBag.Action = (recipe.RecipeId == 0) ? "Add" : "Edit";
     }
     return(View(recipe));
 }
Exemplo n.º 20
0
        public ActionResult <RecipeDto> AddRecipe(RecipeForCreationDto recipeForCreation)
        {
            var validationResults = new RecipeForCreationDtoValidator().Validate(recipeForCreation);

            validationResults.AddToModelState(ModelState, null);

            if (!ModelState.IsValid)
            {
                return(BadRequest(new ValidationProblemDetails(ModelState)));
                //return ValidationProblem();
            }

            var recipe = _mapper.Map <Recipe>(recipeForCreation);

            _recipeRepository.AddRecipe(recipe);
            _recipeRepository.Save();

            var recipeDto = _mapper.Map <RecipeDto>(recipe);

            return(CreatedAtRoute("GetRecipe",
                                  new { recipeDto.RecipeId },
                                  recipeDto));
        }
Exemplo n.º 21
0
        public IActionResult AddRecipe(Recipe newrecipe)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            /*string uniquefilename = null;
             * if(recipeViewModel.image!=null)
             * {
             *  string uploadsfolder = Path.Combine(_hostingEnvironment.WebRootPath, "images");
             *  uniquefilename = Guid.NewGuid().ToString() + "_" + recipeViewModel.image.FileName;
             *  string filePath = Path.Combine(uploadsfolder, uniquefilename);
             *  recipeViewModel.image.CopyTo(new FileStream(filePath, FileMode.Create));
             * }*/
            /*Recipe newrecipe = new Recipe
             * {
             *  title = recipeViewModel.title,
             *  ingredients = recipeViewModel.ingredients,
             *  method = recipeViewModel.method,
             *  category = recipeViewModel.category,
             *  image = uniquefilename,
             *  otherdetails = recipeViewModel.otherdetails,
             *  likes = 0,
             *  dislikes = 0,
             *  Date = DateTime.Now,
             *  UserId = (int)recipeViewModel.UserId
             * };*/
            string response = _recipeRepository.AddRecipe(newrecipe);

            if (response == "success")
            {
                return(Ok(response));
            }
            return(StatusCode(StatusCodes.Status500InternalServerError, response));
        }
Exemplo n.º 22
0
        public IActionResult CreateRecipe([FromBody] RecipeForCreationDto recipeDto)
        {
            if (recipeDto == null)
            {
                return(StatusCode(400, "Wrong JSON object."));
            }

            if (recipeDto.Categories.Count() < 1)
            {
                ModelState.AddModelError(nameof(RecipeForCreationDto),
                                         "You should fill out at least one category.");
            }

            if (recipeDto.Ingredients.Count() < 1)
            {
                ModelState.AddModelError(nameof(RecipeForCreationDto),
                                         "You should fill out at least one ingredient.");
            }

            if (String.IsNullOrEmpty(recipeDto.Directions.Step))
            {
                ModelState.AddModelError(nameof(RecipeForCreationDto),
                                         "You should fill out direction step.");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            if (_recipeRepository.RecipeExist(recipeDto.Title))
            {
                return(StatusCode(409, "Recipe duplicated."));
            }

            var recipeEntity = Mapper.Map <Recipe>(recipeDto);

            foreach (var categoryName in recipeDto.Categories)
            {
                var recipeCategory = new RecipeCategory();
                var category       = _recipeRepository.GetCategory(categoryName);

                if (category == null)
                {
                    recipeCategory.Category = new Category()
                    {
                        CategoryId = Guid.NewGuid(),
                        Name       = categoryName
                    };
                }
                else
                {
                    recipeCategory.Category = category;
                }
                recipeEntity.RecipeCategories.Add(recipeCategory);
            }

            _recipeRepository.AddRecipe(recipeEntity);

            if (!_recipeRepository.Save())
            {
                return(StatusCode(500, "Internal error occured."));
            }

            var recipeToReturn = Mapper.Map <RecipeDto>(recipeEntity);

            return(CreatedAtRoute("GetRecipes", null, recipeToReturn));
        }
Exemplo n.º 23
0
        public static void Seed(IRecipeRepository repo, UserManager <SiteUser> userManager, RoleManager <IdentityRole> roleManager)
        {
            List <Recipe> recipes = repo.Recipes.ToList();

            //Begin Categories for reuse
            Category comfortFood = new Category
            {
                Name = "Comfort Food"
            };

            repo.AddCategory(comfortFood);

            Category dessert = new Category
            {
                Name = "Dessert"
            };

            repo.AddCategory(dessert);

            Category fromScratch = new Category
            {
                Name = "From Scratch"
            };

            repo.AddCategory(fromScratch);

            Category drinks = new Category
            {
                Name = "Drinks"
            };

            repo.AddCategory(drinks);

            var result = roleManager.CreateAsync(new IdentityRole("Member")).Result;

            result = roleManager.CreateAsync(new IdentityRole("Admin")).Result;

            // Seeding a default administrator. They will need to change their password after logging in.
            SiteUser siteadmin = new SiteUser
            {
                UserName = "******",
            };

            userManager.CreateAsync(siteadmin, "Secret-123").Wait();
            IdentityRole adminRole = roleManager.FindByNameAsync("Admin").Result;

            userManager.AddToRoleAsync(siteadmin, adminRole.Name);



            //begin actual recipes
            if (recipes.Count == 0)
            {
                Recipe recipe = new Recipe
                {
                    RecipeName   = "Macaroni and Cheese",
                    Ingredients  = "5 cups milk, 1 lb elbow macaroni dry, 2 cups shredded cheddar cheese",
                    Instructions = "In a large pot, bring the milk to a boil. Add the pasta and stir constantly until " +
                                   "the pasta is cooked, about 10 minutes. Turn off the heat, then add the cheddar. " +
                                   "Stir until the cheese is melted and the pasta is evenly coated. Enjoy!",
                    OverallRating = 4,
                    UserRating    = 3,
                    DateSubmitted = DateTime.Parse("1/1/2019"),
                    LastUpdated   = DateTime.Parse("2/14/2020"),
                    Category      = comfortFood,
                    Image         = "/css/images/macncheese.jpg",
                    User          = new SiteUser()
                    {
                        UserName = "******", Nickname = "Bertha"
                    }
                };

                repo.AddRecipe(recipe);

                recipe = new Recipe
                {
                    RecipeName   = "Peanut Butter Cookies",
                    Ingredients  = "200g peanut butter (crunchy or smooth is fine), 175g golden caster sugar, ¼ tsp fine table salt, 1 large egg",
                    Instructions = "Heat oven to 180C/160C and line 2 large baking trays with baking parchment. " +
                                   "Measure the peanut butter and sugar into a bowl. Add ¼ tsp fine table salt and mix well with a wooden spoon. " +
                                   "Add the egg and mix again until the mixture forms a dough. Break off cherry tomato sized chunks of dough and place, " +
                                   "well spaced apart, on the trays. Press the cookies down with the back of a fork to squash them a little. The cookies " +
                                   "can now be frozen for 2 months, cook from frozen adding an extra min or 2 to the cooking time. Bake for 12 mins, until " +
                                   "golden around the edges and paler in the centre. Cool on the trays for 10 mins, then transfer to a wire rack and cool completely. " +
                                   "Store in a cookie jar for up to 3 days. ",

                    OverallRating = 5,
                    UserRating    = 5,
                    DateSubmitted = DateTime.Parse("7/18/2019"),
                    LastUpdated   = DateTime.Parse("5/13/2020"),
                    Category      = dessert,
                    Image         = "/css/images/pbcookies.jpg",
                    User          = new SiteUser()
                    {
                        UserName = "******", Nickname = "Tiff"
                    }
                };
                repo.AddRecipe(recipe);

                recipe = new Recipe
                {
                    RecipeName   = "Fresh Pasta",
                    Ingredients  = "300g ‘00’ pasta flour (plus extra for dusting), 2 eggs and 4 yolks (lightly beaten), semolina flour (for dusting)",
                    Instructions = "Put the flour in a food processor with ¾ of your egg mixture and a pinch of salt. Blitz to large crumbs – " +
                                   "they should come together to form a dough when squeezed (if it feels a little dry gradually add a bit more egg). Tip the " +
                                   "dough onto a lightly floured surface, knead for 1 min or until nice and smooth – don’t worry if it’s quite firm as it will soften " +
                                   "when it rests. Cover with cling film and leave to rest for 30 mins. Cut away ¼ of the dough (keep the rest covered with cling film) " +
                                   "and feed it through the widest setting on your pasta machine. (If you don’t have a machine, use a heavy rolling pin to roll the " +
                                   "dough as thinly as possible.) Then fold into three, give the dough a quarter turn and feed through the pasta machine again. Repeat " +
                                   "this process once more then continue to pass the dough through the machine, progressively narrowing the rollers, one notch at a time, " +
                                   "until you have a smooth sheet of pasta. On the narrowest setting, feed the sheet through twice. Cut as required to use for filled pastas " +
                                   "like tortellini, or cut into lengths to make spaghetti, linguine, tagliatelle, or pappardelle. Then, dust in semolina flour and set aside, " +
                                   "or hang until dry (an hour will be enough time.) Store in a sealed container in the fridge and use within a couple of days, or freeze for 1 month.",
                    OverallRating = 3,
                    UserRating    = 4,
                    DateSubmitted = DateTime.Parse("3/25/2016"),
                    LastUpdated   = DateTime.Parse("12/13/2020"),
                    Category      = fromScratch,
                    Image         = "/css/images/pasta.jpg",
                    User          = new SiteUser()
                    {
                        UserName = "******", Nickname = "DudeBro"
                    }
                };
                repo.AddRecipe(recipe);

                recipe = new Recipe
                {
                    RecipeName   = "Earl Grey Martini",
                    Ingredients  = "1 tbsp good loose-leaf Earl Grey tea, 700ml bottle of decent gin, ice",
                    Instructions = "Put the Earl Grey tea in a large jug. Pour the gin over and stir with a long-handled spoon for about 45 secs. " +
                                   "Strain the gin through a tea strainer over a funnel back into the bottle. You’ll see small particles of leaf still suspended in the gin. " +
                                   "Rinse out the jug and, using a coffee filter or some muslin inside the funnel, strain the gin a second time to remove all the particles. " +
                                   "In this way, the gin will be stable and the flavour won’t change – it’ll be good for months and months until the final sip. To serve, " +
                                   "shake or stir over ice – I like how the flavours change as the drink dilutes.",

                    OverallRating = 3,
                    UserRating    = 5,
                    DateSubmitted = DateTime.Parse("12/1/2020"),
                    LastUpdated   = DateTime.Parse("12/1/2020"),
                    Category      = drinks,
                    Image         = "/css/images/earlgreymartini.jpg",
                    User          = new SiteUser()
                    {
                        UserName = "******", Nickname = "Charlie"
                    }
                };
                repo.AddRecipe(recipe);

                recipe = new Recipe
                {
                    RecipeName  = "Homemade Chili",
                    Ingredients = "1.5lbs lean ground beef, 1 onion(chopped), 1 small green bell pepper(chopped), 2 garlic cloves (minced), 2 (16oz) cans red kidney beans" +
                                  "(rinsed and drained), 2(14.5oz) cans diced tomatoes, 2-3 tbsp chili powder, 1 tsp salt, 1 tsp pepper, 1 tsp ground cumin",
                    Instructions = "Cook first 4 ingredients in a large skillet over medium-high heat, stirring until beef crumbles and is no longer pink; drain. " +
                                   "Place mixture in 5-quart slow cooker; stir in beans and remaining ingredients. Cook at HIGH 3 to 4 hours or at LOW 5 to 6 hours. Note: If you " +
                                   "want to thicken this saucy chili, stir in finely crushed saltine crackers until the desired thickness is achieved.",

                    OverallRating = 5,
                    UserRating    = 5,
                    DateSubmitted = DateTime.Parse("3/9/2020"),
                    LastUpdated   = DateTime.Parse("3/9/2020"),
                    Category      = comfortFood,
                    Image         = "/css/images/chili.jpg",
                    User          = new SiteUser()
                    {
                        UserName = "******", Nickname = "Bilbo"
                    }
                };
                repo.AddRecipe(recipe);

                recipe = new Recipe
                {
                    RecipeName  = "Lemon Blueberry Layered Dessert",
                    Ingredients = "15 lemon cookies (coarsely crushed), 1(21oz) can blueberry pie filling, 1(8oz, thawed) container frozen whippped topping, 1 (14oz) can sweetened" +
                                  "condensed milk, 1 (6oz, thawed) can frozen lemonade concentrate",
                    Instructions = "Sprinkle 1 tablespoon crushed cookies into each of 8 (8-ounce) parfait glasses. Spoon 1 1/2 tablespoons pie filling over cookies in each glass." +
                                   "Spoon whipped topping into a bowl; fold in condensed milk and lemonade concentrate. Spoon 2 tablespoons whipped topping mixture over pie filling in each glass. " +
                                   "Repeat layers once. Top evenly with remaining crushed cookies. Cover and chill 4 hours.",

                    OverallRating = 4,
                    UserRating    = 2,
                    DateSubmitted = DateTime.Parse("3/9/2020"),
                    LastUpdated   = DateTime.Parse("3/9/2020"),
                    Category      = dessert,
                    Image         = "/css/images/lemonblueberry.jpg",
                    User          = new SiteUser()
                    {
                        UserName = "******", Nickname = "MC"
                    }
                };
                repo.AddRecipe(recipe);

                recipe = new Recipe
                {
                    RecipeName   = "From Scratch Oven Fries",
                    Ingredients  = "1.5lbs medium sized baking potatoes (peeled and cut into 0.5in thick strips), 1tbsp vegetable oil, 1/2 tsp kosher salt",
                    Instructions = "Preheat oven to 450°. Rinse potatoes in cold water. Drain and pat dry. Toss together potatoes, oil, and salt in a large bowl." +
                                   "Place a lightly greased wire rack in a jelly-roll pan. Arrange potatoes in a single layer on wire rack." +
                                   "Bake at 450° for 40 to 45 minutes or until browned. Serve immediately with ketchup, if desired.",

                    OverallRating = 3,
                    UserRating    = 5,
                    DateSubmitted = DateTime.Parse("3/9/2020"),
                    LastUpdated   = DateTime.Parse("3/9/2020"),
                    Category      = fromScratch,
                    Image         = "/css/images/fries.jpg",
                    User          = new SiteUser()
                    {
                        UserName = "******", Nickname = "Huckleberry"
                    }
                };
                repo.AddRecipe(recipe);

                recipe = new Recipe
                {
                    RecipeName   = "Whiskey Sour",
                    Ingredients  = "2 ounces bourbon whiskey, 1 ounce lemon juice, 1 1/2 tbsps maple syrup (or simple syrup), garnish of orange peel and cocktail cherry, ice for serving",
                    Instructions = "Add the bourbon whiskey, lemon juice, and syrup to a cocktail shaker. Fill with a handful of ice and shake until very cold." +
                                   "Strain the drink into a lowball or Old Fashioned glass. Serve with ice, an orange peel and a cocktail cherry. ",

                    OverallRating = 5,
                    UserRating    = 5,
                    DateSubmitted = DateTime.Parse("3/9/2020"),
                    LastUpdated   = DateTime.Parse("3/9/2020"),
                    Category      = drinks,
                    Image         = "/css/images/whiskeysour.jpg",
                    User          = new SiteUser()
                    {
                        UserName = "******", Nickname = "Chicken"
                    }
                };
                repo.AddRecipe(recipe);
            }
            ;
        }
Exemplo n.º 24
0
        public void SaveRecipeEditViewModel(RecipeEditViewModel model)
        {
            #region Recipe

            int measurementRecipeId = _measurementRepository.FindOrAddMeasurement(model.Measurement);

            IRecipeData recipeData = new RecipeData()
            {
                Id               = model.Id,
                Content          = model.Content,
                Description      = model.Description,
                IsPublished      = model.IsPublished,
                IsOnlyForFriends = model.IsOnlyForFriends,
                Name             = model.Name,
                Url              = model.Name.BuildUrl(),
                PublishDate      = ConvertPublishDate(model.PublishDate, model.PublishHour, model.PublishMinute),
                IngredientCount  = model.IngredientCount,
                Measurement      = new MeasurementData()
                {
                    Id = measurementRecipeId, Name = model.Measurement
                },
                PreparationTime = model.PreparationTime,
                WaitingTime     = model.WaitingTime,
                TeaserImageUrl  = model.TeaserImageUrl
            };
            if (model.Id == 0)
            {
                model.Id = _recipeRepository.AddRecipe(recipeData);
            }
            else
            {
                _recipeRepository.EditRecipe(recipeData);
            }
            #endregion

            #region TeaserImage
            if (model.TeaserImageUrl != null && model.TeaserImageUrl.ToLower().StartsWith("/upload/"))
            {
                string fileName    = model.TeaserImageUrl.ToLower().Replace("/upload/", "");
                string newFileName = fileName.BuildUrl();
                string mediaPath;
                string mediaExtension = "";
#if DEBUG
                mediaPath = "D:\\Dropbox\\Dokumente Peter\\Visual Studio\\ImageManager\\ImageManager.Web\\media\\LudwigsRezepte";
#else
                mediaPath = "C:\\DarkZero\\Dropbox\\DarkServer\\Webs\\ImageManager\\media\\LudwigsRezepte";
#endif

                mediaPath = mediaPath + "\\" + model.Id + "\\teaser\\";
                string uploadPath = Path.Combine(Environment.CurrentDirectory, "upload\\");

                Directory.CreateDirectory(mediaPath);
                if (File.Exists(mediaPath + newFileName))
                {
                    File.Delete(mediaPath + newFileName);
                }
                if (File.Exists(uploadPath + fileName))
                {
                    File.Move(uploadPath + fileName, mediaPath + newFileName);
                }

                string imageUrl = model.Id + "/teaser/" + newFileName;
                _recipeRepository.EditTeaserImage(model.Id, imageUrl);
            }
            #endregion

            #region IngredientList
            if (model.IngredientList != null)
            {
                List <int> IngredientListIds   = new List <int>();
                int        ingredientListOrder = 0;
                int        measurementId;
                int        ingredientId;
                foreach (IngredientListItemViewModel ingredientListItemViewModel in model.IngredientList)
                {
                    measurementId = _measurementRepository.FindOrAddMeasurement(ingredientListItemViewModel.MeasurementName);
                    ingredientId  = _ingredientRepository.FindOrAddIngredient(ingredientListItemViewModel.IngredientName);


                    if (measurementId != 0 && ingredientId != 0)
                    {
                        ingredientListOrder = ingredientListOrder + 1;
                        IngredientListIds.Add(_ingredientListRepository.AddOrUpdateIngredientListFromRecipe(new IngredientListData()
                        {
                            Id            = ingredientListItemViewModel.Id,
                            Amount        = ingredientListItemViewModel.Amount,
                            SortOrder     = ingredientListOrder,
                            IngredientId  = ingredientId,
                            MeasurementId = measurementId,
                            RecipeId      = model.Id
                        }));
                    }
                }
                _ingredientListRepository.DeleteIngredientListFromRecipeWhereNotInList(IngredientListIds, model.Id);
            }
            #endregion

            #region Categories
            List <int> categoryIds = model.Categories.Where(x => x.IsSelected == true).Select(x => x.Id).ToList();
            _categoryRespository.AddAndRemoveCategoriesFromRecipe(categoryIds, model.Id);
            List <int> subCategoryIds = model.Categories.SelectMany(x => x.SubCategories).Where(x => x.IsSelected == true).Select(x => x.Id).ToList <int>();
            _categoryRespository.AddAndRemoveSubCategoriesFromRecipe(subCategoryIds, model.Id);
            #endregion

            #region Contents
            _recipeRepository.DeleteAllRecipeContents(model.Id);
            int sortOrder = 1;
            foreach (var contentItem in model.ContentItems.OrderBy(x => x.SortOrder))
            {
                if (String.IsNullOrWhiteSpace(contentItem.Content))
                {
                    continue;
                }
                _recipeRepository.AddRecipeContent(model.Id, new LudwigRecipe.Data.DataModels.Recipe.RecipeContent()
                {
                    Content             = contentItem.Content,
                    RecipeContentTypeId = (int)contentItem.ContentType,
                    SortOrder           = sortOrder
                });
                sortOrder = sortOrder + 1;
            }
            #endregion
        }
        //public ViewResult Insert(RecipeModel recipeModel, string[] IngredientString)
        public ViewResult Insert(RecipeModel recipeModel)
        {
            if (ModelState.IsValid)
            {
                recipeModel.Recipe.DateTimeUpdate = DateTime.Now;

                long   size     = 0;
                string fileName = Request.Form.Files.ElementAt(0).FileName.ToString();

                foreach (var file in Request.Form.Files)
                {
                    var filename = ContentDispositionHeaderValue
                                   .Parse(file.ContentDisposition)
                                   .FileName
                                   .Trim('"');
                    filename = this.ihostingEnvironment.WebRootPath + url + fileName;
                    var urlfilename = this.ihostingEnvironment.WebRootPath + url + fileName;

                    size += file.Length;
                    using (FileStream fs = System.IO.File.Create(filename))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                }

                //The end of Upload File

                if (iRecipeRepo.Recipes.Where(r => r.RecipeId == recipeModel.Recipe.RecipeId).Count() == 0)
                {
                    recipeModel.Recipe.FileToUpload = url + fileName;

                    //Insert new recipe in recipe table
                    iRecipeRepo.AddRecipe(recipeModel.Recipe);

                    /**
                     * It is being generated loop to create ingredientDetail and RecipeIngredient table
                     * at the same time as much as the number of Ingredients by user
                     */

                    foreach (string ingredientString in recipeModel.IngredientString)
                    {
                        if (string.IsNullOrEmpty(ingredientString))
                        {
                            Console.WriteLine("There is a empty or null in the ingredient detail by the user input (ingredientString is null) in the recipe Id ["
                                              + recipeModel.Recipe.RecipeId + "]");
                        }
                        else
                        {
                            IngredientDetail ingredientDetail = new IngredientDetail();
                            ingredientDetail.IngredientString = ingredientString;
                            //Insert Ingredients details (IngredientString) of New Recipe in IngredientDetail Table
                            iIngredientDetailRepo.AddIngredientDetail(ingredientDetail);
                            // Insert Ingredients of New Recipe in RecipeIngredient Table as Bridge Table for many to many relations
                            // Between Recipe and IngredientDetail Table (Ingredient Informations)
                            iRecipeIngredientRepo.AddRecipeIngredient(
                                recipeModel.Recipe.RecipeId, ingredientDetail);
                        }
                    }


                    // Insert data (Model ID : 1, 2, 3 by the relationship Modal of new recipe) in RecipeModal Table as bridge table between recipe and Model (Model Id: 1, 2, 3)
                    //to display View/Edit/Delete Button in "Data/List.cshtml"

                    recipeModel.AllModalDetails = iModalDetailRepo.ModalDetails.ToList <ModalDetail>();

                    foreach (ModalDetail modalDetail in recipeModel.AllModalDetails)
                    {
                        iRecipeModalRepo.AllRecipeModal(recipeModel.Recipe.RecipeId, modalDetail);
                    }

                    return(View("../Recipe/Display", new SearchRecipeModel
                    {
                        RecipeCollection = iRecipeRepo.Recipes
                    }));
                }
                else
                {
                    return(View("Insert", recipeModel));
                }
            }
            else
            {
                return(View("Insert", recipeModel));
            }
        }
Exemplo n.º 26
0
 public void AddRecipe(Recipe recipe)
 {
     _recipeRepository.AddRecipe(recipe);
 }
Exemplo n.º 27
0
 public async Task <IActionResult> AddRecipe(AddRecipeDto newRecipe)
 {
     return(Ok(await _recipeRepository.AddRecipe(newRecipe)));
 }
Exemplo n.º 28
0
 public Recipe Post([FromBody] Recipe recipe)
 {
     _recipeRepository.AddRecipe(recipe);
     return(recipe);
 }
Exemplo n.º 29
0
 public IActionResult AddRecipe(Recipe recipe)
 {
     _recipes.AddRecipe(recipe);
     return(View());
 }