forked from maxole/experiments
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataRepository.cs
73 lines (64 loc) · 2.07 KB
/
DataRepository.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
// ReSharper disable once CheckNamespace
namespace Core.Repository
{
using Entity;
using Serializer;
public interface IDataRepository
{
IEnumerable<T> Fetch<T>() where T : IEntity;
void Save<T>(T data) where T : IEntity;
void Delete<T>(T data) where T : IEntity;
void DeleteAll();
}
public class DataRepository : IDataRepository
{
private readonly Encoding _encoding = Encoding.UTF8;
public IEnumerable<T> Fetch<T>() where T : IEntity
{
var path = GetDirectory();
var serializer = new XmlDataSerializer();
return Directory.GetFiles(path, "*.xml")
.Select(file =>
{
var content = File.ReadAllText(file, _encoding);
return new StringBuilder(content);
})
.Where(serializer.CanDeserialize<T>)
.Select(serializer.Deserialize<T>);
}
public void Save<T>(T data) where T : IEntity
{
Delete(data);
var xml = new XmlDataSerializer().Serialize(data);
File.WriteAllText(BuildFileName(data), xml.ToString(), _encoding);
}
public void Delete<T>(T data) where T : IEntity
{
var path = BuildFileName(data);
if (File.Exists(path))
File.Delete(path);
}
public void DeleteAll()
{
var path = GetDirectory();
Directory.Delete(path, true);
}
private string GetDirectory()
{
var path = Path.Combine(Environment.CurrentDirectory, "data");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
return path;
}
private string BuildFileName(IEntity data)
{
var path = GetDirectory();
return Path.Combine(path, data.SystemId + ".xml");
}
}
}