/
SettingsStore.cs
74 lines (65 loc) · 2.41 KB
/
SettingsStore.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using Newtonsoft.Json;
using LetsEncrypt.Azure.Core.Models;
using System.Diagnostics;
namespace LetsEncrypt.Azure.Core
{
public class SettingsStore
{
private static readonly SettingsStore _instance = new SettingsStore();
private string _settingsFilePath;
public static SettingsStore Instance { get { return _instance; } }
public SettingsStore()
{
string folder;
if (Util.IsAzure)
{
// e.g. D:\home\SiteExtensions\SettingsAPISample -> 'SettingsAPISample'
string extensionName = "letsencrypt";
// e.g. d:\home\data\SettingsAPISample
folder = Path.Combine(Environment.ExpandEnvironmentVariables(@"%HOME%\data"), extensionName);
}
else
{
// Use regular App_Data outside of Azure
folder = HostingEnvironment.MapPath("~/App_Data") ?? Path.Combine(Directory.GetCurrentDirectory(), "App_Data");
}
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
_settingsFilePath = Path.Combine(folder, "settings.json");
}
public List<SettingEntry> Load()
{
if (File.Exists(_settingsFilePath))
{
Trace.TraceInformation($"Trying to load setttings from {_settingsFilePath}");
string contents = String.Empty;
try
{
contents = File.ReadAllText(_settingsFilePath);
return JsonConvert.DeserializeObject<List<SettingEntry>>(contents);
} catch(Exception e)
{
Trace.TraceError($"Unable to deserialize content from {_settingsFilePath} contents was: '{contents}'");
return new List<SettingEntry>();
}
}
else
{
Trace.TraceInformation($"Settings not found at {_settingsFilePath} returning empty settings");
return new List<SettingEntry>();
}
}
public void Save(List<SettingEntry> settings)
{
File.WriteAllText(_settingsFilePath, JsonConvert.SerializeObject(settings));
}
}
}