72 lines
2.3 KiB
C#
72 lines
2.3 KiB
C#
|
using System;
|
|||
|
using System.Dynamic;
|
|||
|
using System.Reflection;
|
|||
|
using System.Runtime.CompilerServices;
|
|||
|
using Newtonsoft.Json;
|
|||
|
|
|||
|
[assembly: InternalsVisibleTo("deployment.tests")]
|
|||
|
namespace greyn.Deployment
|
|||
|
{
|
|||
|
public static class Configurator<T> where T : new()
|
|||
|
{
|
|||
|
private const string confpath = "appsettings.json";
|
|||
|
private static FileSystemWatcher appsettingsWatcher = new FileSystemWatcher(".");
|
|||
|
|
|||
|
public static event EventHandler Changed;
|
|||
|
public static event System.IO.ErrorEventHandler Error;
|
|||
|
|
|||
|
private static T config;
|
|||
|
|
|||
|
public static T Load()
|
|||
|
{
|
|||
|
if (File.Exists(confpath))
|
|||
|
{
|
|||
|
/*
|
|||
|
* if the configuration expects new values we write them in.
|
|||
|
* if you left other junk for whatever reason, get rekt
|
|||
|
*/
|
|||
|
config = JsonConvert.DeserializeObject<T>(File.ReadAllText(confpath)) ?? new T();
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
config = new T();
|
|||
|
}
|
|||
|
File.WriteAllText(confpath, JsonConvert.SerializeObject(config, Formatting.Indented));
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
appsettingsWatcher.Filter = confpath;
|
|||
|
|
|||
|
appsettingsWatcher.NotifyFilter = NotifyFilters.LastWrite
|
|||
|
| NotifyFilters.Security
|
|||
|
| NotifyFilters.Size;
|
|||
|
|
|||
|
appsettingsWatcher.Changed += internalOnChanged;
|
|||
|
appsettingsWatcher.Created += internalOnChanged;
|
|||
|
appsettingsWatcher.Deleted += internalOnChanged;
|
|||
|
appsettingsWatcher.Renamed += internalOnChanged;
|
|||
|
appsettingsWatcher.Error += Error;
|
|||
|
|
|||
|
appsettingsWatcher.EnableRaisingEvents = true;
|
|||
|
|
|||
|
return config;
|
|||
|
}
|
|||
|
|
|||
|
internal static void internalOnChanged(object sender, FileSystemEventArgs e)
|
|||
|
{
|
|||
|
appsettingsWatcher.EnableRaisingEvents = false;
|
|||
|
|
|||
|
Load();
|
|||
|
Changed(sender, new ConfigChangedEventArgs(){NewConfig = config});
|
|||
|
}
|
|||
|
|
|||
|
//I would like to just pudate the values on our held reference, but we'd have to update each value by reflection.
|
|||
|
//2lazy.
|
|||
|
public class ConfigChangedEventArgs : EventArgs
|
|||
|
{
|
|||
|
public T NewConfig;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|