/
TodoDataStore.cs
102 lines (88 loc) · 2.77 KB
/
TodoDataStore.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
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using DemoNancy.Model;
namespace DemoNancy.Data
{
public class TodoDataStore : IDataStore<Todo>
{
private readonly string _filePath;
//private static readonly string TodoFilePath = HttpContext.Current.Server.MapPath("~/App_Data/Todo.xml");
private readonly XDocument _todosXmlDoc;
public TodoDataStore(IFilePathProvider filePathProvider)
{
_filePath = filePathProvider.GetPath();
if (!File.Exists(_filePath))
{
_todosXmlDoc = new XDocument(new XElement("todos"));
Save();
}
else
{
_todosXmlDoc = XDocument.Load(_filePath);
}
}
public virtual bool Add(Todo todo)
{
try
{
if (_todosXmlDoc.Root.Elements(Todo.KeyTodo).Any(x => x.Element("id").Value.ToInt() == todo.Id))
{
return false;
}
_todosXmlDoc.Root.Add(todo.AsXElement());
Save();
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
return false;
}
return true;
}
public void Clear()
{
_todosXmlDoc.Root.Elements(Todo.KeyTodo).Remove();
Save();
}
public int Count => _todosXmlDoc.Root?.Elements().Count() ?? 0;
public Todo Get(int id)
{
return _todosXmlDoc.Root.Elements(Todo.KeyTodo)
.Where(x => x.Element(Todo.KeyId).Value == id.ToString())
.Select(y => new Todo().FromXElement(y)).SingleOrDefault();
}
public IEnumerable<Todo> GetAll()
{
return from xElement in _todosXmlDoc.Root.Elements(Todo.KeyTodo)
select new Todo().FromXElement(xElement);
}
public virtual bool Remove(int id)
{
try
{
_todosXmlDoc.Root.Elements(Todo.KeyTodo)
.First(x => x.Element(Todo.KeyId).Value == id.ToString())
.Remove();
Save();
}
catch (Exception)
{
return false;
}
return true;
}
public bool Update(Todo todo)
{
if (!Remove(todo.Id) || !Add(todo)) return false;
Save();
return true;
}
public virtual void Save()
{
_todosXmlDoc.Save(_filePath);
}
}
}