Exemplo n.º 1
0
        public async Task <IActionResult> Edit(RecipeViewModel recipeViewModel)
        {
            if (base.ModelState.IsValid)
            {
            }
            Recipe recipe = new Recipe
            {
                RecipeId            = recipeViewModel.RecipeId,
                Title               = recipeViewModel.Title,
                MealSize            = recipeViewModel.MealSize,
                MealPreparationTime = recipeViewModel.MealPreparationTime,
                Directions          = recipeViewModel.Directions,
                UrlImage            = recipeViewModel.UrlImage,
                Ingredients         = recipeViewModel.Ingredients
            };
            await _recipeService.EditRecipe(recipe);

            if (recipe == null)
            {
                return(NotFound());
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Edit(RecipeViewModel model)
        {
            if (ModelState.IsValid)
            {
                var path = model.ImageUrl;

                if (model.ImageFile != null)
                {
                    path = await _imageHelper.UploadImageAsync(model.ImageFile);
                }

                var recipe = await _converterHelper.ToRecipeAsync(model, path);

                _context.Recipes.Update(recipe);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }


            model.RecipeTypes = _combosHelper.GetComboRecipeTypes();
            return(View(model));
        }
Exemplo n.º 3
0
        public IList <RecipeViewModel> GetRecipes()
        {
            var recipes = appDbContext.Recipes.ToList();
            IList <RecipeViewModel> recipeViewModels = new List <RecipeViewModel>();

            foreach (Recipe recipe in recipes)
            {
                var ingredientAssignments = appDbContext.IngredientAssignments.Select(n => n)
                                            .Where(c => c.Recipe.IsActive)
                                            .Where(c => c.Recipe.Id == recipe.Id).ToList();

                RecipeViewModel recipeViewModel = new RecipeViewModel
                {
                    Id           = recipe.Id,
                    Name         = recipe.Name,
                    Instruction  = recipe.Instruction,
                    Type_of_dish = recipe.Type_of_dish,
                    Ingredients  = ingredientAssignments
                };
                recipeViewModels.Add(recipeViewModel);
            }
            return(recipeViewModels);
        }
Exemplo n.º 4
0
        public ResultDto <RecipeDto> Insert(RecipeViewModel recipeViewModel)
        {
            var result = new ResultDto <RecipeDto>();

            if (_recipeRepository.Exist(x => x.Name.ToLower() == recipeViewModel.Name.ToLower() && x.Author.ToLower() == recipeViewModel.Author.ToLower()))
            {
                result.Errors.Add(_Errors.RecipeDoesNotExist);
            }
            if (result.IsError)
            {
                return(result);
            }
            var recipe = _mapper.Map <Recipe>(recipeViewModel);

            if (_recipeRepository.Insert(recipe) == 0)
            {
                result.Errors.Add(_Errors.SaveFail);
                return(result);
            }
            result.SuccessResult = _mapper.Map <RecipeDto>(recipe);

            return(result);
        }
        // GET: Instructors/Edit/5
        public IActionResult Edit(int id)
        {
            var recipe = _recipeRepository.GetById <Recipe>(id);

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

            RecipeViewModel recipeViewModel = new RecipeViewModel
            {
                RecipeId       = recipe.RecipeId,
                Name           = recipe.Name,
                PictureId      = recipe.PictureId,
                Description    = recipe.Description,
                Price          = recipe.Price,
                RecipeCategory = recipe.Category
            };

            PopulateCategoriesList(recipe.RecipeId);

            return(View(recipeViewModel));
        }
Exemplo n.º 6
0
        // GET /api/recipes/1
        public IHttpActionResult GetRecipe(int id)
        {
            var recipe = db.Recipes.SingleOrDefault(r => r.Id == id);

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

            var ingredients = db.Ingredients
                              .Include(i => i.Unit)
                              .Include(i => i.Product)
                              .Where(i => i.Recipe.Id == recipe.Id).ToList();


            var products = new List <Product>();
            var units    = new List <Unit>();
            var amounts  = new List <float>();

            foreach (var ingredient in ingredients)
            {
                products.Add(ingredient.Product);
                units.Add(ingredient.Unit);
                amounts.Add(ingredient.Amount);
            }

            var recipeViewModel = new RecipeViewModel()
            {
                Recipe   = recipe,
                Products = products,
                Units    = units,
                Amounts  = amounts
            };


            return(Ok(recipeViewModel));
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Index(string searchString)
        {
            _recipesContext = await _context.Recipe.Include(r => r.User)
                              .Where(r => r.RecipeApprovalStatus == RecipeApprovalStatus.Approved)
                              .OrderByDescending(r => r.ApprovedDate)
                              .ToListAsync();

            ViewData["IsFiltered"] = false;
            if (!string.IsNullOrEmpty(searchString))
            {
                _recipesContext = _recipesContext
                                  .Where(r => r.User.FirstName.ToLower().Contains(searchString.ToLower()) ||
                                         r.User.LastName.ToLower().Contains(searchString.ToLower()) ||
                                         r.RecipeName.ToLower().Contains(searchString.ToLower()))
                                  .OrderByDescending(r => r.ApprovedDate)
                                  .ToList();

                ViewData["IsFiltered"] = true;
            }

            if (_recipesContext.Count() > ITEMS_PER_PAGE)
            {
                ViewData["PaginationCount"] = ((_recipesContext.Count() - 1) / ITEMS_PER_PAGE) + 1;
            }
            _currentRange = 0;

            RecipeViewModel model = new RecipeViewModel();

            model.Recipes = _recipesContext.OrderByDescending(r => r.ApprovedDate).Skip(_currentRange).Take(ITEMS_PER_PAGE).ToList();
            BannerImages bannerImages = _context.BannerImages.Where(bi => bi.BannerType == BannerType.Recipe && bi.BannerStatus == BannerStatus.Active).FirstOrDefault();

            if (bannerImages != null)
            {
                model.RecipeBannerImageUrl = bannerImages.BannerUrl;
            }
            return(View(model));
        }
Exemplo n.º 8
0
        public void EditRecipe_CategoryChanged_RecipeUpdated()
        {
            var newRecipe = new RecipeViewModel()
            {
                Categories   = "1, 2",
                Ingredients  = "cheese",
                Instructions = "just cook and eat",
                Name         = "aaaa",
                RecipeId     = 1,
            };

            var newContext = new ApplicationContext(options);

            recipeController = new RecipeController(newContext);

            recipeController.EditRecipe(newRecipe).Wait();

            navMenu.CategoriesMenuViewModels = NavMenu.GenerateMenu(newContext.Recipes.ToList());

            newContext.Recipes.Count().Should().Be(3);

            newContext.Recipes.First(r => r.RecipeId == 1).Name.Should().Be("aaaa");
            navMenu.CategoriesMenuViewModels.Count.Should().Be(2);
        }
Exemplo n.º 9
0
        public IActionResult Index(RecipeViewModel recipeViewModel)
        {
            var recipeEnt = db.Recipes.Add(recipeViewModel.Recipe).Entity;
            var waterEnt  = db.Waters.Add(recipeViewModel.Water).Entity;

            db.WatersRecipes.Add(new WaterRecipe()
            {
                Recipe   = recipeEnt,
                RecipeId = recipeEnt.RecipeId,
                Water    = waterEnt,
                WaterId  = waterEnt.WaterId
            });

            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                throw;
            }

            return(View());
        }
Exemplo n.º 10
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            RecipeViewModel rvm    = new RecipeViewModel();
            Recipe          recipe = db.Recipes.Find(id);

            // Check if Author is Owner of the Recipe
            if (User.Identity.Name == recipe.Author || User.IsInRole("Admin"))
            {
                var tags = db.Tags.ToList();
                rvm.Recipe        = recipe;
                rvm.Recipe.Author = User.Identity.Name;
                rvm.AllTags       = tags.Select(m => new SelectListItem {
                    Text = m.Name, Value = m.Id.ToString()
                });

                List <int> selectedTags = new List <int>();
                foreach (var tag in rvm.Recipe.Tags)
                {
                    selectedTags.Add(tag.Id);
                }

                ViewBag.recipeSelectedTagsIds = selectedTags;

                if (recipe == null)
                {
                    return(HttpNotFound());
                }
                return(View(rvm));
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 11
0
        public IActionResult Recipe(RecipeViewModel recipeViewModel)
        {
            var waterEnt       = db.Waters.Add(recipeViewModel.Water).Entity;
            var hopEnt         = db.Hops.Add(recipeViewModel.Hop).Entity;
            var fermentableEnt = db.Fermentable.Add(recipeViewModel.Fermentable).Entity;
            var yeastEnt       = db.Yeast.Add(recipeViewModel.Yeast).Entity;
            var miscEnt        = db.Misc.Add(recipeViewModel.Misc).Entity;
            var equipmentEnt   = db.Equipment.Add(recipeViewModel.Equipment).Entity;
            var mashEnt        = db.Mash.Add(recipeViewModel.Mash).Entity;
            var styleEnt       = db.Style.Add(recipeViewModel.Style).Entity;

            recipeViewModel.Recipe.StyleId = styleEnt.StyleId;
            var recipeEnt = db.Recipes.Add(recipeViewModel.Recipe).Entity;

            foreach (var item in recipeViewModel.MashSteps)
            {
                if (item.Name != null) //  zabezpieczenie z powodu luki w oknie modal js
                {
                    var mashStepEnt = db.MashStep.Add(item).Entity;

                    var mashStepMash = db.MashStepMash.Add(new MashStepMash()
                    {
                        Mash       = mashEnt,
                        MashId     = mashEnt.MashId,
                        MashStep   = mashStepEnt,
                        MashStepId = mashStepEnt.MashStepId
                    }).Entity;
                }
            }

            db.WatersRecipes.Add(new WaterRecipe()
            {
                Recipe   = recipeEnt,
                RecipeId = recipeEnt.RecipeId,
                Water    = waterEnt,
                WaterId  = waterEnt.WaterId
            });

            db.HopRecipes.Add(new HopRecipe()
            {
                Recipe   = recipeEnt,
                RecipeId = recipeEnt.RecipeId,
                Hop      = hopEnt,
                HopId    = hopEnt.HopId
            });

            db.FermentableRecipes.Add(new FermentableRecipe()
            {
                Recipe        = recipeEnt,
                RecipeId      = recipeEnt.RecipeId,
                Fermentable   = fermentableEnt,
                FermentableId = fermentableEnt.FermentableId
            });

            db.YeastRecipe.Add(new YeastRecipe()
            {
                Recipe   = recipeEnt,
                RecipeId = recipeEnt.RecipeId,
                Yeast    = yeastEnt,
                YeastId  = yeastEnt.YeastId
            });

            db.MiscRecipe.Add(new MiscRecipe()
            {
                Recipe   = recipeEnt,
                RecipeId = recipeEnt.RecipeId,
                Misc     = miscEnt,
                MiscId   = miscEnt.MiscId
            });

            db.EquipmentRecipe.Add(new EquipmentRecipe()
            {
                Recipe      = recipeEnt,
                RecipeId    = recipeEnt.RecipeId,
                Equipment   = equipmentEnt,
                EquipmentId = equipmentEnt.EquipmentId
            });

            db.MashRecipe.Add(new MashRecipe()
            {
                Recipe   = recipeEnt,
                RecipeId = recipeEnt.RecipeId,
                Mash     = mashEnt,
                MashId   = mashEnt.MashId
            });

            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                throw;
            }

            return(RedirectToAction("Index", "Display"));
        }
Exemplo n.º 12
0
 //updates ingredients to save for later
 public void SaveIngredientsForLater(RecipeViewModel recipeViewModel)
 {
     _databaseRepository.SaveIngredientsForLater(_mapperService.MapIngredientList(recipeViewModel.Ingredients));
 }
Exemplo n.º 13
0
        public IActionResult AddRecipe([FromBody] RecipeViewModel recipe)
        {
            var response = _RecipeService.AddRecipe(recipe).Result;

            return(new OkObjectResult(response));
        }
Exemplo n.º 14
0
 /// <summary>
 /// Add View Model for recipe to list of all recipesViewModels.
 /// </summary>
 /// <param name="recipeViewModel"></param>
 public static void AddRecipe([NotNull] RecipeViewModel recipeViewModel)
 {
     recipeList.AddIfNotContains(recipeViewModel);
     resourceDictionaryPaths.Add(recipeViewModel.ResourceDictionaryFolderName +
                                 recipeViewModel.ResourceDictionaryName);
 }
Exemplo n.º 15
0
        /// <summary>
        /// Populate allEntityDictionary for all instance of IProtoEntity with corresponding ViewModels.
        /// </summary>
        private static void SetAllEntitiesViewModels()
        {
            List <IProtoEntity> allEntitiesList = Api.FindProtoEntities <IProtoEntity>();

            foreach (IProtoEntity entity in allEntitiesList)
            {
                Type entityType = entity.GetType();
                //Api.Logger.Warning("CNEI: Looking types for " + entity);
                bool templateFound = false;
                ProtoEntityViewModel newEntityViewModel = null;
                do
                {
                    Type currentType = Type.GetType("CryoFall.CNEI.UI.Data." +
                                                    GetNameWithoutGenericArity(entityType.Name) + "ViewModel");
                    //Api.Logger.Info("CNEI: " + entityType.Name + "  " + GetNameWithoutGenericArity(entityType.Name)
                    //                + " " + currentType);
                    if (currentType != null && !currentType.IsAbstract)
                    {
                        try
                        {
                            if (currentType == typeof(RecipeViewModel))
                            {//This is shit code and I don't like it.
                                newEntityViewModel = RecipeViewModel.SelectBasicRecipe(entity);
                            }
                            else
                            {
                                newEntityViewModel = (ProtoEntityViewModel)Activator.CreateInstance(currentType, entity);
                            }
                        }
                        catch (MissingMethodException)
                        {
                            Api.Logger.Error("CNEI: Can not apply constructor of " + currentType + " type for " + entity);
                        }
                        if (newEntityViewModel != null)
                        {
                            if (newEntityViewModel is RecipeViewModel newRecipeViewModel)
                            {
                                AddRecipe(newRecipeViewModel);
                            }
                            EntityTypeHierarchy.Add(entity.GetType(), newEntityViewModel);
                            allEntityDictionary.Add(entity, newEntityViewModel);
                            resourceDictionaryPaths.Add(newEntityViewModel.ResourceDictionaryFolderName +
                                                        newEntityViewModel.ResourceDictionaryName);
                            templateFound = true;
                        }
                    }
                    entityType = entityType.BaseType;
                } while (entityType != null && (entityType.BaseType != null) && (!templateFound));
                if (entityType == null)
                {
                    Api.Logger.Warning("CNEI: Template for " + entity + "not found");
                    newEntityViewModel = new ProtoEntityViewModel(entity);
                    EntityTypeHierarchy.Add(entity.GetType(), newEntityViewModel);
                    allEntityDictionary.Add(entity, newEntityViewModel);
                    resourceDictionaryPaths.Add(newEntityViewModel.ResourceDictionaryFolderName +
                                                newEntityViewModel.ResourceDictionaryName);
                }
            }

            allEntityCollection = new ObservableCollection <ProtoEntityViewModel>(allEntityDictionary.Values);
            allEntityWithTemplatesCollection = new ObservableCollection <ProtoEntityViewModel>(
                allEntityCollection.Where(vm => vm.GetType().IsSubclassOf(typeof(ProtoEntityViewModel))));
        }
Exemplo n.º 16
0
 /// <summary>
 /// Add View Model for recipe to list of all recipesViewModels.
 /// </summary>
 /// <param name="recipeViewModel"></param>
 public static void AddRecipe([NotNull] RecipeViewModel recipeViewModel)
 {
     recipeList.AddIfNotContains(recipeViewModel);
 }
        public ActionResult View(int id)
        {
            var recipeBL = recipeService.GetRecipeByID(id);

            var recipe = new RecipeViewModel()
            {
                RecipeID        = recipeBL.RecipeID,
                CookTime        = recipeBL.CookTime,
                Description     = recipeBL.Description,
                LongDescription = recipeBL.LongDescription,
                Name            = recipeBL.Name,
                RatingID        = recipeBL.RatingID,
                PictureLocation = recipeBL.PictureLocation,
                PrepTime        = recipeBL.PrepTime
            };
            var ingredientsBL  = ingredientService.GetAllIngredientsForRecipe(recipe.RecipeID);
            var instructionsBL = instructionsService.GetAllInstructionsForRecipe(recipe.RecipeID);
            var commentsBL     = commentService.GetAllCommentsForRecipe(recipe.RecipeID);
            var ratingBL       = ratingService.GetRatingByID(recipe.RatingID);

            var ingredients  = new List <IngredientViewModel>();
            var instructions = new List <InstructionViewModel>();
            var comments     = new List <CommentsViewModel>();
            var rating       = new RatingViewModel()
            {
                RatingID        = ratingBL.RatingID,
                NumberOfRatings = ratingBL.NumberOfRatings,
                Score           = ratingBL.Score,
                SumRatings      = ratingBL.SumRatings
            };



            foreach (var i in ingredientsBL)
            {
                ingredients.Add(new IngredientViewModel()
                {
                    IngredientID = i.IngredientID,
                    Name         = i.Name,
                    Quantity     = i.Quantity
                });
            }

            foreach (var i in instructionsBL)
            {
                instructions.Add(new InstructionViewModel()
                {
                    InstructionID   = i.InstructionID,
                    InstructionText = i.InstructionText
                });
            }

            foreach (var i in commentsBL)
            {
                comments.Add(new CommentsViewModel()
                {
                    CommentID = i.CommentID,
                    Comment   = i.CommentText,
                    RecipeID  = id
                });
            }
            recipe.Score            = rating.Score;
            recipe.NrOfRatings      = rating.NumberOfRatings;
            recipe.ListIngredients  = ingredients;
            recipe.ListInstructions = instructions;
            recipe.ListComments     = comments;
            return(View(recipe));
        }
Exemplo n.º 18
0
        public IActionResult Edit(Recipe recipe)
        {
            Ingredient tempIngredient;

            foreach (var component in recipe.RecipeComponents)
            {
                tempIngredient = _ingredientData.GetIngredientByExactName(component.Ingredient.Name);
                if (tempIngredient != null)
                {
                    component.Ingredient   = tempIngredient;
                    component.IngredientId = tempIngredient.Id;
                }

                if (component.Id > 0)
                {
                    _recipeComponentData.Update(component);
                }
                else
                {
                    _recipeComponentData.Add(component);
                }
            }


            if (!ModelState.IsValid)
            {
                var viewModel = new RecipeViewModel(_htmlHelper)
                {
                    Recipe = recipe
                };
                return(View(recipe));
            }
            string webRootPath = _webHostEnvironment.WebRootPath;
            var    files       = HttpContext.Request.Form.Files;

            if (recipe.Id > 0)
            {
                if (files.Count > 0)
                {
                    string fileName      = Guid.NewGuid().ToString();
                    var    uploads       = Path.Combine(webRootPath, @"images\recipes");
                    var    extension_new = Path.GetExtension(files[0].FileName);
                    string currentImg    = "";
                    if (recipe.ImageUrl != null)
                    {
                        currentImg = recipe.ImageUrl.TrimStart('\\');
                    }

                    var imagePath = Path.Combine(webRootPath, currentImg);
                    if (System.IO.File.Exists(imagePath))
                    {
                        System.IO.File.Delete(imagePath);
                    }
                    using (var fileStreams = new FileStream(Path.Combine(uploads, fileName + extension_new), FileMode.Create))
                    {
                        var imageFactory = new ImageFactory(true);
                        imageFactory.Load(files[0].OpenReadStream()).Resize(
                            new ResizeLayer(new Size(720, 480), ResizeMode.Max)).Save(fileStreams);

                        //files[0].CopyTo(fileStreams);
                    }
                    recipe.ImageUrl = @"\images\recipes\" + fileName + extension_new;
                }


                _recipeData.Update(recipe);
            }
            else
            {
                if (files.Count > 0)
                {
                    string fileName  = Guid.NewGuid().ToString();
                    var    uploads   = Path.Combine(webRootPath, @"images\recipes");
                    var    extension = Path.GetExtension(files[0].FileName);

                    using (var fileStreams = new FileStream(Path.Combine(uploads, fileName + extension), FileMode.Create))
                    {
                        var imageFactory = new ImageFactory(true);
                        imageFactory.Load(files[0].OpenReadStream()).Resize(
                            new ResizeLayer(new Size(1080, 720), ResizeMode.Max)).Save(fileStreams);


                        //files[0].CopyTo(fileStreams);
                    }
                    recipe.ImageUrl = @"\images\recipes\" + fileName + extension;
                }
                recipe.CreationDate = DateTime.Now;
                _recipeData.Add(recipe);
            }
            _recipeData.Commit();


            return(RedirectToAction("Detail", new { area = "Common", recipeId = recipe.Id }));
        }
Exemplo n.º 19
0
 //a constructor who get information from the list.
 public RecipeDetails(RecipeViewModel viewModel, int rid)
 {
     InitializeComponent();
     RidToDelete    = rid;
     BindingContext = this.viewModel = viewModel;
 }
Exemplo n.º 20
0
        public async Task <IActionResult> Edit(int id, Recipe recipe, RecipeViewModel model)//[Bind("RecipeImage,RecipeId,RecipeName,DishType,RecipeDescription,Ingredients,PreCookingPreparationMode,CookingPreparationMode,PostCookingPreparationMode,FoodAllergies,Symptoms,Antidote,Author")] RecipeViewModel model)
        {
            var recipeContext = await _context.Recipe.FindAsync(id);

            // Reference: https://stackoverflow.com/questions/48117961/the-instance-of-entity-type-cannot-be-tracked-because-another-instance-of-th/48132201#48132201
            _context.Entry(recipeContext).State = EntityState.Detached;

            string Image = recipeContext.RecipePicture.ToString();

            if (id != model.RecipeId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    string uniqueFileName = UploadedFile(model);


                    Recipe recipe1 = new Recipe
                    {
                        RecipePicture              = uniqueFileName,
                        RecipeId                   = model.RecipeId,
                        RecipeName                 = model.RecipeName,
                        DishType                   = model.DishType,
                        RecipeDescription          = model.RecipeDescription,
                        Ingredients                = model.Ingredients,
                        PreCookingPreparationMode  = model.PreCookingPreparationMode,
                        CookingPreparationMode     = model.CookingPreparationMode,
                        PostCookingPreparationMode = model.PostCookingPreparationMode,
                        FoodAllergies              = model.FoodAllergies,
                        Author = User.Identity.Name,
                    };

                    _context.Update(recipe1);
                    await _context.SaveChangesAsync();

                    // Deleting old image from file folder
                    var imagePath = Path.Combine(webHostEnvironment.WebRootPath, "images", "recipe_images", Image);
                    if (System.IO.File.Exists(imagePath))
                    {
                        System.IO.File.Delete(imagePath);
                    }
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!RecipeExists(model.RecipeId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(recipe));
        }
Exemplo n.º 21
0
 public SingleRecipePage(RecipeViewModel model)
 {
     InitializeComponent();
     this.BindingContext = new SingleRecipeViewModel(model);
 }
Exemplo n.º 22
0
        public async Task <IActionResult> UpdateRecipe(RecipeViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var qry = _recipeQueryFactory.CreateRecipesQuery();
            var dto = await qry.ExecuteAsync(model.Id).ConfigureAwait(false);

            dto.Title         = model.Title;
            dto.Variety.Id    = model.Variety.Id;
            dto.Yeast.Id      = model.Yeast.Id ?? 0;
            dto.Description   = model.Description;
            dto.Enabled       = model.Enabled;
            dto.Hits          = model.Hits;
            dto.Ingredients   = model.Ingredients;
            dto.Instructions  = model.Instructions;
            dto.NeedsApproved = model.NeedsApproved;

            if (model.Target.HasTargetData())
            {
                var tCmd = _journalCommandFactory.CreateTargetsCommand();

                if (dto.Target?.Id.HasValue == true)
                {
                    // update target
                    var tQry = _journalQueryFactory.CreateTargetsQuery();
                    var t    = await tQry.ExecuteAsync(dto.Target.Id.Value).ConfigureAwait(false);

                    t.EndSugar   = model.Target.EndingSugar;
                    t.pH         = model.Target.pH;
                    t.StartSugar = model.Target.StartingSugar;
                    t.TA         = model.Target.TA;
                    t.Temp       = model.Target.FermentationTemp;

                    if (model.Target.StartSugarUOM != null)
                    {
                        t.StartSugarUom = new UnitOfMeasure()
                        {
                            Id = model.Target.StartSugarUOM.Value
                        }
                    }
                    ;

                    if (model.Target.TempUOM != null)
                    {
                        t.TempUom = new UnitOfMeasure()
                        {
                            Id = model.Target.TempUOM.Value
                        }
                    }
                    ;

                    if (model.Target.EndSugarUOM != null)
                    {
                        t.EndSugarUom = new UnitOfMeasure()
                        {
                            Id = model.Target.EndSugarUOM.Value
                        }
                    }
                    ;

                    var result = await tCmd.UpdateAsync(t).ConfigureAwait(false);

                    dto.Target = result;
                }
                else
                {
                    // add target
                    var t = new TargetDto
                    {
                        EndSugar      = model.Target.EndingSugar,
                        pH            = model.Target.pH,
                        StartSugar    = model.Target.StartingSugar,
                        TA            = model.Target.TA,
                        Temp          = model.Target.FermentationTemp,
                        StartSugarUom = new UnitOfMeasure(),
                        TempUom       = new UnitOfMeasure(),
                        EndSugarUom   = new UnitOfMeasure()
                    };

                    if (model.Target.StartSugarUOM != null)
                    {
                        t.StartSugarUom.Id = model.Target.StartSugarUOM.Value;
                    }

                    if (model.Target.TempUOM != null)
                    {
                        t.TempUom.Id = model.Target.TempUOM.Value;
                    }

                    if (model.Target.EndSugarUOM != null)
                    {
                        t.EndSugarUom.Id = model.Target.EndSugarUOM.Value;
                    }

                    var result = await tCmd.AddAsync(t).ConfigureAwait(false);

                    dto.Target = result;
                }
            }

            var cmd = _recipeCommandFactory.CreateRecipesCommand();
            await cmd.UpdateAsync(dto).ConfigureAwait(false);

            return(RedirectToAction("Index", "Admin", new { id = "recipes" }));
        }
Exemplo n.º 23
0
 public Recipe1View()
 {
     InitializeComponent();
     BindingContext = new RecipeViewModel();
 }
        public ActionResult Update(int id)
        {
            var recipeBL = recipeService.GetRecipeByID(id);
            var recipe   = new RecipeViewModel()
            {
                RecipeID        = recipeBL.RecipeID,
                CookTime        = recipeBL.CookTime,
                Description     = recipeBL.Description,
                LongDescription = recipeBL.LongDescription,
                Name            = recipeBL.Name,
                RatingID        = recipeBL.RatingID,
                PictureLocation = recipeBL.PictureLocation,
                PrepTime        = recipeBL.PrepTime
            };
            var categoriesBL     = categoryService.GetAllCategoriesForRecipe(recipe.RecipeID);
            var listOfCategories = new List <CategoryViewModel>();

            var allCategoriesBL = categoryService.GetAllCategories();

            var subcategoriesBL     = subcategoryService.GetAllSubCategoriesForRecipe(recipe.RecipeID);
            var listOfSubcategories = new List <SubcategoryViewModel>();

            var allSubcategoriesBL = subcategoryService.GetAllSubcategories();


            foreach (var c in allCategoriesBL)
            {
                if (categoriesBL.Any(prod => prod.Name == c.Name))
                {
                    listOfCategories.Add(new CategoryViewModel
                    {
                        IsSelected = true,
                        CategoryID = c.CategoryID,
                        Name       = c.Name
                    });
                }
                else
                {
                    listOfCategories.Add(new CategoryViewModel
                    {
                        IsSelected = false,
                        CategoryID = c.CategoryID,
                        Name       = c.Name
                    });
                }
            }



            foreach (var i in listOfCategories)
            {
                recipe.Categories.Add(i);
            }

            foreach (var c in allSubcategoriesBL)
            {
                if (subcategoriesBL.Any(prod => prod.Name == c.Name))
                {
                    listOfSubcategories.Add(new SubcategoryViewModel
                    {
                        SubcategoryID = c.SubcategoryID,
                        Name          = c.Name,
                        IsSelected    = true
                    });
                }
                else
                {
                    listOfSubcategories.Add(new SubcategoryViewModel
                    {
                        SubcategoryID = c.SubcategoryID,
                        Name          = c.Name,
                        IsSelected    = false
                    });
                }
            }

            recipe.Categories    = listOfCategories;
            recipe.Subcategories = listOfSubcategories;

            return(View(recipe));
        }
 public uctrlLotPerformance()
 {
     InitializeComponent();
     _DC = (RecipeViewModel)this.DataContext;
 }
 public GroupedComponentsPage(bool isEditMode, RecipeViewModel recipeViewModel, RecipeComponentViewModel recipeComponentViewModel)
 {
     InitializeComponent();
     BindingContext = new GroupedComponentsViewModel(isEditMode, recipeViewModel, recipeComponentViewModel);
 }
Exemplo n.º 27
0
 public IActionResult Index(Guid Id)
 {
     return(View(RecipeViewModel.GetFromId(Id, _dataRepository)));
 }
Exemplo n.º 28
0
        // GET: Recipe
        public ActionResult Index()
        {
            RecipeViewModel model = new RecipeViewModel(repo.GetAll());

            return(View(model));
        }
Exemplo n.º 29
0
        public ActionResult Edit(RecipeViewModel recipeViewModel, ICollection <string> instrStepDesc, ICollection <HttpPostedFileBase> insrStepPhotos, HttpPostedFileBase image = null)
        {
            if (ModelState.IsValid)
            {
                if (image != null)
                {
                    recipeViewModel.Recipe.ImageMimeType = image.ContentType;
                    recipeViewModel.Recipe.ImageData     = new byte[image.ContentLength];
                    image.InputStream.Read(recipeViewModel.Recipe.ImageData, 0, image.ContentLength);
                }
                Recipe recipe = new Recipe();
                recipe = recipeViewModel.Recipe;
                List <string> ingredients = recipeViewModel.IngredientsList.ToLower().Trim('\n', ' ').Split('\n').ToList();
                foreach (var ingr in ingredients)
                {
                    var ingred = new Ingredient();
                    ingred.Name = ingr.Trim();
                    if (ingred.Name != "")
                    {
                        recipe.Ingredients.Add(ingred);
                    }
                }
                if (instrStepDesc != null)
                {
                    for (int i = 0; i < instrStepDesc.Count; i++)
                    {
                        if (insrStepPhotos.ToList()[i] != null)
                        {
                            var tempImageMimeType = insrStepPhotos.ToList()[i].ContentType;
                            var tempImageData     = new byte[insrStepPhotos.ToList()[i].ContentLength];
                            insrStepPhotos.ToList()[i].InputStream.Read(tempImageData, 0,
                                                                        insrStepPhotos.ToList()[i].ContentLength);
                            recipe.InstructionSteps.Add(new InstructionStep()
                            {
                                Description   = instrStepDesc.ToList()[i],
                                ImageMimeType = tempImageMimeType,
                                ImageData     = tempImageData
                            });
                        }
                        else
                        {
                            recipe.InstructionSteps.Add(new InstructionStep()
                            {
                                Description = instrStepDesc.ToList()[i]
                            });
                        }
                    }
                }

                //Устанавливаем автора рецепта
                //recipe.AppUser = UserManager.FindById(User.Identity.GetUserId());
                recipe.AppUserId = User.Identity.GetUserId();
                repository.SaveRecipe(recipe);

                TempData["message"] = string.Format("Изменения в рецепте \"{0}\" были сохранены", recipe.Name);
                return(RedirectToAction("Index"));
            }
            else
            {
                // Что-то не так со значениями данных
                return(View(recipeViewModel));
            }
        }
Exemplo n.º 30
0
 public RecipeDetailsPage(RecipeViewModel recipeViewModel)
 {
     InitializeComponent();
     BindingContext = recipeViewModel;
 }