public List <RecipeInfo> ConvertToListRecipeInfo(string dataString) { List <RecipeInfo> recipeList = new List <RecipeInfo>(); JToken token = JToken.Parse(dataString); JArray recipesArray = JArray.Parse(token.ToString()); Debug.Log("Recipes count:" + recipesArray.Count); for (int i = 0; i < recipesArray.Count; i++) { RecipeInfo recipeInfo = new RecipeInfo(); JToken recipeToken = recipesArray[i]; recipeInfo.recipeID = int.Parse(recipeToken["ID"].ToString()); recipeInfo.name = recipeToken["Name"].ToString(); recipeInfo.energy = int.Parse(recipeToken["Energy"].ToString()); recipeInfo.description = recipeToken["Description"].ToString(); recipeInfo.imgURL = recipeToken["Image"].ToString(); JArray ingredientsArray = (JArray)recipeToken["Recipe"]; recipeInfo.IngredientDetails = new List <IngredientDetail>(); for (int j = 0; j < ingredientsArray.Count; j++) { IngredientDetail ingredientDetail = new IngredientDetail(); JToken ingredientToken = ingredientsArray[j]; ingredientDetail.ingredientID = int.Parse(ingredientToken["ID"].ToString()); ingredientDetail.amount = int.Parse(ingredientToken["Amount"].ToString()); ingredientDetail.energy = int.Parse(ingredientToken["Energy"].ToString()); ingredientDetail.imgURL = ingredientToken["Image"].ToString(); ingredientDetail.name = ingredientToken["Name"].ToString(); recipeInfo.IngredientDetails.Add(ingredientDetail); } JArray detailsArray = JArray.Parse(recipeToken["Detail"].ToString()); recipeInfo.RecipeDetails = new List <ItemDetail>(); for (int k = 0; k < detailsArray.Count; k++) { JToken detailToken = detailsArray[k]; ItemDetail itemDetail = new ItemDetail(); itemDetail.name = detailToken["Name"].ToString(); itemDetail.value = float.Parse(detailToken["Value"].ToString()); recipeInfo.RecipeDetails.Add(itemDetail); } recipeList.Add(recipeInfo); } return(recipeList); }
/// <summary> /// Using the materials in the passed inventory, crafts and returns the item the /// passed recipe is for. /// </summary> /// <param name="recipe"></param> /// <param name="inventory"></param> /// <returns>The recipe's result if the inventory has the mats. Null otherwise.</returns> public ItemInfo Craft(RecipeInfo recipe, PP_Inventory inventory) { ItemInfo itemToCraft = recipe.result; // check if the passed inventory has the materials for the recipe foreach (ItemInfo material in recipe.materials) { if (inventory.CountOf(material) < recipe.CountOf(material)) { string messageFormat = "Could not craft {0}; the inventory doesn't have enough {1}s."; Debug.Log(string.Format(messageFormat, itemToCraft.name, material.name)); return(null); } } // Use up the materials foreach (ItemInfo material in recipe.materials) { inventory.Remove(material); } // and voila! Item-crafting success! Debug.Log("Successfully crafted a(n) " + itemToCraft.name); return(itemToCraft.Copy()); }
public void GenerateRecipeInfo() { RecipeInfo.Clear(); int index = 0; MRecipe.BeginGetAllLayers(RecipeVm, (layer) => { if (layer.TileDescriptions.Count() <= 0) { layer.GenerateTileDescriptionsFromSettings( GeometricArithmeticModule.CalculateExtents(FetchDXF(layer)) ); } var info = new RecipeProcessEntityInfo() { Index = index++, Layer = layer, EstimatedTime = EstimateProcessTime(layer) }; RecipeInfo.Add(info); }); // fetch recipe's count and extents (RecipeGeometriesCount, RecipeExtents) = MRecipe.CalculateExtents(RecipeVm); }
public virtual async Task <NotificationResult> InsertAsync(InsertRecipeCommand command) { var result = new NotificationResult(); var item = new RecipeInfo(command); result.Add(item.GetNotificationResult()); if (!result.IsValid) { return(result); } result.Add(await _recipeRepository.InsertAsync(item)); if (result.IsValid) { if (command.RecipeIngredients != null && command.RecipeIngredients.Count > 0) { foreach (var recipeIngredientCommand in command.RecipeIngredients) { var recipeIngredient = new RecipeIngredientInfo(recipeIngredientCommand); recipeIngredient.SetRecipeId(item.Id.Value); result.Add(await _recipeIngredientRepository.InsertAsync(recipeIngredient)); } } result.Data = item.Id; result.AddMessage(Shared.Domain.Resources.Handler.InsertSuccess_Message); } else { result.AddErrorOnTop(Shared.Domain.Resources.Handler.InsertError_Message); } return(result); }
public InteractionNode GetNextNodeForChoiceAndMake(Inventory inventory, RecipeInfo recipe) { var port_name = "cancel"; if (recipe != null) { port_name = "default"; ItemInfo choosen_output = recipe.output.info; for (int i = 0; i < on_recipe_chosen.Count; i++) { if (on_recipe_chosen[i].when_making == choosen_output) { port_name = $"on_recipe_chosen[{i}]"; } } inventory.make(recipe); } var port = GetPort(port_name); if (port == null) { return(null); } if (!port.IsConnected) { return(null); } return(port.ConnectedPorts[0].node as InteractionNode); }
private void ParseCrafting(IList<string> lines) { for (int i = 0; i < lines.Count; i++) { if (!lines[i].ToUpper().StartsWith(RecipeKey)) continue; while (++i < lines.Count) { if (lines[i].StartsWith("[")) return; if (String.IsNullOrEmpty(lines[i])) continue; var data = lines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); ItemInfo info = Envir.GetItemInfo(data[0]); if (info == null) continue; RecipeInfo recipe = Envir.RecipeInfoList.SingleOrDefault(x => x.MatchItem(info.Index)); if (recipe == null) { MessageQueue.Enqueue(string.Format("Could not find recipe: {0}, File: {1}", lines[i], FileName)); continue; } if (recipe.Ingredients.Count == 0) { MessageQueue.Enqueue(string.Format("Could not find ingredients: {0}, File: {1}", lines[i], FileName)); continue; } CraftGoods.Add(recipe); } } }
private bool UserFilter(object item) { RecipeInfo info = (item as RecipeInfo); string[] args = TextBoxSearchStringName.Text.ToLower().Split(' '); bool e1 = String.IsNullOrEmpty(TextBoxSearchStringName.Text); bool e2 = String.IsNullOrEmpty(TextBoxSearchIngredient.Text); if (e1 && e2) { return(true); } if (!e1) { string s = info.InfoString.ToLower(); bool contains = args.All(x => s.Contains(x)); if (contains) { return(true); } } if (!e2) { string ingredient = TextBoxSearchIngredient.Text.ToLower(); if (G.Ingredients[info].Any(x => x.Name.ToLower() == ingredient)) { return(true); } } return(false); }
public void LoadRecipe(RecipeInfo recipeInfo) { Dispatcher.Invoke(() => { ButtonSelectRecipe.Content = recipeInfo.Name; TextBoxRecipeLevel.Text = recipeInfo.Level.ToString(); TextBoxSuggestedCraftsmanship.Text = recipeInfo.RequiredCraftsmanship.ToString(); TextBoxSuggestedControl.Text = recipeInfo.RequiredControl.ToString(); TextBoxDurability.Text = recipeInfo.Durability.ToString(); TextBoxMaxProgress.Text = recipeInfo.MaxProgress.ToString(); TextBoxMaxQuality.Text = recipeInfo.MaxQuality.ToString(); }); Dispatcher.Invoke(() => { ListViewAvailableIncreasesProgress.ItemsSource = null; ListViewAvailableIncreasesQuality.ItemsSource = null; ListViewAvailableAddsBuff.ItemsSource = null; ListViewAvailableOther.ItemsSource = null; Sim.SetRecipe(recipeInfo); UpdateAvailableActions(recipeInfo); CollectionView view = null; view = (CollectionView)CollectionViewSource.GetDefaultView(ListViewAvailableIncreasesProgress.ItemsSource); view.SortDescriptions.Clear(); view.SortDescriptions.Add(new SortDescription("ProgressIncrease", ListSortDirection.Descending)); }); UpdateRotationsCount(); }
public List <RecipeInfo> ConvertToListRecipeInfo(string dataString) { string parsedString = ParseString(dataString); List <RecipeInfo> recipeList = new List <RecipeInfo>(); JsonData recipesArray = LitJson.JsonMapper.ToObject(parsedString); for (int i = 0; i < recipesArray.Count; i++) { RecipeInfo recipeInfo = new RecipeInfo(); JsonData recipeToken = recipesArray[i]; recipeInfo.recipeID = int.Parse(recipeToken["ID"].ToString()); recipeInfo.name = recipeToken["Name"].ToString(); recipeInfo.energy = int.Parse(recipeToken["Energy"].ToString()); recipeInfo.description = recipeToken["Description"].ToString(); recipeInfo.imgURL = recipeToken["Image"].ToString(); JsonData ingredientsArray = recipeToken["Recipe"]; recipeInfo.IngredientDetails = new List <IngredientDetail>(); for (int j = 0; j < ingredientsArray.Count; j++) { IngredientDetail ingredientDetail = new IngredientDetail(); JsonData ingredientToken = ingredientsArray[j]; ingredientDetail.ingredientID = int.Parse(ingredientToken["ID"].ToString()); ingredientDetail.amount = int.Parse(ingredientToken["Amount"].ToString()); ingredientDetail.energy = int.Parse(ingredientToken["Energy"].ToString()); ingredientDetail.imgURL = ingredientToken["Image"].ToString(); ingredientDetail.name = ingredientToken["Name"].ToString(); recipeInfo.IngredientDetails.Add(ingredientDetail); } JsonData detailsArray = LitJson.JsonMapper.ToObject(recipeToken["Detail"].ToString()); recipeInfo.RecipeDetails = new List <ItemDetail>(); for (int k = 0; k < detailsArray.Count; k++) { JsonData detailToken = detailsArray[k]; ItemDetail itemDetail = new ItemDetail(); itemDetail.name = detailToken["Name"].ToString(); itemDetail.value = float.Parse(detailToken["Value"].ToString()); recipeInfo.RecipeDetails.Add(itemDetail); } recipeList.Add(recipeInfo); } return(recipeList); }
public UpdateRecipeCommand(Guid id, string name, string description, RecipeInfo recipeInfo, IEnumerable <RecipeIngredientDto> recipeIngredients) { Id = id; Name = name; Description = description; RecipeInfo = recipeInfo; RecipeIngredients = recipeIngredients; }
public static RecipeInfo Modify(this RecipeModifier modifier, RecipeInfo cheeseType) { if (modifier == null) { return(cheeseType); } return(new RecipeInfo(modifier.Name + " " + cheeseType.Name, Math.Sign(cheeseType.Points) * modifier.Points + cheeseType.Points)); }
private void UpdateAvailableActions(RecipeInfo recipeInfo) { AvailableActions = CraftingAction.CraftingActions.Values.Where(xx => xx.Level <= Sim.Level).Select(x => new CraftingActionContainer(Sim, x)).ToArray(); ListViewAvailableIncreasesProgress.ItemsSource = AvailableActions.Where(x => x.Action.IncreasesProgress); ListViewAvailableIncreasesQuality.ItemsSource = AvailableActions.Where(x => x.Action.IncreasesQuality); ListViewAvailableAddsBuff.ItemsSource = AvailableActions.Where(x => x.Action.AddsBuff); ListViewAvailableOther.ItemsSource = AvailableActions.Where(x => !x.Action.IncreasesProgress && !x.Action.IncreasesQuality && !x.Action.AddsBuff); }
public Recipe RecipeFromDto(RecipeDto dto) { var recipeInfo = new RecipeInfo(dto.RecipeInfo.DifficultyLevel, dto.RecipeInfo.PreparationTime, dto.RecipeInfo.ApproximateCost, dto.RecipeInfo.MealTypes.ToMealType()); return(new Recipe(dto.Id, dto.Name, dto.Description, recipeInfo, dto.RecipeIngredients)); }
public void AddRecipe(GoodsRecipe.Recipe Recipe, string CompanyName) { RecipeInfo newRecipe = new RecipeInfo(); newRecipe.Recipe = Recipe; newRecipe.Maker = CompanyName; newRecipe.Owner = CompanyName; AvailableRecipe.Add(newRecipe); }
private void AddRecipe(ICreateRecipeService service, RecipeInfo recipe) { try { service.UpdateRecipeWithLocation(recipe.ItemCreated, recipe.Location, recipe.CreateCount, recipe.Requirements.Select(CreateIngredient)); } catch (RecipeLocationAlreadyExistsError) { } }
public virtual void SetRecipe(RecipeInfo recipe) { if (CurrentRecipe == recipe) { return; } CurrentRecipe = recipe; LevelDifference = Utils.GetCraftingLevelDifference(ActualLevel - recipe.Level); ExecuteActions(); }
public void AddRotations(RecipeInfo recipeInfo) { ClassJobInfo = recipeInfo.ClassJob; AbstractRecipeInfo = recipeInfo.GetAbstractData(); Dispatcher.Invoke(() => { var rotations = GameData.RecipeRotations[AbstractRecipeInfo].Select(x => new RotationInfoContainer(x, ClassJobInfo)); DataGridRotations.ItemsSource = rotations; }); }
private void MouseDoubleClickRecipe(object sender, MouseButtonEventArgs e) { DataGrid parent = (sender as DataGrid); if (parent != null && parent.SelectedValue != null) { DialogResult = true; SelectedRecipe = (parent.SelectedValue as RecipeInfo); Close(); } }
/// <summary> /// 编辑食谱 /// </summary> /// <returns></returns> public ActionResult Edit() { int kid = GetValueInt("kid"); int contentid = GetValueInt("contentid"); RecipeInfo rec = RecipeDataProxy.Recipe_GetModel(contentid); ViewData["kid"] = kid; ViewData["contentid"] = contentid; ViewData["recipeType"] = rec.Rec_types; return(View(rec)); }
//Handle the delete button click event public void Delete_Recipes(object sender, DataGridCommandEventArgs e) { if ((e.CommandName == "Delete")) { TableCell iIdNumber2 = e.Item.Cells[0]; TableCell iIRecipename = e.Item.Cells[1]; #region Delete Recipe Image //Delete the recipe image if the recipe has an image. //Instantiate sql params object Blogic FetchData = new Blogic(); try { IDataReader dr = FetchData.GetRecipeImageFileNameForUpdate(int.Parse(iIdNumber2.Text)); dr.Read(); if (dr["RecipeImage"] != DBNull.Value) { System.IO.File.Delete(Server.MapPath(GetRecipeImage.ImagePath + dr["RecipeImage"].ToString())); } dr.Close(); } catch { } FetchData = null; #endregion //Refresh cached data Caching.PurgeCacheItems("MainCourse_RecipeCategory"); Caching.PurgeCacheItems("Ethnic_RecipeCategory"); Caching.PurgeCacheItems("RecipeCategory_SideMenu"); Caching.PurgeCacheItems("Newest_RecipesSideMenu_"); //Instantiate delete recipe object RecipeInfo DelRecipe = new RecipeInfo(); DelRecipe.ID = int.Parse(iIdNumber2.Text); //Perform delete recipe DelRecipe.Delete(); DelRecipe = null; //Redirect to confirm delete page strURLRedirect = "confirmdel.aspx?catname=" + iIRecipename.Text + "&mode=del"; Server.Transfer(strURLRedirect); } }
public void LoadItemRecipe(RecipeInfo newRecipeInfo) { recipeInfo = newRecipeInfo; recipeName.text = recipeInfo.name; recipeCraftTime.text = GetStringCraftTime(newRecipeInfo.energy); CloudGoods.GetItemTexture(recipeInfo.imgURL, OnReceivedRecipeImage); LoadIngredients(recipeInfo.IngredientDetails); }
public bool Contains(RecipeInfo recipe) { for (int i = 0; i < recipes.Length; i++) { if (recipes[i].Equals(recipe)) { return(true); } } return(false); }
// Use this for initialization void Start() { gameController = GameController.instance; player = gameController.player; craftingController = CraftingController.instance; itemDatabase = ItemDatabase.instance; recipeDatabase = RecipeDatabase.instance; recipe = recipeDatabase.GetRecipe(recipeId); craftingButton = GetComponent <Button>(); craftingButton.onClick.AddListener(Craft); }
public RecipeInfo GetRecipe(string Name) { RecipeInfo Result = null; foreach (var Recipe in AvailableRecipe) { if (Recipe.Recipe.OutputName == Name) { Result = Recipe; } } return(Result); }
public ActionResult GetModel() { int kid = GetValueInt("kid"); int contentid = GetValueInt("contentid"); recipeJson recJson = new recipeJson(); RecipeInfo rec = RecipeDataProxy.Recipe_GetModel(contentid); recJson = rec.GetJson(true); ViewData["kid"] = kid; ViewData["contentid"] = contentid; return(Json(recJson.week_contents, JsonRequestBehavior.AllowGet)); }
public MRecipeDeviceLayer GetClosestLayer() { if (RecipeVm == null) { return(null); } else if (SelectedSubProcessInfo == null) { return(RecipeInfo.FirstOrDefault()?.Layer); } return(SelectedSubProcessInfo?.Layer); }
// GET: Foods/Details/5 public async Task <IActionResult> Details(string id) { if (id == null) { return(NotFound()); } RecipeInfo recipeInfo = await _recipeInfoRequest.GetRecipeInfo(id); if (recipeInfo == null) { return(NotFound()); } return(View(recipeInfo)); }
public async Task <RecipeInfo> GetRecipeInfo(string id) { string url = $"https://api.spoonacular.com/recipes/{id}/information?includeNutrition=false&apiKey={APIKEYS.spoonKey}"; HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { string json = await response.Content.ReadAsStringAsync(); RecipeInfo recipeInfo = JsonConvert.DeserializeObject <RecipeInfo>(json); return(recipeInfo); } return(null); }
private void RecipesTabControl_SelectedIndexChanged(object sender, EventArgs e) { if (RecipesTabControl.TabPages[RecipesTabControl.SelectedIndex].Equals(RecipeInfo)) { if (recipesDataGrid.CurrentRowIndex < 0 || recipesDataGrid.CurrentRowIndex >= dataManager.RecipesList.Recipes.Count) { RecipeInfo.Hide(); } else { Recipe recipe = dataManager.RecipesList.Recipes[recipesDataGrid.CurrentRowIndex]; recipesInfoNumSteps.Text = recipe.Steps.Count + ""; recipesInfoSteps.Maximum = recipe.Steps.Count; recipesInfoSteps.Value = 0; recipesInfoStepDescription.Text = recipe.Description; recipesInfoStepName.Text = recipe.Name; recipesInfoServVal.Text = recipe.NumberOfServings + ""; recipesInfoTimeVal.Text = recipe.MinutesToPrepare + ""; recipesInfoServ.Show(); recipesInfoServVal.Show(); recipesInfoTime.Show(); recipesInfoTimeVal.Show(); recipesInfoStepIngredients.Hide(); recipesInfoIngridLabel.Hide(); RecipeInfo.Show(); } } else if (RecipesTabControl.TabPages[RecipesTabControl.SelectedIndex].Equals(recipesNew)) { newRecipe = new Recipe(); newRecipe.Steps = new List <RecipeStep>(); recipesNewSteps.Value = 0; recipesNewSteps.Maximum = 0; prev = 0; recipesNewStepsCount.Text = recipesNewSteps.Maximum + ""; recipesNewServings.Show(); recipesNewServingsVal.Show(); recipesNewTime.Show(); recipesNewTimeVal.Show(); recipesNewStepIngredients.Hide(); recipesNewStepIngridLabel.Hide(); } }
public async Task <NotificationResult> UpdateAsync(RecipeInfo item) { var result = new NotificationResult(); try { _context.Attach(item); _context.Entry(item).State = EntityState.Modified; await _context.SaveChangesAsync(); } catch (Exception ex) { result.AddError(ex); } return(result); }
//Handles insert recipe public void Add_Recipe(Object s, EventArgs e) { //Perform spam validation by matching the value of the textbox security code to the session state variable //that store the random number. if (Page.IsValid && (txtsecfield.Text.ToString() == Session["randomstrsub"].ToString())) { //If all the fields are filled correctly, then process recipe submission. //Instantiate the SQL command object RecipeInfo Add = new RecipeInfo(); //Filters harmful scripts from input string. Add.RecipeName = Util.FormatTextForInput(Request.Form[Name.UniqueID]); Add.Author = Util.FormatTextForInput(Request.Form[Author.UniqueID]); Add.CatID = (int)Util.Val(Request.QueryString["catid"]); Add.Category = Util.FormatTextForInput(Request.Form[Category.UniqueID]); Add.Ingredients = Util.FormatTextForInput(Request.Form[Ingredients.UniqueID]); Add.Instructions = Util.FormatTextForInput(Request.Form[Instructions.UniqueID]); #region Form Input Validator //Validate for empty recipe name if (Add.RecipeName.Length == 0) { lbvalenght.Text = "<br>Error: Recipe Name is empty, please enter a recipe name."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } //Validate for empty author name if (Add.Author.Length == 0) { lbvalenght.Text = "<br>Error: Author Name is empty, please enter the author name"; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } //Validate for empty ingredients if (Add.Ingredients.Length == 0) { lbvalenght.Text = "<br>Error: Ingredients is empty, please enter an ingredients."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } //Validate for empty instruction if (Add.Instructions.Length == 0) { lbvalenght.Text = "<br>Error: Instructions is empty, please enter an instruction."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } //Recipe name maximum of 50 char allowed if (Add.RecipeName.Length > 50) { lbvalenght.Text = "<br>Error: Recipe Name is too long. Max of 50 characters."; lbvalenght.Visible = true; Name.Value = ""; txtsecfield.Text = ""; return; } //Author name maximum of 25 char allowed if (Add.Author.Length > 25) { lbvalenght.Text = "<br>Error: Author Name is too long. Max of 25 characters."; lbvalenght.Visible = true; Author.Value = ""; txtsecfield.Text = ""; return; } //Ingredients maximum of 500 char allowed if (Add.Ingredients.Length > 500) { lbvalenght.Text = "<br>Error: Ingredients is too long. Max of 500 characters."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } //Instruction maximum of 700 char allowed if (Add.Instructions.Length > 700) { lbvalenght.Text = "<br>Error: Instructions is too long. Max of 700 characters."; lbvalenght.Visible = true; txtsecfield.Text = ""; return; } #endregion #region Recipe Image Upload if (RecipeImageFileUpload.HasFile) //Check if there is a file { //Constant variables string Directory = GetRecipeImage.ImagePathDetail; //Directory to store recipe images int maxFileSize = 30000; // Maximum file size limit int FileSize = RecipeImageFileUpload.PostedFile.ContentLength; //Get th file lenght string contentType = RecipeImageFileUpload.PostedFile.ContentType; // Get the file type string FileExist = Directory + RecipeImageFileUpload.PostedFile.FileName; // Get the filename from the directory and compare string FileName = Path.GetFileNameWithoutExtension(RecipeImageFileUpload.PostedFile.FileName); //Get the posted filename string FileExtention = Path.GetExtension(RecipeImageFileUpload.PostedFile.FileName); //Get the posted file extension string FilePath; string FileNameWithExtension; //File type validation if (!contentType.Equals("image/gif") && !contentType.Equals("image/jpeg") && !contentType.Equals("image/jpg") && !contentType.Equals("image/png")) { lbvalenght.Text = "<br>File format is invalid. Only gif, jpg, jpeg or png files are allowed."; lbvalenght.Visible = true; return; } // File size validation else if (FileSize > maxFileSize) { lbvalenght.Text = "<br>File size exceed the maximun allowed 30000 bytes"; lbvalenght.Visible = true; return; } else { //Check wether the image name already exist. //If the image name already exist, append a random //numeric and letter to ensure the image name is always unqiue. if (File.Exists(Server.MapPath(FileExist))) { //Create a random alpha numeric to make sure the updated image name is unique. Random rand = new Random((int)DateTime.Now.Ticks); int randnum = rand.Next(1, 10); int CharCode = rand.Next(Convert.ToInt32('a'), Convert.ToInt32('z')); char RandomChar = Convert.ToChar(CharCode); //Get directory, the file name and the extension. FilePath = string.Concat(Directory, FileName + randnum + RandomChar, "", FileExtention); //Joined the filename and extension to insert into the database. FileNameWithExtension = FileName + randnum + RandomChar + FileExtention; //Initialize Add recipe object property to get the full image name Add.RecipeImage = FileNameWithExtension; try { //Save the recipe image to the specified directory //Make sure the "RecipeImage" folder has write permission to upload image RecipeImageFileUpload.SaveAs(Server.MapPath(FilePath)); } catch (Exception ex) { JSLiteral.Text = "Error: " + ex.Message; return; } } else { //Get directory, the file name and the extension. FilePath = string.Concat(Directory, FileName, "", FileExtention); //Joined the filename and extension to insert into the database. FileNameWithExtension = FileName + FileExtention; //Initialize Add recipe object property to get the full image name Add.RecipeImage = FileNameWithExtension; try { //Save the recipe image to the specified directory //Make sure the "RecipeImage" folder has write permission to upload image RecipeImageFileUpload.SaveAs(Server.MapPath(FilePath)); } catch (Exception ex) { JSLiteral.Text = "Error: " + ex.Message; return; } } } } else { //If there is no image to be uploaded, then assign an empty string to the property Add.RecipeImage = string.Empty; } #endregion //Insert recipe to database. If an error occured notify user. if (Add.Add() != 0) { JSLiteral.Text = "Error occured while processing your submit."; return; } //Instantiate email template object //Comment this part if you don't want to receive an email notification EmailTemplate SendEMail = new EmailTemplate(); SendEMail.ItemName = Add.RecipeName; //Send an email notification to the webmaster in HTML format. //Comment this part if you don't want to receive an email notification SendEMail.SendEmailAddRecipeNotify(); //Release allocated memory Add = null; SendEMail = null; //If success, redirect to confirmation and thank you page. Util.PageRedirect(3); Util = null; } else { //Javascript validation JSLiteral.Text = Util.JSAlert("Invalid security code. Make sure you type it correctly."); return; // lblinvalidsecode.Text = "Invalid security code. Make sure you type it correctly."; // lblinvalidsecode.Visible = true; } }
public List<RecipeInfo> ConvertToListRecipeInfo(string dataString) { string parsedString = ParseString(dataString); List<RecipeInfo> recipeList = new List<RecipeInfo>(); JsonData recipesArray = LitJson.JsonMapper.ToObject(parsedString); for (int i = 0; i < recipesArray.Count; i++) { RecipeInfo recipeInfo = new RecipeInfo(); JsonData recipeToken = recipesArray[i]; recipeInfo.recipeID = int.Parse(recipeToken["ID"].ToString()); recipeInfo.name = recipeToken["Name"].ToString(); recipeInfo.energy = int.Parse(recipeToken["Energy"].ToString()); recipeInfo.description = recipeToken["Description"].ToString(); recipeInfo.imgURL = recipeToken["Image"].ToString(); JsonData ingredientsArray = recipeToken["Recipe"]; recipeInfo.IngredientDetails = new List<IngredientDetail>(); for (int j = 0; j < ingredientsArray.Count; j++) { IngredientDetail ingredientDetail = new IngredientDetail(); JsonData ingredientToken = ingredientsArray[j]; ingredientDetail.ingredientID = int.Parse(ingredientToken["ID"].ToString()); ingredientDetail.amount = int.Parse(ingredientToken["Amount"].ToString()); ingredientDetail.energy = int.Parse(ingredientToken["Energy"].ToString()); ingredientDetail.imgURL = ingredientToken["Image"].ToString(); ingredientDetail.name = ingredientToken["Name"].ToString(); recipeInfo.IngredientDetails.Add(ingredientDetail); } JsonData detailsArray = LitJson.JsonMapper.ToObject(recipeToken["Detail"].ToString()); recipeInfo.RecipeDetails = new List<ItemDetail>(); for (int k = 0; k < detailsArray.Count; k++) { JsonData detailToken = detailsArray[k]; ItemDetail itemDetail = new ItemDetail(); itemDetail.name = detailToken["Name"].ToString(); itemDetail.value = float.Parse(detailToken["Value"].ToString()); recipeInfo.RecipeDetails.Add(itemDetail); } recipeList.Add(recipeInfo); } return recipeList; }
public List<RecipeInfo> ConvertToListRecipeInfo(string dataString) { List<RecipeInfo> recipeList = new List<RecipeInfo>(); JToken token = JToken.Parse(dataString); JArray recipesArray = JArray.Parse(token.ToString()); Debug.Log("Recipes count:" + recipesArray.Count); for (int i = 0; i < recipesArray.Count; i++) { RecipeInfo recipeInfo = new RecipeInfo(); JToken recipeToken = recipesArray[i]; recipeInfo.recipeID = int.Parse(recipeToken["ID"].ToString()); recipeInfo.name = recipeToken["Name"].ToString(); recipeInfo.energy = int.Parse(recipeToken["Energy"].ToString()); recipeInfo.description = recipeToken["Description"].ToString(); recipeInfo.imgURL = recipeToken["Image"].ToString(); JArray ingredientsArray = (JArray)recipeToken["Recipe"]; recipeInfo.IngredientDetails = new List<IngredientDetail>(); for (int j = 0; j < ingredientsArray.Count; j++) { IngredientDetail ingredientDetail = new IngredientDetail(); JToken ingredientToken = ingredientsArray[j]; ingredientDetail.ingredientID = int.Parse(ingredientToken["ID"].ToString()); ingredientDetail.amount = int.Parse(ingredientToken["Amount"].ToString()); ingredientDetail.energy = int.Parse(ingredientToken["Energy"].ToString()); ingredientDetail.imgURL = ingredientToken["Image"].ToString(); ingredientDetail.name = ingredientToken["Name"].ToString(); recipeInfo.IngredientDetails.Add(ingredientDetail); } JArray detailsArray = JArray.Parse(recipeToken["Detail"].ToString()); recipeInfo.RecipeDetails = new List<ItemDetail>(); for (int k = 0; k < detailsArray.Count; k++) { JToken detailToken = detailsArray[k]; ItemDetail itemDetail = new ItemDetail(); itemDetail.name = detailToken["Name"].ToString(); itemDetail.value = float.Parse(detailToken["Value"].ToString()); recipeInfo.RecipeDetails.Add(itemDetail); } recipeList.Add(recipeInfo); } return recipeList; }
//Handles update recipe public void Update_Recipe(object sender, EventArgs e) { RecipeInfo Update = new RecipeInfo(); Update.ID = (int)Util.Val(Request.QueryString["id"]); Update.RecipeName = Request.Form["Name"]; Update.Author = Request.Form["Author"]; Update.CatID = int.Parse(Request.Form["CategoryID"]); Update.Ingredients = Request.Form["Ingredients"]; Update.Instructions = Request.Form["Instructions"]; Update.Hits = int.Parse(Request.Form["Hits"]); #region Upload New Photo/Update Photo if (RecipeImageFileUpload.HasFile) //Check if there is a file { //Constant variables string Directory = GetRecipeImage.ImagePath; //Directory to store recipe images int maxFileSize = 30000; // Maximum file size limit int FileSize = RecipeImageFileUpload.PostedFile.ContentLength; //Get th file lenght string contentType = RecipeImageFileUpload.PostedFile.ContentType; // Get the file type string FileExist = Directory + RecipeImageFileUpload.PostedFile.FileName; // Get the filename from the directory and compare string FileName = Path.GetFileNameWithoutExtension(RecipeImageFileUpload.PostedFile.FileName); //Get the posted filename string FileExtention = Path.GetExtension(RecipeImageFileUpload.PostedFile.FileName); //Get the posted file extension string FilePath; string FileNameWithExtension; //File type validation if (!contentType.Equals("image/gif") && !contentType.Equals("image/jpeg") && !contentType.Equals("image/jpg") && !contentType.Equals("image/png")) { lbvalenght.Text = "File format is invalid. Only gif, jpg, jpeg or png files are allowed."; lbvalenght.Visible = true; return; } // File size validation else if (FileSize > maxFileSize) { lbvalenght.Text = "File size exceed the maximun allowed 30000 bytes"; lbvalenght.Visible = true; return; } else { //Check wether the image name already exist. //We don't want images stored in the directory if they are not being use. if (File.Exists(Server.MapPath(FileExist))) { //Create a random alpha numeric to make sure the updated image name is unique. Random rand = new Random((int)DateTime.Now.Ticks); int randnum = rand.Next(1, 10); int CharCode = rand.Next(Convert.ToInt32('a'), Convert.ToInt32('z')); char RandomChar = Convert.ToChar(CharCode); //Get directory, the file name and the extension. FilePath = string.Concat(Directory, FileName + randnum + RandomChar, "", FileExtention); //Joined the filename and extension to insert into the database. FileNameWithExtension = FileName + randnum + RandomChar + FileExtention; //Initialize Add recipe object property to get the full image name Update.RecipeImage = FileNameWithExtension; try { //Delete old image File.Delete(Server.MapPath(Directory + FileName + FileExtention)); //Save the recipe image to the specified directory //Make sure the "RecipeImage" folder has write permission to upload image RecipeImageFileUpload.SaveAs(Server.MapPath(FilePath)); } catch (Exception ex) { JSLiteral.Text = "Error: " + ex.Message; return; } } else { //Get directory, the file name and the extension. FilePath = string.Concat(Directory, FileName, "", FileExtention); //Joined the filename and extension to insert into the database. FileNameWithExtension = FileName + FileExtention; //Initialize Add recipe object property to get the full image name Update.RecipeImage = FileNameWithExtension; try { //Save the recipe image to the specified directory //Make sure the "RecipeImage" folder has write permission to upload image RecipeImageFileUpload.SaveAs(Server.MapPath(FilePath)); } catch (Exception ex) { JSLiteral.Text = "Error: " + ex.Message; return; } } } } else { //This section is executed if the input file is empty. //Then it check if an image filename exist in the database. //If it exist, just update it with the same value, else update it with an empty string. IDataReader dr = myBL.GetRecipeImageFileNameForUpdate(Update.ID); dr.Read(); if (dr["RecipeImage"] != DBNull.Value) { Update.RecipeImage = (string)dr["RecipeImage"]; } else { Update.RecipeImage = string.Empty; } dr.Close(); } #endregion //Notify user if error occured. if (Update.Update() != 0) { JSLiteral.Text = Util.JSProcessingErrorAlert; return; } string strURLRedirect; strURLRedirect = "confirmdel.aspx?catname=" + Update.RecipeName + "&mode=update"; //Release allocated memory Update = null; Util = null; Response.Redirect(strURLRedirect); }
public TrinketRecipeItem AddOneItem(RecipeInfo info) { if (this.TrinketRecipePrefab == null) { this.TrinketRecipePrefab = Res.LoadGUI("GUI/TrinketRecipeItem"); } GameObject gameObject = (GameObject)UnityEngine.Object.Instantiate(this.TrinketRecipePrefab); gameObject.transform.parent = this.mRecipeTable.gameObject.transform; gameObject.transform.localPosition = Vector3.zero; gameObject.transform.localScale = Vector3.one; TrinketRecipeItem trinketRecipeItem = gameObject.AddComponent<TrinketRecipeItem>(); trinketRecipeItem.Init(info); return trinketRecipeItem; }