Updated the way application settings are loaded and added some intialization functions to the various manager classes to load and validate all the user supplied options at start up instead of constantly reevaluating them over the course of the application's runtime.

This commit is contained in:
2021-03-10 21:27:19 -06:00
parent 3d3b9c1e68
commit baf2518fe8
5 changed files with 97 additions and 61 deletions
+36 -11
View File
@@ -1,17 +1,25 @@
using System.IO;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using Newtonsoft.Json.Linq;
namespace SecureCore
{
public static class AppSettingsManager
{
private static JObject Settings { get; set; }
private static string AppSettingsPath { get; } = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
public static bool TryGetConnectionString(string connectionStringName, out string connectionString)
{
connectionString = string.Empty;
try
{
connectionString = GetConfiguration().GetConnectionString(connectionStringName);
var token = Settings.SelectToken($"ConnectionStrings.{connectionStringName}");
if (token == null) return false;
connectionString = token.ToObject<string>();
if (!string.IsNullOrEmpty(connectionString)) return true;
else return false;
@@ -25,7 +33,11 @@ namespace SecureCore
try
{
setting = GetConfiguration().GetSection(sectionName)[key];
var token = Settings.SelectToken($"{sectionName}.{key}");
if (token == null) return false;
setting = token.ToObject<string>();
if(!string.IsNullOrEmpty(setting)) return true;
else return false;
@@ -39,20 +51,33 @@ namespace SecureCore
try
{
var settingString = GetConfiguration().GetSection(sectionName)[key];
var token = Settings.SelectToken($"{sectionName}.{key}");
if (int.TryParse(settingString, out setting)) return true;
if (token == null) return false;
if (int.TryParse(token.ToObject<string>(), out setting)) return true;
else return false;
}
catch { return false; }
}
private static IConfigurationRoot GetConfiguration()
public static void InitializeSettings()
{
return new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
if (Settings != null) throw new InvalidOperationException("The in memory JSON settings has already been loaded. Operation aborted.");
if (!File.Exists(AppSettingsPath)) throw new FileNotFoundException($"The app settings file '{AppSettingsPath}' couldn't be found.");
try
{
using var reader = new StreamReader(AppSettingsPath);
Settings = JObject.Parse(reader.ReadToEnd());
reader.Close();
}
catch
{
throw;
}
}
}
}