You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
3.0 KiB
102 lines
3.0 KiB
using Microsoft.Extensions.Configuration;
|
|
using System.Configuration;
|
|
using System.Reflection;
|
|
|
|
namespace DealerSelection.Common.Configuration;
|
|
|
|
public static class ConfigurationHelper
|
|
{
|
|
public static int SetEnvironmentVariables(string settingsFile)
|
|
{
|
|
IConfigurationRoot? config = LoadSettingsFile(settingsFile);
|
|
int count = 0;
|
|
|
|
if (config != null)
|
|
{
|
|
foreach (KeyValuePair<string, string?> pair in config.AsEnumerable())
|
|
{
|
|
if (pair.Value == null)
|
|
continue;
|
|
|
|
Environment.SetEnvironmentVariable(pair.Key, pair.Value);
|
|
count++;
|
|
}
|
|
}
|
|
|
|
return count;
|
|
}
|
|
|
|
public static IConfigurationRoot? LoadSettingsFile(string settingsFile)
|
|
{
|
|
string basePath = FindBaseLocation(settingsFile);
|
|
IConfigurationBuilder builder = new ConfigurationBuilder()
|
|
.SetBasePath(basePath)
|
|
.AddJsonFile(settingsFile);
|
|
|
|
return builder.Build();
|
|
}
|
|
|
|
public static string GetConnectionString(string cxnName, string cfgFile = "connectionString.json")
|
|
{
|
|
IConfigurationRoot? root = LoadSettingsFile(cfgFile);
|
|
string settings = root.GetConnectionString(cxnName);
|
|
if (!string.IsNullOrEmpty(settings))
|
|
{
|
|
return settings;
|
|
}
|
|
throw new ConfigurationErrorsException($"Connection stirng {cxnName} not found in connection strings cfg file {cfgFile}.");
|
|
}
|
|
private static string FindBaseLocation(string settingsFile)
|
|
{
|
|
string?[] baseLocations =
|
|
{
|
|
Directory.GetCurrentDirectory(),
|
|
AppDomain.CurrentDomain.BaseDirectory,
|
|
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
|
|
};
|
|
|
|
foreach (string? baseLocation in baseLocations)
|
|
{
|
|
if (string.IsNullOrEmpty(baseLocation))
|
|
continue;
|
|
string path = Path.Combine(baseLocation, settingsFile);
|
|
if (File.Exists(path))
|
|
return baseLocation;
|
|
}
|
|
|
|
return baseLocations[1]!;
|
|
}
|
|
|
|
public static T? GetSetting<T>(string key, bool mustExist)
|
|
{
|
|
return GetSetting(key, default(T), mustExist);
|
|
}
|
|
|
|
public static T? GetSetting<T>(string key, T? defaultValue = default)
|
|
{
|
|
return GetSetting(key, defaultValue, false);
|
|
}
|
|
|
|
public static T GetSetting<T>(string key, T defaultValue, bool mustExist)
|
|
{
|
|
string? valString = Environment.GetEnvironmentVariable(key);
|
|
|
|
if (valString == null)
|
|
{
|
|
if (mustExist)
|
|
{
|
|
throw new ConfigurationErrorsException($"Setting {key} not found");
|
|
}
|
|
return defaultValue;
|
|
}
|
|
|
|
try
|
|
{
|
|
return (T)Convert.ChangeType(valString, typeof(T));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw new ConfigurationErrorsException($"Settings {key} ('{valString}') cannot be converted to type {typeof(T).Name}", ex);
|
|
}
|
|
}
|
|
}
|