public MensagemDto EditRecipe(int id, RecipeDto recipe)
        {
            var RecipeToAdd = ConvertRecipeDto(recipe);
            var status      = _recipeRepository.EditRecipe(RecipeToAdd, id);

            return(MensagemToResponse(1, "Recipe Edit"));
        }
Esempio n. 2
0
        public void AddRecipeTest()
        {
            Database  database  = new Database();
            RecipeDto newRecipe = new RecipeDto()
            {
                Amount = 2,
                Name   = "Test",
                PreparationDescription = "DescriptionTest",
                PreparationTime        = new TimeSpan(0, 20, 0),
                SkillLevel             = "Begginer",
                Ingredients            = new List <IngredientDto>()
                {
                    new IngredientDto()
                    {
                        Amount = 2, IngredientName = "IngredientTest", Unit = "UnitTest"
                    },
                    new IngredientDto()
                    {
                        Amount = 2, IngredientName = "IngredientTest2", Unit = "UnitTest"
                    }
                }
            };

            database.AddRecipe(newRecipe);
            List <RecipeSimplifiedDto> list = database.GetRecipeList();

            foreach (RecipeSimplifiedDto r in list)
            {
                if (r.Name == "Test")
                {
                    return;
                }
            }
            Assert.Fail();
        }
Esempio n. 3
0
        public async Task <RecipeDto> Create(int userId, Recipe recipe)
        {
            string insertCommandText = @"INSERT INTO [dbo].[recipes] (recipe_title, recipe_description, recipe_slug, recipe_category, user_id)
                values (@recipeTitle, @recipeDescription, @recipeSlug, @recipeCategory, @userId)";

            SqlParameter recipe_title       = new SqlParameter("@recipeTitle", recipe.Title);
            SqlParameter recipe_description = new SqlParameter("@recipeDescription", recipe.Description);
            SqlParameter recipe_slug        = new SqlParameter("@recipeSlug", recipe.SlugUrl);
            SqlParameter recipe_category    = new SqlParameter("@recipeCategory", recipe.Category);
            SqlParameter user_id            = new SqlParameter("@userId", userId);

            Int32 rows = await SqlHelper.ExecuteNonQueryAsync(conStr, insertCommandText, CommandType.Text,
                                                              recipe_title, recipe_description, recipe_slug, recipe_category, user_id);

            if (rows >= 1)
            {
                var recipeToReturn = new RecipeDto
                {
                    Title       = recipe.Title,
                    Description = recipe.Description,
                    Url         = recipe.SlugUrl,
                    Category    = recipe.Category.ToString()
                };
                return(recipeToReturn);
            }

            throw new Exception("Problem creating recipe");
        }
Esempio n. 4
0
        // GET: Recipes/Details/5
        public ActionResult Details(int id)
        {
            ShowRecipe          ViewModel = new ShowRecipe();
            string              url       = "recipedata/findrecipe/" + id;
            HttpResponseMessage response  = client.GetAsync(url).Result;

            //Can catch the status code (200 OK, 301 REDIRECT), etc.
            //Debug.WriteLine(response.StatusCode);
            if (response.IsSuccessStatusCode)
            {
                //Put data into recipe data transfer object
                RecipeDto result         = response.Content.ReadAsAsync <RecipeDto>().Result;
                RecipeDto SelectedRecipe = result;
                ViewModel.recipe = SelectedRecipe;


                url              = "recipedata/finddishforrecipe/" + id;
                response         = client.GetAsync(url).Result;
                ViewModel.recipe = SelectedRecipe;

                return(View(ViewModel));
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
Esempio n. 5
0
        private void AddRate(RecipeDto recipe)
        {
            var rates = _ratesService.GetRates(recipe.Id);

            if (_loggedUser != null)
            {
                var loggedUserRate = rates.SingleOrDefault(x => x.User.Id == _loggedUser.Id);
                if (loggedUserRate != null)
                {
                    Console.WriteLine($"Your rate: {loggedUserRate.Score}");
                }
                else
                {
                    var choice = _getDataFromUser.GetData("Do you want to rate this recipe? Y/N");

                    if (choice.ToUpper() == "Y")
                    {
                        var score = _getDataFromUser.GetNumber("Your rate (0-10): ", 0, 10);
                        var rate  = new RateDto
                        {
                            Id     = Guid.NewGuid(),
                            Score  = score,
                            User   = _loggedUser,
                            Recipe = recipe
                        };
                        var result = _ratesService.AddRate(rate);
                        ShowResult(result);
                        UpdateLoggedUser();
                    }
                    ;
                }
            }
        }
Esempio n. 6
0
        public void updateRecipe_Test()
        {
            var listitemup = new RecipePatchDto {
                creatorId   = 1,
                name        = "Bulgur",
                description = "Boiled Bulgur fried with butter",
                rating      = 9.8F,
                tag         = "Turkish Cuisine"
            };
            var listitem = new RecipeDto {
                id          = 1,
                creatorId   = 1,
                name        = "Bulgur",
                description = "Boiled Bulgur fried with butter",
                rating      = 9.8F,
                tag         = "Turkish Cuisine"
            };
            var tobereturned = new List <RecipeDto>
            {
                listitem
            };

            _recipeRepository.Setup(x => x.UpdateRecipeById(1, listitemup)).Returns(listitem);
            _recipeRepository.Setup(x => x.GetRecipeById(1)).Returns(listitem);
            _recipeRepository.Setup(x => x.GetRecipes()).Returns(tobereturned);


            var tmp = _sut.ServiceUpdateRecipeById(1, listitemup);

            tmp.Should().BeEquivalentTo(listitem,
                                        options => options.ComparingByMembers <RecipeDto>());;
        }
        private static MashStepDto GetMashStepDto(RecipeDto recipeDto, int time)
        {
            var mashStepsDto = recipeDto.Steps.OfType <MashStepDto>();
            var mashStepDto  = mashStepsDto.Select(c => c).FirstOrDefault(m => m.Length == time);

            return(mashStepDto);
        }
Esempio n. 8
0
        public async Task <IActionResult> OnGet(int?recipeId)
        {
            Units = htmlHelper.GetEnumSelectList <UnitType>();

            var products = await repository.GetAllProductsAsync();

            Products = new SelectList(products.Select(p => p.Name));

            if (recipeId.HasValue)
            {
                var recipe = await repository.GetRecipeAsync(recipeId.Value);

                if (recipe == null)
                {
                    return(RedirectToPage("./NotFound"));
                }

                RecipeDto = mapper.Map <RecipeDto>(recipe);
            }
            else
            {
                RecipeDto = new RecipeDto();
            }

            return(Page());
        }
Esempio n. 9
0
        public void UpdateRecipe(int id, RecipeDto recipeDto)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            var recipeInDb = _context.Recipes.SingleOrDefault(c => c.Id == id);

            if (recipeInDb == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            //This line can be simplified to removing the <RecipeDto, Recipe>
            Mapper.Map <RecipeDto, Recipe>(recipeDto, recipeInDb);

            // The line above means we dont need to track changes via assignment, we're doing it via mapping instead.

            //recipeInDb.Name = recipeDto.Name;
            //recipeInDb.RecipeTypeId = recipeDto.RecipeTypeId;
            //recipeInDb.PrepTime = recipeDto.PrepTime;
            //recipeInDb.CookTime = recipeDto.CookTime;
            //recipeInDb.Description = recipeDto.Description;
            //recipeInDb.Directions = recipeDto.Directions;
            //recipeInDb.Ingredients = recipeDto.Ingredients;
            //recipeInDb.Username = recipeDto.Username;

            _context.SaveChanges();
        }
        private void SetStepNumber(RecipeDto recipeDto)
        {
            var stepNumber = 1;

            foreach (var item in recipeDto.Steps.OfType <MashStepDto>())
            {
                var mashStep = item;
                mashStep.StepNumber = stepNumber;
                stepNumber++;
            }
            //TODO: SPARGE STEP
            //if (recipeDto.Steps.All(s => s.Type != "sparge"))
            //{
            //    recipeDto.SpargeStep.StepNumber = stepNumber;
            //    stepNumber++;
            //}

            foreach (var boilStep in recipeDto.Steps.OfType <BoilStepDto>())
            {
                boilStep.StepNumber = stepNumber;
                stepNumber++;
            }

            foreach (var item in recipeDto.Steps.OfType <FermentationStepDto>())
            {
                var fermentationStep = item;
                fermentationStep.StepNumber = stepNumber;
                stepNumber++;
            }
        }
Esempio n. 11
0
        public async Task <ActionResult <IEnumerable <RecipeDto> > > GetAsync()
        {
            var recipes = await this.recipeProvider.GetAll();

            var returnValue = new List <RecipeDto>();

            foreach (var recipe in recipes)
            {
                var ingredients = await this.ingredientProvider.GetAllByRecipeId(recipe.Id);

                var howTos = await this.cookingProcedureProvider.GetAllByRecipeId(recipe.Id);

                var mappedRecipe = new RecipeDto();

                mappedRecipe.Id                    = recipe.Id;
                mappedRecipe.Title                 = recipe.Title;
                mappedRecipe.Description           = recipe.Description;
                mappedRecipe.Image                 = recipe.Image;
                mappedRecipe.SourceUrl             = recipe.SourceUrl;
                mappedRecipe.Ingredients           = ingredients?.ToList();
                mappedRecipe.CookingProcedureSteps = howTos?.Select(x => x.Step).ToArray();

                returnValue.Add(mappedRecipe);
            }

            return(Ok(returnValue));
        }
Esempio n. 12
0
        public void Post([FromBody] RecipeDto value)
        {
            var recipe = _mapper.Map <Recipe>(value);

            recipe.Id = Guid.NewGuid();
            _repo.Insert(recipe);
        }
Esempio n. 13
0
 public RecipeSelect(RecipeDto dto)
 {
     Id          = dto.Id;
     Name        = dto.Name;
     Ingredients = dto.Ingredients ?? new List <IngredientDto>();
     Price       = dto.Price;
 }
Esempio n. 14
0
        public void Save(RecipeDto recipeDto)
        {
            Recipe recipe;

            if (recipeDto.Id == 0)
            {
                recipe = new Recipe();
                _appDbContext.Add(recipe);
            }
            else
            {
                recipe = this._appDbContext.Recipes.Find(recipeDto.Id);
            }

            recipe.Calories    = recipeDto.Calories;
            recipe.Country     = recipeDto.Country;
            recipe.Description = recipeDto.Description;
            recipe.Ingredients = recipeDto.Ingredients;
            recipe.Name        = recipeDto.Name;
            recipe.Year        = recipeDto.Year;

            _appDbContext.Entry(recipe).OriginalValues["RowVersion"] = recipeDto.RowVersion;

            try
            {
                _appDbContext.SaveChanges();
            }
            catch (DbUpdateConcurrencyException e)
            {
                throw new WebApiException("Item already updated by someone, please refresh entity");
            }


            _recepieHistoryService.AddRecord(recipe);
        }
Esempio n. 15
0
        public async Task <ActionResult> Post(RecipeDto recipeDto)
        {
            var recipe = mapper.Map <Recipe>(recipeDto);

            context.Recipes.Add(recipe);

            await context.SaveChangesAsync();

            //try
            //{
            //    await context.SaveChangesAsync();
            //}
            //catch (Exception ex)
            //{
            //    if (ex.InnerException != null)
            //    {
            //        Console.WriteLine(ex.InnerException.Message.ToString());
            //    }
            //    else
            //    {
            //        Console.WriteLine("chuj");
            //    }
            //}

            return(new OkResult());
        }
Esempio n. 16
0
        private static List <RecipeTool> RecipeDtoToRecipeTools(RecipeDto recipeDto)
        {
            var recipeTools = new List <RecipeTool>();

            foreach (var toolDto in recipeDto.Tools)
            {
                var recipeTool = new RecipeTool()
                {
                    Recipe = new Recipe()
                    {
                        Id   = recipeDto.Id,
                        Name = recipeDto.Name
                    },
                    Tool = new Tool()
                    {
                        Id   = toolDto.Id,
                        Name = toolDto.Name
                    },
                    Quantity = toolDto.Quantity
                };

                recipeTools.Add(recipeTool);
            }

            return(recipeTools);
        }
Esempio n. 17
0
        public void UpdateRecipeTest()
        {
            // Arrange
            var repoMock = new Mock <IRecipeRepo>();
            var id       = 1;
            var after    = new RecipePatchDto()
            {
                creatorId   = 1,
                name        = "test",
                description = "test",
                rating      = 6.7F,
                tag         = "test"
            };
            var returned = new RecipeDto()
            {
                id          = 1,
                creatorId   = 1,
                name        = "test",
                description = "test",
                rating      = 6.7F,
                tag         = "test"
            };

            repoMock.Setup(p => p.UpdateRecipeById(id, after)).Returns(returned);
            var service = new AdminManageRecipeServices(repoMock.Object);
            var ctl     = new AdminManageRecipeController(service);
            // Act
            var result = ctl.updateRecipe(id, after).Result as OkObjectResult;

            // Assert
            result.Value.Should().BeEquivalentTo(returned, options => options.ComparingByMembers <Recipe>());
        }
Esempio n. 18
0
 public Recipe(RecipeDto dto)
 {
     Id    = dto.Id;
     Name  = dto.Name;
     Price = dto.Price;
     IngredientsForRecipe = dto.Ingredients ?? new List <IngredientDto>();
 }
Esempio n. 19
0
        public IBUDto CalculateIBUDto(RecipeDto recipe)
        {
            var og  = recipe.OG;
            var ibu = new IBUDto();

            var tinseth = 0.0;
            var rager   = 0.0;

            foreach (var item in recipe.Steps.OfType <BoilStepDto>())
            {
                var boilStep           = (BoilStepDto)item;
                var tinsethUtilisation = Formulas.TinsethUtilisation(og, boilStep.Length);
                var ragerUtilisation   = Formulas.RangerUtilisation(boilStep.Length);
                foreach (var hop in boilStep.Ingredients.OfType <HopStepDto>())
                {
                    var tinasethMgl = Formulas.TinsethMgl(hop.Amount, hop.AAValue, recipe.Volume);
                    tinseth += Formulas.TinsethIbu(tinasethMgl, tinsethUtilisation);
                    rager   += Formulas.RangerIbu(hop.Amount, ragerUtilisation, hop.AAValue, recipe.Volume, og);
                }
            }

            ibu.Tinseth  = Math.Round(tinseth, 1);
            ibu.Standard = Math.Round(tinseth, 1);
            ibu.Rager    = Math.Round(rager, 1);
            return(ibu);
        }
        private static FermentationStepDto GetFermentationStepDto(RecipeDto recipeDto, int time)
        {
            var fermentationSteps = recipeDto.Steps.OfType <FermentationStepDto>();
            var fermentationStep  = fermentationSteps?.FirstOrDefault(f => f.Length == time / 24);

            return(fermentationStep != null ? fermentationStep : fermentationSteps?.Select(f => f).FirstOrDefault());
        }
Esempio n. 21
0
        /// <summary>
        /// Converts the recipe to its update variant
        /// </summary>
        /// <param name="recipe"></param>
        /// <returns></returns>
        public static RecipeUpdate ToUpdate(this RecipeDto recipe)
        {
            //TODO: no, just no
            var json = Json.Serialize(recipe);

            return(Json.Deserialize <RecipeUpdate>(json));
        }
Esempio n. 22
0
        public bool Create(RecipeDto recipe)
        {
            using (var db = new SqlConnection(ConfigurationManager.ConnectionStrings["AmberAndGrain"].ConnectionString))
            {
                db.Open();

                var numberCreated = db.Execute(@"INSERT INTO [dbo].[Recipes]
                                               ([Name]
                                               ,[PercentWheat]
                                               ,[PercentCorn]
                                               ,[BarrelAge]
                                               ,[BarrelMaterial]
                                               ,[Creator])
                                         VALUES
                                               (@Name
                                               ,@PercentWheat
                                               ,@PercentCorn
                                               ,@BarrelAge
                                               ,@BarrelMaterial
                                               ,@Creator)", recipe);
                // success is that we created exactly one thing
                // if one thing was not created, the method does not work
                return(numberCreated == 1);
            }
        }
        public void Change(RecipeDto recipeDto)
        {
            if (recipeDto is null)
            {
                throw new ArgumentNullException();
            }

            if (recipeDto.Id == 0)
            {
                throw new ArgumentException("Id cannot be zero");
            }

            var recipe = _db.Recipes.GetOne(obj
                                            => obj.Id == recipeDto.Id);

            _mapper.Map(recipeDto, recipe);

            recipe.Ingredients = AddIngredients(recipeDto.Ingredients);

            if (recipe.PricePerGram != recipeDto.PricePerGram)
            {
                recipe.Dishes = ChangeDishes(recipe.Dishes.ToList(), recipeDto.PricePerGram);
            }

            _db.Save();
        }
        public IHttpActionResult GetRecipeById(int id)
        {
            try
            {
                using (var db = new ApplicationDbContext())
                {
                    var recipe = db.Recipes.Find(id);
                    if (recipe == null)
                    {
                        return(NotFound());
                    }
                    var rec = new RecipeDto()
                    {
                        Id          = recipe.Id,
                        Name        = recipe.Name,
                        DateAdded   = recipe.DateAdded,
                        ImageUrl    = recipe.ImageUrl,
                        Description = recipe.Description,
                        AddedBy     = recipe.AddedBy,
                        TimeToMake  = recipe.TimeToMake
                    };

                    return(Ok(rec));
                }
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }
        }
Esempio n. 25
0
        public void UpdateRecipe(RecipeDto recipeToUpdate, RecipeDto recipeDtoWithNewValues)
        {
            var recipe = recipeContext.Recipes.SingleOrDefault(r => r.Id == recipeToUpdate.Id);

            mapper.Map(recipeDtoWithNewValues, recipe);
            recipeContext.SaveChanges();
        }
Esempio n. 26
0
        public async Task <ActionResult <Recipe> > PostRecipe(RecipeDto newRecipe)
        {
            var ingredients    = newRecipe.Ingredients;
            var newIngredients = new List <Ingredient>();

            foreach (var ingredient in ingredients)
            {
                var newIngredient = await createNewIngredient(ingredient);

                newIngredients.Add(newIngredient);
            }

            var recipe = new Recipe
            {
                Name        = newRecipe.Name,
                Description = newRecipe.Description,
                Ingredients = newIngredients
            };

            await _context.Recipes.AddAsync(recipe);

            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetRecipeById), new { id = recipe.Id }, recipe));
        }
        public MensagemDto AddRecipe(RecipeDto recipe)
        {
            var RecipeToAdd = ConvertRecipeDto(recipe);
            var status      = _recipeRepository.AddRecipe(RecipeToAdd);

            return(MensagemToResponse(1, "Recipe Add"));
        }
Esempio n. 28
0
        public static IBUDto CalculateIBUDto(RecipeDto recipe)
        {
            var og  = recipe.OG;
            var ibu = new IBUDto {
                IbuId = recipe.Id
            };

            var tinseth = 0.0;
            var rager   = 0.0;

            foreach (var boilStep in recipe.BoilSteps)
            {
                var tinsethUtilisation = Formulas.TinsethUtilisation(og, boilStep.Length);
                var ragerUtilisation   = Formulas.RangerUtilisation(boilStep.Length);
                foreach (var hop in boilStep.Hops)
                {
                    var tinasethMgl = Formulas.TinsethMgl(hop.Amount, hop.AAValue, recipe.Volume);
                    tinseth += Formulas.TinsethIbu(tinasethMgl, tinsethUtilisation);
                    rager   += Formulas.RangerIbu(hop.Amount, ragerUtilisation, hop.AAValue, recipe.Volume, og);
                }
            }

            ibu.Tinseth  = Math.Round(tinseth, 1);
            ibu.Standard = Math.Round(tinseth, 1);
            ibu.Rager    = Math.Round(rager, 1);
            return(ibu);
        }
Esempio n. 29
0
        // GET: Recipe/Edit/5
        public ActionResult Edit(int id)
        {
            UpdateRecipe ViewModel = new UpdateRecipe();

            string url = "recipedata/findrecipe/" + id;
            HttpResponseMessage response = client.GetAsync(url).Result;

            //Can catch the status code (200 OK, 301 REDIRECT), etc.
            //Debug.WriteLine(response.StatusCode);
            if (response.IsSuccessStatusCode)
            {
                //Put data into recipe data transfer object
                RecipeDto SelectedRecipes = response.Content.ReadAsAsync <RecipeDto>().Result;
                ViewModel.recipe = SelectedRecipes;

                //get information about dish this recipe COULD be used for.
                url      = "dishdata/getdishes";
                response = client.GetAsync(url).Result;
                IEnumerable <DishesDto> PotentialDishes = response.Content.ReadAsAsync <IEnumerable <DishesDto> >().Result;
                ViewModel.alldishes = PotentialDishes;

                return(View(ViewModel));
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
        public ActionResult Create()
        {
            var recipeDto = new RecipeDto();

            recipeDto.UserId = Convert.ToInt32(Session["UserID"]);
            return(View(recipeDto));
        }
Esempio n. 31
0
 private async Task SetDirections(RecipeDto recipe)
 {
     using (var dc = RecipeContext.ContextFactory())
     {
         recipe.Directions = await dc.Directions
         .Where(d => d.Recipe.RecipeId == recipe.Id)
         .OrderBy(d => d.LineNumber)
         .Select(d => d.Description)
         .ToListAsync();
     }
 }
Esempio n. 32
0
 private async Task SetIngredients(RecipeDto recipe)
 {
     using (var dc = RecipeContext.ContextFactory())
     {
         recipe.Ingredients = await 
             (from r in dc.Recipes
              where r.RecipeId == recipe.Id
              from i in r.Ingredients
              orderby i.SortOrder
              select new IngredientDto { Decription = i.Description, Amount = i.Units, AmountType = i.UnitType })
             .ToListAsync();
     }  
 }
Esempio n. 33
0
 private async Task SetCategories(RecipeDto recipe)
 {
     using (var dc = RecipeContext.ContextFactory())
     {
         recipe.Categories = await dc.Categories
         .Where(c => c.Recipes.Any(r => r.RecipeId == recipe.Id))
         .Select(c => c.Description)
         .ToListAsync();
     }
 }