Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swapping from ConfigurationManager to XElement to avoid "The configur… #4

Merged
merged 1 commit into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions ApiClient/ApiClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,28 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<SignAssembly>False</SignAssembly>
</PropertyGroup>

<ItemGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<Optimize>False</Optimize>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<Optimize>False</Optimize>
</PropertyGroup>

<ItemGroup>
<Compile Remove="Properties\**" />
<EmbeddedResource Remove="Properties\**" />
<None Remove="Properties\**" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="8.0.0" />
</ItemGroup>

</Project>
19 changes: 7 additions & 12 deletions ApiClient/Core/Configuration/ApiClientConfigHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@

using ApiClient.Core.Configuration.Interfaces;
using ApiClient.Exception;
using System.Configuration;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace ApiClient.Core.Configuration
{
Expand All @@ -24,10 +24,10 @@ public class ApiClientConfigHelper : ConfigurationHelper, IApiClientConfigHelper
// Static members are 'eagerly initialized', that is,
// immediately when class is loaded for the first time.
// .NET guarantees thread safety for static initialization
private static readonly ExeConfigurationFileMap _map = GetMap();
private static readonly string _configFile = GetConfigFilePath();
private static readonly ApiClientConfigHelper _thisInstance = new();

public static ExeConfigurationFileMap Map { get => _map; }
public static string ConfigFile { get => _configFile; }

private const string _ClientId = "ApiClient.ClientId";
private const string _ClientSecret = "ApiClient.ClientSecret";
Expand All @@ -40,25 +40,20 @@ private ApiClientConfigHelper()
{
try
{
Console.WriteLine($"map.ExeConfigFilename {_map.ExeConfigFilename}");
_config = ConfigurationManager.OpenMappedExeConfiguration(_map, ConfigurationUserLevel.None);
Console.WriteLine($"XML file: {_configFile}");
_xconfig = XElement.Load(_configFile);
}
catch (System.Exception ex)
{
throw new ApiException($"Error in ApiClientConfigHelper on opening up apiclient.config {ex.Message}");
}
}

private static ExeConfigurationFileMap GetMap()
private static string GetConfigFilePath()
{
var environmentPath = Environment.GetEnvironmentVariable("APICLIENT_CONFIG_PATH");
var filePath = environmentPath ?? FindSolutionDir();

var map = new ExeConfigurationFileMap
{
ExeConfigFilename = filePath
};
return map;
return filePath;
}

private static string FindSolutionDir()
Expand Down
53 changes: 26 additions & 27 deletions ApiClient/Core/Configuration/ConfigurationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@
//-----------------------------------------------------------------------

using ApiClient.Core.Configuration.Interfaces;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using ConfigurationManager = System.Configuration.ConfigurationManager;
using System.Xml.Linq;

namespace ApiClient.Core.Configuration
{
Expand All @@ -27,7 +26,7 @@ public class ConfigurationHelper : IConfigurationHelper
/// <summary>
/// This object represents the config file
/// </summary>
protected System.Configuration.Configuration? _config;
protected XElement? _xconfig;

/// <summary>
/// Updates the value for the specified key in the AppSettings of the Config file.
Expand All @@ -36,10 +35,29 @@ public class ConfigurationHelper : IConfigurationHelper
/// <param name="value">The value.</param>
public void Update(string key, string value)
{
if (_config?.AppSettings.Settings[key] == null)
_config?.AppSettings.Settings.Add(key, value);
if (Setting(key) == null)
AppSettings?.Add(CreateElement(key, value));
else
_config.AppSettings.Settings[key].Value = value;
Value(Setting(key))!.SetValue(value);
}

public XElement? AppSettings { get => _xconfig?.Descendants("appSettings")?.FirstOrDefault(); }

public IEnumerable<XElement>? Settings { get => AppSettings?.Descendants("add"); }

public static XElement CreateElement(string key, string value)
{
return new XElement("add", new XAttribute("key", key), new XAttribute("value", value));
}

public XElement? Setting(string name)
{
return Settings?.Where(e => e.Attributes().Where(r => r.Name == "key" && r.Value == name).Any()).FirstOrDefault();
}

public static XAttribute? Value(XElement? setting)
{
return setting?.Attributes().Where(l => l.Name == "value").FirstOrDefault();
}

/// <summary>
Expand All @@ -51,7 +69,7 @@ public string GetAttribute(string attrName)
{
try
{
return _config?.AppSettings.Settings[attrName]?.Value!;
return Value(Setting(attrName))?.Value!;
}
catch (System.Exception)
{
Expand Down Expand Up @@ -82,26 +100,7 @@ public bool GetBooleanAttribute(string attrName)
/// </summary>
public void Save()
{
try
{
_config?.Save(ConfigurationSaveMode.Modified);
}
catch (ConfigurationErrorsException cee)
{
if (!cee.Message.StartsWith("The configuration file has been changed by another program."))
throw;

_config = ConfigurationManager.OpenMappedExeConfiguration(ApiClientConfigHelper.Map, ConfigurationUserLevel.None);
}
ConfigurationManager.RefreshSection("appSettings");
}

/// <summary>
/// Refreshes the application settingses.
/// </summary>
public void RefreshAppSettings()
{
ConfigurationManager.RefreshSection("appSettings");
_xconfig!.Save(ApiClientConfigHelper.ConfigFile);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,5 @@ public interface IConfigurationHelper
/// Saves changes to the Config file
/// </summary>
void Save();

/// <summary>
/// Refreshes the application settingses.
/// </summary>
void RefreshAppSettings();
}
}