.NET/Przepisy/ViewModels/RecipesVM.cs
2019-06-02 10:23:04 +02:00

68 lines
1.7 KiB
C#

using Przepisy.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Przepisy.ViewModels
{
public class RecipesVM
{
public ObservableCollection<Recipe> Recipes { get; set; }
public RecipesVM()
{
Recipes = new ObservableCollection<Recipe>();
}
public void AddRecipe(string name, string description)
{
Recipes.Add(new Recipe(name, description));
}
public async Task SaveToFileAsync()
{
string jsonTodo = JsonConvert.SerializeObject(Recipes);
using (StreamWriter writer = new StreamWriter("Recipes.txt"))
{
await writer.WriteAsync(jsonTodo);
}
Console.WriteLine("Zapisano.");
}
public async Task ReadFileAsync()
{
string json;
try
{
using (StreamReader reader = new StreamReader("Recipes.txt"))
{
json = await reader.ReadToEndAsync();
List<Recipe> items = JsonConvert.DeserializeObject<List<Recipe>>(json);
foreach (var item in items)
Recipes.Add(new Recipe(item.Name, item.Description));
}
}
catch (IOException e)
{
Console.WriteLine("Wystąpił błąd.");
Console.WriteLine(e.Message);
}
}
}
}