private void AddSearchResult(Recipe recipe) { var control = new ucSearchResult(recipe); control.Dock = DockStyle.Top; pcFindRecipe.Controls.Add(control); }
void SetFailure (Recipe r) { AudioSource.PlayClipAtPoint(failSound2, transform.position); r.isFinished = true; r.isSuccessful = false; r.currentTimer = 0; }
public IHttpActionResult PutRecipe(int id, Recipe recipe) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != recipe.RecipeId) { return BadRequest(); } _collector.Recipes.Update(recipe); try { _collector.Save(); } catch (DbUpdateConcurrencyException) { if (!_collector.Recipes.ItemExists(id)) { return NotFound(); } return BadRequest(); } return StatusCode(HttpStatusCode.NoContent); }
void PopulateKitchenPanel(Recipe recipe){ GameObject newBtnPrefab = Instantiate(recipeBtnPrefab); switch(recipe.recipeType){ // case Recipe.RecipeType.salad: // break; case Recipe.RecipeType.soup: newBtnPrefab.transform.SetParent(soupPanel, false); break; case Recipe.RecipeType.meal: newBtnPrefab.transform.SetParent(mealPanel, false); break; case Recipe.RecipeType.dessert: newBtnPrefab.transform.SetParent(dessertPanel, false); break; default: newBtnPrefab.transform.SetParent(saladPanel, false); // newBtnPrefab.transform.SetParent(basicPanel, false); break; } newBtnPrefab.GetComponent<RecipeBtnPrefab>().recipe = recipe; newBtnPrefab.GetComponentInChildren<Text>().text = recipe.recipeName; }
/// <summary> /// Creates a new recipe /// </summary> /// <returns>The recipe or null if aborted</returns> private static Recipe CreateRecipe() { Console.Clear(); RecipeView.RenderHeader(" Nytt recept "); string name = ReadRecipeName(); if (name == null) { return null; } Recipe recipe = new Recipe(name); List<Ingredient> ingredients = ReadIngredients(); if (ingredients == null) { return null; } foreach (Ingredient ingredient in ingredients) { recipe.Add(ingredient); } List<string> directions = ReadDirections(); if (directions == null) { return null; } foreach (string direction in directions) { recipe.Add(direction); } return recipe; }
public static int CalculateCost(Recipe recipe, List<Ingredient> simIngredients, List<Ingredient> lotIngredients, bool isSnack) { List<Ingredient> list = null; List<Ingredient> list2 = null; List<IngredientData> list3 = null; return CalculateCost(recipe, simIngredients, lotIngredients, ref list, ref list2, out list3, isSnack); }
public static string PrepareTestResultCheckAndGrayedOutPieMenuSet(Sim preparer, Recipe recipe, string dishName, bool isSnack) { StringBuilder sb = new StringBuilder(); sb.Append(Localization.LocalizeString("Gameplay/Objects/FoodObjects/Food:Requires", new object[] { dishName })); //If snack, only use one ingredient if (isSnack) { if (recipe.Ingredient1 != null) { sb.Append("\n"); sb.Append(recipe.Ingredient1.Name); } } else { foreach (IngredientData current in recipe.Ingredients.Keys) { sb.Append("\n"); sb.Append(current.Name); if (recipe.Ingredients[current] > 1) { sb.Append(" ("); sb.Append(recipe.Ingredients[current].ToString()); sb.Append(")"); } } } return sb.ToString(); }
public static int CalculateCost(Recipe recipe, List<Ingredient> simIngredients, List<Ingredient> lotIngredients, ref List<Ingredient> toRemoveFromSim, ref List<Ingredient> toRemoveFromFridge, out List<IngredientData> remainingIngredients, bool isSnack) { if (simIngredients == null || lotIngredients == null) { remainingIngredients = null; return 0; } remainingIngredients = BuildIngredientList(recipe, simIngredients, lotIngredients, ref toRemoveFromSim, ref toRemoveFromFridge, isSnack); int num = 0; foreach (IngredientData current in remainingIngredients) { if (!current.IsAbstract) { if (!current.CanBuyFromStore) { return -2147483648; } num += current.Price; } else { IngredientData cheapestIngredientOfAbstractType = IngredientData.GetCheapestIngredientOfAbstractType(current.Key, false); if (cheapestIngredientOfAbstractType != null) { num += cheapestIngredientOfAbstractType.Price; } } } //return num + (int)Math.Ceiling((double)((float)(num * Recipe.kFridgeRestockingPriceMarkupPercentage) / 100f)); if (num > 0) num = -2147483648; return num; }
// Use this for initialization void Start() { database = FindObjectOfType<ItemDatabase>(); recipe = database.recipeCollection[0]; TextSetup (); // This populates the icons for the ingredients for (int i = 0; i < recipe.recipeIngredients.Length; i++){ GameObject slot = (GameObject)Instantiate(slots); slot.GetComponent<RecipeSlot>().slotNumber = i; slot.name = ("Recipe Icon " + (i+1)); slot.transform.SetParent(this.gameObject.transform); slot.GetComponent<RectTransform>().localPosition = new Vector3(-145f + (45*i), -170f, 0f); slot.GetComponent<RectTransform>().localScale = new Vector3(1f, 1f, 1f); } // This populates the instruction lists for (int j = 0; j < recipe.recipeInstructions.Length; j++){ GameObject instruction = (GameObject) Instantiate(instructions); Text text = instruction.GetComponent<Text>(); text.text = recipe.recipeInstructions[j]; instruction.name = ("Recipe Instruction " + (j+1)); instruction.transform.SetParent(this.gameObject.transform); instruction.GetComponent<RectTransform>().localPosition = new Vector3(0f, -222f - (35f * j), 0f); instruction.GetComponent<RectTransform>().localScale = new Vector3(1f, 1f, 1f); } }
private void GenerateRecipes() { var recipe = new Recipe(); recipe.Name = "Non greasy gamer snacks"; recipe.Description = "Perfect snacks for gamers wich doesn't make your hands greasy and slippery."; recipe.Ingredients.Add(new Ingredient{ Name = "Snack", Amount = "1 bag"}); recipe.Ingredients.Add(new Ingredient { Name = "Non Greasy Stuff", Amount = "1 l" }); Recipes.Add(recipe); recipe = new Recipe(); recipe.Name = "Nerd burgers"; recipe.Description = "The nerdy burger is perfect for NerdDinner(s)"; recipe.Ingredients.Add(new Ingredient { Name = "Burger", Amount = "4" }); recipe.Ingredients.Add(new Ingredient { Name = "Ners", Amount = "4" }); Recipes.Add(recipe); recipe = new Recipe(); recipe.Name = "Potato soup"; recipe.Description = "Peel the potatoes. Fry the leek and onion for a short while and add water and potatoes. Boil the potatoes... etc."; recipe.Ingredients.Add(new Ingredient { Name = "Potatoes", Amount = "12" }); recipe.Ingredients.Add(new Ingredient { Name = "Water", Amount = "0.6 litres" }); recipe.Ingredients.Add(new Ingredient { Name = "Bouillon cubes (meat)", Amount = "2" }); recipe.Ingredients.Add(new Ingredient { Name = "Onion", Amount = "1" }); recipe.Ingredients.Add(new Ingredient { Name = "Leek", Amount = "0.5" }); recipe.Ingredients.Add(new Ingredient { Name = "Creme fraiche", Amount = "1 dl" }); Recipes.Add(recipe); }
public int Add(string title, string preparation, int categoryId, string userId, IEnumerable<string> ingradients, IEnumerable<HttpPostedFileBase> images, string tags) { var recipeImages = this.HttpFileToRecipeImage(images); var recipeTags = tags.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries) .Select(t => new Tag() { Text = t }).ToList(); var newRecipe = new Recipe() { Title = title, Preparation = preparation, Ingredients = ingradients.Select(i => new Ingredient() { Text = i }).ToList(), Images = recipeImages, Tags = recipeTags, UserId = userId, CategoryId = categoryId }; newRecipe.Tags.Add(new Tag() { Text = GlobalConstants.DefaultTagName }); this.recipes.Add(newRecipe); this.recipes.SaveChanges(); return newRecipe.Id; }
public virtual void DoTransmute(Mobile from, Recipe r) { if(UsesRemaining > 0) { UsesRemaining--; } }
/// <summary> /// Adds ingredients from recipe to shoppinglist and recipe to foodplan. /// </summary> /// <param name="recipe">Recipe to add</param> /// <param name="date">Date the recipe shall be added to the foodplan</param> public async void Add(Recipe recipe, DateTime date) { if (recipe?.Ingredients?.Count > 0) { if (_foodPlan.RecipeList != null) foreach (var rec in _foodPlan.RecipeList) { if (rec.Item2.Date == date.Date) { _msgBoxService.ShowError("Opskrift eksisterer allerede på dato"); return; } } foreach (var ingredient in recipe.Ingredients) { try { _shoppingListModel.AddItem(new Item() {Name = ingredient.Name}); } catch (Exception e) { Log.File.Exception(e); throw; } } } _foodplanCollector.AddRecipeTupleToFoodplan(_loginModel.FoodplanId, new Tuple<Recipe, DateTime>(recipe, date)); await Update(); }
partial void Merge(Recipe entity, RecipeDTO dto, object state) { if (state == null) { throw new ArgumentNullException("state", "Precondition: state is IResponse"); } var response = state as IResponse; if (response == null) { throw new ArgumentException("Precondition: state is IResponse", "state"); } entity.Culture = response.Culture; entity.RecipeId = dto.Id; entity.OutputItemId = dto.OutputItemId; entity.OutputItemCount = dto.OutputItemCount; entity.MinimumRating = dto.MinRating; entity.TimeToCraft = TimeSpan.FromMilliseconds(dto.TimeToCraftMs); if (dto.Disciplines != null) { entity.CraftingDisciplines = this.craftingDisciplineCollectionConverter.Convert(dto.Disciplines, dto); } if (dto.Flags != null) { entity.Flags = this.recipeFlagCollectionConverter.Convert(dto.Flags, dto); } if (dto.Ingredients != null) { entity.Ingredients = this.ingredientsCollectionConverter.Convert(dto.Ingredients, dto); } }
private void MigrateRecipe(object sender, RoutedEventArgs e) { // zrobić sprawdzenie czy przepis o podanej nazwie już ustnieje w bazie danych + nazwy składników!!! if (ForeignDbListViev.SelectedItems.Count == 1 && ContainsRecipe(MainColection.ListOfRecipes, (Recipe)ForeignDbListViev.SelectedItems[0]))//!MainColection.ListOfRecipes.Contains((Recipe)ForeignDbListViev.SelectedItems[0]))//tutaj mam źle { Recipe tempRecipe = new Recipe(); tempRecipe = (Recipe)ForeignDbListViev.SelectedItem; MainColection.ListOfRecipes.Add(tempRecipe); List<Component> componentsMigrating = new List<Component>(); componentsMigrating.AddRange(ForeignColection.GetComponentList(tempRecipe));//get all components of chosen foreing recipe; MainDB.InsertData(string.Format("INSERT INTO RecipiesTable (Name,Recipe,Persons,Type)VALUES('{0}','{1}','{2}','{3}')", tempRecipe.Name, tempRecipe.RecipeTxt, tempRecipe.Persons, tempRecipe.TypeOfDish));//Insert chosen recipe into MainDB Recipe containerRecipe = new Recipe(MainDB.GetData( string.Format("SELECT Id,Name,Recipe,Persons,Type FROM RecipiesTable WHERE Name='{0}'", tempRecipe.Name)).Tables[0].Rows[0]);// Get inserted new id(for set relations in different table) and other fields of Recipe for (int i = 0; i < componentsMigrating.Count; ++i) { if (ContainsComponent(MainColection.ListOfComponents, componentsMigrating[i])) //if (!MainColection.ListOfComponents.Contains(componentsMigrating[i]))//Tutaj mam źle { MainDB.InsertData(string.Format("INSERT INTO ResourcesTable (Resource,Value)VALUES ('{0}','{1}')", componentsMigrating[i].Name, componentsMigrating[i].Value.Replace(".", ",")));// Insert Components into mainDB } // if doesn't exit in mainDB } List<int> compIds = new List<int>(); for (int i = 0; i < componentsMigrating.Count; ++i) { compIds.Add(Convert.ToInt32(MainDB.GetData(string.Format("SELECT Idres FROM ResourcesTable WHERE Resource='{0}'", componentsMigrating[i].Name)).Tables[0].Rows[0].ItemArray[0]));// get ids of components from mainDb } for (int i = 0; i < componentsMigrating.Count; ++i) { MainDB.InsertData(string.Format("INSERT INTO RelationsTable (ComponentId,RecipeId,Amount)VALUES('{0}','{1}','{2}')", compIds[i], containerRecipe.Id, "1"));// Set relations in mainDb } MainDbListViev.ItemsSource = null; MainDbListViev.ItemsSource = MainColection.ListOfRecipes; //pomyśleć jak to skrócić | zredukować operacje na bazie. Ale bałagan } else { MessageBox.Show("przepis już istnieje"); } }
public RecipeIndividualSteps(RecipeOverview parentPage, Recipe rec) { InitializeComponent(); canvAchievement.Visibility = Visibility.Hidden; canvAchievement.Opacity = 0; overview = parentPage; aRecipe = rec; userDb = Database.getInstance(); mainUser = userDb.userList[0]; // load first step stepIndex = 0; lastStep = aRecipe.Steps.Count() - 1; txtBlkStep.Text = aRecipe.Steps[stepIndex]; progBar.Maximum = lastStep; lblProg.Content = "Steps " + (progBar.Value + 1) + "/" + (lastStep +1); // load picture if exists if (aRecipe.StepPictures.Count == lastStep + 1) imgStep.Source = ImageLoader.ToWPFImage(aRecipe.StepPictures[stepIndex]); else imgStep.Source = ImageLoader.ToWPFImage(HCI_Cooking.Properties.Resources.placeholder_2); //load the only achievment on this page imgAchievement.Source = ImageLoader.ToWPFImage(new Bitmap(HCI_Cooking.Properties.Resources.mango_cake)); lblAchievementContent.Content = "First Mango Pudding!"; }
public ucSearchResult(Recipe recipe) : this() { Recipe = recipe; hlRecipeName.Text = recipe.Name; SetDescription(PrepareShortDescription(recipe)); IsOpened = false; }
public CookingLessonTemplate(RecipeSelectionMenu page, Recipe rec) { selectMenu = page; aRecipe = rec; InitializeComponent(); lblRecipeTitle.Content = rec.Title; imgVidPlaceholder.Source = ImageLoader.ToWPFImage(HCI_Cooking.Properties.Resources.video_placeholder); }
public override FoodMenuInteractionDefinition<Fridge, Fridge_Have> Create(string menuText, Recipe recipe, string[] menuPath, GameObject objectClickedOn, Recipe.MealDestination destination, Recipe.MealQuantity quantity, Recipe.MealRepetition repetition, bool bWasHaveSomething, int cost) { if (cost > 0) { cost = -2147483648; } return new Definition(menuText, recipe, menuPath, objectClickedOn, destination, quantity, repetition, bWasHaveSomething, cost); }
bool AllowPotion(Recipe newRecipe) { foreach(Recipe r in GeneratedRecipes) { if (r.CheckPotion(newRecipe.requiredIngredients) || r.potionName.Equals(newRecipe.potionName)) return false; } return true; }
//lägger till ett recept public Recipe AddRecipe(string name, List<List<object>> ingredients) { if (!Regex.IsMatch(name, @"^[a-zA-Z ]+$")) { errorMessage = "Var god fyll i ett receptnamn (endast bokstäver)"; throw new ArgumentException(); } if (!ingredients.Any()) { errorMessage = "Var god lägg till minst 1 ingrediens"; throw new ArgumentException(); } try { CreateMissingIngredients(ingredients); } catch (InvalidOperationException) { //felmedelandet = stack trace från createMissingIngredients(); throw new ArgumentException(); } Recipe newRecipe = new Recipe { recipeName = name }; thDb.Recipe.Add(newRecipe); try { thDb.SaveChanges(); } catch (DbUpdateException) { errorMessage = "Recept finns redan i databas, välj ett annat namn"; thDb.Recipe.Remove(newRecipe); throw new ArgumentException(); } foreach (List<object> l in ingredients) { IngredientRecipe iR = new IngredientRecipe { recipeName = name, ingredientName = (l[0] as string).ToLower(), amount = (int)l[1], unit = l[2] as string }; try { thDb.IngredientRecipe.Add(iR); thDb.SaveChanges(); } catch(DbUpdateException) { errorMessage = "Var god gruppera ingredienserna"; thDb.IngredientRecipe.Remove(iR); thDb.Recipe.Remove(newRecipe); thDb.SaveChanges(); throw new ArgumentException(); } } return newRecipe; }
// Use this for initialization void Start() { recipeCard = GetComponentInParent<HomeRecipeCard>(); recipe = recipeCard.recipe; itemImage = transform.GetChild(0).GetComponent<Image>(); itemAmount = transform.GetChild(1).GetComponent<Text>(); itemImage.sprite = recipe.recipeIngredients[slotNumber].itemIcon; itemQuantity = recipe.recipeIngredientQuantity[slotNumber]; itemAmount.text = itemQuantity.ToString(); }
public void SaveRecipe(Recipe recipe){ using (var db = GetConnection()) { if(recipe.Id <= 0) { int id = db.Insert(recipe); recipe.Id = id; } else { db.Update(recipe); } } }
public Product(double price, double fruitValue, string name, JamType jamType, JamVariant jamVariant, double weight, Recipe recipe) { this.price = price; this.fruitValue = fruitValue; this.name = name; this.jamType = jamType; this.jamVariant = jamVariant; this.weight = weight; this.recipe = recipe; }
public CommandProperty(string parameters, Recipe recipe) : base(parameters, recipe) { Match match = pattern.Match(parameters); if (!match.Success) throw new ArgumentException( $"Failed to initialise command {CommandName} with parameters {parameters.Trim()}!"); Property = PropertyCollection.GetProperty(match.Groups["name"].Value, match.Groups["value"].Value); if (Property == null) throw new ArgumentException($"Failed to initialise command {CommandName}'s property!"); Name = match.Groups["name"].Value; }
protected void BuildBonneMos() { Recipe r = new Recipe("bonnemos", "Bønnemos", @"Svits løg og chili. Hæl bønnerne i og mos det hele."); r.AddIngredient(400, "g", "Sorte bønner"); r.AddIngredient(2, "stk", "Løg"); r.AddIngredient(4, "stk", "Chili"); RecipeRepository.Add(r); BonneMosRecipe = r; }
public static void DoRecipe(Recipe recipe){ foreach(Plant ingredient in recipe.ingredients){ ingredient.productNumber--; ingredient.plantBtn.GetComponent<BtnPlant>().RefreshInventory(); } recipe.quantity++; UIManager.ShowRecipeDetails(); // UIManager.Instance.AdjustHunger(recipe.calories); }
public CastSpellAction(Recipe recipe, int repeat, RepeatCalculationType repeatType) : this() { Recipe = recipe; Repeat = new DynamicProperty<int>(this,repeat.ToString(CultureInfo.InvariantCulture)); Entry = recipe.ID; RepeatType = repeatType; //Properties["Recipe"].Show = true; Properties["SpellName"].Value = SpellName; Pb.UpdateMaterials(); }
void Init () { _recipe = _recipeManager.recipes[playerNum - 1]; for(int i = 0; i < _recipe.itemsRecipe.Count; i++) { ingredientsIcon[i].sprite = _recipe.itemsSprites[i]; } CalculateScore(); }
void CreateNewPanel(Recipe r){ //Transform location = GameObject.Find("PanelStartPosition").transform; //GameObject panel = (GameObject)Instantiate(recipePanel,new Vector3(location.position.x, location.position.y),location.rotation); //Text panelNameText = //panel.transform.Find ("PanelName").GetComponent<Text> ().text = r.recipeName; //panelNameText.text= r.recipeName; //RecipePanel rp = (RecipePanel) panel; //.Add (panel); }
protected void SaveRecipe(object sender, EventArgs e) { bool isFileExtensionSupported = false; string imagesPath = Server.MapPath("~/Recipes/Images/"); if (ImageUpload.HasFile) { string fileExtension = System.IO.Path.GetExtension(ImageUpload.FileName).ToLower(); string[] supportedExtensions = { ".gif", ".png", ".jpeg", ".jpg" }; isFileExtensionSupported = supportedExtensions.Contains(fileExtension); } if (isFileExtensionSupported) { try { var physicalImageUrl = imagesPath + ImageUpload.FileName; // Save to Images folder. ImageUpload.PostedFile.SaveAs(physicalImageUrl); // Save to Images/Thumbs folder. //ImageUpload.PostedFile.SaveAs(imagesPath + "Thumbs/" + ImageUpload.FileName); var imageTitle = System.IO.Path.GetFileNameWithoutExtension(ImageUpload.FileName); var imageUrl = System.IO.Path.GetFileName(ImageUpload.FileName); var image = new BonApetit.Models.Image() { Title = imageTitle, AltText = imageTitle, Caption = imageTitle, CreatedDate = DateTime.Now, ImageUrl = imageUrl }; List <Ingredient> ingredients = this.Ingredients.GetAllValues().Select(s => (Ingredient)s).ToList(); List <Category> categories = new List <Category>(); foreach (var index in this.CategoriesList.GetSelectedIndices()) { var categoryId = new Guid(this.CategoriesList.Items[index].Value); var category = db.GetCategory(categoryId); categories.Add(category); } var recipe = new Recipe(this.Name.Text) { Description = HttpUtility.HtmlDecode(this.Description.Text), PrepareInstructions = HttpUtility.HtmlDecode(this.PreparationInstructions.Text), Image = image, Ingredients = ingredients, Categories = categories }; db.AddRecipe(recipe); db.SaveChanges(); Response.Redirect("~/Recipes/RecipeDetails?recipeId=" + recipe.Id); } catch (Exception ex) { FailureText.Text = ex.Message; } } else { FailureText.Text = "Unsupported file type."; } }
public void PutRecipe(Recipe recipe) { _context.Entry(recipe).State = EntityState.Modified; _context.SaveChanges(); _context.Entry(recipe).State = EntityState.Detached; }
public void DeleteRecipe(Recipe recipe) { _context.Recipes.Remove(recipe); _context.SaveChanges(); }
public void RecipeRW() { Recipe recipe = new Recipe() { SourceAet = "SOURCE_AET", PatientId = "", PatientFullName = "", PatientBirthDate = "", CurrentSeriesDicomFolder = "D:/temp/current/", CurrentAccession = "ABC123", CurrentSeriesCriteria = new List <SeriesSelectionCriteria>(), PriorSeriesDicomFolder = "D:/temp/prior/", PriorAccession = "ABC122", PriorSeriesCriteria = new List <SeriesSelectionCriteria>(), ExtractBrain = true, RegisterTo = Recipe.RegisterToOption.PRIOR, BiasFieldCorrection = false, CompareSettings = new CompareSettings() { BackgroundThreshold = 10, MinRelevantStd = -1, MaxRelevantStd = 5, MinChange = 0.8f, MaxChange = 5, CompareDecrease = false, CompareIncrease = true, GenerateHistogram = true }, OutputSettings = new OutputSettings() { ResultsDicomSeriesDescription = "VT Results", ReslicedDicomSeriesDescription = "Resliced", FilesystemDestinations = new List <string>(), OnlyCopyResults = false, DicomDestinations = new List <string>(), } }; recipe.CurrentSeriesCriteria.Add(new SeriesSelectionCriteria()); recipe.OutputSettings.DicomDestinations.Add("The CLOUD!"); var recipestring = JsonConvert.SerializeObject(recipe, Formatting.Indented); var recipe2 = JsonConvert.DeserializeObject <Recipe>(recipestring); Assert.IsTrue(recipe2.SourceAet.Equals("SOURCE_AET")); Assert.IsTrue(recipe2.PatientId.Equals("")); Assert.IsTrue(recipe2.PatientFullName.Equals("")); Assert.IsTrue(recipe2.PatientBirthDate.Equals("")); Assert.IsTrue(recipe2.CurrentSeriesDicomFolder.Equals("D:/temp/current/")); Assert.IsTrue(recipe2.CurrentAccession.Equals("ABC123")); Assert.IsTrue(recipe2.CurrentSeriesCriteria.Count == 1); Assert.IsTrue(recipe2.PriorSeriesDicomFolder.Equals("D:/temp/prior/")); Assert.IsTrue(recipe2.PriorAccession.Equals("ABC122")); Assert.IsTrue(recipe2.PriorSeriesCriteria.Count == 0); Assert.IsTrue(recipe2.ExtractBrain); Assert.IsTrue(recipe2.RegisterTo == Recipe.RegisterToOption.PRIOR); Assert.IsFalse(recipe2.BiasFieldCorrection); Assert.IsTrue(recipe2.CompareSettings.BackgroundThreshold == 10); Assert.IsTrue(recipe2.CompareSettings.MinRelevantStd == -1); Assert.IsTrue(recipe2.CompareSettings.MaxRelevantStd == 5); Assert.IsTrue(recipe2.CompareSettings.MinChange == 0.8f); Assert.IsTrue(recipe2.CompareSettings.MaxChange == 5); Assert.IsFalse(recipe2.CompareSettings.CompareDecrease); Assert.IsTrue(recipe2.CompareSettings.CompareIncrease); Assert.IsTrue(recipe2.CompareSettings.GenerateHistogram); Assert.IsTrue(recipe2.OutputSettings.ResultsDicomSeriesDescription.Equals("VT Results")); Assert.IsTrue(recipe2.OutputSettings.ReslicedDicomSeriesDescription.Equals("Resliced")); Assert.IsTrue(recipe2.OutputSettings.FilesystemDestinations.Count == 0); Assert.IsFalse(recipe2.OutputSettings.OnlyCopyResults); Assert.IsTrue(recipe2.OutputSettings.DicomDestinations[0].Equals("The CLOUD!")); File.WriteAllText("D:/recipe.json", recipestring); //Assert.IsTrue(recipe.CurrentAccession.Equals("ABC123")); }
public int AddRecipe(Recipe recipe) { return(mock.Object.AddRecipe(recipe)); }
public void TestCost() { var workspace = PrepareMenu("c:\\sd1.txt"); var iskender = workspace.Single <MenuItem>(x => x.Name.ToLower().Contains("iskender")); iskender.Portions[0].MenuItemId = iskender.Id; Assert.IsTrue(workspace.All <MenuItem>().Count() > 0); Assert.IsNotNull(iskender); Assert.IsTrue(iskender.Portions.Count == 1); var donerEti = new InventoryItem { Name = "Döner Eti", BaseUnit = "GR", GroupCode = "", TransactionUnit = "KG", TransactionUnitMultiplier = 1000 }; var yogurt = new InventoryItem { Name = "Yoğurt", BaseUnit = "GR", GroupCode = "", TransactionUnit = "KG", TransactionUnitMultiplier = 1000 }; var pide = new InventoryItem { Name = "Pide", BaseUnit = "Yarım", GroupCode = "", TransactionUnit = "Adet", TransactionUnitMultiplier = 2 }; var zeytinYagi = new InventoryItem { Name = "Zeytin Yağı", BaseUnit = "Ölçü", GroupCode = "", TransactionUnit = "Litre", TransactionUnitMultiplier = 100 }; workspace.Add(donerEti); workspace.Add(yogurt); workspace.Add(pide); workspace.Add(zeytinYagi); var rp = new Recipe { Name = "İskender Reçetesi", Portion = iskender.Portions[0] }; workspace.Add(rp); rp.RecipeItems.Add(new RecipeItem { InventoryItem = donerEti, Quantity = 120 }); rp.RecipeItems.Add(new RecipeItem { InventoryItem = yogurt, Quantity = 50 }); rp.RecipeItems.Add(new RecipeItem { InventoryItem = pide, Quantity = 2 }); rp.RecipeItems.Add(new RecipeItem { InventoryItem = zeytinYagi, Quantity = 1 }); AppServices.MainDataContext.StartWorkPeriod("", 0, 0, 0); var transaction = new Transaction { Date = DateTime.Now, Name = "1" }; workspace.Add(transaction); transaction.TransactionItems.Add(new TransactionItem { InventoryItem = donerEti, Multiplier = 1000, Price = 16, Quantity = 10, Unit = "KG" }); transaction.TransactionItems.Add(new TransactionItem { InventoryItem = pide, Multiplier = 2, Price = 1, Quantity = 50, Unit = "Adet" }); transaction.TransactionItems.Add(new TransactionItem { InventoryItem = yogurt, Multiplier = 1000, Price = 4, Quantity = 30, Unit = "KG" }); transaction.TransactionItems.Add(new TransactionItem { InventoryItem = zeytinYagi, Multiplier = 100, Price = 5, Quantity = 5, Unit = "Litre" }); var ticket = new Ticket(); workspace.Add(ticket); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); var pc = InventoryService.GetCurrentPeriodicConsumption(workspace); workspace.Add(pc); var iskenderCostItem = pc.CostItems.Single(x => x.Portion.MenuItemId == iskender.Id); Assert.AreEqual(iskenderCostItem.Quantity, 3); var etCost = ((16m / 1000m) * 120m); var pideCost = ((1m / 2m) * 2m); var yogurtCost = ((4m / 1000m) * 50m); var zeytinYagiCost = ((5m / 100m) * 1m); var iskenderCost = decimal.Round(etCost + pideCost + yogurtCost + zeytinYagiCost, 2); Assert.AreEqual(iskenderCost, iskenderCostItem.CostPrediction); var etpc = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == donerEti.Id); var pidepc = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == pide.Id); var yogurtpc = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == yogurt.Id); var zeytinYagipc = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == zeytinYagi.Id); etpc.PhysicalInventory = 9.5m; yogurtpc.PhysicalInventory = 28; zeytinYagipc.PhysicalInventory = 4.5m; InventoryService.CalculateCost(pc, AppServices.MainDataContext.CurrentWorkPeriod); etCost = (etpc.GetConsumption() * etCost) / etpc.GetPredictedConsumption(); pideCost = (pidepc.GetConsumption() * pideCost) / pidepc.GetPredictedConsumption(); yogurtCost = (yogurtpc.GetConsumption() * yogurtCost) / yogurtpc.GetPredictedConsumption(); zeytinYagiCost = (zeytinYagipc.GetConsumption() * zeytinYagiCost) / zeytinYagipc.GetPredictedConsumption(); Assert.AreEqual(iskenderCostItem.Cost, decimal.Round(etCost + pideCost + yogurtCost + zeytinYagiCost, 2)); }
/// <summary> /// Searches for a recipe that matches the search criteria exactly, then returns it. That means the recipe will have exactly the same ingredients, tiles, liquid requirements, recipe groups, and result; even the stack sizes will match. If no recipe with an exact match is found, this will return null. /// </summary> /// <returns>The recipe found matching the finder's criteria.</returns> public Recipe FindExactRecipe() { for (int k = 0; k < Recipe.numRecipes; k++) { Recipe recipe = Main.recipe[k]; bool matches = true; List <Item> checkItems = new List <Item>(items); for (int i = 0; i < Recipe.maxRequirements; i++) { Item item = recipe.requiredItem[i]; if (item.type == 0) { break; } bool itemMatched = false; for (int j = 0; j < checkItems.Count; j++) { if (item.type == checkItems[j].type && item.stack == checkItems[j].stack) { itemMatched = true; checkItems.RemoveAt(j); break; } } if (!itemMatched) { matches = false; break; } } if (checkItems.Count > 0) { matches = false; } List <int> checkGroups = new List <int>(groups); List <int> acceptedGroups = GetAcceptedGroups(recipe); for (int i = 0; i < acceptedGroups.Count; i++) { int group = acceptedGroups[i]; bool groupMatched = false; for (int j = 0; j < checkGroups.Count; j++) { if (group == checkGroups[j]) { groupMatched = true; checkGroups.RemoveAt(j); break; } } if (!groupMatched) { matches = false; break; } } if (checkGroups.Count > 0) { matches = false; } if (result.type != recipe.createItem.type || result.stack != recipe.createItem.stack) { matches = false; } List <int> checkTiles = new List <int>(tiles); for (int i = 0; i < Recipe.maxRequirements; i++) { int tile = recipe.requiredTile[i]; if (tile == -1) { break; } bool tileMatched = false; for (int j = 0; j < checkTiles.Count; j++) { if (tile == checkTiles[j]) { tileMatched = true; checkTiles.RemoveAt(j); break; } } if (!tileMatched) { matches = false; break; } } if (checkTiles.Count > 0) { matches = false; } if (needWater != recipe.needWater) { matches = false; } else if (needLava != recipe.needLava) { matches = false; } else if (needHoney != recipe.needHoney) { matches = false; } if (matches) { return(recipe); } } return(null); }
private void OnClick_Craft(object sender, RoutedEventArgs e) { Recipe recipe = ((FrameworkElement)sender).DataContext as Recipe; _gameSession.CraftItemUsing(recipe); }
public int CreateNewRecipe(RecipeVM recipe) { try { var entity = new Recipe(); entity.CategoryId = recipe.CategoryId; entity.Name = recipe.Name; entity.DescriptionPrimary = recipe.DescriptionPrimary; entity.DescriptionSecondary = recipe.DescriptionSecondary; entity.Ingredients = new List <Ingredient>(); for (int i = 0; i < recipe.Ingredients.Count; i++) { var currentIngredient = recipe.Ingredients[i]; if (!string.IsNullOrEmpty(currentIngredient.Name)) { var ingredient = new Ingredient(); _mapper.Map(currentIngredient, ingredient); ingredient.PositionNo = i + 1; entity.Ingredients.Add(ingredient); } } entity.MethodItems = new List <MethodItem>(); for (int i = 0; i < recipe.MethodItems.Count; i++) { var currentMethodItem = recipe.MethodItems[i]; if (!string.IsNullOrEmpty(currentMethodItem.Text)) { var methodItem = new MethodItem(); _mapper.Map(currentMethodItem, methodItem); methodItem.StepNo = i + 1; entity.MethodItems.Add(methodItem); } } // trim file to convert to base64 if (!string.IsNullOrEmpty(recipe.ImageFile)) { var base64 = recipe.ImageFile.Substring(recipe.ImageFile.LastIndexOf(',') + 1); byte[] imageBytes = Convert.FromBase64String(base64); using (var stream = new MemoryStream(imageBytes)) { IFormFile file = new FormFile(stream, 0, imageBytes.Length, "", ""); var fileNameTask = _azureBlobService.UploadSingleAsync(file, imageContainerName); entity.ImageUrl = fileNameTask.Result; } } //add image // will be receiving a base64 byte array from front end //var file = recipe.Image; //_azureBlobService.UploadSingleAsync() _db.Recipes.Add(entity); _db.SaveChanges(); return(entity.RecipeId); } catch (Exception e) { var xx = e; return(0); } }
public int EditRecipe(RecipeVM recipe) { var entity = _db.Recipes .Include(r => r.Category) .FirstOrDefault(rcp => rcp.RecipeId == recipe.RecipeId); // edit existing entity if (entity == null) { entity = new Recipe(); } //_db.Recipes.Update(entity); //REMOVE existing values from lists var recipeIngredients = _db.Ingredients.Where(i => i.RecipeId == entity.RecipeId).ToList(); _db.Ingredients.RemoveRange(recipeIngredients); var methodItems = _db.MethodItems.Where(i => i.RecipeId == entity.RecipeId).ToList(); _db.MethodItems.RemoveRange(methodItems); //foreach (var ingredient in entity.Ingredients.ToList()) //{ // _db.Ingredients.Remove(ingredient); //} //foreach (var methodItem in entity.MethodItems.ToList()) //{ // _db.MethodItems.Remove(methodItem); //} _db.SaveChanges(); _mapper.Map(recipe, entity); entity.Category = _db.Categories.FirstOrDefault(c => c.CategoryId == recipe.CategoryId); entity.CategoryId = recipe.CategoryId; entity.Ingredients = new List <Ingredient>(); entity.MethodItems = new List <MethodItem>(); for (int i = 0; i < recipe.Ingredients.ToList().Count; i++) { var currentIngredient = recipe.Ingredients[i]; if (!string.IsNullOrEmpty(currentIngredient.Name)) { var ingredient = new Ingredient(); ingredient.Name = currentIngredient.Name; ingredient.Measure = currentIngredient.Measure; ingredient.Quantity = currentIngredient.Quantity; ingredient.PositionNo = i + 1; ingredient.RecipeId = entity.RecipeId; ingredient.Seperator = currentIngredient.Seperator; _db.Ingredients.Add(ingredient); } } for (int i = 0; i < recipe.MethodItems.Count; i++) { var currentMethodItem = recipe.MethodItems[i]; if (!string.IsNullOrEmpty(currentMethodItem.Text)) { var methodItem = new MethodItem(); methodItem.Text = currentMethodItem.Text; methodItem.StepNo = i + 1; methodItem.RecipeId = entity.RecipeId; methodItem.Seperator = currentMethodItem.Seperator; _db.MethodItems.Add(methodItem); } } // remove the existing image file from Azure if (entity.ImageUrl != null) { _azureBlobService.DeleteByNameAsync(entity.ImageUrl, imageContainerName); } // trim file to convert to base64 if (!string.IsNullOrEmpty(recipe.ImageFile)) { var base64 = recipe.ImageFile.Substring(recipe.ImageFile.LastIndexOf(',') + 1); byte[] imageBytes = Convert.FromBase64String(base64); using (var stream = new MemoryStream(imageBytes)) { IFormFile file = new FormFile(stream, 0, imageBytes.Length, "", ""); var fileNameTask = _azureBlobService.UploadSingleAsync(file, imageContainerName); entity.ImageUrl = fileNameTask.Result; } } //_db.Recipes.Update(entity); _db.SaveChanges(); return(entity.RecipeId); }
public void SmokeTest() { var aorig = new Matrix(new double[, ] { { 100.0, 15.0, 0.01 }, { 15.0, 2.3, 0.01 }, { 0.01, 0.01, 1.0 } }); // Copy the matrix var a = new Matrix(aorig.Rows, aorig.Columns); for (var i = 0; i < a.Rows; ++i) { for (var j = 0; j < a.Columns; ++j) { a[i, j] = aorig[i, j]; } } // Decompose. var p = new Vector(aorig.Columns); Recipe.choldc(a, p.Length, p); // Original matrix var chol = new Matrix(a.Rows, a.Columns); for (var i = 0; i < a.Rows; ++i) { for (var j = 0; j < a.Columns; ++j) { if (i > j) { chol[i, j] = a[i, j]; } else { chol[i, j] = i == j ? p[i] : 0.0; } } } // Product of Cholesky factors var atest = new Matrix(chol.Rows, chol.Columns); for (var i = 0; i < chol.Rows; ++i) { for (var j = 0; j < chol.Columns; ++j) { var sum = 0.0; for (var k = 0; k < chol.Columns; ++k) { sum += chol[i, k] * chol[j, k]; } atest[i, j] = sum; } } // Check solution vector var b = new Vector(new double[] { 0.4, 0.02, 99.0 }); var x = new Vector(b.Length); Recipe.cholsl(a, a.Rows, p, b, x); for (var i = 0; i < aorig.Rows; ++i) { var sum = 0.0; for (var j = 0; j < aorig.Columns; ++j) { sum += aorig[i, j] * x[j]; } p[i] = sum; Assert.AreEqual(p[i], b[i], 0.00001); } }
public void CreateRecipe(CreateRecipeRequest request, User user) { if (request == null) { throw new ActionFailedException("invalid request body"); } if (string.IsNullOrWhiteSpace(request.Title)) { throw new ActionFailedException("title cannot be empty"); } if (string.IsNullOrWhiteSpace(request.Text)) { throw new ActionFailedException("title cannot be empty"); } request.Title = request.Title.Trim(); request.Text = request.Text.Trim(); if (request.Title.Length < 4) { throw new ActionFailedException("title is too short"); } if (request.Text.Length < 6) { throw new ActionFailedException("recipe details is too short"); } if (request.Portion <= 0) { throw new ActionFailedException("portion cannot be smaller than 1"); } if (request.Portion > 200) { throw new ActionFailedException("portion is too large"); } if (request.PrepareTime <= 0) { throw new ActionFailedException("prepare time cannot be smaller than 1"); } if (request.PrepareTime > 600) { throw new ActionFailedException("prepare time is too large"); } if (request.Ingredients == null) { request.Ingredients = new string[0]; } if (request.Steps == null) { request.Steps = new string[0]; } foreach (var item in request.Steps) { if (string.IsNullOrWhiteSpace(item)) { throw new ActionFailedException("step items cannot be empty"); } } if (request.Photos == null) { request.Photos = new List <string>(); } if (request.Tags == null) { request.Tags = new string[0]; } //if (request.Photos.Count == 0) // throw new ActionFailedException("Select at least one image"); Recipe recipe = new Recipe(); recipe.Id = 0; recipe.Title = request.Title; recipe.Text = request.Text; recipe.Ingredients = JsonConvert.SerializeObject(request.Ingredients); recipe.Steps = JsonConvert.SerializeObject(request.Steps); recipe.CreatedTime = DateTime.Now; recipe.ModifiedTime = DateTime.Now; recipe.Portion = request.Portion; recipe.PrepareTime = request.PrepareTime; recipe.User = user; recipe.Photos = JsonConvert.SerializeObject(request.Photos); recipe.RecipeTags = new List <RecipeTag>(); recipeContext.Recipes.Add(recipe); recipeContext.SaveChanges(); foreach (var item in request.Tags) { if (string.IsNullOrWhiteSpace(item)) { throw new ActionFailedException("tags cannot be empty"); } var tagText = item.ToLower(); Tag tag = recipeContext.Tags.FirstOrDefault(x => x.Text == tagText); if (tag == null) { tag = new Tag(); tag.Text = tagText; recipeContext.Tags.Add(tag); recipeContext.SaveChanges(); } recipe.RecipeTags.Add(new RecipeTag { Recipe = recipe, Tag = tag, RecipeId = recipe.Id, TagId = tag.Id }); } recipeContext.SaveChanges(); }
protected void Page_Load(object sender, EventArgs e) { string userName = User.Identity.Name; if (userName == "") { userName = "******"; } Session.Add("userName", userName); try { // Preload reg recipe list database to be displayed on grid view RecipeWS.RecipeWebService ws = new RecipeWS.RecipeWebService(); RecipeWS.WSRecipe[] wsList = ws.GetWebServiceRecipes(); int count = wsList.Length; for (int i = 0; i < count; i++) { Recipe recipe = new Recipe(); recipe.RecipeName = wsList[i].RecipeName; recipe.RecipeIngredients = wsList[i].RecipeIngredients; recipe.RecipeInstructions = wsList[i].RecipeInstructions; recipe.RecipeSize = wsList[i].RecipeSize; recipe.RecipeImage = wsList[i].RecipeImage; list.Add(recipe); } } catch { Debug.WriteLine("Unable to load data from Service1Client!"); Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('Error! Unable to retrieve recipe list from host!');</script>"); } RecipeMgr recipeMgr = new RecipeMgr(); RecipeLists loadData = new RecipeLists(); // Create the recipe list database with preloaded recipes recipeMgr.storeRecipes(list); // Try to retrieve bool recipeAdded variable if available try { recipeAdded = (bool)(Session["recipeAdded"]); } catch (Exception ex) { Debug.Write(ex.StackTrace); Debug.WriteLine("Form loaded with no recipeAdded variable available."); } // Try to retrieve recipeDeleted bool variable if available try { recipeDeleted = (bool)(Session["recipeDeleted"]); } catch (Exception ex) { Debug.Write(ex.StackTrace); Debug.WriteLine("Form loaded with no recipeDeleted variable available."); } // Display success message if recipe successfully added to list from AddRecipeForm // Change the session bool variables back to false if (recipeAdded) { Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('Success! Recipe Added to List!');</script>"); Session["recipeAdded"] = false; } else if (recipeDeleted) { Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('Recipe successfully deleted from list!');</script>"); Session["recipeDeleted"] = false; } }
private void AddInRecipe(Recipe recipe) { InRecipes.Add(recipe); }
public void TestPurchase() { var workspace = PrepareMenu("c:\\sd2.txt"); var iskender = workspace.Single <MenuItem>(x => x.Name.ToLower().Contains("iskender")); iskender.Portions[0].MenuItemId = iskender.Id; Assert.IsTrue(workspace.All <MenuItem>().Count() > 0); Assert.IsNotNull(iskender); Assert.IsTrue(iskender.Portions.Count == 1); var donerEti = new InventoryItem { Name = "Döner Eti", BaseUnit = "GR", GroupCode = "", TransactionUnit = "KG", TransactionUnitMultiplier = 1000 }; var yogurt = new InventoryItem { Name = "Yoğurt", BaseUnit = "GR", GroupCode = "", TransactionUnit = "KG", TransactionUnitMultiplier = 1000 }; var pide = new InventoryItem { Name = "Pide", BaseUnit = "Yarım", GroupCode = "", TransactionUnit = "Adet", TransactionUnitMultiplier = 2 }; workspace.Add(donerEti); workspace.Add(yogurt); workspace.Add(pide); var rp = new Recipe { Name = "İskender Reçetesi", Portion = iskender.Portions[0] }; workspace.Add(rp); rp.RecipeItems.Add(new RecipeItem { InventoryItem = donerEti, Quantity = 120 }); rp.RecipeItems.Add(new RecipeItem { InventoryItem = yogurt, Quantity = 50 }); rp.RecipeItems.Add(new RecipeItem { InventoryItem = pide, Quantity = 2 }); AppServices.MainDataContext.StartWorkPeriod("", 0, 0, 0); var transaction = new Transaction { Date = DateTime.Now, Name = "1" }; workspace.Add(transaction); transaction.TransactionItems.Add(new TransactionItem { InventoryItem = donerEti, Multiplier = 1000, Price = 16, Quantity = 10, Unit = "KG" }); transaction.TransactionItems.Add(new TransactionItem { InventoryItem = pide, Multiplier = 2, Price = 1, Quantity = 50, Unit = "Adet" }); transaction.TransactionItems.Add(new TransactionItem { InventoryItem = yogurt, Multiplier = 1000, Price = 4, Quantity = 30, Unit = "KG" }); var transactionTotal = transaction.TransactionItems.Sum(x => x.Price * x.Quantity); Assert.AreEqual(transactionTotal, (16 * 10) + (50 * 1) + (30 * 4)); var ticket = new Ticket(); workspace.Add(ticket); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); var transaction2 = new Transaction { Date = DateTime.Now, Name = "1" }; workspace.Add(transaction2); transaction2.TransactionItems.Add(new TransactionItem { InventoryItem = donerEti, Multiplier = 1000, Price = 15, Quantity = 10, Unit = "KG" }); var pc = InventoryService.GetCurrentPeriodicConsumption(workspace); workspace.Add(pc); var etpc = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == donerEti.Id); Assert.IsNotNull(etpc); Assert.AreEqual(etpc.InStock, 0); Assert.AreEqual(etpc.Purchase, 20); Assert.AreEqual(etpc.Consumption, 0.24m); Assert.AreEqual(etpc.Cost, 15.5m); var yogurtpc = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == yogurt.Id); Assert.IsNotNull(yogurtpc); Assert.AreEqual(yogurtpc.InStock, 0); Assert.AreEqual(yogurtpc.Purchase, 30); Assert.AreEqual(yogurtpc.Consumption, 0.1m); var pidepc = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == pide.Id); Assert.IsNotNull(pidepc); Assert.AreEqual(pidepc.InStock, 0); Assert.AreEqual(pidepc.Purchase, 50); Assert.AreEqual(pidepc.Consumption, 2); Assert.AreEqual(pc.CostItems.Count(), 1); AppServices.MainDataContext.StopWorkPeriod(""); Thread.Sleep(1); AppServices.MainDataContext.StartWorkPeriod("", 0, 0, 0); Thread.Sleep(1); transaction = new Transaction { Date = DateTime.Now, Name = "1" }; workspace.Add(transaction); const int etAlimMiktari = 50; var ti = new TransactionItem { InventoryItem = donerEti, Multiplier = 1000, Price = 12, Quantity = etAlimMiktari, Unit = "KG" }; transaction.TransactionItems.Add(ti); ticket = new Ticket(); workspace.Add(ticket); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); pc = InventoryService.GetCurrentPeriodicConsumption(workspace); workspace.Add(pc); var etpc2 = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == donerEti.Id); Assert.IsNotNull(etpc2); Assert.AreEqual(etpc2.InStock, etpc.GetInventoryPrediction()); Assert.AreEqual(etpc2.Purchase, etAlimMiktari); Assert.AreEqual(etpc2.GetInventoryPrediction(), etpc.GetInventoryPrediction() + etAlimMiktari - 0.24m); var cost = ((etpc.Cost * etpc.GetInventoryPrediction()) + (ti.Price * ti.Quantity)) / (etpc2.InStock + etpc2.Purchase); cost = decimal.Round(cost, 2); Assert.AreEqual(etpc2.Cost, cost); AppServices.MainDataContext.StopWorkPeriod(""); Thread.Sleep(1); AppServices.MainDataContext.StartWorkPeriod("", 0, 0, 0); Thread.Sleep(1); transaction = new Transaction { Date = DateTime.Now, Name = "1" }; workspace.Add(transaction); ti = new TransactionItem { InventoryItem = donerEti, Multiplier = 1000, Price = 10, Quantity = etAlimMiktari, Unit = "KG" }; transaction.TransactionItems.Add(ti); ticket = new Ticket(); workspace.Add(ticket); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); pc = InventoryService.GetCurrentPeriodicConsumption(workspace); workspace.Add(pc); var etpc3 = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == donerEti.Id); Assert.IsNotNull(etpc3); Assert.AreEqual(etpc3.InStock, etpc2.GetInventoryPrediction()); Assert.AreEqual(etpc3.Purchase, etAlimMiktari); Assert.AreEqual(etpc3.GetInventoryPrediction(), etpc2.GetInventoryPrediction() + etAlimMiktari - 0.24m); cost = ((etpc2.Cost * etpc2.GetInventoryPrediction()) + (ti.Price * ti.Quantity)) / (etpc3.InStock + etpc3.Purchase); cost = decimal.Round(cost, 2); Assert.AreEqual(etpc3.Cost, cost); }
/// <summary> /// Searches for all recipes that include the search criteria, then returns them in a list. In terms of ingredients, it will search for recipes that include all the search criteria ingredients, with stack sizes greater than or equal to the search criteria. It will also make sure the recipes include all search criteria recipe groups and tiles. If the search criteria includes a result, the recipes will also have the same result with a stack size greater than or equal to the search criteria. Finally, if needWater, needLava, or needHoney are set to true, the found recipes will also have them set to true. /// </summary> /// <returns>A list containing found recipes matching the finder's criteria.</returns> public List <Recipe> SearchRecipes() { List <Recipe> recipes = new List <Recipe>(); for (int k = 0; k < Recipe.numRecipes; k++) { Recipe recipe = Main.recipe[k]; bool matches = true; List <Item> checkItems = new List <Item>(items); for (int i = 0; i < Recipe.maxRequirements; i++) { Item item = recipe.requiredItem[i]; if (item.type == 0) { break; } for (int j = 0; j < checkItems.Count; j++) { if (item.type == checkItems[j].type && item.stack >= checkItems[j].stack) { checkItems.RemoveAt(j); break; } } } if (checkItems.Count > 0) { matches = false; } List <int> checkGroups = new List <int>(groups); List <int> acceptedGroups = GetAcceptedGroups(recipe); for (int i = 0; i < acceptedGroups.Count; i++) { int group = acceptedGroups[i]; for (int j = 0; j < checkGroups.Count; j++) { if (group == checkGroups[j]) { checkGroups.RemoveAt(j); break; } } } if (checkGroups.Count > 0) { matches = false; } if (result.type != 0) { if (result.type != recipe.createItem.type) { matches = false; } else if (result.stack > recipe.createItem.stack) { matches = false; } } List <int> checkTiles = new List <int>(tiles); for (int i = 0; i < Recipe.maxRequirements; i++) { int tile = recipe.requiredTile[i]; if (tile == -1) { break; } for (int j = 0; j < checkTiles.Count; j++) { if (tile == checkTiles[j]) { checkTiles.RemoveAt(j); break; } } } if (checkTiles.Count > 0) { matches = false; } if (needWater && !recipe.needWater) { matches = false; } else if (needLava && !recipe.needLava) { matches = false; } else if (needHoney && !recipe.needHoney) { matches = false; } if (matches) { recipes.Add(recipe); } } return(recipes); }
public int EditRecipe(Recipe recipe, int id) { return(mock.Object.EditRecipe(recipe, id)); }
public static void Main(string[] args) { Recipe r = new Recipe(); r.Run(args[0]); }
private void btnGetHtmlCooking_Click(object sender, EventArgs e) { HTML charcaterList = new HTML(txtCookingLink.Text, "POST"); txtAll.Text = charcaterList.Content; string RecipeName = "unAssigned"; List <string> answer = HTML.GetListOfAllRecipe(txtAll.Text); List <Recipe> realanswer = new List <Recipe>(); Recipe eachRecipe = new Recipe(); foreach (string relatedHtml in answer) { string[] keyNVAlue = relatedHtml.Split(':'); if (keyNVAlue.Length > 1) { string key = keyNVAlue[0]; string value = keyNVAlue[1].Replace("\"", string.Empty).Replace("-", string.Empty).Trim(); if (key.Contains("Required Utensils")) { eachRecipe.RequiredUtensils = value; } else if (key.Contains("Required Ingredients")) { eachRecipe.RequiredIngredients = value; } else if (key.Contains("Required Seasoning")) { eachRecipe.RequiredSeasoning = value; } else if (key.Contains("Optional Utensils")) { eachRecipe.OptionalUtensils = value; } else if (key.Contains("Optional Ingredients")) { eachRecipe.OptionalIngredients = value; } else if (key.Contains("Optional Seasoning")) { eachRecipe.OptionalSeasoning = value; realanswer.Add(eachRecipe); eachRecipe = new Recipe(); } } else { eachRecipe.RecipeName = relatedHtml; } } string yeahh = Xmls.WriteXML(realanswer); string zzz = string.Empty; //try //{ // charName = man.Link; // string link = string.Format("http://harvestmoonbacktonatureguide.com/{0}", man.Link); // HTML charcaterList = new HTML(link, "POST"); // CharacterFavourite eachFavour = new CharacterFavourite() { characterLink = man.Link }; // txtAll.Text = charcaterList.Content; // List<string> favourListLine = HTML.GetListOfAllFavouriteLine(charcaterList.Content); // foreach (string loveList in favourListLine) // { // if (loveList.ToLower().Contains("dislike")) // eachFavour.DislikedItem = loveList; // else if (loveList.ToLower().Contains("love")) // eachFavour.LovedItem = loveList; // else if (loveList.ToLower().Contains("like")) // eachFavour.LikedItem = loveList; // else if (loveList.ToLower().Contains("neutral")) // eachFavour.NauturalItem = loveList; // else if (loveList.ToLower().Contains("hate")) // eachFavour.HatedItem = loveList; // else // eachFavour.ElseItem += loveList; // } // charFavour.Add(eachFavour); // doneCOunt++; // pgbWaitLoadCharFavour.Value += 1; // // txtLoadInfo.Text = string.Format("Loaded {0} out of 27", doneCOunt.ToString()); //} //catch //{ // error.AppendLine( string.IsNullOrEmpty(error.ToString()) ? string.Empty : ", " + charName ); // continue; //} }
public void createOnClick(Recipe rec, clickFunc func) { onClick = func; }
public void setCFunc(ComboGrid cGrid, Recipe rec, clickFunc func) { grid = cGrid; recipe = rec; onClick = func; }
internal static void do_Load(object threadContext) { if (!LoadMods()) { Main.menuMode = Interface.errorMessageID; return; } if (Main.dedServ) { Console.WriteLine("Adding mod content..."); } int num = 0; foreach (Mod mod in mods.Values) { Interface.loadMods.SetProgressInit(mod.Name, num, mods.Count); try { mod.Autoload(); mod.Load(); } catch (Exception e) { DisableMod(mod.File); ErrorLogger.LogLoadingError(mod.Name, mod.tModLoaderVersion, e); Main.menuMode = Interface.errorMessageID; return; } num++; } Interface.loadMods.SetProgressSetup(0f); ResizeArrays(); num = 0; foreach (Mod mod in mods.Values) { Interface.loadMods.SetProgressLoad(mod.Name, num, mods.Count); try { mod.SetupContent(); mod.PostSetupContent(); } catch (Exception e) { DisableMod(mod.File); ErrorLogger.LogLoadingError(mod.Name, mod.tModLoaderVersion, e); Main.menuMode = Interface.errorMessageID; return; } num++; } if (Main.dedServ) { ModNet.AssignNetIDs(); } MapLoader.SetupModMap(); ItemSorting.SetupWhiteLists(); Interface.loadMods.SetProgressRecipes(); for (int k = 0; k < Recipe.maxRecipes; k++) { Main.recipe[k] = new Recipe(); } Recipe.numRecipes = 0; RecipeGroupHelper.ResetRecipeGroups(); try { Recipe.SetupRecipes(); } catch (AddRecipesException e) { ErrorLogger.LogLoadingError(e.modName, version, e.InnerException, true); Main.menuMode = Interface.errorMessageID; return; } if (PostLoad != null) { PostLoad(); PostLoad = null; } else { Main.menuMode = 0; } GameInput.PlayerInput.ReInitialize(); }
public void PostRecipe(Recipe recipe) { _context.Recipes.Add(recipe); _context.SaveChanges(); _context.Entry(recipe).State = EntityState.Detached; }
public override bool NewRightClick(int i, int j) { Player player = Main.LocalPlayer; if (Main.tile[Player.tileTargetX, Player.tileTargetY].frameY == 0) { Main.CancelClothesWindow(true); Main.mouseRightRelease = false; int left = (int)(Main.tile[Player.tileTargetX, Player.tileTargetY].frameX / 18); left %= 3; left = Player.tileTargetX - left; int top = Player.tileTargetY - (int)(Main.tile[Player.tileTargetX, Player.tileTargetY].frameY / 18); if (player.sign > -1) { Main.PlaySound(SoundID.MenuClose); player.sign = -1; Main.editSign = false; Main.npcChatText = string.Empty; } if (Main.editChest) { Main.PlaySound(SoundID.MenuTick); Main.editChest = false; Main.npcChatText = string.Empty; } if (player.editedChestName) { NetMessage.SendData(MessageID.SyncPlayerChest, -1, -1, NetworkText.FromLiteral(Main.chest[player.chest].name), player.chest, 1f, 0f, 0f, 0, 0, 0); player.editedChestName = false; } if (Main.netMode == NetmodeID.MultiplayerClient) { if (left == player.chestX && top == player.chestY && player.chest != -1) { player.chest = -1; Recipe.FindRecipes(); Main.PlaySound(SoundID.MenuClose); } else { NetMessage.SendData(MessageID.RequestChestOpen, -1, -1, null, left, (float)top, 0f, 0f, 0, 0, 0); Main.stackSplit = 600; } } else { player.flyingPigChest = -1; int num213 = Chest.FindChest(left, top); if (num213 != -1) { Main.stackSplit = 600; if (num213 == player.chest) { player.chest = -1; Recipe.FindRecipes(); Main.PlaySound(SoundID.MenuClose); } else if (num213 != player.chest && player.chest == -1) { player.chest = num213; Main.playerInventory = true; Main.recBigList = false; Main.PlaySound(SoundID.MenuOpen); player.chestX = left; player.chestY = top; } else { player.chest = num213; Main.playerInventory = true; Main.recBigList = false; Main.PlaySound(SoundID.MenuTick); player.chestX = left; player.chestY = top; } Recipe.FindRecipes(); } } } else { Main.playerInventory = false; player.chest = -1; Recipe.FindRecipes(); Main.dresserX = Player.tileTargetX; Main.dresserY = Player.tileTargetY; Main.OpenClothesWindow(); } return(true); }
public override void OnCraft(Recipe recipe) { crafted = true; }
public RecipeInfoPageViewModel() { CurrentRecipe = new Recipe(); }
public string getRecipeDescription(Recipe r) { return(r.description); //Pending. }
public static void RemoveRecipe(Recipe recipe) { var dbHandler = new CoffeeBookDbHandlerFactory().GetDbHandler(); dbHandler.DeleteRecipeAsync(recipe.Id); }
public void UpdateRecipes(UpdateRecipeRequest request) { if (request == null) { throw new ActionFailedException("invalid request body"); } if (request.Id == 0) { throw new ActionFailedException("id cannot be empty"); } if (string.IsNullOrWhiteSpace(request.Title)) { throw new ActionFailedException("title cannot be empty"); } if (string.IsNullOrWhiteSpace(request.Text)) { throw new ActionFailedException("title cannot be empty"); } request.Title = request.Title.Trim(); request.Text = request.Text.Trim(); if (request.Title.Length < 8) { throw new ActionFailedException("title is too short"); } if (request.Text.Length < 20) { throw new ActionFailedException("recipe details is too short"); } if (request.Portion <= 0) { throw new ActionFailedException("portion cannot be smaller than 1"); } if (request.Portion > 20) { throw new ActionFailedException("portion is too large"); } if (request.PrepareTime <= 0) { throw new ActionFailedException("prepare time cannot be smaller than 1"); } if (request.PrepareTime > 600) { throw new ActionFailedException("prepare time is too large"); } if (request.Ingredients == null) { throw new ActionFailedException("ingredients cannot be empty"); } if (request.Steps == null) { throw new ActionFailedException("steps cannot be empty"); } foreach (var item in request.Ingredients) { if (string.IsNullOrWhiteSpace(item)) { throw new ActionFailedException("ingredient items cannot be empty"); } } foreach (var item in request.Steps) { if (string.IsNullOrWhiteSpace(item)) { throw new ActionFailedException("step items cannot be empty"); } } Recipe recipe = recipeContext.Recipes.Include(x => x.RecipeTags).FirstOrDefault(x => x.Id == request.Id); if (recipe == null) { throw new ActionFailedException("invalid recipe"); } if (request.Tags == null) { request.Tags = new string[0]; } recipe.RecipeTags.Clear(); recipe.Title = request.Title; recipe.Text = request.Text; recipe.Ingredients = JsonConvert.SerializeObject(request.Ingredients); recipe.Steps = JsonConvert.SerializeObject(request.Steps); recipe.ModifiedTime = DateTime.Now; recipe.Portion = request.Portion; recipe.PrepareTime = request.PrepareTime; if (request.Photos != null) { recipe.Photos = JsonConvert.SerializeObject(request.Photos); } recipe.RecipeTags = new List <RecipeTag>(); foreach (var item in request.Tags) { if (string.IsNullOrWhiteSpace(item)) { throw new ActionFailedException("tags cannot be empty"); } var tagText = item.ToLower(); Tag tag = recipeContext.Tags.FirstOrDefault(x => x.Text == tagText); if (tag == null) { tag = new Tag(); tag.Text = tagText; recipeContext.Tags.Add(tag); } recipe.RecipeTags.Add(new RecipeTag { Recipe = recipe, Tag = tag }); } //TO-DO Recipe.User //TO-DO Photo ve Tag için add remove endpoint recipeContext.SaveChanges(); }
private void AddOutRecipe(Recipe recipe) { OutRecipes.Add(recipe); }