2019-03-17 18:37:50 -04:00
|
|
|
|
using Newtonsoft.Json;
|
2020-01-17 18:31:53 -05:00
|
|
|
|
using SharedLibraryCore.Exceptions;
|
2018-04-08 02:44:42 -04:00
|
|
|
|
using SharedLibraryCore.Interfaces;
|
2019-04-12 23:25:18 -04:00
|
|
|
|
using System;
|
2018-03-18 22:25:11 -04:00
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
2018-04-08 02:44:42 -04:00
|
|
|
|
namespace SharedLibraryCore.Configuration
|
2018-03-18 22:25:11 -04:00
|
|
|
|
{
|
|
|
|
|
public class BaseConfigurationHandler<T> : IConfigurationHandler<T> where T : IBaseConfiguration
|
|
|
|
|
{
|
2019-03-17 18:37:50 -04:00
|
|
|
|
readonly string _configurationPath;
|
2018-03-18 22:25:11 -04:00
|
|
|
|
T _configuration;
|
|
|
|
|
|
|
|
|
|
public BaseConfigurationHandler(string fn)
|
|
|
|
|
{
|
2019-03-17 18:37:50 -04:00
|
|
|
|
_configurationPath = Path.Join(Utilities.OperatingDirectory, "Configuration", $"{fn}.json");
|
2018-03-18 22:25:11 -04:00
|
|
|
|
Build();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Build()
|
|
|
|
|
{
|
2019-03-18 11:36:31 -04:00
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var configContent = File.ReadAllText(_configurationPath);
|
|
|
|
|
_configuration = JsonConvert.DeserializeObject<T>(configContent);
|
|
|
|
|
}
|
2020-01-20 12:49:56 -05:00
|
|
|
|
|
|
|
|
|
catch (FileNotFoundException)
|
|
|
|
|
{
|
|
|
|
|
_configuration = default;
|
|
|
|
|
}
|
|
|
|
|
|
2020-01-17 18:31:53 -05:00
|
|
|
|
catch (Exception e)
|
2019-03-17 18:37:50 -04:00
|
|
|
|
{
|
2020-01-17 18:31:53 -05:00
|
|
|
|
throw new ConfigurationException("MANAGER_CONFIGURATION_ERROR")
|
|
|
|
|
{
|
|
|
|
|
Errors = new[] { e.Message }
|
|
|
|
|
};
|
2019-03-17 18:37:50 -04:00
|
|
|
|
}
|
2018-03-18 22:25:11 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Task Save()
|
|
|
|
|
{
|
|
|
|
|
var appConfigJSON = JsonConvert.SerializeObject(_configuration, Formatting.Indented);
|
2019-03-17 18:37:50 -04:00
|
|
|
|
return File.WriteAllTextAsync(_configurationPath, appConfigJSON);
|
2018-03-18 22:25:11 -04:00
|
|
|
|
}
|
|
|
|
|
|
2019-03-17 18:37:50 -04:00
|
|
|
|
public T Configuration()
|
|
|
|
|
{
|
|
|
|
|
return _configuration;
|
|
|
|
|
}
|
2018-03-18 22:25:11 -04:00
|
|
|
|
|
|
|
|
|
public void Set(T config)
|
|
|
|
|
{
|
|
|
|
|
_configuration = config;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|