-
Notifications
You must be signed in to change notification settings - Fork 53
/
Settings.cs
152 lines (133 loc) · 3.83 KB
/
Settings.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// Copyright (c) 2016 Framefield. All rights reserved.
// Released under the MIT license. (see LICENSE.txt)
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
namespace Framefield.Core
{
public class Settings
{
public Object this[string key]
{
get
{
if (_values.ContainsKey(key))
{
return _values[key];
}
throw new ArgumentException(String.Format("Requesting undefined setting: '{0}'", key));
}
set
{
_values[key] = value;
}
}
public Settings(String filepath)
{
_filepath = filepath;
if (File.Exists(_filepath))
{
string json = null;
using (var reader = new StreamReader(_filepath))
{
json = reader.ReadToEnd();
}
_values = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
}
else
{
_values = new Dictionary<string, object>();
}
}
~Settings()
{
Save();
}
public bool Contains(string key)
{
return _values.ContainsKey(key);
}
public void Remove(string key)
{
_values.Remove(key);
}
public string TryGet(string key, string defaultValue)
{
object value;
if (_values.TryGetValue(key, out value))
{
return Convert.ToString(value);
}
return defaultValue;
}
public double TryGet(string key, double defaultValue)
{
object value;
if (_values.TryGetValue(key, out value))
{
return Convert.ToDouble(value);
}
return defaultValue;
}
public bool TryGet(string key, bool defaultValue)
{
object value;
if (_values.TryGetValue(key, out value))
{
return Convert.ToBoolean(value);
}
return defaultValue;
}
public string GetOrSetDefault(string key, string defaultValue)
{
if (!_values.ContainsKey(key))
{
_values[key] = defaultValue;
return defaultValue;
}
else
{
return Convert.ToString(_values[key]);
}
}
public double GetOrSetDefault(string key, double defaultValue)
{
if (!_values.ContainsKey(key))
{
_values[key] = defaultValue;
return defaultValue;
}
else
{
return Convert.ToDouble(_values[key]);
}
}
public bool GetOrSetDefault(string key, bool defaultValue)
{
if (!_values.ContainsKey(key))
{
_values[key] = defaultValue;
return defaultValue;
}
else
{
return Convert.ToBoolean(_values[key]);
}
}
public void Save()
{
SaveAs(_filepath);
}
public void SaveAs(string filePath)
{
var json = JsonConvert.SerializeObject(_values, Formatting.Indented);
using (var sw = new StreamWriter(filePath))
{
sw.Write(json);
}
}
private readonly string _filepath;
private Dictionary<String, Object> _values;
}
}