-
Notifications
You must be signed in to change notification settings - Fork 0
/
TeaManager.cs
92 lines (85 loc) · 2.78 KB
/
TeaManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace TeaLog
{ //This class does the adding, editing, deleting of the tea.
public class TeaManager
{
private List<Tea> Teas;
public string FilePath;
public TeaManager(string filePath)
{
FilePath = filePath;
}
//Deserialize list of teas from file and return.
public List<Tea> ReadTeas()
{
List<Tea> teas = new List<Tea>();
var serializer = new JsonSerializer();
using (var reader = new StreamReader(FilePath))
using (var jsonReader = new JsonTextReader(reader))
{
teas = serializer.Deserialize<List<Tea>>(jsonReader);
}
return teas;
}
//Add new tea to tea list then serialize back to original file.
public void AddTea(Tea tea)
{
List<Tea> teas = ReadTeas();
teas.Add(tea);
SaveTeas(teas);
}
//Edit existing tea and update to file.
public void EditTea(Tea tea, string fieldName, string fieldValue)
{
List<Tea> teas = ReadTeas();
tea = teas.Find(e => e.TeaName == tea.TeaName);
if(fieldName == "Tea Name")
{
tea.TeaName = fieldValue;
}
else if(fieldName == "Tea Type")
{
tea.TeaType = fieldValue;
}
else if(fieldName == "Company Name")
{
tea.CompanyName = fieldValue;
}
else if(fieldName == "Caffeine")
{
tea.ContainsCaffeine = fieldValue;
}
else if(fieldName == "Rating")
{
tea.Rating = Int32.Parse(fieldValue);
}
else if(fieldName == "Notes")
{
tea.Notes = fieldValue;
}
SaveTeas(teas);
}
//Delete an existing tea and update file.
public void DeleteTea(string teaName)
{
List<Tea> teas = ReadTeas();
Tea teaToRemove = teas.Find(t => t.TeaName == teaName);
teas.Remove(teaToRemove);
SaveTeas(teas);
}
//Serialize tea list to tea.json.
private void SaveTeas(List<Tea> teas)
{
JsonSerializer serializer = new JsonSerializer();
using (StreamWriter writer = new StreamWriter(FilePath))
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
{
serializer.Serialize(jsonWriter, teas);
}
}
}
}