Init...
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
|
||||
namespace Swan.Configuration
|
||||
{
|
||||
/// <summary>
|
||||
/// Base class for objects whose configuration may be locked,
|
||||
/// thus becoming read-only, at a certain moment in their lifetime.
|
||||
/// </summary>
|
||||
public abstract class ConfiguredObject
|
||||
{
|
||||
private readonly object _syncRoot = new object();
|
||||
private bool _configurationLocked;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether s configuration has already been locked
|
||||
/// and has therefore become read-only.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <see langword="true"/> if the configuration is locked; otherwise, <see langword="false"/>.
|
||||
/// </value>
|
||||
/// <seealso cref="EnsureConfigurationNotLocked"/>
|
||||
protected bool ConfigurationLocked
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
return _configurationLocked;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <para>Locks this instance's configuration, preventing further modifications.</para>
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>Configuration locking must be enforced by derived classes
|
||||
/// by calling <see cref="EnsureConfigurationNotLocked"/> at the start
|
||||
/// of methods and property setters that could change the object's
|
||||
/// configuration.</para>
|
||||
/// <para>Immediately before locking the configuration, this method calls <see cref="OnBeforeLockConfiguration"/>
|
||||
/// as a last chance to validate configuration data, and to lock the configuration of contained objects.</para>
|
||||
/// </remarks>
|
||||
/// <seealso cref="OnBeforeLockConfiguration"/>
|
||||
protected void LockConfiguration()
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
if (_configurationLocked)
|
||||
return;
|
||||
|
||||
OnBeforeLockConfiguration();
|
||||
_configurationLocked = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called immediately before locking the configuration.
|
||||
/// </summary>
|
||||
/// <seealso cref="LockConfiguration"/>
|
||||
protected virtual void OnBeforeLockConfiguration()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a module's configuration has become read-only
|
||||
/// and, if so, throws an <see cref="InvalidOperationException"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The configuration is locked.</exception>
|
||||
/// <seealso cref="ConfigurationLocked"/>
|
||||
protected void EnsureConfigurationNotLocked()
|
||||
{
|
||||
if (ConfigurationLocked)
|
||||
throw new InvalidOperationException($"Configuration of this {GetType().Name} instance is locked.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
|
||||
namespace Swan.Configuration
|
||||
{
|
||||
/// <summary>
|
||||
/// An attribute used to include additional information to a Property for serialization.
|
||||
///
|
||||
/// Previously we used DisplayAttribute from DataAnnotation.
|
||||
/// </summary>
|
||||
/// <seealso cref="System.Attribute" />
|
||||
[AttributeUsage(AttributeTargets.Property)]
|
||||
public sealed class PropertyDisplayAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the name.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The name.
|
||||
/// </value>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the description.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The description.
|
||||
/// </value>
|
||||
public string Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the group.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The name of the group.
|
||||
/// </value>
|
||||
public string GroupName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the default value.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The default value.
|
||||
/// </value>
|
||||
public object DefaultValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the format string to call with method <c>ToString</c>.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The format.
|
||||
/// </value>
|
||||
public string Format { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Swan.Formatters;
|
||||
using Swan.Reflection;
|
||||
|
||||
namespace Swan.Configuration
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a provider to save and load settings using a plain JSON file.
|
||||
/// </summary>
|
||||
/// <example>
|
||||
/// The following example shows how to save and load settings.
|
||||
/// <code>
|
||||
/// using Swan.Configuration;
|
||||
///
|
||||
/// public class Example
|
||||
/// {
|
||||
/// public static void Main()
|
||||
/// {
|
||||
/// // get user from settings
|
||||
/// var user = SettingsProvider<Settings>.Instance.Global.User;
|
||||
///
|
||||
/// // modify the port
|
||||
/// SettingsProvider<Settings>.Instance.Global.Port = 20;
|
||||
///
|
||||
/// // if we want these settings to persist
|
||||
/// SettingsProvider<Settings>.Instance.PersistGlobalSettings();
|
||||
/// }
|
||||
///
|
||||
/// public class Settings
|
||||
/// {
|
||||
/// public int Port { get; set; } = 9696;
|
||||
///
|
||||
/// public string User { get; set; } = "User";
|
||||
/// }
|
||||
/// }
|
||||
/// </code>
|
||||
/// </example>
|
||||
/// <typeparam name="T">The type of settings model.</typeparam>
|
||||
public sealed class SettingsProvider<T>
|
||||
: SingletonBase<SettingsProvider<T>>
|
||||
{
|
||||
private readonly object _syncRoot = new object();
|
||||
|
||||
private T _global;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the configuration file path. By default the entry assembly directory is used
|
||||
/// and the filename is 'appsettings.json'.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The configuration file path.
|
||||
/// </value>
|
||||
public string ConfigurationFilePath { get; set; } =
|
||||
Path.Combine(SwanRuntime.EntryAssemblyDirectory, "appsettings.json");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the global settings object.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// The global settings object.
|
||||
/// </value>
|
||||
public T Global
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
if (Equals(_global, default(T)))
|
||||
ReloadGlobalSettings();
|
||||
|
||||
return _global;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reloads the global settings.
|
||||
/// </summary>
|
||||
public void ReloadGlobalSettings()
|
||||
{
|
||||
if (File.Exists(ConfigurationFilePath) == false || File.ReadAllText(ConfigurationFilePath).Length == 0)
|
||||
{
|
||||
ResetGlobalSettings();
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_syncRoot)
|
||||
_global = Json.Deserialize<T>(File.ReadAllText(ConfigurationFilePath));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the global settings.
|
||||
/// </summary>
|
||||
public void PersistGlobalSettings() => File.WriteAllText(ConfigurationFilePath, Json.Serialize(Global, true));
|
||||
|
||||
/// <summary>
|
||||
/// Updates settings from list.
|
||||
/// </summary>
|
||||
/// <param name="propertyList">The list.</param>
|
||||
/// <returns>
|
||||
/// A list of settings of type ref="ExtendedPropertyInfo".
|
||||
/// </returns>
|
||||
/// <exception cref="ArgumentNullException">propertyList.</exception>
|
||||
public List<string> RefreshFromList(List<ExtendedPropertyInfo<T>> propertyList)
|
||||
{
|
||||
if (propertyList == null)
|
||||
throw new ArgumentNullException(nameof(propertyList));
|
||||
|
||||
var changedSettings = new List<string>();
|
||||
var globalProps = PropertyTypeCache.DefaultCache.Value.RetrieveAllProperties<T>();
|
||||
|
||||
foreach (var property in propertyList)
|
||||
{
|
||||
var propertyInfo = globalProps.FirstOrDefault(x => x.Name == property.Property);
|
||||
|
||||
if (propertyInfo == null) continue;
|
||||
|
||||
var originalValue = propertyInfo.GetValue(Global);
|
||||
var isChanged = propertyInfo.PropertyType.IsArray
|
||||
? property.Value is IEnumerable enumerable && propertyInfo.TrySetArray(enumerable.Cast<object>(), Global)
|
||||
: SetValue(property.Value, originalValue, propertyInfo);
|
||||
|
||||
if (!isChanged) continue;
|
||||
|
||||
changedSettings.Add(property.Property);
|
||||
PersistGlobalSettings();
|
||||
}
|
||||
|
||||
return changedSettings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list.
|
||||
/// </summary>
|
||||
/// <returns>A List of ExtendedPropertyInfo of the type T.</returns>
|
||||
public List<ExtendedPropertyInfo<T>>? GetList()
|
||||
{
|
||||
var jsonData = Json.Deserialize(Json.Serialize(Global)) as Dictionary<string, object>;
|
||||
|
||||
return jsonData?.Keys
|
||||
.Select(p => new ExtendedPropertyInfo<T>(p) { Value = jsonData[p] })
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the global settings.
|
||||
/// </summary>
|
||||
public void ResetGlobalSettings()
|
||||
{
|
||||
lock (_syncRoot)
|
||||
_global = Activator.CreateInstance<T>();
|
||||
|
||||
PersistGlobalSettings();
|
||||
}
|
||||
|
||||
private bool SetValue(object property, object originalValue, PropertyInfo propertyInfo)
|
||||
{
|
||||
switch (property)
|
||||
{
|
||||
case null when originalValue == null:
|
||||
break;
|
||||
case null:
|
||||
propertyInfo.SetValue(Global, null);
|
||||
return true;
|
||||
default:
|
||||
if (propertyInfo.PropertyType.TryParseBasicType(property, out var propertyValue) &&
|
||||
!propertyValue.Equals(originalValue))
|
||||
{
|
||||
propertyInfo.SetValue(Global, propertyValue);
|
||||
return true;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user