This repository has been archived by the owner on Dec 18, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
SimpleDataStore.cs
99 lines (87 loc) · 3.09 KB
/
SimpleDataStore.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Serialization;
using Cirrious.CrossCore.Exceptions;
using Cirrious.CrossCore;
using Cirrious.CrossCore.Platform;
using Cirrious.MvvmCross.Plugins.File;
using Cirrious.MvvmCross.Plugins.ResourceLoader;
namespace CustomerManagement.Core.Models
{
public class SimpleDataStore
: IDataStore
{
public SimpleDataStore()
{
Load();
}
public void UpdateCustomer(Customer customer)
{
var toUpdate = _customers.First(c => c.ID == customer.ID);
toUpdate.CloneFrom(customer);
Save();
}
public void DeleteCustomer(string customerId)
{
_customers.Remove(_customers.First(c => c.ID == customerId));
Save();
}
public void CreateCustomer(Customer customer)
{
_customers.Add(customer);
Save();
}
public Customer GetCustomer(string customerId)
{
return _customers.First(c => c.ID == customerId);
}
private const string StoreFileName = "customers.xml";
private const string ResourceFileName = "Xml/Customers.xml";
private void Load()
{
var fileService = Mvx.Resolve<IMvxFileStore>();
if (!fileService.TryReadBinaryFile(StoreFileName, LoadFrom))
{
var resourceLoader = Mvx.Resolve<IMvxResourceLoader>();
resourceLoader.GetResourceStream(ResourceFileName, (inputStream) => LoadFrom(inputStream));
}
}
private bool LoadFrom(Stream inputStream)
{
try
{
var loadedData = XDocument.Load(inputStream);
if (loadedData.Root == null)
return false;
using (var reader = loadedData.Root.CreateReader())
{
var list = (List<Customer>)new XmlSerializer(typeof(List<Customer>)).Deserialize(reader);
_customers = new SimpleObservableCollection<Customer>(list);
return true;
}
}
catch (Exception exception)
{
CustomerManagementTrace.Trace("Problem loading customer list {0}", exception.ToLongString());
return false;
}
}
private void Save()
{
var fileService = Mvx.Resolve<IMvxFileStore>();
fileService.WriteFile(StoreFileName, (stream) =>
{
var serializer = new XmlSerializer(typeof(List<Customer>));
serializer.Serialize(stream, _customers.ToList());
});
}
private IObservableCollection<Customer> _customers;
public IObservableCollection<Customer> Customers
{
get { return _customers; }
}
}
}