// Get the recepie entity by id private ActionResult GetRecepieById(int?RecepieId) { try { // Check if recepie id is null if (RecepieId == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } // Get the user entity Recepie currRecepie = AmatziaDB.Recepies.Find(RecepieId); // Check if recepie with this id was found if (currRecepie == null) { return(HttpNotFound("Recepie with recepie id " + RecepieId.ToString() + " not found")); } return(View(currRecepie)); } catch (Exception ex) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } }
public ActionResult Edit([Bind(Include = "Id,RecepieId,Title,Content")] Comment comment) { try { // Get the logged user User currUser = Session["LoggedUser"] as User; Recepie recepie = AmatziaDB.Recepies.Find(comment.RecepieId); comment.User = currUser; comment.UserId = currUser.UserId; comment.Recepie = recepie; if (ModelState.IsValid) { AmatziaDB.Entry(currUser).State = System.Data.Entity.EntityState.Modified; AmatziaDB.Entry(recepie).State = System.Data.Entity.EntityState.Modified; AmatziaDB.Entry(comment).State = System.Data.Entity.EntityState.Modified; AmatziaDB.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.RecepieId = new SelectList(AmatziaDB.Recepies, "Id", "Name", comment.RecepieId); return(View(comment)); } catch (Exception ex) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } }
public async Task <IActionResult> Edit(int id, [Bind("RecepieID,RecepieName,Description,ImagePath,TimeToCook")] Recepie recepie) { if (id != recepie.RecepieID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(recepie); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RecepieExists(recepie.RecepieID)) { return(NotFound()); } else { ModelState.AddModelError("", "Номерът вече съществува, моля въведете друг."); } } return(RedirectToAction(nameof(Index))); } return(View(recepie)); }
/// <summary> /// Attempt to craft the given recepie /// </summary> /// <param name="recepie"> The recepie to craft </param> /// <returns> true if the recpie was crafted successfully, false if not </returns> public bool Craft(Recepie recepie) { if (!CanCraft(recepie)) { Debug.LogWarning(string.Format("Tried to craft {0} but check failed", recepie.Produces.GetType().FullName)); return(false); } foreach (var requiredItem in recepie.RequiredItems) { for (int i = 0; i < requiredItem.Count; i++) { if (!Remove(requiredItem.Item)) { // Something bad happened Debug.LogWarning(string.Format("While trying to craft {0}, failed to remove one {1} from inventory", recepie.GetType().FullName, requiredItem.Item.GetType().FullName)); return(false); } } } Add(recepie.Produces); return(true); }
private bool TryOpenFile(string aFileName) { XmlSerializer serializer = new XmlSerializer(typeof(Recepie)); FileStream loadStream = new FileStream(aFileName, FileMode.Open, FileAccess.Read); XmlReader reader = new XmlTextReader(loadStream); if (!serializer.CanDeserialize(reader)) { return(false); } try { Recepie loadedObject = (Recepie)serializer.Deserialize(reader); PopulateGUI(loadedObject); } catch (Exception e) { MessageBox.Show("The recipe can be parsed. {0}", e.ToString()); } finally { loadStream.Close(); } return(true); }
public ActionResult Create([Bind(Include = "Name,Ingredients,Instructions,Difficulty,duration")] Recepie NewRecepie) { try { if (ModelState.IsValid) { // Get the logged user User currUser = Session["LoggedUser"] as User; NewRecepie.UserId = currUser.UserId; NewRecepie.Id = new Random().Next(1, 1000); NewRecepie.UploadDate = DateTime.Now; NewRecepie.User = currUser; AmatziaDB.Recepies.Add(NewRecepie); AmatziaDB.Users.Attach(NewRecepie.User); AmatziaDB.Entry(currUser).State = System.Data.Entity.EntityState.Modified; AmatziaDB.SaveChanges(); return(RedirectToAction("Index", "Post")); } return(View(NewRecepie)); } catch (Exception ex) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } }
private void initCraftingManager() { List <Recepie> recepies = new List <Recepie>(); Dictionary <InventoryItem, int> input1 = new Dictionary <InventoryItem, int>(); input1.Add(BlockPrototype.stone, 8); KeyValuePair <InventoryItem, int> output1; output1 = new KeyValuePair <InventoryItem, int>(BlockPrototype.dirt, 1); Recepie recepie1 = new Recepie(input1, output1); recepies.Add(recepie1); Dictionary <InventoryItem, int> input5 = new Dictionary <InventoryItem, int>(); input5.Add(BlockPrototype.ironOre, 1); recepies.Add(new Recepie(input5, new KeyValuePair <InventoryItem, int>(ItemTemplate.ironBar.createNew(), 1))); Dictionary <InventoryItem, int> input2 = new Dictionary <InventoryItem, int>(); input2.Add(BlockPrototype.sand, 1); recepies.Add(new Recepie(input2, new KeyValuePair <InventoryItem, int>(BlockPrototype.glass, 1))); craftingManager = new CraftingManager(recepies); }
void AddRecepieToGroceryList(Recepie rec) { if (rec == null) { return; } foreach (Ingredient ing in rec.Ingredients) { if (!inList.Contains(ing.Name)) { inList.Add(ing.Name); GroceryList.Add(new Ingredient(ing.Name, ing.Count, ing.Units)); } else { for (int k = 0; k < GroceryList.Count; k++) { if (GroceryList[k].Name == ing.Name) { GroceryList[k].SumIngredient(ing); k = GroceryList.Count; } } } } }
private void handleSelectHops() { HopAddition h = new HopAddition(); if (HopsListView.SelectedItem != null) { var bsh = BSBoilHops.First(); h.Hop = (Hops)(HopsListView.SelectedItem); Debug.Assert(WorkRecepie.BatchVolume != 0); h.Amount = (bsh.Amount) / (WorkRecepie.BatchVolume); h.Duration = bsh.BoilTime; WorkRecepie.BoilHops.Add(h); var del = BSBoilHops.First(); BSBoilHops.Remove(del); if (BSGrainBill.Count == 0) { ImportedRecepie = WorkRecepie; this.Close(); } else { TextblockHops.Text = "Please select a corresponding hops for " + BSBoilHops.First().Name + " with alpha acid " + BSBoilHops.First().AlphaAcid.ToString(); } } else { MessageBox.Show("Please select a hop in the list to match the imported one"); } }
/// <summary> /// Check whether the given recepie can be crafted by the inventory /// </summary> /// <param name="recepie"> The recepie to check </param> /// <returns> true if the recepie can be crafted, false if not </returns> public bool CanCraft(Recepie recepie) { foreach (var requiredItem in recepie.RequiredItems) { var materialStackEntry = Find(requiredItem.Item); if (materialStackEntry == null) { // Item isn't in inventory at all, can't craft Debug.LogWarning(string.Format("Can't craft {0}, {1} wasn't present at all", recepie.GetType().FullName, requiredItem.Item.GetType().FullName)); return(false); } if (materialStackEntry.Count < requiredItem.Count) { // Don't have enough of that item to craft Debug.LogWarning(string.Format("Can't craft {0}, didnt have enough of {1}", recepie.GetType().FullName, requiredItem.Item.GetType().FullName)); return(false); } } return(true); }
private ListViewItem ConvertRecepieToListViewItem(Recepie recepie) { ListViewItem item = new ListViewItem(); item.Text = recepie.Title + System.Environment.NewLine + "[" + recepie.PrepTime + " min] - [" + recepie.Calories + " kcal]" + (recepie.Rating > 0 ? " - [" + recepiesEngine.GenerateStarString(recepie.Rating) + "]" : ""); item.ToolTipText = recepie.RecepieUrl; item.ImageIndex = recepieImageIndex[recepie.RecepieUrl]; return(item); }
public void ChangeRecepie(Recepie rec) { if (rec == null) { return; } RecepieName = rec.RecepieName; RecepieInstruction = rec.Instruction; RecepieIngredients = rec.Ingredients; RecepieLabel = rec.Label.ToString(); }
public RecepieBase() { PlanForWeek = new Recepie[7][]; for (int i = 0; i < PlanForWeek.Length; i++) { PlanForWeek[i] = new Recepie[3]; } Recepies = new ObservableCollection <Recepie>(); LoadRecepiesFromFile(); }
public IActionResult UpdateRecepie([FromBody] Recepie recepie, int id) { var resoult = _settingsRepository.EditRecepie(id, recepie); if (resoult == true) { return(StatusCode(StatusCodes.Status201Created)); } else { return(StatusCode(StatusCodes.Status501NotImplemented)); } }
public IActionResult AddRecepieImg([FromForm] Recepie recepie) { bool resoult = _settingsRepository.AddRecepieImg(recepie); if (resoult == true) { return(StatusCode(StatusCodes.Status201Created)); } else { return(StatusCode(StatusCodes.Status501NotImplemented)); } }
private void PopulateGUI(Recepie aRecepie) { Grist.Clear(); foreach (GristPart g in aRecepie.Fermentables) { Grist.Add(g); } BoilHops.Clear(); foreach (HopAddition h in aRecepie.BoilHops) { BoilHops.Add(h); } MashProfileList.Clear(); foreach (Domain.MashProfileStep mps in aRecepie.MashProfile) { MashProfileList.Add(mps); } OtherIngredientsList.Clear(); foreach (OtherIngredient o in aRecepie.OtherIngredients) { OtherIngredientsList.Add(o); } Volumes.FinalBatchVolume = aRecepie.BatchVolume; BatchSizeVolumeTextBox.Text = Volumes.FinalBatchVolume.ToString(); Volumes.PreBoilTapOff = aRecepie.PreBoilTapOffVolume; PreBoilVolumeTextBox.Text = Volumes.PreBoilTapOff.ToString(); TopUpMashWater = aRecepie.TopUpMashWater; TopUpMashWaterVolumeTextBox.Text = TopUpMashWater.ToString(); OriginalGravity = aRecepie.OriginalGravity; ExpectedOriginalGravityTextBox.Text = OriginalGravity.ToString(); BoilTime = aRecepie.BoilTime; BoilTimeTextBox.Text = BoilTime.ToString(); NameTextBox.Text = aRecepie.Name; recalculateGrainBill(); recalculateIbu(); updateGuiText(); }
public AddRecepieViewModel() { AddToList = new RelayCommand(AddIngredient, CanAddIngredient); AddRecepiesToBase = new RelayCommand(AddRecepies, CanAddRecepies); DeleteIng = new RelayCommand(DeleteIngredient, CanDeleteIngredient); PlanForWeek = RecepieBase.Instance.PlanForWeek; NewRecepie = new Recepie("", "", new ObservableCollection <Ingredient>(), new NutritionLabel(0, 0, 0, 0, 0, 0)); UnitList = new List <string>() { "-", "g", "dag", "kg", "ml", "tbsp", "tsp" }; SelectedUnit = UnitList[0]; }
public TCW(string aBSExportFilename, FermentableRepository aMaltRepo, HopsRepository aHopsRepo) { InitializeComponent(); this.MaltsRepo = aMaltRepo; this.HopsRepo = aHopsRepo; FermentablesObservableList = new ObservableCollection <FermentableAdjunct>(aMaltRepo.Get()); HopsObservableList = new ObservableCollection <Hops>(aHopsRepo.Get()); BeersmithImporter = new BSImporter(aBSExportFilename); RecipeNameCombobox.ItemsSource = BeersmithImporter.GetAllRecipes(); RecipeNameCombobox.SelectedIndex = 0; HopsListView.ItemsSource = HopsObservableList; MaltsListView.ItemsSource = FermentablesObservableList; WorkRecepie = new Recepie(); }
public static void Delete(Recepie receptura) { KalkulatorDietyDatabase DataSet = new KalkulatorDietyDatabase(); String XML_Location = @"DataBase.xml"; DataSet.ReadXml(XML_Location); if (DataSet.Receptury.Rows.Count > 0) { for (int i = 0; i < DataSet.Receptury.Rows.Count; i++) { if (DataSet.Receptury.Rows[i]["Nazwa receptury"].ToString() == receptura.nazwa && DataSet.Receptury.Rows[i]["Skład receptury"].ToString() == receptura.sklad) { DataSet.Receptury.Rows[i].Delete(); } } } DataSet.WriteXml(XML_Location); }
private void MenuItem_FileSave(object sender, RoutedEventArgs e) { var r = new Recepie(); r.Fermentables = Grist.ToList(); r.BoilHops = BoilHops.ToList(); r.MashProfile = MashProfileList.ToList(); r.OtherIngredients = OtherIngredientsList.ToList(); r.Name = NameTextBox.Text; r.BatchVolume = Volumes.FinalBatchVolume; r.PreBoilTapOffVolume = Volumes.PreBoilTapOff; r.TopUpMashWater = 0; r.OriginalGravity = OriginalGravity; r.BoilTime = BoilTime; // Create OpenFileDialog Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".gsrx"; dlg.Filter = "Grainfather recipe files (*.gsrx)|*.gsrx"; dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); dlg.FileName = NameTextBox.Text; // Display OpenFileDialog by calling ShowDialog method Nullable <bool> result = dlg.ShowDialog(); if (result != true) { return; } XmlSerializer serializer = new XmlSerializer(typeof(Recepie)); FileStream saveStream = new FileStream(dlg.FileName, FileMode.OpenOrCreate, FileAccess.Write); serializer.Serialize(saveStream, r); saveStream.Close(); }
// GET: Recepie/Edit/[id] public ActionResult Edit(int?RecepieId) { try { Recepie currRecepie = AmatziaDB.Recepies.Where(r => r.Id == RecepieId).FirstOrDefault(); User currUser = Session["LoggedUser"] as User; if (currUser.UserId != currRecepie.UserId) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "User is not allowd to edit this recepie")); } return(this.GetRecepieById(RecepieId)); } catch (Exception ex) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } }
public async Task <IActionResult> Create([Bind("RecepieID,RecepieName,Description,ImagePath,TimeToCook")] Recepie recepie) { try { if (ModelState.IsValid) { _context.Add(recepie); await _context.SaveChangesAsync(); return(RedirectToAction("Create", "RecProds", new { recepieid = recepie.RecepieID })); //return RedirectToAction(nameof(Index)); } } catch { ModelState.AddModelError("", "Номерът вече съществува, моля въведете друг."); } return(View(recepie)); }
public ActionResult Edit([Bind(Include = "Id, UserId, Name, Ingredients, Instructions, UploadDate, Difficulty, duration")] Recepie currRecepie) { try { if (ModelState.IsValid) { User currUser = Session["LoggedUser"] as User; currRecepie.User = currUser; currRecepie.UserId = currUser.UserId; AmatziaDB.Entry(currRecepie).State = EntityState.Modified; AmatziaDB.SaveChanges(); return(RedirectToAction("Index")); } return(View(currRecepie)); } catch (Exception ex) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } }
public List <Recepie> GetRecepiesForMain(string recepieType) { string connString = "Data Source = RARES\\SQLEXPRESS ; Initial Catalog=lab8; Integrated Security = true"; SqlConnection conn = new SqlConnection(connString); List <Recepie> rlist = new List <Recepie>(); try { conn.Open(); string query = "SELECT * FROM recepies where type=@givenType"; SqlCommand cmd = new SqlCommand(query, conn); cmd.Parameters.AddWithValue("@givenType", recepieType); SqlDataReader myreader = cmd.ExecuteReader(); while (myreader.Read()) { Recepie recepie = new Recepie(); recepie.Id = Convert.ToInt32(myreader["rId"]); recepie.Title = myreader["title"].ToString(); recepie.Description = myreader["description"].ToString(); recepie.Type = myreader["type"].ToString(); rlist.Add(recepie); } myreader.Close(); conn.Close(); } catch (MySql.Data.MySqlClient.MySqlException ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } return(rlist); }
private void RunRecepieProductPhase() { Dictionary <string, Recepie> fullRecepies = new Dictionary <string, Recepie>(); WebClient client = new WebClient(); foreach (Recepie recepie in _recepies.Values) { if (recepie.LastUpdated < DateTime.UtcNow.AddDays(-5) || recepie.Calories == 0) { Recepie fullRecepie = ConvertWebStringToRecepie(client.DownloadString(recepie.RecepieUrl), recepie); fullRecepies.Add(fullRecepie.RecepieUrl, fullRecepie); } else { fullRecepies.Add(recepie.RecepieUrl, recepie); } } _recepies = new ConcurrentDictionary <string, Recepie>(fullRecepies); SaveRecepies(_defaultFilePath); }
private void CalculateIngredients() { DataTable dt = new DataTable(); dt.Columns.Add("Ingredient"); dt.Columns.Add("Quantity", typeof(float)); dt.Columns.Add("Measurement"); Dictionary <string, Ingredient> ingredients = new Dictionary <string, Ingredient>(); foreach (ListViewItem item in lstSelection.Items) { Recepie recepie = recepiesEngine.Recepies[item.ToolTipText]; foreach (Ingredient ingredient in recepie.Ingredients.Values) { if (ingredients.ContainsKey(ingredient.Name)) { ingredients[ingredient.Name].Quantity += ingredient.Quantity; } else { ingredients.Add(ingredient.Name, new Ingredient() { Name = ingredient.Name, Quantity = ingredient.Quantity, MeasurmentType = ingredient.MeasurmentType }); } } } foreach (Ingredient ingredient in ingredients.Values) { dt.Rows.Add(ingredient.Name, ingredient.Quantity, ingredient.MeasurmentType); } dataGridView1.DataSource = dt; }
public async Task <List <Recepie> > Delete([FromQuery] int deleteId) { var userId = _caller.Claims.Single(c => c.Type == "id"); var customer = await _appDbContext.Customers.Include(c => c.Identity) .Include(x => x.Identity.Recepies) .SingleAsync(c => c.Identity.Id == userId.Value); Recepie recepie = new Recepie(); foreach (var item in customer.Identity.Recepies.Where(x => x.Id == deleteId)) { recepie = item; } if (recepie.IdentityId == customer.Identity.Id) { var ingredients = _appDbContext.Ingridients.Where(x => x.RecepieId == deleteId).ToList(); _appDbContext.Remove(recepie); _appDbContext.RemoveRange(ingredients); if (!string.IsNullOrEmpty(recepie.ImageUrl)) { var uploads = Path.Combine(_hostingEnvironment.ContentRootPath, "src"); var pathToData = Path.GetFullPath(Path.Combine(uploads, "assets")); var filePath = Path.Combine(pathToData, recepie.ImageUrl); System.IO.File.Delete(filePath); } await _appDbContext.SaveChangesAsync(); } var recpieList = _appDbContext.Recepies.Where(x => x.IdentityId == customer.Identity.Id).ToList(); return(recpieList); }
private void PeriodicRecepieScrape_Elapsed(Object source, ElapsedEventArgs e) { periodicRecepieScrape.Stop(); Dictionary <string, Recepie> IncompleteRecepies = _recepies.Where(a => (a.Value.Ingredients == null || a.Value.Ingredients.Count == 0) && (a.Value.IgnoreProductCompletely == false || a.Value.LastUpdated < DateTime.UtcNow.AddDays(-5))).ToDictionary(k => k.Key, v => v.Value); if (IncompleteRecepies.Count > 0) { foreach (Recepie incompleteRecepie in IncompleteRecepies.Values) { LogMessage($"Recepie {incompleteRecepie.Title} doesn't have ingredients. Attempting to gather them."); WebClient client = new WebClient(); Recepie fullRecepie = ConvertWebStringToRecepie(client.DownloadString(incompleteRecepie.RecepieUrl), incompleteRecepie); if (fullRecepie.Ingredients.Count == 0) { fullRecepie.IgnoreProductCompletely = true; LogMessage($"Recepie {incompleteRecepie.Title} STILL doesn't have ingredients. Marking as bad and will re-attempt in 5 days"); } _recepies[fullRecepie.RecepieUrl] = fullRecepie; } SaveRecepies(_defaultFilePath); } if (_recepies.Count > 0) { WebClient client = new WebClient(); if (_recepies.Values.ToList()[_recepieScrapeCount].LastUpdated < DateTime.UtcNow.AddDays(-5) || _recepies.Values.ToList()[_recepieScrapeCount].Calories == 0) { LogMessage($"Scraping recepie '{_recepies.Values.ToList()[_recepieScrapeCount].Title}' as it's been five days since last scrape."); Recepie fullRecepie = ConvertWebStringToRecepie(client.DownloadString(_recepies.Values.ToList()[_recepieScrapeCount].RecepieUrl), _recepies.Values.ToList()[_recepieScrapeCount]); _recepies[fullRecepie.RecepieUrl] = fullRecepie; SaveRecepies(_defaultFilePath); } _recepieScrapeCount++; if (_recepieScrapeCount > _recepies.Values.Count) { _recepieScrapeCount = 0; } } Random rnd = new Random(); if (_recepies.Count == 0) { periodicRecepieScrape.Interval = 1 * 1000; } else if (_discoveryPhaseStarted) { periodicRecepieScrape.Interval = 1 * 1000; _waitingToFinish = true; } else if (!_discoveryPhaseStarted && _waitingToFinish) { _waitingToFinish = false; } else { periodicRecepieScrape.Interval = rnd.Next(300, 900) * 1000; } periodicRecepieScrape.Start(); }
private Recepie ConvertWebStringToRecepie(string webstring, Recepie recepie = null) { if (recepie == null) { recepie = new Recepie(); } if (recepie.Ingredients == null) { recepie.Ingredients = new Dictionary <string, Ingredient>(); } recepie.LastUpdated = DateTimeOffset.UtcNow; recepie.Calories = int.Parse(webstring.Split(new string[] { " nutritional-info-table" }, StringSplitOptions.None)[1].Split(new string[] { " kcal" }, StringSplitOptions.None)[1].Split(new string[] { "<br/>" }, StringSplitOptions.None)[1]); recepie.Carbs = decimal.Parse(webstring.Split(new string[] { " nutritional-info-table" }, StringSplitOptions.None)[1].Split(new string[] { "Carbohydrate<br>" }, StringSplitOptions.None)[1].Split(new string[] { " g<br" }, StringSplitOptions.None)[0].Split(new string[] { "<td>" }, StringSplitOptions.None)[1]); recepie.PrepTime = int.Parse(webstring.Split(new string[] { "Prep Time</p>" }, StringSplitOptions.None)[1] .Split(new string[] { "<p class=\"recipehighlight-box-value\">" }, StringSplitOptions.None)[1] .Split(new string[] { " min</p>" }, StringSplitOptions.None)[0]); recepie.Cuisine = webstring.Split(new string[] { "Cuisine</p>" }, StringSplitOptions.None)[1] .Split(new string[] { "<p class=\"recipehighlight-box-value\">" }, StringSplitOptions.None)[1] .Split(new string[] { "</p>" }, StringSplitOptions.None)[0]; string[] ingredients = webstring.Split(new string[] { "indivrecipe-ingredients-text\">" }, StringSplitOptions.None); for (int i = 1; i < ingredients.Length; i++) { Ingredient ingredient = new Ingredient(); int guineapig = 0; if (ingredients[i].Substring(0, 30).ToLower().Contains("tbsp")) { ingredient.MeasurmentType = QuantityType.Tbsp; try { ingredient.Quantity = float.Parse(ingredients[i].Split(new string[] { " tbsp ", "tbsp " }, StringSplitOptions.None)[0]); } catch { ingredient.Quantity = (float)FractionToDouble(ingredients[i].Split(new string[] { " tbsp ", "tbsp " }, StringSplitOptions.None)[0]); } ingredient.Name = ingredients[i].Split(new string[] { " tbsp ", "tbsp " }, StringSplitOptions.None)[1] .Split(new string[] { "</figcaption>" }, StringSplitOptions.None)[0]; } else if (ingredients[i].Substring(0, 30).ToLower().Contains("tsp")) { ingredient.MeasurmentType = QuantityType.Tsp; try { ingredient.Quantity = float.Parse(ingredients[i].Split(new string[] { " tsp ", "tsp " }, StringSplitOptions.None)[0]); } catch { ingredient.Quantity = (float)FractionToDouble(ingredients[i].Split(new string[] { " tsp ", "tsp " }, StringSplitOptions.None)[0]); } ingredient.Name = ingredients[i].Split(new string[] { " tsp ", "tsp " }, StringSplitOptions.None)[1] .Split(new string[] { "</figcaption>" }, StringSplitOptions.None)[0]; } else if (Regex.IsMatch(ingredients[i].Substring(0, 30), @"^\d{1,}[m][l]")) { ingredient.MeasurmentType = QuantityType.ml; ingredient.Quantity = float.Parse(ingredients[i].Split(new string[] { "ml " }, StringSplitOptions.None)[0]); ingredient.Name = ingredients[i].Split(new string[] { "ml " }, StringSplitOptions.None)[1] .Split(new string[] { "</figcaption>" }, StringSplitOptions.None)[0]; } else if (Regex.IsMatch(ingredients[i].Substring(0, 30), @"^\d{1,}[g]")) { ingredient.MeasurmentType = QuantityType.g; ingredient.Quantity = float.Parse(ingredients[i].Split(new string[] { "g " }, StringSplitOptions.None)[0]); ingredient.Name = ingredients[i].Split(new string[] { "g " }, StringSplitOptions.None)[1] .Split(new string[] { "</figcaption>" }, StringSplitOptions.None)[0]; } else if (Regex.IsMatch(ingredients[i].Substring(0, 30), @"\d{1,}[g]")) { ingredient.MeasurmentType = QuantityType.g; Match m = Regex.Match(ingredients[i].Substring(0, 250), @"\d{1,}[g]", RegexOptions.IgnoreCase); if (m.Success) { ingredient.Quantity = float.Parse(m.Groups[0].Value.Replace("g", "")); ingredient.Name = ingredients[i].Split(new string[] { "</figcaption>" }, StringSplitOptions.None)[0].Replace(m.Groups[0].Value, ""); ingredient.Name = ingredient.Name.Replace("()", ""); } } else if (Regex.IsMatch(ingredients[i].Substring(0, 30), @"\d{1,}[m][l]")) { ingredient.MeasurmentType = QuantityType.ml; Match m = Regex.Match(ingredients[i].Substring(0, 250), @"\d{1,}[m][l]", RegexOptions.IgnoreCase); if (m.Success) { ingredient.Quantity = float.Parse(m.Groups[0].Value.Replace("ml", "")); ingredient.Name = ingredients[i].Split(new string[] { "</figcaption>" }, StringSplitOptions.None)[0].Replace(m.Groups[0].Value, ""); ingredient.Name = ingredient.Name.Replace("()", ""); } } else if (Regex.IsMatch(ingredients[i].Substring(0, 30), @"^\d{1,}\/\d{1,}")) { ingredient.MeasurmentType = QuantityType.Unit; ingredient.Quantity = (float)FractionToDouble(ingredients[i].Split(new string[] { " " }, StringSplitOptions.None)[0]); ingredient.Name = ingredients[i].Split(new string[] { "</figcaption>" }, StringSplitOptions.None)[0].Replace(ingredients[i].Split(new string[] { " " }, StringSplitOptions.None)[0] + " ", ""); } else if (int.TryParse(ingredients[i].Substring(0, 1), out guineapig)) { ingredient.MeasurmentType = QuantityType.Unit; ingredient.Quantity = float.Parse(ingredients[i].Split(new string[] { " " }, StringSplitOptions.None)[0]); ingredient.Name = ingredients[i].Split(new string[] { "</figcaption>" }, StringSplitOptions.None)[0].Replace(ingredients[i].Split(new string[] { " " }, StringSplitOptions.None)[0] + " ", ""); } else { throw new Exception("No f*****g clue, debug time!"); } ingredient.Name = WebUtility.HtmlDecode(ingredient.Name).Replace(" †", ""); if (recepie.Ingredients.ContainsKey(ingredient.Name)) { recepie.Ingredients.Remove(ingredient.Name); } recepie.Ingredients.Add(ingredient.Name, ingredient); } return(recepie); }
//CRUD // Create public Recepie Create(Recepie recepie) { recepie.Id = _database.Count + 1; _database.Add(recepie.Id, recepie); return(recepie); }