Пример #1
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            Models.Recipe recipeToDelete = await _context.Recipes
                                           .Include(r => r.RecipeCategories)
                                           .SingleAsync(r => r.Id == id);

            if (recipeToDelete.PhotoPath != null)
            {
                var imgPath = Path.Combine(_hostEnvironment.WebRootPath, recipeToDelete.PhotoPath.TrimStart('\\'));
                if (System.IO.File.Exists(imgPath))
                {
                    System.IO.File.Delete(imgPath);
                }
            }
            if (recipeToDelete != null)
            {
                _context.Recipes.Remove(recipeToDelete);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
Пример #2
0
        public async Task <IActionResult> Create([Bind("Name, Instructions, Notes, History, ImagePath, VideoLink")] Models.Recipe recipe)
        {
            if (recipe.History == null)
            {
                recipe.History = "";
            }
            if (recipe.ImagePath == null)
            {
                recipe.ImagePath = "~/Media/Recipes/default.jpg";
            }
            else
            {
                recipe.ImagePath = "~/Media/Recipes/" + recipe.ImagePath;
            }
            if (recipe.VideoLink == null)
            {
                recipe.VideoLink = "";
            }

            if (ModelState.IsValid)
            {
                _context.Add(recipe);
                await _context.SaveChangesAsync();

                return(RedirectToAction("List"));
            }

            return(View(recipe));
        }
Пример #3
0
        public async Task <IActionResult> Edit([Bind("ID, Name, Instructions, Notes, History, ImagePath, VideoLink")] Models.Recipe recipe)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(recipe);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!_context.Recipes.Any(r => r.ID == recipe.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(List)));
            }

            return(View(recipe));
        }
Пример #4
0
        public IActionResult Recipe(string id)
        {
            long idAsLong = 0;

            if (!long.TryParse(id, out idAsLong))
            {
                throw new Exception("Invalid id");
            }

            Models.Recipe recipe = RecipeManager.GetRecipeById(idAsLong);
            if (recipe == null)
            {
                throw new Exception($"Recipe not found for id {id}");
            }

            // Demo: Data breakpoints
            if (recipe.Hits == null)
            {
                recipe.Hits = 1;
            }
            else
            {
                recipe.Hits++;
            }
            RecipeManager.UpdateRecipe(idAsLong, recipe);

            return(View(recipe));
        }
Пример #5
0
        public async System.Threading.Tasks.Task OnGetAsync(int id)
        {
            List <int> recipeid_list = null;
            int        recent_count  = 0;

            //Empty session
            if (HttpContext.Session.Get <List <int> >(StaticDetails.RecentlyViewed) == default)
            {
                recipeid_list = new List <int>();
            }
            else
            {
                recipeid_list = HttpContext.Session.Get <List <int> >(StaticDetails.RecentlyViewed);
            }
            recent_count = HttpContext.Session.Get <int>(StaticDetails.RecentlyViewedCount);
            if (!recipeid_list.Exists(rId => rId == id))
            {
                recipeid_list.Add(id);
                recent_count++;
            }


            HttpContext.Session.Set(StaticDetails.RecentlyViewed, recipeid_list);
            HttpContext.Session.Set(StaticDetails.RecentlyViewedCount, recent_count);
            Recipe = await _context.Recipes
                     .Include(r => r.RecipeCategories)
                     .ThenInclude(r => r.Category)
                     .SingleAsync(r => r.Id == id);
        }
        public IHttpActionResult SaveRecipe(Models.Recipe rcp)
        {
            try
            {
                if (User.IsInRole("ADMIN"))
                {
                    int index = 0;
                    foreach (Models.RecipeIngredient ing in rcp.IngredientList)
                    {
                        ing.SortOrder = index++;
                    }
                    index = 0;
                    foreach (Models.RecipeDirection dir in rcp.DirectionList)
                    {
                        dir.SortOrder = index++;
                    }
                    index = 0;
                    foreach (Models.RecipeImage img in rcp.ImageList)
                    {
                        img.SortOrder = index++;
                    }

                    rcp.SaveRecipe();
                }

                return(Ok(rcp.RecipeID));
            }
            catch (Exception ex)
            {
                PortalUtility.SendErrorEmail(ex);
                return(new PortalUtility.PlainTextResult(ex.Message, HttpStatusCode.InternalServerError));
            }
        }
Пример #7
0
        public BrewingControl(Models.Recipe recipe)
        {
            InitializeComponent();
            BrewingViewModel dataContext = new BrewingViewModel(recipe);

            DataContext = dataContext;
        }
Пример #8
0
        public IActionResult OnGet()
        {
            var recipe = new Models.Recipe();

            recipe.RecipeCategories = new List <RecipeCategory>();

            //CategoryList = _unitofWork.Category.GetCategoryListForDropDown();
            PopulateRecipeCategories(_context, recipe);
            return(Page());
        }
Пример #9
0
        public IActionResult OnGet()
        {
            var recipe = new Models.Recipe();

            recipe.RecipeCategories = new List <RecipeCategory>();
            PopulateRecipeCategories(_context, recipe);


            return(Page());
        }
Пример #10
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                Recipe = new Models.Recipe
                {
                    Name         = Input.Name,
                    CreationDate = DateTime.UtcNow,
                    Time         = Input.Time,
                    People       = Input.People,
                    Description  = Input.Description,
                    Ingredients  = Ingredients,
                    Author       = _db.Users.Where(r => r.Id == int.Parse(_userManager.GetUserId(User))).SingleOrDefault(),
                    Category     = _db.Categories.Where(r => r.Name == Category).SingleOrDefault(),
                    Instructions = new List <Instruction>()
                };

                string directory = Path.Combine(_environment.WebRootPath, "Images", Input.Name);
                Directory.CreateDirectory(directory);
                string FileName = Guid.NewGuid() + Path.GetExtension(Input.Image.FileName);
                string File     = Path.Combine(directory, FileName);
                using (var fileStream = new FileStream(File, FileMode.Create))
                {
                    await Input.Image.CopyToAsync(fileStream);
                }

                Recipe.ImagePath = "/Images/" + Recipe.Name + "/" + FileName;

                foreach (InstructionInput instruction in Instructions)
                {
                    Instruction instruction1 = new Instruction();
                    instruction1.Content = instruction.Content;

                    if (instruction.Image != null)
                    {
                        string file = Path.Combine(directory, "Images");
                        Directory.CreateDirectory(file);
                        string instructionFileName = Guid.NewGuid() + Path.GetExtension(instruction.Image.FileName);
                        string instructionFile     = Path.Combine(file, instructionFileName);
                        using (var fileStream = new FileStream(instructionFile, FileMode.Create))
                        {
                            await instruction.Image.CopyToAsync(fileStream);
                        }
                        instruction1.ImagePath = "/Images/" + Recipe.Name + "/Images/" + instructionFileName;
                    }
                    Recipe.Instructions.Add(instruction1);
                }

                _db.Recipes.Add(Recipe);
                _db.SaveChanges();

                return(RedirectToPage("/Index", new { area = "Recipe", Id = Recipe.Id }));
            }
            return(Page());
        }
Пример #11
0
        // GET: Recipes/Create
        public ActionResult Create()
        {
            Recipe recipe = new Models.Recipe();

            recipe.Name   = "New Recipe";
            recipe.UserID = User.Identity.GetUserId();
            db.Recipes.Add(recipe);
            db.SaveChanges();

            return(RedirectToAction("Edit", new { id = recipe.RecipeID }));
        }
Пример #12
0
        /// <summary>
        /// Maps recipe to recipe history item
        /// </summary>
        /// <param name="recipe">recipe</param>
        /// <returns>recipe history item</returns>
        private ObservableCollection <RecipeHistoryItem> Map(Models.Recipe recipe)
        {
            var historyItems = new ObservableCollection <RecipeHistoryItem>();

            foreach (var item in recipe.RecipeItems)
            {
                historyItems.Add(new RecipeHistoryItem {
                    MedicineId = item.Medicine.Id
                });
            }

            return(historyItems);
        }
Пример #13
0
        public static void UpdateRecipe(long id, Models.Recipe recipe)
        {
            // TODO: when there's time, write the updated stuff to the actual file
            // recipes[id] = recipe;

            // Write recipe updates to original JSON file
            string recipeFile = resolvedPath + "/" + recipe.Id + ".json";

            using (StreamWriter file = File.CreateText(recipeFile))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(file, recipe);
            }
        }
Пример #14
0
        public void Delete_Post_ExpectRecipeRemoved()
        {
            //arrange
            Models.ICookbookContext           context    = AddTestData(new TestContext());
            Controllers.CookbookMVCController controller = new Controllers.CookbookMVCController(context);
            IEnumerable <Models.Recipe>       recipes    = context.Recipes;

            Models.Recipe condemnedRecipe = recipes.Where(r => r.RecipeId == 1).FirstOrDefault();

            //act
            controller.DeleteConfirmed(condemnedRecipe.RecipeId);

            //assert
            Assert.IsTrue(!recipes.Contains(condemnedRecipe));
        }
        public void PopulateRecipeCategories(ApplicationDbContext context,
                                             Models.Recipe recipe)
        {
            var allCategories    = context.Categories;
            var recipeCategories = new HashSet <int>(
                recipe.RecipeCategories.Select(c => c.CategoryId));

            RecipeCategoryDataList = new List <RecipeCategoryData>();
            foreach (var category in allCategories)
            {
                RecipeCategoryDataList.Add(new RecipeCategoryData {
                    CategoryId = category.Id,
                    Name       = category.Name
                });
            }
        }
Пример #16
0
        public void Edit_Get_ExpectRecipe()
        {
            //Arrange
            Models.ICookbookContext           context    = AddTestData(new TestContext());
            Controllers.CookbookMVCController controller = new Controllers.CookbookMVCController(context);

            //act
            ViewResult result = controller.Edit(1) as ViewResult;

            Models.Recipe foundRecipe = result.Model as Models.Recipe;

            //assert
            //Test Recipe #1
            Assert.IsNotNull(result);
            Assert.AreEqual("Test Recipe #1", foundRecipe.Title);
        }
Пример #17
0
        public ActionResult Recipe(string recipeid, decimal quantity = 1)
        {
            List<SelectListItem> qtyvalues = new List<SelectListItem>();
            qtyvalues.Add(new SelectListItem() { Text = "1/2", Value = ".5" });
            qtyvalues.Add(new SelectListItem() { Text = "1", Value = "1" });
            qtyvalues.Add(new SelectListItem() { Text = "1 1/2", Value = "1.5" });
            qtyvalues.Add(new SelectListItem() { Text = "2", Value = "2" });
            qtyvalues.Add(new SelectListItem() { Text = "2 1/2", Value = "2.5" });
            qtyvalues.Add(new SelectListItem() { Text = "3", Value = "3" });
            qtyvalues.Add(new SelectListItem() { Text = "4", Value = "4" });
            qtyvalues.Add(new SelectListItem() { Text = "5", Value = "5" });
            ViewBag.QuantityValues = qtyvalues;

            Models.Recipe rcp = new Models.Recipe(recipeid, quantity);

            return View(rcp);
        }
Пример #18
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            Recipe = await _context.Recipes
                     .Include(r => r.RecipeCategories)
                     .ThenInclude(r => r.Category)
                     .SingleAsync(r => r.Id == id);

            if (Recipe == null)
            {
                return(NotFound());
            }
            return(Page());
        }
        public Models.Recipe Get(string id)
        {
            long idAsLong = 0;

            if (!long.TryParse(id, out idAsLong))
            {
                throw new HttpException(404, "Invalid id");
            }

            Models.Recipe recipe = Models.RecipeManager.Singleton.GetRecipeById(idAsLong);

            if (recipe == null)
            {
                throw new HttpException(404, $"Recipe not found for id {id}");
            }

            return(recipe);
        }
Пример #20
0
        public async Task <IActionResult> Recipe(string id)
        {
            long idAsLong = 0;

            if (!long.TryParse(id, out idAsLong))
            {
                throw new Exception("Invalid id");
            }

            Models.Recipe recipe = await GetRecipeById(idAsLong);

            if (recipe == null)
            {
                throw new Exception($"Recipe not found for id {id}");
            }

            return(View(recipe));
        }
Пример #21
0
        public void Validation_ExpectTitleRequired()
        {
            //arrange
            Models.Recipe testRecipe = new Models.Recipe
            {
                RecipeId = 55,
                Title    = ""
            };

            ValidationContext       validatoinContext = new ValidationContext(testRecipe, null, null);
            List <ValidationResult> validationResults = new List <ValidationResult>();

            bool result = Validator.TryValidateObject(testRecipe, validatoinContext, validationResults, true);


            Assert.IsFalse(result);
            Assert.AreEqual(validationResults[0].ErrorMessage, "Title is required.");
        }
Пример #22
0
        public void Create_ExpectCreateViewIfModelStateIsNotValid()
        {
            //Arrange
            Models.ICookbookContext           context    = AddTestData(new TestContext());
            Controllers.CookbookMVCController controller = new Controllers.CookbookMVCController(context);
            controller.ModelState.AddModelError("", "mock error message");
            Models.Recipe testRecipe = new Models.Recipe
            {
                RecipeId = 55,
                Title    = "Test Bad"
            };

            //act
            var result = (ViewResult)controller.Create(testRecipe);

            //assert
            Assert.AreEqual("Create", result.ViewName);
        }
Пример #23
0
        protected override void Seed(PersonalBrewery.Models.PersonalBreweryContext context)
        {
            Models.Ingredient i1 = new Models.Ingredient {
                Id = 1, Name = "Hops", Created = DateTime.Now
            };
            Models.Ingredient i2 = new Models.Ingredient {
                Id = 2, Name = "Water", Created = DateTime.Now
            };
            Models.Ingredient i3 = new Models.Ingredient {
                Id = 3, Name = "Barly", Created = DateTime.Now
            };
            Models.Ingredient i4 = new Models.Ingredient {
                Id = 4, Name = "Fizz", Created = DateTime.Now
            };
            Models.Ingredient i5 = new Models.Ingredient {
                Id = 5, Name = "Bang", Created = DateTime.Now
            };

            context.Ingredients.AddOrUpdate(i1, i2, i3, i4, i5);

            Models.Recipe r1 = new Models.Recipe {
                Id = 1, Name = "Killer Beer", Created = DateTime.Now, Ingredients = new System.Collections.Generic.List <Models.Ingredient>()
            };
            Models.Recipe r2 = new Models.Recipe {
                Id = 2, Name = "No So Good Beer", Created = DateTime.Now, Ingredients = new System.Collections.Generic.List <Models.Ingredient>()
            };
            Models.Recipe r3 = new Models.Recipe {
                Id = 3, Name = "Awesome Beer", Created = DateTime.Now, Ingredients = new System.Collections.Generic.List <Models.Ingredient>()
            };

            r1.Ingredients.Add(i1);
            r1.Ingredients.Add(i2);
            r1.Ingredients.Add(i3);

            r2.Ingredients.Add(i1);
            r2.Ingredients.Add(i2);
            r2.Ingredients.Add(i4);

            r3.Ingredients.Add(i1);
            r3.Ingredients.Add(i5);
            r3.Ingredients.Add(i4);

            context.Recipes.AddOrUpdate(r1, r2, r3);
        }
Пример #24
0
        public void Edit_Post_ExpectEditViewIfModelStateIsNotValid()
        {
            //arrange
            Models.ICookbookContext           context    = AddTestData(new TestContext());
            Controllers.CookbookMVCController controller = new Controllers.CookbookMVCController(context);
            controller.ModelState.AddModelError("", "mock error message");
            Models.Recipe badRecipe = new Models.Recipe
            {
                RecipeId = 55,
                Title    = "Bad"
            };

            //act
            ViewResult result = controller.Edit(badRecipe) as ViewResult;

            //assert
            Assert.IsNotNull(result);
            Assert.AreEqual("Edit", result.ViewName);
        }
Пример #25
0
        public void Create_ExpectValidRecipeAdded()
        {
            //arrange
            Models.ICookbookContext           context    = AddTestData(new TestContext());
            Controllers.CookbookMVCController controller = new Controllers.CookbookMVCController(context);
            Models.Recipe testRecipe = new Models.Recipe
            {
                RecipeId = 55,
                Title    = "Test Good"
            };

            //act
            controller.Create(testRecipe);

            //Assert
            IEnumerable <Models.Recipe> recipes = context.Recipes;

            Assert.IsTrue(recipes.Contains(testRecipe));
        }
Пример #26
0
            public void Post_ExpectSameRecipe()
            {
                //arrange
                Models.Recipe newRecipe = new Models.Recipe()
                {
                    RecipeId = 33,
                    Title    = "Test post"
                };
                Models.ICookbookContext       context    = AddTestData(new TestContext());
                Controllers.RecipesController controller = new Controllers.RecipesController(context);

                //act
                var result = controller.PostRecipe(newRecipe) as CreatedAtRouteNegotiatedContentResult <Models.Recipe>;

                //assert
                Assert.IsNotNull(result);
                Assert.AreEqual(result.RouteName, "DefaultApi");
                Assert.AreEqual(result.RouteValues["Id"], result.Content.RecipeId);
                Assert.AreEqual(result.Content.Title, newRecipe.Title);
            }
Пример #27
0
            public void Put_ExpectStatusCode()
            {
                //arrange
                Models.Recipe recipe = new Models.Recipe()
                {
                    RecipeId = 1,
                    Title    = "Edited recipe"
                };
                int id = 1;

                Models.ICookbookContext       context    = AddTestData(new TestContext());
                Controllers.RecipesController controller = new Controllers.RecipesController(context);

                //act
                var result = controller.PutRecipe(id, recipe) as StatusCodeResult;

                //assert
                Assert.IsNotNull(result);
                Assert.IsInstanceOfType(result, typeof(StatusCodeResult));
                Assert.AreEqual(HttpStatusCode.NoContent, result.StatusCode);
            }
Пример #28
0
        public void Create_ExpectIndexViewIfModelStateIsValid()
        {
            //arrange
            Models.ICookbookContext           context    = AddTestData(new TestContext());
            Controllers.CookbookMVCController controller = new Controllers.CookbookMVCController(context);
            Models.Recipe testRecipe = new Models.Recipe
            {
                RecipeId = 55,
                Title    = "Test Good"
            };

            //act
            ActionResult result = controller.Create(testRecipe);

            //assert
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
            RedirectToRouteResult routeResult = result as RedirectToRouteResult;

            Assert.AreEqual(routeResult.RouteValues["action"], "Index");
        }
Пример #29
0
        public ActionResult Create(Models.Recipe tempRecipe, HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0 && file.ContentType.StartsWith("image/"))
            {
                try
                {
                    string temppath = Guid.NewGuid() + Path.GetExtension(file.FileName);
                    string path     = Path.Combine(Server.MapPath("~/Images/siteimg"), temppath);
                    int    i;
                    file.SaveAs(path);
                    ViewBag.Message    = "File uploaded successfully";
                    tempRecipe.ImgPath = Path.Combine("~/Images/siteimg", temppath);
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            }
            else
            {
                ModelState.AddModelError("file", "You have not specified a file // wrong file type");
            }
            var context  = new UsersContext();
            var username = User.Identity.Name;
            var user     = context.UserProfiles.SingleOrDefault(u => u.UserName == username);

            tempRecipe.UserId       = user.UserId;
            tempRecipe.TimeStamp    = DateTime.Now;
            tempRecipe.FinalRate    = 0;
            tempRecipe.RatingPeople = 0;
            if (ModelState.IsValid)
            {
                var db = new RecipeDataContext();

                db.Recipes.Add(tempRecipe);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(tempRecipe));
        }
Пример #30
0
        public ActionResult Edit(Models.Recipe tempRecipe, HttpPostedFileBase file)
        {
            var db            = new RecipeDataContext();
            var tempRecipeold = db.Recipes.Find(tempRecipe.Id);

            if (file != null && file.ContentLength > 0 && file.ContentType.StartsWith("image/"))
            {
                try
                {
                    string temppath = Guid.NewGuid() + Path.GetExtension(file.FileName);
                    string path     = Path.Combine(Server.MapPath("~/Images/siteimg"), temppath);
                    int    i;
                    file.SaveAs(path);
                    ViewBag.Message    = "File uploaded successfully";
                    tempRecipe.ImgPath = Path.Combine("~/Images/siteimg", temppath);
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            }


            tempRecipeold.TimeStamp = DateTime.Now;
            for (int i = 0; i < tempRecipe.Ingredients.Count; i++)
            {
                tempRecipeold.Ingredients[i].Name   = tempRecipeold.Ingredients[i].Name;
                tempRecipeold.Ingredients[i].Amount = tempRecipeold.Ingredients[i].Amount;
                tempRecipeold.Ingredients[i].Unit   = tempRecipeold.Ingredients[i].Unit;
            }
            tempRecipeold.Ingredients = tempRecipe.Ingredients;

            tempRecipe.RatingPeople = tempRecipeold.RatingPeople;
            if (ModelState.IsValid)
            {
                db.SaveChanges();
            }
            return(RedirectToAction("RecipeDetails", new { id = tempRecipeold.Id }));
        }
        public void UpdateRecipeCategories(ApplicationDbContext context,
                                           string[] selectedCategories, Models.Recipe recipeToUpdate)
        {
            if (selectedCategories == null)
            {
                recipeToUpdate.RecipeCategories = new List <RecipeCategory>();
                return;
            }

            var selectedCategoryHS = new HashSet <string>(selectedCategories);
            var recipeCategories   = new HashSet <int>
                                         (recipeToUpdate.RecipeCategories.Select(c => c.Category.Id));

            foreach (var category in context.Categories)
            {
                if (selectedCategoryHS.Contains(category.Id.ToString()))
                {
                    if (!recipeCategories.Contains(category.Id))
                    {
                        recipeToUpdate.RecipeCategories.Add(
                            new RecipeCategory {
                            RecipeId   = recipeToUpdate.Id,
                            CategoryId = category.Id
                        });
                    }
                }
                else
                {
                    if (recipeCategories.Contains(category.Id))
                    {
                        RecipeCategory categoryToRemove
                            = recipeToUpdate
                              .RecipeCategories
                              .SingleOrDefault(i => i.CategoryId == category.Id);
                        context.Remove(categoryToRemove);
                    }
                }
            }
        }
Пример #32
0
        public ActionResult Create(string recipeid = "")
        {
            Models.Recipe rcp = new Models.Recipe();
            if (String.IsNullOrEmpty(recipeid))
            {
                ViewBag.Title = "New Recipe";
            }
            else
            {
                ViewBag.Title = "Edit Recipe";
                rcp = new Models.Recipe(recipeid);
            }

            List<Models.Recipe.Category> allcat = Models.Recipe.Category.GetAllCategories();
            foreach (Models.Recipe.Category cat in rcp.CategoryList)
            { allcat.Find(act => act.CategoryCode == cat.CategoryCode).IsSelected = true; }
            rcp.CategoryList = allcat;

            return View(rcp);
        }
Пример #33
0
        public void ParseBeerXML(string fileLocation)
        {
            XmlTextReader reader = new XmlTextReader(fileLocation);
            var currentNodeName = "";

            Models.Recipe recipe = null;
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        currentNodeName = reader.Name;
                        switch (currentNodeName)
                        {
                            case "RECIPE":
                                recipe = new Models.Recipe();
                                break;
                            case "STYLE":
                                Models.Style style = ParseStyle(reader);
                                using (var context = new Models.ModelsContext())
                                {
                                    if (context.Styles.Find(style.Name) == null)
                                    {
                                        context.Styles.Add(style);
                                        context.SaveChanges();
                                    }
                                }
                                recipe.Style = style;
                                break;
                             case "HOP":
                                string HopUses_Name = "";
                                float Amount = 0;
                                float Time = 0;
                                Models.Hop hop = ParseHop(reader, ref HopUses_Name, ref Amount, ref Time);
                                Models.RecipeHop recipeHop = new Models.RecipeHop();
                                recipeHop.Recipe_Name = recipe.Name;
                                recipeHop.Hop_Name = hop.Name;
                                recipeHop.HopUses_Name = HopUses_Name;
                                recipeHop.Amount = Amount;
                                recipeHop.Time = Time;

                                using (var context = new Models.ModelsContext())
                                {
                                    if (context.Hops.Find(hop.Name) == null)
                                    {
                                        context.Hops.Add(hop);
                                        context.SaveChanges();
                                    }
                                }
                                if (!recipe.RecipeHops.Contains(recipeHop))
                                {
                                    recipe.RecipeHops.Add(recipeHop);
                                }
                                break;
                             case "FERMENTABLE":
                                bool AddAfterBoil = false;
                                bool IsMashed = false;
                                Amount = 0;
                                Models.Fermentable fermentable = ParseFermentable(reader, ref AddAfterBoil, ref IsMashed, ref Amount);

                                Models.RecipeFermentable recipeFermentable = new Models.RecipeFermentable();
                                recipeFermentable.AddAfterBoil = AddAfterBoil;
                                recipeFermentable.IsMashed = IsMashed;
                                recipeFermentable.Fermentable_Name = fermentable.Name;
                                recipeFermentable.Recipe_Name = recipe.Name;
                                recipeFermentable.Amount = Amount;

                                using (var context = new Models.ModelsContext())
                                {
                                    if (context.Fermentables.Find(fermentable.Name) == null)
                                    {
                                        context.Fermentables.Add(fermentable);
                                        context.SaveChanges();
                                    }
                                }

                                if (!recipe.RecipeFermentables.Contains(recipeFermentable))
                                {
                                    recipe.RecipeFermentables.Add(recipeFermentable);
                                }
                                break;
                             case "YEAST":
                                bool AddToSecondary = false;
                                bool AmountIsWeight = false;
                                Amount = 0;
                                Models.Yeast yeast = ParseYeasts(reader, ref AddToSecondary, ref Amount, ref AmountIsWeight);

                                Models.RecipeYeast recipeYeast = new Models.RecipeYeast();
                                recipeYeast.AddToSecondary = AddToSecondary;
                                recipeYeast.Recipe_Name = recipe.Name;
                                recipeYeast.Yeast_Name = yeast.Name;
                                recipeYeast.AmountIsWeight = AmountIsWeight;
                                recipeYeast.Amount = Amount;

                                using (var context = new Models.ModelsContext())
                                {
                                    if (context.Yeasts.Find(yeast.Name) == null)
                                    {
                                        context.Yeasts.Add(yeast);
                                        context.SaveChanges();
                                    }
                                }
                                if (!recipe.RecipeYeasts.Contains(recipeYeast))
                                {
                                    recipe.RecipeYeasts.Add(recipeYeast);
                                }
                                break;
                             case "MASH":
                                Models.MashProfile mash = ParseMash(reader);
                                recipe.Mash = mash;
                                break;
                            case "EQUIPMENT":
                                ParseEquipment(reader);
                                break;
                        }
                        break;
                    case XmlNodeType.Text:
                        if (recipe == null)
                        {
                            break;
                        }
                        switch (currentNodeName)
                        {
                            case "NAME":
                                recipe.Name = reader.Value;
                                break;
                            case "TYPE":
                                Models.RecipieType recipieType = new Models.RecipieType() { Name = reader.Value };
                                using (var context = new Models.ModelsContext())
                                {
                                    if (context.RecipieTypes.Find(recipieType.Name) == null)
                                    {
                                        context.RecipieTypes.Add(recipieType);
                                        context.SaveChanges();
                                    }
                                }
                                recipe.RecipieType_Name = reader.Value;
                                break;
                            case "BATCH_SIZE":
                                recipe.BatchSize = float.Parse(reader.Value);
                                break;
                            case "BOIL_SIZE":
                                recipe.BoilSize = float.Parse(reader.Value);
                                break;
                            case "BOIL_TIME":
                                recipe.BoilTime = float.Parse(reader.Value);
                                break;
                            case "EFFICIENCY":
                                recipe.Efficiency = float.Parse(reader.Value);
                                break;
                            case "NOTES":
                                recipe.Notes = reader.Value;
                                break;
                            case "TASTE_NOTES":
                                recipe.TasteNotes = reader.Value;
                                break;
                            case "TASTE_RATING":
                                recipe.TasteRating = float.Parse(reader.Value);
                                break;
                            case "OG":
                                recipe.OG = float.Parse(reader.Value);
                                break;
                            case "FG":
                                recipe.FG = float.Parse(reader.Value);
                                break;
                            case "FERMENTATION_STAGES":
                                recipe.FermentationStages = int.Parse(reader.Value);
                                break;
                            case "PRIMARY_AGE":
                                recipe.PrimayAge = float.Parse(reader.Value);
                                break;
                            case "PRIMARY_TEMP":
                                recipe.PrimayTemp = float.Parse(reader.Value);
                                break;
                            case "SECONDARY_AGE":
                                recipe.SecondaryAge = float.Parse(reader.Value);
                                break;
                            case "SECONDARY_TEMP":
                                recipe.SecondaryTemp = float.Parse(reader.Value);
                                break;
                            case "TERTIARY_AGE":
                                recipe.TertiaryAge = float.Parse(reader.Value);
                                break;
                            case "TERTIARY_TEMP":
                                recipe.TertiaryTemp = float.Parse(reader.Value);
                                break;
                            case "AGE":
                                recipe.Age = float.Parse(reader.Value);
                                break;
                            case "AGE_TEMP":
                                recipe.AgeTemp = float.Parse(reader.Value);
                                break;
                            case "DATE":
                                DateTime maxDt = new DateTime(2000,1,1,17,0,0);
                                TimeSpan timeSpan = DateTime.Today - maxDt;
                                var randomTest = new Random();
                                TimeSpan newSpan = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0);
                                DateTime newDate = maxDt + newSpan;
                                recipe.Date = DateTime.Today;
                                break;
                            case "CARBONATION":
                                recipe.Carbonation = float.Parse(reader.Value);
                                break;
                            case "FORCED_CARBONATION":
                                recipe.ForcedCarbonation = bool.Parse(reader.Value);
                                break;
                            case "PRIMING_SUGAR_NAME":
                                recipe.PrimingSugarName = reader.Value;
                                break;
                            case "CARBONATION_TEMP":
                                recipe.CarbonationTemp = float.Parse(reader.Value);
                                break;
                            case "PRIMING_SUGAR_EQUIV":
                                recipe.PrimingSugarEquiv = float.Parse(reader.Value);
                                break;
                            case "KEG_PRIMING_FACTOR":
                                recipe.KegPrimingFactor = float.Parse(reader.Value);
                                break;
                        }
                        break;
                    case XmlNodeType.EndElement:
                        if (reader.Name == "RECIPE" && recipe != null)
                        {
                            using (var context = new Models.ModelsContext())
                            {
                                if (context.Recipes.Find(recipe.Name) == null)
                                {
                                    //foreach (Models.Yeast yeast in recipe.Yeasts)
                                    //{
                                    //    context.Yeasts.Attach(yeast);
                                    //    yeast.UsingRecipes.Add(recipe);
                                    //}

                                    //foreach (Models.Fermentable fermentable in recipe.Fermentables)
                                    //{
                                    //    context.Fermentables.Attach(fermentable);
                                    //    fermentable.UsingRecipes.Add(recipe);
                                    //}

                                    //foreach (Models.Hop hop in recipe.Hops)
                                    //{
                                    //    context.Hops.Attach(hop);
                                    //    hop.UsingRecipes.Add(recipe);
                                    //}

                                    context.Styles.Attach(recipe.Style);
                                    recipe.Style.UsingRecipes.Add(recipe);

                                    context.MashProfiles.Add(recipe.Mash);

                                    context.Recipes.Add(recipe);
                                    context.SaveChanges();
                                }
                            }
                            recipe = null;
                        }
                        break;
                }
            }
        }
        public string CreateDataBackupScripts()
        {
            try
            {
                string recipesaveproc = "call Recipe_SaveRecipe('{0}','{1}',0,pRecipeID);";
                string ingredientsaveproc = "call Recipe_SaveIngredient(0,pRecipeID,'{0}',{1},'{2}','{3}','{4}',{5},pIngredientID);";
                string directionsaveproc = "call Recipe_SaveDirections(0,pRecipeID,{0},'{1}','{2}',pDirectionID);";
                string categorysaveproc = "call Recipe_SaveRecipeCategory(pRecipeID,'{0}');";
                string imagesaveproc = "call Recipe_SaveImage(pRecipeID,'{0}','{1}','{2}');";

                StringBuilder backupscript = new StringBuilder();
                backupscript.AppendLine("declare pRecipeID varchar(36);");
                backupscript.AppendLine("declare pIngredientID int;");
                backupscript.AppendLine("declare pDirectionID int;");
                backupscript.AppendLine();
                backupscript.AppendLine("TRUNCATE TABLE Recipe_Recipes;");
                backupscript.AppendLine("TRUNCATE TABLE Recipe_Ingredients;");
                backupscript.AppendLine("TRUNCATE TABLE Recipe_Directions;");
                backupscript.AppendLine("TRUNCATE TABLE Recipe_Categories;");
                backupscript.AppendLine("TRUNCATE TABLE Recipe_Images;");
                backupscript.AppendLine();

                List<Models.Recipe> recipes = Models.Recipe.SearchRecipes(String.Empty, new string[] { }, new string[] { });
                foreach (Models.Recipe item in recipes)
                {
                    Models.Recipe rcp = new Models.Recipe(item.RecipeID);

                    backupscript.AppendLine(String.Format(recipesaveproc, rcp.Title.Replace("'", "''"), rcp.Description.Replace("'", "''")));

                    foreach (Models.RecipeIngredient ing in rcp.IngredientList)
                    {
                        backupscript.AppendLine(String.Format(ingredientsaveproc, ing.IngredientName.Trim().Replace("'", "''"), ing.Quantity, ing.UnitOfMeasure.Replace("'", "''"), ing.Notes.Trim().Replace("'", "''"), Enum.GetName(ing.DisplayType.GetType(), ing.DisplayType), ing.SortOrder));
                    }

                    foreach (Models.RecipeDirection dir in rcp.DirectionList)
                    {
                        backupscript.AppendLine(String.Format(directionsaveproc, dir.SortOrder, dir.DirectionText.Trim().Replace("'", "''"), Enum.GetName(dir.DisplayType.GetType(), dir.DisplayType)));
                    }

                    foreach (Models.Recipe.Category ctg in rcp.CategoryList)
                    {
                        backupscript.AppendLine(String.Format(categorysaveproc, ctg.CategoryCode));
                    }

                    foreach (Models.RecipeImage img in rcp.ImageList)
                    {
                        backupscript.AppendLine(String.Format(imagesaveproc, img.ImageName, img.IsPrimary, img.SortOrder));
                    }
                    backupscript.AppendLine();
                    backupscript.AppendLine();
                }

                System.IO.File.WriteAllText(Server.MapPath("/DownloadFiles/DataRestoreScript.sql"), backupscript.ToString());

                return "Success";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }