archive
/
product-list
Archived
1
Fork 0

Add JSON storage engine

This commit is contained in:
Jake Howard 2016-04-15 14:58:45 +01:00
parent c5721159a4
commit e777427de8
3 changed files with 43 additions and 2 deletions

View File

@ -1,5 +1,5 @@
using System; using System;
using Newtonsoft.Json;
namespace productlist namespace productlist
{ {
@ -27,6 +27,14 @@ namespace productlist
return String.Format ("Product {0}", this.name); return String.Format ("Product {0}", this.name);
} }
public string serialize() {
return JsonConvert.SerializeObject (this);
}
public static Product fromJSON(string json) {
return JsonConvert.DeserializeObject<Product> (json);
}
public void display() { public void display() {
string output = String.Format(@" string output = String.Format(@"
{0} {0}

View File

@ -1,16 +1,37 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Newtonsoft.Json;
namespace productlist namespace productlist
{ {
public static class Storage public static class Storage
{ {
private static List<Product> productStorageList = new List<Product>(); private static List<Product> productStorageList = new List<Product>();
private static readonly string filePath = @"data.json";
public static void Add(Product p) { public static void Add(Product p) {
productStorageList.Add (p); productStorageList.Add (p);
} }
public static void dump() {
if (productStorageList.Count < 1) {
Console.WriteLine ("Nothing to dump");
return;
}
string json = JsonConvert.SerializeObject (productStorageList);
System.IO.File.WriteAllText (filePath, json);
}
public static void load() {
if (!System.IO.File.Exists (filePath)) {
Console.WriteLine ("Data file not found!");
return;
}
string text = System.IO.File.ReadAllText (filePath);
productStorageList = JsonConvert.DeserializeObject<List<Product>> (text);
}
private static void listProducts() { private static void listProducts() {
if (productStorageList.Count < 1) { if (productStorageList.Count < 1) {
Console.WriteLine ("No Products found!"); Console.WriteLine ("No Products found!");

14
UI.cs
View File

@ -8,7 +8,9 @@ namespace productlist
create, create,
delete, delete,
list, list,
help help,
dump,
load
} }
private static inputType decodeInputType(string input) { private static inputType decodeInputType(string input) {
string command = input.Split (null, 1)[0]; string command = input.Split (null, 1)[0];
@ -22,6 +24,10 @@ namespace productlist
default: default:
case "help": case "help":
return inputType.help; return inputType.help;
case "dump":
return inputType.dump;
case "load":
return inputType.load;
} }
} }
@ -56,6 +62,12 @@ namespace productlist
case inputType.list: case inputType.list:
Storage.List (); Storage.List ();
break; break;
case inputType.dump:
Storage.dump ();
break;
case inputType.load:
Storage.load ();
break;
} }
} }
} }