IW4M-Admin/Application/Misc/BaseConfigurationHandler.cs

101 lines
2.8 KiB
C#
Raw Permalink Normal View History

2022-01-28 10:35:01 -05:00
using SharedLibraryCore;
using SharedLibraryCore.Exceptions;
2018-04-08 02:44:42 -04:00
using SharedLibraryCore.Interfaces;
using System;
using System.IO;
2022-01-28 10:35:01 -05:00
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
2022-01-28 10:35:01 -05:00
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace IW4MAdmin.Application.Misc
{
/// <summary>
/// default implementation of IConfigurationHandler
/// </summary>
/// <typeparam name="T">base configuration type</typeparam>
public class BaseConfigurationHandler<T> : IConfigurationHandler<T> where T : IBaseConfiguration
{
2022-01-28 10:35:01 -05:00
private T _configuration;
private readonly SemaphoreSlim _onSaving;
2022-01-28 10:35:01 -05:00
private readonly JsonSerializerOptions _serializerOptions;
2022-01-28 10:35:01 -05:00
public BaseConfigurationHandler(string fileName)
{
2022-01-28 10:35:01 -05:00
_serializerOptions = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
2022-01-28 10:35:01 -05:00
};
_serializerOptions.Converters.Add(new JsonStringEnumConverter());
_onSaving = new SemaphoreSlim(1, 1);
2022-01-28 10:35:01 -05:00
FileName = Path.Join(Utilities.OperatingDirectory, "Configuration", $"{fileName}.json");
}
public BaseConfigurationHandler() : this(typeof(T).Name)
{
}
~BaseConfigurationHandler()
{
_onSaving.Dispose();
}
public string FileName { get; }
2022-01-28 10:35:01 -05:00
public async Task BuildAsync()
{
try
{
2022-01-28 10:35:01 -05:00
await using var fileStream = File.OpenRead(FileName);
_configuration = await JsonSerializer.DeserializeAsync<T>(fileStream, _serializerOptions);
}
catch (FileNotFoundException)
{
_configuration = default;
}
catch (Exception e)
{
throw new ConfigurationException("Could not load configuration")
{
Errors = new[] { e.Message },
ConfigurationFileName = FileName
};
}
}
2022-01-26 11:32:16 -05:00
public async Task Save()
{
try
{
await _onSaving.WaitAsync();
2022-01-29 14:30:48 -05:00
await using var fileStream = File.Create(FileName);
2022-01-28 10:35:01 -05:00
await JsonSerializer.SerializeAsync(fileStream, _configuration, _serializerOptions);
}
finally
{
if (_onSaving.CurrentCount == 0)
{
_onSaving.Release(1);
}
}
}
public T Configuration()
{
return _configuration;
}
public void Set(T config)
{
_configuration = config;
}
}
}