Example #1
0
        public async Task <IActionResult> Add(AddRecipeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                ModelState.AddModelError("", "Błąd dodawania przepisu.");
                return(View(model));
            }

            var recipe = new Recipe()
            {
                Preparation     = model.Preparation,
                Name            = model.Name,
                PreparationTime = model.PreparationTime,
                Ingredients     = model.Ingredients,
                Description     = model.Description,
                User            = user
            };

            var result = await _recipeService.CreateAsync(recipe);

            if (result == false)
            {
                ModelState.AddModelError("", "Błąd dodawania przepisu.");
                return(View(model));
            }

            return(RedirectToAction("List", "Recipe"));
        }
Example #2
0
        public AddRecipePage()
        {
            InitializeComponent();
            var viewModel = new AddRecipeViewModel();

            BindingContext = viewModel;
        }
        public void RedirectToActionIndex_WithTheCorrectModel__WhenModelStateIsValid()
        {
            //Arrange
            var ingredientsServiceMock    = new Mock <IIngredientsService>();
            var foodCategoriesServiceMock = new Mock <IFoodCategoriesService>();
            var recipesServiceMock        = new Mock <IRecipesService>();
            var mappingServiceMock        = new Mock <IMappingService>();
            var controller = new RecipesController(recipesServiceMock.Object, ingredientsServiceMock.Object, foodCategoriesServiceMock.Object, mappingServiceMock.Object);

            Guid recipeId       = Guid.NewGuid();
            Guid foodCategoryId = Guid.NewGuid();
            IEnumerable <AddIngredientViewModel> ingredients = new List <AddIngredientViewModel>()
            {
                new AddIngredientViewModel()
                {
                    Name = "Blueberries"
                }
            };
            AddRecipeViewModel model = new AddRecipeViewModel()
            {
                Title       = null,
                Describtion = "A long describtion",
                Ingredients = ingredients
            };
            IEnumerable <string>  ingredientNames      = new List <string>();
            IEnumerable <double>  ingredientQuantities = new List <double>();
            IEnumerable <decimal> ingredientPrices     = new List <decimal>();
            IEnumerable <Guid>    foodCategories       = new List <Guid>();


            //Act & Assert
            controller.WithCallTo(x => x.AddRecipe(model, ingredientNames, ingredientQuantities, ingredientPrices, foodCategories))
            .ShouldRedirectTo(x => x.Index());
        }
Example #4
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="logger"></param>
        /// <param name="meal">食事モデル</param>
        public MealViewModel(ISettings settings, ILogger logger, MealModel meal)
        {
            this._settings = settings;
            this._logger   = logger;
            this.Meal      = meal.AddTo(this.CompositeDisposable);

            // Property
            // 食事ID
            this.MealId = this.Meal.MealId.ToReactivePropertyAsSynchronized(x => x.Value).AddTo(this.CompositeDisposable);
            // レシピリスト
            this.RecipeList = this.Meal.Recipes.ToReadOnlyReactiveCollection(recipe => Creator.CreateRecipeViewModelInstance(settings, logger, recipe)).AddTo(this.CompositeDisposable);
            // 食事タイプ
            this.MealType = this.Meal.MealType.ToReactivePropertyAsSynchronized(x => x.Value).AddTo(this.CompositeDisposable);
            // 食事タイプリスト
            this.MealTypes = this.Meal.MealTypes.ToReadOnlyReactiveCollection().AddTo(this.CompositeDisposable);

            // Command
            // レシピ追加コマンド
            this.AddRecipeCommand.Subscribe(() => {
                using (var vm = new AddRecipeViewModel(this._settings, this._logger, Method.HistorySearch | Method.Download | Method.Original)) {
                    this.Messenger.Raise(new TransitionMessage(vm, "OpenSearchRecipeWindow"));
                    if (vm.IsSelectionCompleted.Value)
                    {
                        this.Meal.AddRecipe(vm.SelectionResult.Value.Recipe);
                    }
                }
            }).AddTo(this.CompositeDisposable);
            // レシピ削除コマンド
            this.RemoveRecipeCommand.Subscribe(rvm => {
                using (var vm = new DialogWindowViewModel(
                           "削除確認",
                           "食事からレシピを削除します。よろしいですか。",
                           DialogWindowViewModel.DialogResult.Yes,
                           DialogWindowViewModel.DialogResult.No
                           )) {
                    this.Messenger.Raise(new TransitionMessage(vm, TransitionMode.Modal, "OpenDialogWindow"));
                    if (vm.Result == DialogWindowViewModel.DialogResult.Yes)
                    {
                        this.Meal.RemoveRecipe(rvm.Recipe);
                    }
                }
            }).AddTo(this.CompositeDisposable);

            // 食事削除コマンド
            this.RemoveMealCommand.Subscribe(() => {
                using (var vm = new DialogWindowViewModel(
                           "削除確認",
                           "食事を削除します。よろしいですか。",
                           DialogWindowViewModel.DialogResult.Yes,
                           DialogWindowViewModel.DialogResult.No
                           )) {
                    this.Messenger.Raise(new TransitionMessage(vm, TransitionMode.Modal, "OpenDialogWindow"));
                    if (vm.Result == DialogWindowViewModel.DialogResult.Yes)
                    {
                        this.Meal.RemoveMeal();
                    }
                }
            }).AddTo(this.CompositeDisposable);
        }
        public ActionResult Add(AddRecipeViewModel recipe)
        {
            var validTypes = new[] { "image/jpeg", "image/pjpeg", "image/png", "image/gif" };

            if (recipe.PhotoUpload != null && !validTypes.Contains(recipe.PhotoUpload.ContentType))
            {
                ModelState.AddModelError("PhotoUpload", "Please upload either a JPG, GIF, or PNG image.");
            }

            if (!ModelState.IsValid)
            {
                IEnumerable <SelectItemViewModel> categoriesList = new List <SelectItemViewModel>();
                categoriesList = _recipeProvider.GetSelectCategories();


                if (recipe.PhotoUpload.ContentLength > 0)
                {
                    // A file was uploaded
                    var    fileName   = Path.GetFileName(recipe.PhotoUpload.FileName);
                    string uploadPath = "~/Images/Recipe/Big/";
                    var    path       = Path.Combine(Server.MapPath(uploadPath));
                    recipe.PhotoUpload.SaveAs(path);
                    recipe.RecipeImage = uploadPath + fileName;
                }


                var viewModel = new AddRecipeViewModel
                {
                    RecipeName        = recipe.RecipeName,
                    RecipeImage       = recipe.RecipeImage,
                    PhotoUpload       = recipe.PhotoUpload,
                    RecipeDescription = recipe.RecipeDescription,
                    CreatedAt         = recipe.CreatedAt,
                    ModefiedAt        = recipe.ModefiedAt,
                    CookingTime       = recipe.CookingTime,
                    RecipeCategoryId  = recipe.RecipeCategoryId,
                    Categories        = categoriesList
                };

                return(View("Add", viewModel));
            }

            if (recipe.PhotoUpload != null && recipe.PhotoUpload.ContentLength > 0)
            {
                // A file was uploaded
                var    fileName   = Path.GetFileName(recipe.PhotoUpload.FileName);
                string uploadPath = "~/Images/Recipe/Big/";
                var    path       = Path.Combine(Server.MapPath(uploadPath), fileName);
                recipe.PhotoUpload.SaveAs(path);
                recipe.RecipeImage = uploadPath + fileName;
            }
            else
            {
                recipe.RecipeImage = "/Images/Recipe/Big/noimage.JPEG";
            }
            _recipeProvider.AddRecipe(recipe);
            return(RedirectToAction("Index"));
        }
        public IHttpActionResult PostRecipe(AddRecipeViewModel model)
        {
            var recipe = new Recipe {
                Title = model.Title, Description = model.Description
            };

            _recipeRepository.Add(recipe);

            return(Ok(recipe));
        }
Example #7
0
        public ActionResult StoreRecipeAndAddProduct(AddRecipeViewModel model)
        {
            HttpCookie cookie = CookieHelper.GetOrCreateCookie(currentRecipeCookie, new TimeSpan(0, 30, 0));

            cookie.SetValue(createdRecipeName, model.Name);
            cookie.SetValue(createdRecipeDesc, model.Description);
            cookie.SetValue <bool>(createdRecipeVege, model.Vegetarian);
            cookie.SetValue <int>(createdRecipePrep, model.PreparationTime);
            cookie.SetValue <Guid>(createdRecipeCate, model.CategoryId);
            cookie.Save();
            return(RedirectToAction("Create", "Product"));
        }
Example #8
0
        private void AddRecipe()
        {
            var vm  = new AddRecipeViewModel();
            var win = new AddRecipeWindow()
            {
                DataContext = vm, Owner = Application.Current.MainWindow
            };

            if (win.ShowDialog() ?? false)
            {
                Recipes.Add(vm.Recipe);
                SelectedRecipe = vm.Recipe;
            }
        }
Example #9
0
        public ActionResult CreateRecipe(AddRecipeViewModel model)
        {
            var errors = ModelState.Values.SelectMany(v => v.Errors);

            if (ModelState.IsValid)
            {
                var recipe = new Entities.Recipe
                {
                    Name            = model.Name,
                    Description     = model.Description,
                    Vegetarian      = model.Vegetarian,
                    PreparationTime = model.PreparationTime,
                    Added           = DateTime.Now,
                    Author          = null
                };

                List <Ingredient> ingredients = new List <Ingredient>();
                ICollection <IngredientCreateViewModel> ingredientsInfo;
                if (CookieHelper.TryReadCookie <ICollection <IngredientCreateViewModel> >(
                        currentRecipeCookie, createdRecipeIngredients, out ingredientsInfo))
                {
                    foreach (var ingr in ingredientsInfo)
                    {
                        ingredients.Add(new Ingredient {
                            Name      = ingr.Alias,
                            ProductId = ingr.ProductId,
                            Product   = ProductManager.FindById(ingr.ProductId),
                            Quantity  = ingr.Quantity,
                            Recipe    = recipe
                        });
                    }
                }
                recipe.Ingredients = ingredients;

                RecipeManager.AddToCategory(recipe, RecipeManager.FindCategoryById(model.CategoryId));
                RecipeManager.Save();

                CookieHelper.DeleteCookie(currentRecipeCookie);

                return(RedirectToAction("CreateResult"));
            }

            ViewBag.Categories        = RecipeManager.RecipeCategories.ToSelectList <Entities.RecipeCategory, RecipeCategoryInfo>();
            ViewBag.OrderedCategories = ProductManager.ProductCategories.ToOrderedSelectList();

            return(View("Create"));
        }
Example #10
0
        // [ValidateAntiForgeryToken]
        public ActionResult Add()
        {
            IEnumerable <SelectItemViewModel> categoriesList = new List <SelectItemViewModel>();

            categoriesList = _recipeProvider.GetSelectCategories();



            var viewModel = new AddRecipeViewModel
            {
                CreatedAt  = DateTime.Now,
                ModefiedAt = DateTime.Now,
                Categories = categoriesList
            };

            return(View(viewModel));
        }
Example #11
0
        public ActionResult Create()
        {
            ViewBag.Categories        = RecipeManager.RecipeCategories.ToSelectList <Entities.RecipeCategory, RecipeCategoryInfo>();
            ViewBag.OrderedCategories = ProductManager.ProductCategories.ToOrderedSelectList();

            HttpCookie cookie = CookieHelper.GetCookie(currentRecipeCookie);

            if (cookie == null)
            {
                return(View(new AddRecipeViewModel
                {
                    PageNumber = 1,
                    PageSize = defaultPageSize,
                    SortType = ProductSortType.NameAscending,
                    DataFilter = new ViewModels.Filter {
                        SearchKeyword = string.Empty
                    },
                    PreparationTime = 30
                }));
            }
            else
            {
                AddRecipeViewModel model = new AddRecipeViewModel();
                model.Name        = CookieHelper.ReadCookie(cookie, createdRecipeName);
                model.Description = CookieHelper.ReadCookie(cookie, createdRecipeDesc);

                bool vege;
                Guid cate;
                int  prep;

                if (CookieHelper.TryReadCookie <bool>(cookie, createdRecipeVege, out vege))
                {
                    model.Vegetarian = vege;
                }
                if (CookieHelper.TryReadCookie <Guid>(cookie, createdRecipeCate, out cate))
                {
                    model.CategoryId = cate;
                }
                if (CookieHelper.TryReadCookie <int>(cookie, createdRecipePrep, out prep))
                {
                    model.PreparationTime = prep;
                }
                return(View(model));
            }
        }
        public void RenderTheRightView_AddRecipe_WithTheCorrectModel_RecipeViewModel_WhenModelStateIsNotValid()
        {
            //Arrange
            var  ingredientsServiceMock    = new Mock <IIngredientsService>();
            var  foodCategoriesServiceMock = new Mock <IFoodCategoriesService>();
            var  recipesServiceMock        = new Mock <IRecipesService>();
            var  mappingServiceMock        = new Mock <IMappingService>();
            var  controller     = new RecipesController(recipesServiceMock.Object, ingredientsServiceMock.Object, foodCategoriesServiceMock.Object, mappingServiceMock.Object);
            Guid recipeId       = Guid.NewGuid();
            Guid foodCategoryId = Guid.NewGuid();
            IEnumerable <AddIngredientViewModel> ingredients = new List <AddIngredientViewModel>()
            {
                new AddIngredientViewModel()
                {
                    Name = "Blueberries"
                }
            };
            AddRecipeViewModel model = new AddRecipeViewModel()
            {
                Title       = null,
                Describtion = "A long describtion",
                Ingredients = ingredients
            };
            IEnumerable <string>  ingredientNames      = new List <string>();
            IEnumerable <double>  ingredientQuantities = new List <double>();
            IEnumerable <decimal> ingredientPrices     = new List <decimal>();
            IEnumerable <Guid>    foodCategories       = new List <Guid>();

            var validationContext = new ValidationContext(model, null, null);
            var validationResults = new List <ValidationResult>();

            Validator.TryValidateObject(model, validationContext, validationResults, true);
            foreach (var validationResult in validationResults)
            {
                controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
            }

            //Act & Assert
            controller.WithCallTo(x => x.AddRecipe(model, ingredientNames, ingredientQuantities, ingredientPrices, foodCategories))
            .ShouldRenderView("AddRecipe")
            .WithModel <AddRecipeViewModel>()
            .AndModelError("Instruction");
        }
Example #13
0
        public ActionResult AddRecipe(AddRecipeViewModel model)
        {
            try
            {
                string[] ingredientsArray = null;
                if (model.Ingredients.Contains("\r"))
                {
                    model.Ingredients = model.Ingredients.Replace('\r', ' ');
                }
                ingredientsArray = model.Ingredients.Split('\n');

                string[] instructionsArray = null;
                if (model.Instructions.Contains("\r"))
                {
                    model.Instructions = model.Instructions.Replace('\r', ' ');
                }
                instructionsArray = model.Instructions.Split('\n');

                model.Ingredients  = JsonConvert.SerializeObject(ingredientsArray);
                model.Instructions = JsonConvert.SerializeObject(instructionsArray);

                var recipe = new AddRecipeViewModel()
                {
                    Name         = model.Name,
                    Category     = model.Category,
                    CookTime     = model.CookTime,
                    Description  = model.Description,
                    Ingredients  = model.Ingredients,
                    Instructions = model.Instructions,
                    Notes        = model.Notes,
                    PrepTime     = model.PrepTime,
                    Servings     = model.Servings
                };

                int RecipeId = recipeService.AddRecipe(recipe);
                return(RedirectToAction("RecipeDetails", "Dashboard", new { id = RecipeId }));
            }
            catch (Exception e)
            {
                Trace.TraceError($"Unable to add recipe: {e.Message}");
            }
            return(RedirectToAction("MainDashboard", "Dashboard"));
        }
        public async Task <IActionResult> AddRecipe(AddRecipeViewModel model)
        {
            var status = "Pending";

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            if (User.IsInRole("Admin"))
            {
                status = "Approved";
            }
            if (model.RecipeType == "Fara restrictii")
            {
                model.RecipeType = "Normal";
            }
            _addRecipeService.AddRecipeAsync(model.RecipeName, status, model.RecipeType, model.Link, model.Ingredients, model.Quantities, model.UnitsOfMeasurement);
            return(RedirectToAction("AddMessage"));
        }
Example #15
0
        public ActionResult Create()
        {
            ViewBag.Categories = RecipeManager.RecipeCategories.ToSelectList<Entities.RecipeCategory, RecipeCategoryInfo>();
            ViewBag.OrderedCategories = ProductManager.ProductCategories.ToOrderedSelectList();

            HttpCookie cookie = CookieHelper.GetCookie(currentRecipeCookie);
            if (cookie == null)
            {
                return View(new AddRecipeViewModel
                {
                    PageNumber = 1,
                    PageSize = defaultPageSize,
                    SortType = ProductSortType.NameAscending,
                    DataFilter = new ViewModels.Filter { SearchKeyword = string.Empty }, 
                    PreparationTime = 30
                });
            }
            else
            {
                AddRecipeViewModel model = new AddRecipeViewModel();
                model.Name = CookieHelper.ReadCookie(cookie, createdRecipeName);
                model.Description = CookieHelper.ReadCookie(cookie, createdRecipeDesc);

                bool vege;
                Guid cate;
                int prep;

                if (CookieHelper.TryReadCookie<bool>(cookie, createdRecipeVege, out vege))
                {
                    model.Vegetarian = vege;
                }
                if (CookieHelper.TryReadCookie<Guid>(cookie, createdRecipeCate, out cate))
                {
                    model.CategoryId = cate;
                }
                if (CookieHelper.TryReadCookie<int>(cookie, createdRecipePrep, out prep))
                {
                    model.PreparationTime = prep;
                }
                return View(model);
            }
        }
Example #16
0
        public ActionResult AddRecipe(
            [Bind(Exclude = "Ingredients")] AddRecipeViewModel recipeModel,
            IEnumerable <string> ingredientNames,
            IEnumerable <double> ingredientQuantities,
            IEnumerable <decimal> ingredientPrices,
            IEnumerable <Guid> foodCategories)
        {
            if (!this.ModelState.IsValid)
            {
                this.AddToastMessage(toastrFailureTitle, string.Format(toastrAddObjectFailureMessage, recipeModel.Title), ToastType.Error);
                return(this.View(recipeModel));
            }

            var recipe = this.mappingService.Map <Recipe>(recipeModel);

            this.recipesService.AddRecipe(recipe, ingredientNames, ingredientQuantities, ingredientPrices, foodCategories);
            this.AddToastMessage(toastrSuccessTitle, string.Format(toastrAddObjectSuccessMessage, recipeModel.Title), ToastType.Success);

            return(this.RedirectToAction("Index", "Recipes"));
        }
Example #17
0
        public int AddRecipe(AddRecipeViewModel model)
        {
            var connection = new SqlConnection(DbConnectionString);

            connection.Open();
            DynamicParameters parameters     = new DynamicParameters();
            const string      outputVariable = "@retId";

            parameters.Add("@Name", model.Name);
            parameters.Add("@Category", model.Category);
            parameters.Add("@CookTime", model.CookTime);
            parameters.Add("@Description", model.Description);
            parameters.Add("@Ingredients", model.Ingredients);
            parameters.Add("@Instructions", model.Instructions);
            parameters.Add("@Notes", model.Notes);
            parameters.Add("@PrepTime", model.PrepTime);
            parameters.Add("@Servings", model.Servings);
            parameters.Add("@retId", -1, DbType.Int32, direction: ParameterDirection.Output);
            connection.Execute("[dbo].[AddRecipe]", parameters, commandType: CommandType.StoredProcedure);
            connection.Close();
            return(parameters.Get <int>(outputVariable));
        }
Example #18
0
        public int AddRecipe(AddRecipeViewModel addRecipe)
        {
            var selecteditem = GetSelectCategories();
            var item         = new SelectItemViewModel();

            Recipe recipe = new Recipe
            {
                RecipeName        = addRecipe.RecipeName,
                RecipeImage       = addRecipe.RecipeImage,
                RecipeDescription = addRecipe.RecipeDescription.Replace("../..", ""),
                CreatedAt         = DateTime.Now,
                ModefiedAt        = DateTime.Now,
                CookingTime       = addRecipe.CookingTime,

                RecipeCategoryId = addRecipe.RecipeCategoryId,
                RecipeCategory   = addRecipe.RecipeCategory,
            };

            _recipeRepository.Add(recipe);
            _recipeRepository.SaveChanges();

            return(recipe.Id);
        }
        public IActionResult Add(AddRecipeViewModel addRecipeViewModel)
        {
            if (ModelState.IsValid)
            {
                var currentUserId = userManager.GetUserId(User);

                Recipe newRecipe = new Recipe
                {
                    Name        = addRecipeViewModel.Name,
                    Description = addRecipeViewModel.Description,
                    Link        = addRecipeViewModel.Link,
                    Image       = addRecipeViewModel.Image,
                    UserId      = currentUserId
                };

                context.Recipes.Add(newRecipe);
                context.SaveChanges();

                return(Redirect("/Recipes"));
            }

            return(View(addRecipeViewModel));
        }
        public IActionResult Add(AddRecipeViewModel addRecipeViewModel)
        {
            if (ModelState.IsValid)
            {
                // Add the new recipe to my existing recipes

                RecipeCategory newRecipeCategory = context.Categories.Single(c => c.ID == addRecipeViewModel.CategoryID);

                Recipe newRecipe = new Recipe
                {
                    Name        = addRecipeViewModel.Name,
                    Description = addRecipeViewModel.Description,
                    Category    = newRecipeCategory
                };

                context.Recipes.Add(newRecipe);
                context.SaveChanges();

                return(Redirect("/Recipe"));
            }

            return(View(addRecipeViewModel));
        }
        public IActionResult Add()
        {
            AddRecipeViewModel addRecipeViewModel = new AddRecipeViewModel(context.Categories.ToList());

            return(View(addRecipeViewModel));
        }
Example #22
0
 public ActionResult StoreRecipeAndAddProduct(AddRecipeViewModel model)
 {
     HttpCookie cookie = CookieHelper.GetOrCreateCookie(currentRecipeCookie, new TimeSpan(0,30,0));
     cookie.SetValue(createdRecipeName, model.Name);
     cookie.SetValue(createdRecipeDesc, model.Description);
     cookie.SetValue<bool>(createdRecipeVege, model.Vegetarian);
     cookie.SetValue<int>(createdRecipePrep, model.PreparationTime);
     cookie.SetValue<Guid>(createdRecipeCate, model.CategoryId);
     cookie.Save();
     return RedirectToAction("Create", "Product");
 }
Example #23
0
 public ActionResult Create(AddRecipeViewModel viewModel)
 {
     return Content("Create");
 }
Example #24
0
        public ActionResult CreateRecipe(AddRecipeViewModel model)
        {
            var errors = ModelState.Values.SelectMany(v => v.Errors);
            if (ModelState.IsValid)
            {
                var recipe = new Entities.Recipe
                {
                    Name = model.Name,
                    Description = model.Description,
                    Vegetarian = model.Vegetarian,
                    PreparationTime = model.PreparationTime,
                    Added = DateTime.Now, 
                    Author = null
                };

                List<Ingredient> ingredients = new List<Ingredient>();
                ICollection<IngredientCreateViewModel> ingredientsInfo;
                if (CookieHelper.TryReadCookie<ICollection<IngredientCreateViewModel>>(
                    currentRecipeCookie, createdRecipeIngredients, out ingredientsInfo))
                {
                    foreach (var ingr in ingredientsInfo)
	                {
		                ingredients.Add(new Ingredient{ 
                            Name = ingr.Alias, 
                            ProductId = ingr.ProductId,
                            Product = ProductManager.FindById(ingr.ProductId), 
                            Quantity = ingr.Quantity,
                            Recipe = recipe});
	                }
                }
                recipe.Ingredients = ingredients;

                RecipeManager.AddToCategory(recipe, RecipeManager.FindCategoryById(model.CategoryId));
                RecipeManager.Save();

                CookieHelper.DeleteCookie(currentRecipeCookie);

                return RedirectToAction("CreateResult");
            }

            ViewBag.Categories = RecipeManager.RecipeCategories.ToSelectList<Entities.RecipeCategory, RecipeCategoryInfo>();
            ViewBag.OrderedCategories = ProductManager.ProductCategories.ToOrderedSelectList();

            return View("Create");
        }
 public int AddRecipe(AddRecipeViewModel model)
 {
     return(recipeRepository.AddRecipe(model));
 }
Example #26
0
        public IActionResult Add()
        {
            AddRecipeViewModel addRecipeViewModel = new AddRecipeViewModel();

            return(View(addRecipeViewModel));
        }
Example #27
0
 public AddRecipeControl(int recipeID, IMainWindow mainWindow)
 {
     InitializeComponent();
     DataContext     = new AddRecipeViewModel(recipeID);
     this.mainWindow = mainWindow;
 }
Example #28
0
        public async Task <IActionResult> Add(AddRecipeViewModel model)
        {
            ViewData["Title"]    = _localizer["PageTitle"];
            ViewData["PageDesc"] = _localizer["PageDesc"];

            var getCategoriesQuery = _queryFactory.CreateCategoriesQuery();
            var cList = await getCategoriesQuery.ExecuteAsync().ConfigureAwait(false);

            var getVarietiesQuery = _queryFactory.CreateVarietiesQuery();
            var vList             = await getVarietiesQuery.ExecuteAsync().ConfigureAwait(false);

            var getYeastQuery = _yeastQueryFactory.CreateYeastsQuery();
            var yList         = await getYeastQuery.ExecuteAsync().ConfigureAwait(false);

            var batchTempQuery = _journalQueryFactory.CreateBatchTempUOMQuery();
            var uomTempList    = await batchTempQuery.ExecuteAsync().ConfigureAwait(false);

            var batchSugarQuery = _journalQueryFactory.CreateBatchSugarUOMQuery();
            var uomSugarList    = await batchSugarQuery.ExecuteAsync().ConfigureAwait(false);

            // must be logged in to continue
            var submittedBy = await UserManagerAgent.GetUserAsync(User).ConfigureAwait(false);

            if (submittedBy == null)
            {
                var addRecipeModel = _modelFactory.CreateAddRecipeModel(cList, vList, yList, uomSugarList, uomTempList, model);
                Warning(_localizer["NoLogIn"], false);
                return(View(addRecipeModel));
            }

            // using model validation attributes, if model state says errors do nothing
            if (!ModelState.IsValid)
            {
                var addRecipeModel = _modelFactory.CreateAddRecipeModel(cList, vList, yList, uomSugarList, uomTempList, model);
                Warning(_localizer["AddGeneralError"], true);
                return(View(addRecipeModel));
            }

            ICode variety = null;

            if (int.TryParse(model?.VarietyId, out int varietyId))
            {
                variety = vList.FirstOrDefault(c => c.Id == varietyId);
            }

            ICode category = null;

            if (variety != null && variety.ParentId.HasValue)
            {
                category = cList.FirstOrDefault(c => c.Id == variety.ParentId.Value);
            }

            YeastDto yeast = null;

            if (int.TryParse(model?.YeastId, out int yeastId))
            {
                yeast = yList.FirstOrDefault(y => y.Id == yeastId);
            }

            Business.Journal.Dto.TargetDto target = null;

            if (model.Target.HasTargetData())
            {
                target = new Business.Journal.Dto.TargetDto
                {
                    EndSugar   = model.Target.EndingSugar,
                    pH         = model.Target.pH,
                    StartSugar = model.Target.StartingSugar,
                    TA         = model.Target.TA,
                    Temp       = model.Target.FermentationTemp,
                };

                if (model.Target.StartSugarUOM.HasValue)
                {
                    target.StartSugarUom = uomSugarList.FirstOrDefault(u => u.Id == model.Target.StartSugarUOM.Value);
                }
                if (model.Target.EndSugarUOM.HasValue)
                {
                    target.EndSugarUom = uomSugarList.FirstOrDefault(u => u.Id == model.Target.EndSugarUOM.Value);
                }
                if (model.Target.TempUOM.HasValue)
                {
                    target.TempUom = uomTempList.FirstOrDefault(u => u.Id == model.Target.TempUOM.Value);
                }
            }
            // convert add model to recipe dto
            var recipeDto = new Business.Recipe.Dto.RecipeDto
            {
                Description   = model.Description,
                Enabled       = false,
                Hits          = 0,
                Ingredients   = model.Ingredients,
                Instructions  = model.Instructions,
                NeedsApproved = true,
                Rating        = null,
                SubmittedBy   = submittedBy.Id,
                Target        = target,
                Title         = model.Title,
                Yeast         = yeast,
                Variety       = variety
            };

            //recipeDto.Id = 1;  // for testing only
            var updateRecipesCommand = _commandsFactory.CreateRecipesCommand();

            recipeDto = await updateRecipesCommand.AddAsync(recipeDto).ConfigureAwait(false);


            // process uploaded files
            if (model.Images != null)
            {
                var           updateImageCommand = _commandsFactory.CreateImageCommand();
                long          maxFileSizeBytes   = 512000;
                List <string> allowedExtensions  = new List <string> {
                    ".jpg", ".jpeg", ".bmp", ".png", ".gif"
                };
                int maxUploads  = 4;
                int uploadCount = 1;

                foreach (FormFile file in model.Images)
                {
                    // Max File Size per Image: 500 KB
                    if (file.Length > maxFileSizeBytes)
                    {
                        continue;
                    }
                    // Allowed Image Extensions: .jpg | .gif | .bmp | .jpeg | .png ONLY
                    var ext = Path.GetExtension(file.FileName);
                    if (!allowedExtensions.Any(e => e.Equals(ext, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }
                    // Pictures Max 4
                    if (uploadCount > maxUploads)
                    {
                        break;
                    }

                    using MemoryStream ms = new MemoryStream();
                    file.OpenReadStream().CopyTo(ms);
                    var imageData = await ResizeImage(ms.ToArray(), 360, 480).ConfigureAwait(false);

                    var thumbData = await ResizeImage(ms.ToArray(), 100, 150).ConfigureAwait(false);

                    var imageDto = _dtoFactory.CreateNewImageFile(recipeDto.Id, file.FileName, file.Name, imageData, thumbData, file.Length, file.ContentType);
                    await updateImageCommand.AddAsync(imageDto).ConfigureAwait(false);

                    uploadCount++;
                }
            }

            var subjectLine = "There is a new recipe is in the approval queue.";
            var bodyContent = "A new recipe has been submitted and needs approved.";

            // notify admin that new recipe is in the approval queue
            await _emailAgent.SendEmailAsync(_appSettings.SMTP.FromEmail, _appSettings.SMTP.FromEmail, _appSettings.SMTP.AdminEmail,
                                             subjectLine, bodyContent, false, null).ConfigureAwait(false);

            // tell user good job and clear or go to thank you page
            ModelState.Clear();
            var addNewRecipeModel = _modelFactory.CreateAddRecipeModel(cList, vList, yList, uomSugarList, uomTempList);

            addNewRecipeModel.User = submittedBy;

            Success(_localizer["AddSuccess"], true);

            return(View(addNewRecipeModel));
        }
Example #29
0
 public AddRecipeView(tblPerson person)
 {
     DataContext = new AddRecipeViewModel(this, person);
     InitializeComponent();
 }