68 lines
1.7 KiB
C#
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);
|
|
}
|
|
|
|
}
|
|
|
|
|
|
}
|
|
}
|