Files
TinyInvoice/Server/Data/SettingsData.cs
2024-11-14 21:17:27 +01:00

70 lines
2.3 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
using Server.Model;
namespace Server.Data
{
public class SettingsData
{
#region Public Properties
public static SettingsData Instance { get; set; } = new();
public Address SellerAddress { get; set; } = new();
public PaymentData PaymentData { get; set; } = new();
public bool Kleinunternehmer { get; set; }
public string? Comment { get; set; }
public string? Logo { get; set; }
#endregion
/// <summary>
/// Retrieves the file path for the settings JSON file.
/// </summary>
/// <returns>The file path of the settings JSON file as a string.</returns>
private static string GetFilePath()
{
var parentDirectory = Directory.GetParent(Directory.GetCurrentDirectory());
if (parentDirectory == null) return "Settings.json";
return Path.Combine(parentDirectory.FullName, "Settings.json");
}
#region Public Method Load
/// <summary>
/// Asynchronously loads the settings from a JSON file and updates the current instance of <see cref="SettingsData" />.
/// </summary>
/// <returns>A task that represents the asynchronous load operation.</returns>
public static async Task LoadAsync()
{
if (!File.Exists(GetFilePath())) return;
var jsonString = await File.ReadAllTextAsync(GetFilePath());
var deserialized = JsonSerializer.Deserialize<SettingsData>(jsonString)!;
Instance = deserialized;
}
#endregion
#region Public Method SaveAsync
/// <summary>
/// Serializes the current instance of <see cref="SettingsData" /> and saves it to a JSON file asynchronously.
/// </summary>
/// <returns>A task that represents the asynchronous save operation.</returns>
public static async Task SaveAsync()
{
var jsonString = JsonSerializer.Serialize(Instance, new JsonSerializerOptions { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull});
await File.WriteAllTextAsync(GetFilePath(), jsonString);
}
#endregion
}
}