//Add a new recipe to the JSON storage. private void AddRecipe(object sender, RoutedEventArgs e) { //Get the user inputs. string recipeName = RecipeNameInput.Text; string recipeTime = RecipeTimeInput.Text; string jsonToOutput; using (var r = new StreamReader("recipes.json")) { //Read the JSON file and convert it to an array. string json = r.ReadToEnd(); JsonConvert.DeserializeObject(json); var jsonArray = JArray.Parse(json); //Create a new JSON element which is created from the users input and add save the file again. var newRecipe = new JObject { ["name"] = recipeName, ["time"] = recipeTime }; jsonArray.Add(newRecipe); jsonToOutput = JsonConvert.SerializeObject(jsonArray, Formatting.Indented); } File.WriteAllText($"{Directory.GetCurrentDirectory()}/recipes.json", jsonToOutput); FillRecipesBar(); //Call an event so the MainWindow dropdown can update its recipes. RecipeUpdate?.Invoke(); Close(); }
//Remove a JSON file from storage. private void RemoveRecipe(object sender, RoutedEventArgs e) { int counter = 0; string jsonToOutput; using (var r = new StreamReader("recipes.json")) { //Read the JSON file and convert it to an array. var id = 0; string json = r.ReadToEnd(); dynamic array = JsonConvert.DeserializeObject(json); //Get the number of the selected recipe. foreach (var item in array) { if (item.name == cbRecipe.SelectedItem.ToString()) { id = counter; } counter++; } cbRecipe.SelectedItem = 1; //Convert to array list, remove the selected recipe, and convert it back to json so it can be saved. ArrayList arrLst = new ArrayList(array); arrLst.RemoveAt(id); dynamic editedArray = arrLst.ToArray(); jsonToOutput = JsonConvert.SerializeObject(editedArray, Formatting.Indented); } File.WriteAllText($"{Directory.GetCurrentDirectory()}/recipes.json", jsonToOutput); FillRecipesBar(); //Call an event so the MainWindow dropdown can update its recipes. RecipeUpdate?.Invoke(); Close(); }