Added json configuration

This commit is contained in:
TheXamlGuy
2024-01-05 17:34:09 +00:00
parent d94add17f9
commit e180c966ff
33 changed files with 527 additions and 40 deletions
@@ -1,3 +1,5 @@
using Hyperbar.Extensions;
using Hyperbar.Lifecycles;
using Microsoft.Extensions.DependencyInjection;
namespace Hyperbar.Desktop.Contextual;
@@ -1,4 +1,7 @@
namespace Hyperbar.Desktop.Contextual;
using Hyperbar.Lifecycles;
using Hyperbar.Templates;
namespace Hyperbar.Desktop.Contextual;
public class ContextualCommandViewModel(ITemplateFactory templateFactory) :
ICommandViewModel,
@@ -1,3 +1,5 @@
using Hyperbar.Extensions;
using Hyperbar.Lifecycles;
using Microsoft.Extensions.DependencyInjection;
namespace Hyperbar.Desktop.Primary;
@@ -1,4 +1,12 @@
namespace Hyperbar.Desktop.Primary;
using Hyperbar.Lifecycles;
using Hyperbar.Templates;
namespace Hyperbar.Desktop.Primary;
public class PrimaryCommandConfiguration
{
}
public class PrimaryCommandViewModel(ITemplateFactory templateFactory) :
ICommandViewModel,
+5 -4
View File
@@ -1,6 +1,8 @@
using Hyperbar.Desktop.Contextual;
using Hyperbar.Desktop.Controls;
using Hyperbar.Desktop.Primary;
using Hyperbar.Lifecycles;
using Hyperbar.Templates;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.UI.Xaml;
@@ -30,11 +32,10 @@ public partial class App :
services.AddTransient<ITemplateFactory, TemplateFactory>();
services.AddTransient<ITemplateGeneratorFactory, TemplateGeneratorFactory>();
services.AddDataTemplate<CommandViewModel, CommandView>("Commands");
services.AddDataTemplate<CommandViewModel, CommandView>();
// Commands
services.AddSomething<ContextualCommandBuilder>();
services.AddSomething<PrimaryCommandBuilder>();
services.AddCommandBuilder<ContextualCommandBuilder>("Contexual.Commands");
services.AddCommandBuilder<PrimaryCommandBuilder>("Primary.Command");
services.AddTransient(provider =>
{
@@ -1,11 +1,12 @@
using Hyperbar.Desktop.Controls;
using Hyperbar.Lifecycles;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
namespace Hyperbar.Desktop;
public class AppInitializer([FromKeyedServices("Commands")] CommandView view,
[FromKeyedServices("Commands")] CommandViewModel viewModel,
public class AppInitializer([FromKeyedServices(nameof(CommandView))] CommandView view,
[FromKeyedServices(nameof(CommandView))] CommandViewModel viewModel,
DesktopFlyout desktopFlyout) :
IInitializer
{
@@ -1,11 +1,14 @@
using Microsoft.Extensions.DependencyInjection;
using Hyperbar.Lifecycles;
using Hyperbar.Templates;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Hyperbar.Desktop
{
public static class IServiceCollectionExtensions
{
public static IServiceCollection AddSomething<TCommandBuilder>(this IServiceCollection services)
public static IServiceCollection AddCommandBuilder<TCommandBuilder>(this IServiceCollection services,
string key)
where TCommandBuilder :
ICommandBuilder, new()
{
@@ -1,4 +1,5 @@
using Microsoft.Extensions.DependencyInjection;
using Hyperbar.Templates;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
@@ -1,4 +1,5 @@
using Microsoft.UI.Xaml;
using Hyperbar.Templates;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
namespace Hyperbar.Desktop;
+3 -1
View File
@@ -1,4 +1,6 @@
using System.Collections;
using Hyperbar.Lifecycles;
using Hyperbar.Templates;
using System.Collections;
using System.Collections.Generic;
namespace Hyperbar.Desktop;
@@ -0,0 +1,21 @@
using Microsoft.Extensions.Configuration;
namespace Hyperbar.Configurations;
public class ConfigurationWriter<TConfiguration>(IConfiguration rootConfiguration) :
IConfigurationWriter<TConfiguration> where TConfiguration : class, new()
{
public void Write(string section, TConfiguration configuration)
{
if (rootConfiguration is IConfigurationRoot root)
{
foreach (IConfigurationProvider? provider in root.Providers)
{
if (provider is IWritableConfigurationProvider writableConfigurationProvider)
{
writableConfigurationProvider.Write(section, configuration);
}
}
}
}
}
@@ -0,0 +1,6 @@
namespace Hyperbar.Configurations;
public interface IConfigurationWriter<TConfiguration> where TConfiguration : class
{
void Write(string section, TConfiguration args);
}
@@ -0,0 +1,6 @@
namespace Hyperbar.Configurations;
public interface IWritableConfigurationProvider
{
void Write<TValue>(string section, TValue value) where TValue : class, new();
}
@@ -0,0 +1,12 @@
namespace Hyperbar.Configurations;
public interface IWritableJsonConfigurationBuilder
{
Stream? DefaultFileStream { get; }
IWritableJsonConfigurationBuilder AddDefaultConfiguration<TConfiguration>(string Key) where TConfiguration : class;
IWritableJsonConfigurationBuilder AddDefaultFileStream(Stream stream);
void Build(string path);
}
@@ -0,0 +1,8 @@
namespace Hyperbar.Configurations;
public interface IWritableJsonConfigurationDescriptor
{
Type ConfigurationType { get; }
string Key { get; }
}
@@ -0,0 +1,110 @@
using Json.Patch;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace Hyperbar.Configurations;
public class WritableJsonConfigurationBuilder :
IWritableJsonConfigurationBuilder
{
private readonly List<IWritableJsonConfigurationDescriptor> descriptors = [];
public Stream? DefaultFileStream { get; private set; }
public IReadOnlyCollection<IWritableJsonConfigurationDescriptor> Descriptors => new ReadOnlyCollection<IWritableJsonConfigurationDescriptor>(descriptors);
public IWritableJsonConfigurationBuilder AddDefaultConfiguration<TConfiguration>(string Key) where TConfiguration : class
{
descriptors.Add(new WritableJsonConfigurationDescriptor(typeof(TConfiguration), Key));
return this;
}
public IWritableJsonConfigurationBuilder AddDefaultFileStream(Stream stream)
{
DefaultFileStream = stream;
return this;
}
public void Build(string path)
{
JsonSerializerOptions options = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull };
JObject? sourceDocument = [];
if (TryLoadSource(out string? defaultContent))
{
sourceDocument = JObject.Parse(defaultContent!);
}
JObject? targetDocument = [];
if (TryLoadTarget(path, out string? targetContent))
{
targetDocument = JObject.Parse(targetContent!);
}
foreach (IWritableJsonConfigurationDescriptor? descriptor in descriptors)
{
if (sourceDocument.SelectToken($"$.{descriptor.Key}") is JToken sourceSection)
{
if (targetDocument.SelectToken($"$.{descriptor.Key}") is JToken targetSection)
{
object? source = JsonSerializer.Deserialize(JsonConvert.SerializeObject(sourceSection), descriptor.ConfigurationType);
object? target = JsonSerializer.Deserialize(JsonConvert.SerializeObject(targetSection), descriptor.ConfigurationType);
JsonPatch? patch = source.CreatePatch(target);
if (patch.Apply(source) is object sourcePatched)
{
targetSection.Replace(JToken.Parse(JsonSerializer.Serialize(sourcePatched, options)));
}
}
else
{
object? source = JsonSerializer.Deserialize(JsonConvert.SerializeObject(sourceSection), descriptor.ConfigurationType);
targetDocument.Add(descriptor.Key, JToken.Parse(JsonSerializer.Serialize(source, options)));
}
}
else
{
object? configuration = Activator.CreateInstance(descriptor.ConfigurationType);
targetDocument.Add(descriptor.Key, JToken.Parse(JsonSerializer.Serialize(configuration, options)));
}
}
using FileStream? fileStream = new(path, FileMode.Create, FileAccess.Write);
using StreamWriter streamWriter = new(fileStream);
using JsonTextWriter writer = new(streamWriter) { Formatting = Formatting.Indented };
targetDocument.WriteTo(writer);
}
private static bool TryLoadTarget(string path, [MaybeNull] out string? content)
{
if (File.Exists(path))
{
using FileStream? fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using StreamReader? streamReader = new(fileStream);
content = streamReader.ReadToEnd();
return true;
}
content = null;
return false;
}
private bool TryLoadSource([MaybeNull] out string? content)
{
if (DefaultFileStream is Stream fileStream)
{
using StreamReader? streamReader = new(fileStream);
content = streamReader.ReadToEnd();
return true;
}
content = null;
return false;
}
}
@@ -0,0 +1,3 @@
namespace Hyperbar.Configurations;
public record WritableJsonConfigurationDescriptor(Type ConfigurationType, string Key) : IWritableJsonConfigurationDescriptor;
@@ -0,0 +1,147 @@
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.Json;
namespace Hyperbar.Configurations;
public class WritableJsonConfigurationFile
{
private readonly Dictionary<string, (JsonValueKind?, string?)> data = new(StringComparer.OrdinalIgnoreCase);
private readonly Stack<string> paths = new();
private JObject tokenCache = [];
private bool isParsing;
public IDictionary<string, string?> Parse(Stream input)
{
return ParseStream(input);
}
public void Write(string key, string value, Stream output)
{
if (isParsing)
{
return;
}
if (key[^1] == ':')
{
key = key[0..^1];
}
string? tokenPath = $"$.{key.Replace(":", ".")}";
key = key.Replace("[", "").Replace("]", "");
if (tokenCache.SelectToken(tokenPath) is JToken token && data.ContainsKey(key))
{
(JsonValueKind? kind, string _) = data[key];
object? newValue = ConvertValue(kind, value);
data[key] = new(kind, value);
token.Replace(JToken.FromObject(newValue));
}
using StreamWriter streamWriter = new(output);
using JsonTextWriter writer = new(streamWriter) { Formatting = Formatting.Indented };
tokenCache.WriteTo(writer);
output.SetLength(output.Position);
}
private static object ConvertValue(JsonValueKind? kind, string value)
{
return kind is JsonValueKind.True or JsonValueKind.False ? bool.Parse(value) : value;
}
private void EnterContext(string context)
{
paths.Push(paths.Count > 0 ? paths.Peek() + ConfigurationPath.KeyDelimiter + context : context);
}
private void ExitContext()
{
_ = paths.Pop();
}
private IDictionary<string, string?> ParseStream(Stream input)
{
data.Clear();
JsonDocumentOptions jsonDocumentOptions = new()
{
CommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
isParsing = true;
using (StreamReader? reader = new(input))
{
string? content = reader.ReadToEnd();
tokenCache = JObject.Parse(content);
using JsonDocument? doc = JsonDocument.Parse(content, jsonDocumentOptions);
VisitElement(doc.RootElement);
}
isParsing = false;
return data.ToDictionary(k => k.Key, v => v.Value.Item2?.ToString() ?? null);
}
private void VisitElement(JsonElement element)
{
bool isEmpty = true;
foreach (JsonProperty property in element.EnumerateObject())
{
isEmpty = false;
EnterContext(property.Name);
VisitValue(property.Value);
ExitContext();
}
if (isEmpty && paths.Count > 0)
{
data[paths.Peek()] = (JsonValueKind.Null, null);
}
}
private void VisitValue(JsonElement value)
{
switch (value.ValueKind)
{
case JsonValueKind.Object:
VisitElement(value);
break;
case JsonValueKind.Array:
int index = 0;
foreach (JsonElement arrayElement in value.EnumerateArray())
{
EnterContext(index.ToString());
VisitValue(arrayElement);
ExitContext();
index++;
}
break;
case JsonValueKind.Number:
case JsonValueKind.String:
case JsonValueKind.True:
case JsonValueKind.False:
case JsonValueKind.Null:
string key = paths.Peek();
if (data.ContainsKey(key))
{
throw new FormatException();
}
data[key] = new(value.ValueKind, value.ToString());
break;
case JsonValueKind.Undefined:
break;
default:
throw new FormatException();
}
}
}
@@ -0,0 +1,43 @@
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.FileProviders;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Hyperbar.Configurations;
public class WritableJsonConfigurationProvider(JsonConfigurationSource source) :
JsonConfigurationProvider(source),
IWritableConfigurationProvider
{
public void Write<TValue>(string section, TValue value) where TValue : class, new()
{
IFileInfo? file = Source.FileProvider?.GetFileInfo(Source.Path ?? string.Empty);
static Stream OpenRead(IFileInfo fileInfo)
{
return fileInfo.PhysicalPath is not null
? new FileStream(fileInfo.PhysicalPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
: fileInfo.CreateReadStream();
}
if (file is null)
{
throw new FileNotFoundException();
}
using Stream stream = OpenRead(file);
using StreamReader? reader = new(stream);
string? content = reader.ReadToEnd();
JObject? document = JObject.Parse(content);
if (document.SelectToken($"$.{section}") is JToken sectionToken)
{
sectionToken.Replace(JToken.Parse(JsonConvert.SerializeObject(value)));
stream.SetLength(0);
using StreamWriter streamWriter = new(stream);
using JsonTextWriter writer = new(streamWriter) { Formatting = Formatting.Indented };
document.WriteTo(writer);
}
}
}
@@ -0,0 +1,28 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.FileProviders;
namespace Hyperbar.Configurations;
public class WritableJsonConfigurationSource :
JsonConfigurationSource
{
public IWritableJsonConfigurationBuilder? Factory { get; set; }
public override IConfigurationProvider Build(IConfigurationBuilder builder)
{
EnsureDefaultsWithSteam(builder);
return new WritableJsonConfigurationProvider(this);
}
private void EnsureDefaultsWithSteam(IConfigurationBuilder builder)
{
EnsureDefaults(builder);
if (FileProvider is PhysicalFileProvider physicalFileProvider)
{
string? outputFile = System.IO.Path.Combine(physicalFileProvider.Root, Path);
Factory?.Build(outputFile);
}
}
}
@@ -1,8 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Hyperbar.Lifecycles;
using Hyperbar.Templates;
using Microsoft.Extensions.DependencyInjection;
namespace Hyperbar;
public static class IServiceCollectionExtensions
{
public static IServiceCollection AddCommandTemplate<TCommand, TCommandTemplate>(this IServiceCollection services)
@@ -12,15 +12,15 @@ public static class IServiceCollectionExtensions
Type dataType = typeof(TCommand);
Type templateType = typeof(TCommandTemplate);
var key = dataType.Name;
string key = dataType.Name;
services.AddTransient(typeof(ICommandViewModel), dataType);
services.AddTransient(templateType);
_ = services.AddTransient(typeof(ICommandViewModel), dataType);
_ = services.AddTransient(templateType);
services.AddKeyedTransient(typeof(ICommandViewModel), key, dataType);
services.AddKeyedTransient(templateType, key);
_ = services.AddKeyedTransient(typeof(ICommandViewModel), key, dataType);
_ = services.AddKeyedTransient(templateType, key);
services.AddTransient<IDataTemplateDescriptor>(provider => new DataTemplateDescriptor
_ = services.AddTransient<IDataTemplateDescriptor>(provider => new DataTemplateDescriptor
{
DataType = dataType,
TemplateType = templateType,
@@ -38,10 +38,10 @@ public static class IServiceCollectionExtensions
key ??= dataType.Name;
services.AddKeyedTransient(dataType, key);
services.AddKeyedTransient(templateType, key);
_ = services.AddKeyedTransient(dataType, key);
_ = services.AddKeyedTransient(templateType, key);
services.AddTransient<IDataTemplateDescriptor>(provider => new DataTemplateDescriptor
_ = services.AddTransient<IDataTemplateDescriptor>(provider => new DataTemplateDescriptor
{
DataType = dataType,
TemplateType = templateType,
@@ -0,0 +1,78 @@
using Hyperbar.Configurations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
namespace Hyperbar.Extensions;
public static class WritableJsonConfigurationExtensions
{
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
string path)
{
return builder.AddWritableJsonFile(null, path, false, false, null);
}
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
string path,
Action<IWritableJsonConfigurationBuilder>? factoryDelegate)
{
return builder.AddWritableJsonFile(null, path, false, false, factoryDelegate);
}
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
string path,
bool optional)
{
return builder.AddWritableJsonFile(null, path, optional, false, null);
}
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
string path,
bool optional,
Action<IWritableJsonConfigurationBuilder>? factoryDelegate)
{
return builder.AddWritableJsonFile(null, path, optional, false, factoryDelegate);
}
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
string path,
bool optional,
bool reloadOnChange)
{
return builder.AddWritableJsonFile(null, path, optional, reloadOnChange, null);
}
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
string path,
bool optional,
bool reloadOnChange,
Action<IWritableJsonConfigurationBuilder>? factoryDelegate)
{
return builder.AddWritableJsonFile(null, path, optional, reloadOnChange, factoryDelegate);
}
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
IFileProvider? provider,
string path,
bool optional,
bool reloadOnChange, Action<IWritableJsonConfigurationBuilder>? writableJsonConfigurationDelegate)
{
IWritableJsonConfigurationBuilder writableJsonConfigurationBuilder = new WritableJsonConfigurationBuilder();
writableJsonConfigurationDelegate?.Invoke(writableJsonConfigurationBuilder);
return builder.AddWritableJsonFile(configuration =>
{
configuration.FileProvider = provider;
configuration.Path = path;
configuration.Optional = optional;
configuration.ReloadOnChange = reloadOnChange;
configuration.Factory = writableJsonConfigurationBuilder;
configuration.ResolveFileProvider();
});
}
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder, Action<WritableJsonConfigurationSource> configureSource)
{
return builder.Add(configureSource);
}
}
+2
View File
@@ -6,5 +6,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="JsonPatch.Net" Version="2.0.4" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>
+5 -5
View File
@@ -1,20 +1,20 @@
using Microsoft.Extensions.Hosting;
using System.Collections.ObjectModel;
namespace Hyperbar;
namespace Hyperbar.Lifecycles;
public class ObservableCollectionViewModel :
public class ObservableCollectionViewModel :
ObservableCollection<object>
{
}
public class AppService(IEnumerable<IInitializer> initializers) :
public class AppService(IEnumerable<IInitializer> initializers) :
IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
foreach (var initializer in initializers)
foreach (IInitializer initializer in initializers)
{
await initializer.InitializeAsync();
}
@@ -22,6 +22,6 @@ public class AppService(IEnumerable<IInitializer> initializers) :
public Task StopAsync(CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
throw new NotImplementedException();
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
namespace Hyperbar;
namespace Hyperbar.Lifecycles;
public class CommandContext(IServiceProvider serviceProvider) :
ICommandContext
+1 -1
View File
@@ -1,6 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
namespace Hyperbar;
namespace Hyperbar.Lifecycles;
public interface ICommandBuilder
{
+1 -1
View File
@@ -1,4 +1,4 @@
namespace Hyperbar;
namespace Hyperbar.Lifecycles;
public interface ICommandContext
{
+1 -1
View File
@@ -1,4 +1,4 @@
namespace Hyperbar;
namespace Hyperbar.Lifecycles;
public interface ICommandViewModel
{
+1 -1
View File
@@ -1,4 +1,4 @@
namespace Hyperbar;
namespace Hyperbar.Lifecycles;
public interface IInitializer
{
+1 -1
View File
@@ -1,4 +1,4 @@
namespace Hyperbar;
namespace Hyperbar.Templates;
public record DataTemplateDescriptor :
IDataTemplateDescriptor
@@ -1,4 +1,4 @@
namespace Hyperbar;
namespace Hyperbar.Templates;
public interface IDataTemplateDescriptor
{
+1 -1
View File
@@ -1,4 +1,4 @@
namespace Hyperbar;
namespace Hyperbar.Templates;
public interface ITemplateFactory
{
+1 -1
View File
@@ -1,4 +1,4 @@
namespace Hyperbar;
namespace Hyperbar.Templates;
public interface ITemplatedViewModel
{