Created
October 23, 2013 20:30
-
-
Save robertiagar/7126137 to your computer and use it in GitHub Desktop.
a simple JsonContext that adds and removes item in a list and then saves the file to the roaming folder of a Windows 8.1 Store app.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Windows.Storage; | |
namespace ExpenseManager.Repository | |
{ | |
public class JsonContext<T> where T : class | |
{ | |
public JsonContext(string fileName) | |
{ | |
this._list = new List<T>(); | |
this._fileName = fileName; | |
this._storageFolder = ApplicationData.Current.RoamingFolder; | |
} | |
private string _fileName; | |
private StorageFolder _storageFolder; | |
protected IList<T> _list; | |
public async Task<bool> AddItemAsync(T item) | |
{ | |
var items = await GetUnderlyingItems(); | |
items.Add(item); | |
return await SaveItems(items); | |
} | |
public async Task<bool> RemoveItemAsync(T item) | |
{ | |
var items = await GetUnderlyingItems(); | |
items.Remove(item); | |
return await SaveItems(items); | |
} | |
public async Task<IList<T>> GetItemsAsync() | |
{ | |
return await GetUnderlyingItems(); | |
} | |
private async Task<IList<T>> GetUnderlyingItems() | |
{ | |
var needToCreate = false; | |
try | |
{ | |
var file = await _storageFolder.GetFileAsync(_fileName); | |
var json = await FileIO.ReadTextAsync(file); | |
var obj = await JsonConvert.DeserializeObjectAsync<List<T>>(json); | |
return obj; | |
} | |
catch | |
{ | |
needToCreate = true; | |
} | |
if (needToCreate) | |
{ | |
await _storageFolder.CreateFileAsync(_fileName, CreationCollisionOption.ReplaceExisting); | |
} | |
return await GetUnderlyingItems(); | |
} | |
private async Task<bool> SaveItems(IList<T> items) | |
{ | |
try | |
{ | |
var file = await _storageFolder.CreateFileAsync(_fileName, CreationCollisionOption.ReplaceExisting); | |
var json = await JsonConvert.SerializeObjectAsync(items); | |
await FileIO.WriteTextAsync(file, json); | |
} | |
catch | |
{ | |
return false; | |
} | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment