84 lines
2.5 KiB
C#
84 lines
2.5 KiB
C#
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
|
|
{
|
|
var token = Settings.SelectToken($"ConnectionStrings.{connectionStringName}");
|
|
|
|
if (token == null) return false;
|
|
|
|
connectionString = token.ToObject<string>();
|
|
|
|
if (!string.IsNullOrEmpty(connectionString)) return true;
|
|
else return false;
|
|
}
|
|
catch { return false; }
|
|
}
|
|
|
|
public static bool TryGetSettingString(string sectionName, string key, out string setting)
|
|
{
|
|
setting = string.Empty;
|
|
|
|
try
|
|
{
|
|
var token = Settings.SelectToken($"{sectionName}.{key}");
|
|
|
|
if (token == null) return false;
|
|
|
|
setting = token.ToObject<string>();
|
|
|
|
if(!string.IsNullOrEmpty(setting)) return true;
|
|
else return false;
|
|
}
|
|
catch { return false; }
|
|
}
|
|
|
|
public static bool TryGetSettingInt(string sectionName, string key, out int setting)
|
|
{
|
|
setting = 0;
|
|
|
|
try
|
|
{
|
|
var token = Settings.SelectToken($"{sectionName}.{key}");
|
|
|
|
if (token == null) return false;
|
|
|
|
if (int.TryParse(token.ToObject<string>(), out setting)) return true;
|
|
else return false;
|
|
}
|
|
catch { return false; }
|
|
}
|
|
|
|
public static void InitializeSettings()
|
|
{
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
}
|