diff --git a/SquidStd.slnx b/SquidStd.slnx
index b6e06793..b6978e23 100644
--- a/SquidStd.slnx
+++ b/SquidStd.slnx
@@ -1,72 +1,72 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
diff --git a/samples/SquidStd.Samples.Actors/Program.cs b/samples/SquidStd.Samples.Actors/Program.cs
index 01f2f0bc..73571e0c 100644
--- a/samples/SquidStd.Samples.Actors/Program.cs
+++ b/samples/SquidStd.Samples.Actors/Program.cs
@@ -1,5 +1,4 @@
using SquidStd.Actors;
-using SquidStd.Actors.Interfaces;
await using var counter = new CounterActor();
@@ -14,7 +13,7 @@
#region step-3
// Request/response: AskAsync enqueues a request and awaits its typed reply.
-var total = await counter.AskAsync(new GetTotal());
+var total = await counter.AskAsync(new());
Console.WriteLine($"Total: {total}");
@@ -40,9 +39,11 @@ protected override ValueTask ReceiveAsync(ICounterMessage message, CancellationT
{
case Increment increment:
_total += increment.By;
+
break;
case GetTotal request:
request.Reply(_total);
+
break;
}
diff --git a/samples/SquidStd.Samples.Caching/Program.cs b/samples/SquidStd.Samples.Caching/Program.cs
index 2caf671f..59a0227e 100644
--- a/samples/SquidStd.Samples.Caching/Program.cs
+++ b/samples/SquidStd.Samples.Caching/Program.cs
@@ -1,10 +1,9 @@
using SquidStd.Caching.Abstractions.Interfaces;
using SquidStd.Caching.Extensions;
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Services.Core.Services.Bootstrap;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
diff --git a/samples/SquidStd.Samples.Crypto/Program.cs b/samples/SquidStd.Samples.Crypto/Program.cs
index 8fdd0532..5372fde4 100644
--- a/samples/SquidStd.Samples.Crypto/Program.cs
+++ b/samples/SquidStd.Samples.Crypto/Program.cs
@@ -1,12 +1,11 @@
using System.Text;
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Crypto.Pgp.Extensions;
using SquidStd.Crypto.Pgp.Interfaces;
using SquidStd.Crypto.Pgp.Services;
using SquidStd.Services.Core.Services.Bootstrap;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
@@ -50,11 +49,11 @@
// Encrypt + sign for the recipient, then decrypt + verify the round-trip.
var armored = await pgp.EncryptAndSignForAsync(
- identity,
- Encoding.UTF8.GetBytes("attack at dawn"),
- identity,
- passphrase
-);
+ identity,
+ Encoding.UTF8.GetBytes("attack at dawn"),
+ identity,
+ passphrase
+ );
var result = await pgp.DecryptAndVerifyAsync(armored, passphrase);
@@ -70,9 +69,7 @@
var reloaded = new PgpKeyring();
await reloaded.LoadAsync(keyStore);
-Console.WriteLine(
- $"Reloaded {reloaded.Keys.Count} key(s) from disk; contains '{identity}': {reloaded.Contains(identity)}"
-);
+Console.WriteLine($"Reloaded {reloaded.Keys.Count} key(s) from disk; contains '{identity}': {reloaded.Contains(identity)}");
#endregion
diff --git a/samples/SquidStd.Samples.Database/Program.cs b/samples/SquidStd.Samples.Database/Program.cs
index 08b45ace..97c8c65a 100644
--- a/samples/SquidStd.Samples.Database/Program.cs
+++ b/samples/SquidStd.Samples.Database/Program.cs
@@ -1,11 +1,10 @@
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Database.Abstractions.Data.Entities;
using SquidStd.Database.Abstractions.Interfaces.Data;
using SquidStd.Database.Extensions;
using SquidStd.Services.Core.Services.Bootstrap;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
@@ -24,14 +23,14 @@
var products = bootstrap.Resolve>();
-await products.InsertAsync(new Product { Name = "Squid Plushie", Price = 19.99m });
-await products.InsertAsync(new Product { Name = "Kraken Mug", Price = 12.50m });
+await products.InsertAsync(new() { Name = "Squid Plushie", Price = 19.99m });
+await products.InsertAsync(new() { Name = "Kraken Mug", Price = 12.50m });
var page = await products.GetPagedAsync(
- 1,
- 10,
- orderBy: product => product.Price
-);
+ 1,
+ 10,
+ orderBy: product => product.Price
+ );
Console.WriteLine($"Found {page.TotalCount} product(s) on page {page.Page}/{page.TotalPages}:");
diff --git a/samples/SquidStd.Samples.Email/Program.cs b/samples/SquidStd.Samples.Email/Program.cs
index 0ca1f7ab..97bdbdaf 100644
--- a/samples/SquidStd.Samples.Email/Program.cs
+++ b/samples/SquidStd.Samples.Email/Program.cs
@@ -1,7 +1,5 @@
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Core.Interfaces.Events;
using SquidStd.Mail.Abstractions.Data;
-using SquidStd.Mail.Abstractions.Data.Config;
using SquidStd.Mail.Abstractions.Data.Events;
using SquidStd.Mail.Abstractions.Interfaces;
using SquidStd.Mail.Abstractions.Types.Mail;
@@ -12,7 +10,7 @@
using SquidStd.Services.Core.Services.Bootstrap;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
@@ -21,8 +19,9 @@
#region step-1
-bootstrap.ConfigureServices(container => container.AddMail(
- new MailOptions
+bootstrap.ConfigureServices(
+ container => container.AddMail(
+ new()
{
Protocol = MailProtocolType.Imap,
Host = "imap.example.com",
@@ -37,8 +36,9 @@
#region step-2
-bootstrap.ConfigureServices(container => container.AddMailSender(
- new SmtpOptions
+bootstrap.ConfigureServices(
+ container => container.AddMailSender(
+ new()
{
Host = "smtp.example.com",
Port = 587
@@ -50,9 +50,10 @@
#region step-3
-bootstrap.ConfigureServices(container => container
- .AddInMemoryMessaging()
- .AddMailQueue()
+bootstrap.ConfigureServices(
+ container => container
+ .AddInMemoryMessaging()
+ .AddMailQueue()
);
#endregion
@@ -65,7 +66,7 @@
var outgoing = new OutgoingMailMessage
{
- To = [new MailAddress("Bob", "bob@example.com")],
+ To = [new("Bob", "bob@example.com")],
Subject = "Hi",
HtmlBody = "Hi
"
};
diff --git a/samples/SquidStd.Samples.EventsJobsScheduling/Program.cs b/samples/SquidStd.Samples.EventsJobsScheduling/Program.cs
index 332014d0..dc3fbc6d 100644
--- a/samples/SquidStd.Samples.EventsJobsScheduling/Program.cs
+++ b/samples/SquidStd.Samples.EventsJobsScheduling/Program.cs
@@ -1,5 +1,4 @@
using SquidStd.Abstractions.Attributes;
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Core.Interfaces.Events;
using SquidStd.Core.Interfaces.Jobs;
using SquidStd.Core.Interfaces.Scheduling;
@@ -8,7 +7,7 @@
using SquidStd.Services.Core.Services.Bootstrap;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
@@ -16,9 +15,10 @@
);
// The cron scheduler and timer wheel are opt-in.
-bootstrap.ConfigureServices(container => container
- .RegisterSchedulerServices()
- .RegisterGeneratedEventListeners()
+bootstrap.ConfigureServices(
+ container => container
+ .RegisterSchedulerServices()
+ .RegisterGeneratedEventListeners()
);
await bootstrap.StartAsync();
diff --git a/samples/SquidStd.Samples.GettingStarted/Program.cs b/samples/SquidStd.Samples.GettingStarted/Program.cs
index e9a6a176..c6dcb6cc 100644
--- a/samples/SquidStd.Samples.GettingStarted/Program.cs
+++ b/samples/SquidStd.Samples.GettingStarted/Program.cs
@@ -1,10 +1,9 @@
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Services.Core.Services.Bootstrap;
#region step-1
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
diff --git a/samples/SquidStd.Samples.Messaging/Program.cs b/samples/SquidStd.Samples.Messaging/Program.cs
index 75202d9e..32489792 100644
--- a/samples/SquidStd.Samples.Messaging/Program.cs
+++ b/samples/SquidStd.Samples.Messaging/Program.cs
@@ -1,10 +1,9 @@
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Messaging.Abstractions.Interfaces;
using SquidStd.Messaging.Extensions;
using SquidStd.Services.Core.Services.Bootstrap;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
diff --git a/samples/SquidStd.Samples.Networking/Program.cs b/samples/SquidStd.Samples.Networking/Program.cs
index 948269b4..8afd2de5 100644
--- a/samples/SquidStd.Samples.Networking/Program.cs
+++ b/samples/SquidStd.Samples.Networking/Program.cs
@@ -9,12 +9,12 @@
var server = new SquidTcpServer(endPoint);
server.OnClientConnect += (_, args) =>
- Console.WriteLine($"Client connected: session {args.Client.SessionId}");
+ Console.WriteLine($"Client connected: session {args.Client.SessionId}");
server.OnDataReceived += (_, args) =>
- Console.WriteLine(
- $"Received {args.Data.Length} byte(s): {Encoding.UTF8.GetString(args.Data.Span)}"
- );
+ Console.WriteLine(
+ $"Received {args.Data.Length} byte(s): {Encoding.UTF8.GetString(args.Data.Span)}"
+ );
#endregion
diff --git a/samples/SquidStd.Samples.Persistence/Program.cs b/samples/SquidStd.Samples.Persistence/Program.cs
index a2bfdc1a..b075c313 100644
--- a/samples/SquidStd.Samples.Persistence/Program.cs
+++ b/samples/SquidStd.Samples.Persistence/Program.cs
@@ -18,10 +18,10 @@ IPersistenceService BuildPersistence()
new PersistenceEntityDescriptor(
serializer,
serializer,
- typeId: 1,
- typeName: "Player",
- schemaVersion: 1,
- keySelector: player => player.Id
+ 1,
+ "Player",
+ 1,
+ player => player.Id
)
);
@@ -50,8 +50,8 @@ IPersistenceService BuildPersistence()
#region step-2: mutate — every upsert/remove is appended to the journal
-var nextId = (await players.CountAsync()) + 1;
-await players.UpsertAsync(new Player { Id = nextId, Name = $"Hero-{nextId}", Level = nextId * 10 });
+var nextId = await players.CountAsync() + 1;
+await players.UpsertAsync(new() { Id = nextId, Name = $"Hero-{nextId}", Level = nextId * 10 });
Console.WriteLine($"Added player #{nextId}; store now holds {await players.CountAsync()} player(s)");
diff --git a/samples/SquidStd.Samples.Plugins/Program.cs b/samples/SquidStd.Samples.Plugins/Program.cs
index 266558f6..5822c920 100644
--- a/samples/SquidStd.Samples.Plugins/Program.cs
+++ b/samples/SquidStd.Samples.Plugins/Program.cs
@@ -14,9 +14,7 @@ public interface IGreeter
public sealed class WeatherGreeter : IGreeter
{
public string Greet(string name)
- {
- return $"Hello {name}, the weather plugin is online.";
- }
+ => $"Hello {name}, the weather plugin is online.";
}
public sealed class WeatherPlugin : ISquidStdPlugin
@@ -25,16 +23,14 @@ public sealed class WeatherPlugin : ISquidStdPlugin
{
Id = "squidstd.weather",
Name = "Weather Plugin",
- Version = new Version(1, 0, 0),
+ Version = new(1, 0, 0),
Author = "SquidStd Samples",
Description = "Registers a greeter service.",
Dependencies = []
};
public void Configure(IContainer container, PluginContext context)
- {
- container.Register(Reuse.Singleton);
- }
+ => container.Register(Reuse.Singleton);
}
#endregion
@@ -43,7 +39,7 @@ internal static class Program
{
private static void Main()
{
- #region step-2
+ #region step-2
var container = new Container();
var context = new PluginContext();
@@ -57,6 +53,6 @@ private static void Main()
var greeter = container.Resolve();
Console.WriteLine(greeter.Greet("squid"));
- #endregion
+ #endregion
}
}
diff --git a/samples/SquidStd.Samples.ScriptingLua/Program.cs b/samples/SquidStd.Samples.ScriptingLua/Program.cs
index 94115310..6d403e7a 100644
--- a/samples/SquidStd.Samples.ScriptingLua/Program.cs
+++ b/samples/SquidStd.Samples.ScriptingLua/Program.cs
@@ -1,6 +1,5 @@
using DryIoc;
using SquidStd.Abstractions.Extensions.Services;
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Generators.Scripting.Lua;
using SquidStd.Scripting.Lua.Attributes;
using SquidStd.Scripting.Lua.Attributes.Scripts;
@@ -10,7 +9,7 @@
using SquidStd.Services.Core.Services.Bootstrap;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
@@ -22,7 +21,8 @@
var scriptsDirectory = Path.Combine(AppContext.BaseDirectory, "scripts");
Directory.CreateDirectory(scriptsDirectory);
-bootstrap.ConfigureServices(container =>
+bootstrap.ConfigureServices(
+ container =>
{
var engineConfig = new LuaEngineConfig(
AppContext.BaseDirectory,
@@ -64,10 +64,7 @@
#region step-3
-[RegisterScriptModule]
-[ScriptModule("sample")]
-internal sealed class SampleLuaModule
-{
-}
+[RegisterScriptModule, ScriptModule("sample")]
+internal sealed class SampleLuaModule { }
#endregion
diff --git a/samples/SquidStd.Samples.Search/Program.cs b/samples/SquidStd.Samples.Search/Program.cs
index 905455ae..25b5594d 100644
--- a/samples/SquidStd.Samples.Search/Program.cs
+++ b/samples/SquidStd.Samples.Search/Program.cs
@@ -1,13 +1,11 @@
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Search.Abstractions.Attributes;
using SquidStd.Search.Abstractions.Interfaces;
-using SquidStd.Search.Elasticsearch.Data.Config;
using SquidStd.Search.Elasticsearch.Extensions;
using SquidStd.Search.Elasticsearch.Linq;
using SquidStd.Services.Core.Services.Bootstrap;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
@@ -16,10 +14,11 @@
#region step-1
-bootstrap.ConfigureServices(container => container.AddElasticsearch(
- new ElasticsearchOptions
+bootstrap.ConfigureServices(
+ container => container.AddElasticsearch(
+ new()
{
- Uri = new Uri("http://localhost:9200")
+ Uri = new("http://localhost:9200")
}
)
);
@@ -35,8 +34,8 @@
await search.IndexAsync(new Order("1", "open", 150), true);
var open = await search.Query()
- .Where(o => o.Status == "open")
- .ToListAsync();
+ .Where(o => o.Status == "open")
+ .ToListAsync();
Console.WriteLine($"found {open.Count} open order(s)");
diff --git a/samples/SquidStd.Samples.Secrets/Program.cs b/samples/SquidStd.Samples.Secrets/Program.cs
index 7f98cb9e..148cd3ad 100644
--- a/samples/SquidStd.Samples.Secrets/Program.cs
+++ b/samples/SquidStd.Samples.Secrets/Program.cs
@@ -1,12 +1,10 @@
using System.Text;
-using SquidStd.Aws.Abstractions.Data.Config;
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Core.Interfaces.Secrets;
using SquidStd.Secrets.Aws.Extensions;
using SquidStd.Services.Core.Services.Bootstrap;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
@@ -16,30 +14,36 @@
#region step-1
// Wire the KMS-backed protector and the Secrets Manager store against a LocalStack endpoint.
-bootstrap.ConfigureServices(container =>
-{
- container.RegisterKmsSecretProtector(options =>
- {
- options.KeyId = "alias/app";
- options.Aws = new AwsConfigEntry
- {
- Region = "us-east-1",
- ServiceUrl = "http://localhost:4566"
- };
- });
-
- container.RegisterAwsSecretsManagerStore(options =>
+bootstrap.ConfigureServices(
+ container =>
{
- options.NamePrefix = "myapp/";
- options.Aws = new AwsConfigEntry
- {
- Region = "us-east-1",
- ServiceUrl = "http://localhost:4566"
- };
- });
-
- return container;
-});
+ container.RegisterKmsSecretProtector(
+ options =>
+ {
+ options.KeyId = "alias/app";
+ options.Aws = new()
+ {
+ Region = "us-east-1",
+ ServiceUrl = "http://localhost:4566"
+ };
+ }
+ );
+
+ container.RegisterAwsSecretsManagerStore(
+ options =>
+ {
+ options.NamePrefix = "myapp/";
+ options.Aws = new()
+ {
+ Region = "us-east-1",
+ ServiceUrl = "http://localhost:4566"
+ };
+ }
+ );
+
+ return container;
+ }
+);
#endregion
@@ -54,6 +58,7 @@
{
Console.WriteLine("Set SQUIDSTD_RUN_AWS=1 with LocalStack running to exercise the live calls.");
await bootstrap.StopAsync();
+
return;
}
diff --git a/samples/SquidStd.Samples.Storage/Program.cs b/samples/SquidStd.Samples.Storage/Program.cs
index cde19fa4..ddaf9985 100644
--- a/samples/SquidStd.Samples.Storage/Program.cs
+++ b/samples/SquidStd.Samples.Storage/Program.cs
@@ -1,10 +1,9 @@
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Services.Core.Services.Bootstrap;
using SquidStd.Storage.Abstractions.Interfaces;
using SquidStd.Storage.Extensions;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
diff --git a/samples/SquidStd.Samples.Templating/Program.cs b/samples/SquidStd.Samples.Templating/Program.cs
index d46884f6..ad2b0e49 100644
--- a/samples/SquidStd.Samples.Templating/Program.cs
+++ b/samples/SquidStd.Samples.Templating/Program.cs
@@ -1,10 +1,9 @@
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Services.Core.Services.Bootstrap;
using SquidStd.Templating.Extensions;
using SquidStd.Templating.Interfaces;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
diff --git a/samples/SquidStd.Samples.Tui/CounterComposedView.cs b/samples/SquidStd.Samples.Tui/CounterComposedView.cs
index 90ff2679..b0cb9bac 100644
--- a/samples/SquidStd.Samples.Tui/CounterComposedView.cs
+++ b/samples/SquidStd.Samples.Tui/CounterComposedView.cs
@@ -6,10 +6,9 @@ namespace SquidStd.Samples.Tui;
public sealed class CounterComposedView : TuiComposedView
{
protected override TuiNode Compose()
- {
- return Ui.VStack(
+ => Ui.VStack(
Ui.Label(x => x.Title),
Ui.Label(x => x.Value),
- Ui.Button("+1", x => x.IncrementCommand));
- }
+ Ui.Button("+1", x => x.IncrementCommand)
+ );
}
diff --git a/samples/SquidStd.Samples.Tui/CounterViewModel.cs b/samples/SquidStd.Samples.Tui/CounterViewModel.cs
index 7f41c638..91ee3807 100644
--- a/samples/SquidStd.Samples.Tui/CounterViewModel.cs
+++ b/samples/SquidStd.Samples.Tui/CounterViewModel.cs
@@ -6,15 +6,11 @@ namespace SquidStd.Samples.Tui;
public sealed partial class CounterViewModel : TuiViewModel
{
- [ObservableProperty]
- private string _title = "SquidStd.Tui — Counter";
+ [ObservableProperty] private string _title = "SquidStd.Tui — Counter";
- [ObservableProperty]
- private string _value = "0";
+ [ObservableProperty] private string _value = "0";
[RelayCommand]
private void Increment()
- {
- Value = (int.Parse(Value) + 1).ToString();
- }
+ => Value = (int.Parse(Value) + 1).ToString();
}
diff --git a/samples/SquidStd.Samples.Vfs/Program.cs b/samples/SquidStd.Samples.Vfs/Program.cs
index 1a577c35..2c346213 100644
--- a/samples/SquidStd.Samples.Vfs/Program.cs
+++ b/samples/SquidStd.Samples.Vfs/Program.cs
@@ -1,5 +1,4 @@
using System.Text;
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Crypto.Vfs.Services;
using SquidStd.Services.Core.Services.Bootstrap;
using SquidStd.Vfs.Abstractions.Interfaces;
@@ -7,7 +6,7 @@
using SquidStd.Vfs.Services;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
diff --git a/samples/SquidStd.Samples.WorkerSystem/Program.cs b/samples/SquidStd.Samples.WorkerSystem/Program.cs
index 0f220543..6c4bb9ce 100644
--- a/samples/SquidStd.Samples.WorkerSystem/Program.cs
+++ b/samples/SquidStd.Samples.WorkerSystem/Program.cs
@@ -1,4 +1,3 @@
-using SquidStd.Core.Data.Bootstrap;
using SquidStd.Generators.Workers;
using SquidStd.Messaging.Extensions;
using SquidStd.Services.Core.Services.Bootstrap;
@@ -10,7 +9,7 @@
using SquidStd.Workers.Manager.Interfaces;
var bootstrap = SquidStdBootstrap.Create(
- new SquidStdOptions
+ new()
{
ConfigName = "squidstd",
RootDirectory = AppContext.BaseDirectory
@@ -19,7 +18,8 @@
#region step-1
-bootstrap.ConfigureServices(c =>
+bootstrap.ConfigureServices(
+ c =>
{
c.AddInMemoryMessaging();
c.AddWorkers();
diff --git a/src/SquidStd.Abstractions/Attributes/RegisterConfigSectionAttribute.cs b/src/SquidStd.Abstractions/Attributes/RegisterConfigSectionAttribute.cs
index d5b94387..bf60a55e 100644
--- a/src/SquidStd.Abstractions/Attributes/RegisterConfigSectionAttribute.cs
+++ b/src/SquidStd.Abstractions/Attributes/RegisterConfigSectionAttribute.cs
@@ -1,23 +1,23 @@
namespace SquidStd.Abstractions.Attributes;
///
-/// Marks a configuration type for generated config-section registration.
+/// Marks a configuration type for generated config-section registration.
///
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class RegisterConfigSectionAttribute : Attribute
{
///
- /// Gets the configuration section name.
+ /// Gets the configuration section name.
///
public string? SectionName { get; }
///
- /// Gets or sets the config loading priority.
+ /// Gets or sets the config loading priority.
///
public int Priority { get; set; }
///
- /// Initializes a new instance of the attribute.
+ /// Initializes a new instance of the attribute.
///
/// The configuration section name.
public RegisterConfigSectionAttribute(string? sectionName = null)
diff --git a/src/SquidStd.Abstractions/Attributes/RegisterEventListenerAttribute.cs b/src/SquidStd.Abstractions/Attributes/RegisterEventListenerAttribute.cs
index a77c6dbe..17f02fa0 100644
--- a/src/SquidStd.Abstractions/Attributes/RegisterEventListenerAttribute.cs
+++ b/src/SquidStd.Abstractions/Attributes/RegisterEventListenerAttribute.cs
@@ -1,9 +1,7 @@
namespace SquidStd.Abstractions.Attributes;
///
-/// Marks an event listener for generated registration.
+/// Marks an event listener for generated registration.
///
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
-public sealed class RegisterEventListenerAttribute : Attribute
-{
-}
+public sealed class RegisterEventListenerAttribute : Attribute { }
diff --git a/src/SquidStd.Abstractions/Attributes/RegisterStdServiceAttribute.cs b/src/SquidStd.Abstractions/Attributes/RegisterStdServiceAttribute.cs
index 53b3d5f9..e64fd1f9 100644
--- a/src/SquidStd.Abstractions/Attributes/RegisterStdServiceAttribute.cs
+++ b/src/SquidStd.Abstractions/Attributes/RegisterStdServiceAttribute.cs
@@ -1,23 +1,23 @@
namespace SquidStd.Abstractions.Attributes;
///
-/// Marks a service implementation for generated SquidStd lifecycle registration.
+/// Marks a service implementation for generated SquidStd lifecycle registration.
///
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class RegisterStdServiceAttribute : Attribute
{
///
- /// Gets the service contract registered for the annotated implementation.
+ /// Gets the service contract registered for the annotated implementation.
///
public Type? ServiceType { get; }
///
- /// Gets or sets the lifecycle start priority.
+ /// Gets or sets the lifecycle start priority.
///
public int Priority { get; set; }
///
- /// Initializes a new instance of the attribute.
+ /// Initializes a new instance of the attribute.
///
/// The service contract registered for the annotated implementation.
public RegisterStdServiceAttribute(Type? serviceType = null)
diff --git a/src/SquidStd.Abstractions/Data/Internal/Commands/CommandHandlerRegistration.cs b/src/SquidStd.Abstractions/Data/Internal/Commands/CommandHandlerRegistration.cs
index 21a569b5..6fb1f582 100644
--- a/src/SquidStd.Abstractions/Data/Internal/Commands/CommandHandlerRegistration.cs
+++ b/src/SquidStd.Abstractions/Data/Internal/Commands/CommandHandlerRegistration.cs
@@ -4,9 +4,9 @@
namespace SquidStd.Abstractions.Data.Internal.Commands;
///
-/// A declarative command-handler registration consumed by the bootstrap activator. The
-/// closure captures the concrete command and handler types at registration
-/// time, so subscription needs no reflection.
+/// A declarative command-handler registration consumed by the bootstrap activator. The
+/// closure captures the concrete command and handler types at registration
+/// time, so subscription needs no reflection.
///
/// The dispatcher context type.
/// The concrete handler implementation type.
diff --git a/src/SquidStd.Abstractions/Data/Internal/Events/EventListenerRegistration.cs b/src/SquidStd.Abstractions/Data/Internal/Events/EventListenerRegistration.cs
index 98b7ffbb..d108d476 100644
--- a/src/SquidStd.Abstractions/Data/Internal/Events/EventListenerRegistration.cs
+++ b/src/SquidStd.Abstractions/Data/Internal/Events/EventListenerRegistration.cs
@@ -4,9 +4,9 @@
namespace SquidStd.Abstractions.Data.Internal.Events;
///
-/// A declarative event-listener registration consumed by the bootstrap activator.
-/// The closure captures the concrete event and listener types at
-/// registration time, so subscription needs no reflection.
+/// A declarative event-listener registration consumed by the bootstrap activator.
+/// The closure captures the concrete event and listener types at
+/// registration time, so subscription needs no reflection.
///
/// The concrete listener implementation type.
/// Resolves the listener and subscribes it to the bus.
diff --git a/src/SquidStd.Abstractions/Extensions/Commands/RegisterCommandHandlerExtension.cs b/src/SquidStd.Abstractions/Extensions/Commands/RegisterCommandHandlerExtension.cs
index d7389d90..8c56e963 100644
--- a/src/SquidStd.Abstractions/Extensions/Commands/RegisterCommandHandlerExtension.cs
+++ b/src/SquidStd.Abstractions/Extensions/Commands/RegisterCommandHandlerExtension.cs
@@ -6,7 +6,7 @@
namespace SquidStd.Abstractions.Extensions.Commands;
///
-/// Registers command handlers for DI-native auto-subscription at bootstrap.
+/// Registers command handlers for DI-native auto-subscription at bootstrap.
///
public static class RegisterCommandHandlerExtension
{
@@ -14,7 +14,7 @@ public static class RegisterCommandHandlerExtension
extension(IContainer container)
{
///
- /// Registers a command handler as a singleton and records it for auto-subscription.
+ /// Registers a command handler as a singleton and records it for auto-subscription.
///
/// The command type the handler handles.
/// The dispatcher context type.
diff --git a/src/SquidStd.Abstractions/Extensions/Config/RegisterConfigSectionExtension.cs b/src/SquidStd.Abstractions/Extensions/Config/RegisterConfigSectionExtension.cs
index 79872dbd..822c32d0 100644
--- a/src/SquidStd.Abstractions/Extensions/Config/RegisterConfigSectionExtension.cs
+++ b/src/SquidStd.Abstractions/Extensions/Config/RegisterConfigSectionExtension.cs
@@ -22,7 +22,8 @@ public static IContainer RegisterConfigSection(
if (container.IsRegistered>())
{
var entries = container.Resolve>();
- var sameSection = entries.FirstOrDefault(entry => string.Equals(
+ var sameSection = entries.FirstOrDefault(
+ entry => string.Equals(
entry.SectionName,
sectionName,
StringComparison.Ordinal
@@ -45,7 +46,7 @@ public static IContainer RegisterConfigSection(
}
}
- var factory = createDefault ?? (() => new TConfig());
+ var factory = createDefault ?? (() => new());
container.AddToRegisterTypedList(new ConfigRegistrationData(sectionName, configType, () => factory(), priority));
return container;
diff --git a/src/SquidStd.Abstractions/Extensions/Container/AddTypedListMethodExtension.cs b/src/SquidStd.Abstractions/Extensions/Container/AddTypedListMethodExtension.cs
index 4eda3f26..570d0122 100644
--- a/src/SquidStd.Abstractions/Extensions/Container/AddTypedListMethodExtension.cs
+++ b/src/SquidStd.Abstractions/Extensions/Container/AddTypedListMethodExtension.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Abstractions.Extensions.Container;
///
-/// Extension methods for registering typed lists in the dependency injection container.
+/// Extension methods for registering typed lists in the dependency injection container.
///
public static class AddTypedListMethodExtension
{
@@ -11,8 +11,8 @@ public static class AddTypedListMethodExtension
extension(IContainer container)
{
///
- /// Adds an entity to a typed list in the DryIoc container.
- /// If the list doesn't exist, it creates and registers a new one.
+ /// Adds an entity to a typed list in the DryIoc container.
+ /// If the list doesn't exist, it creates and registers a new one.
///
/// The type of entities in the list.
/// The entity to add to the list.
diff --git a/src/SquidStd.Abstractions/Extensions/Events/RegisterEventListenerExtension.cs b/src/SquidStd.Abstractions/Extensions/Events/RegisterEventListenerExtension.cs
index 170988bd..b10b7230 100644
--- a/src/SquidStd.Abstractions/Extensions/Events/RegisterEventListenerExtension.cs
+++ b/src/SquidStd.Abstractions/Extensions/Events/RegisterEventListenerExtension.cs
@@ -6,7 +6,7 @@
namespace SquidStd.Abstractions.Extensions.Events;
///
-/// Registers event listeners for DI-native auto-subscription at bootstrap.
+/// Registers event listeners for DI-native auto-subscription at bootstrap.
///
public static class RegisterEventListenerExtension
{
@@ -14,7 +14,7 @@ public static class RegisterEventListenerExtension
extension(IContainer container)
{
///
- /// Registers a listener implementation as a singleton and records it for auto-subscription.
+ /// Registers a listener implementation as a singleton and records it for auto-subscription.
///
/// The event type the listener handles.
/// The listener implementation type.
diff --git a/src/SquidStd.Abstractions/Interfaces/Services/ISquidStdService.cs b/src/SquidStd.Abstractions/Interfaces/Services/ISquidStdService.cs
index dbc57ec2..4e9b5066 100644
--- a/src/SquidStd.Abstractions/Interfaces/Services/ISquidStdService.cs
+++ b/src/SquidStd.Abstractions/Interfaces/Services/ISquidStdService.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Abstractions.Interfaces.Services;
///
-/// Defines lifecycle operations for a SquidStd service.
+/// Defines lifecycle operations for a SquidStd service.
///
public interface ISquidStdService
{
diff --git a/src/SquidStd.Abstractions/README.md b/src/SquidStd.Abstractions/README.md
index 00daacf7..9b2b921e 100644
--- a/src/SquidStd.Abstractions/README.md
+++ b/src/SquidStd.Abstractions/README.md
@@ -26,20 +26,21 @@ container.RegisterConfigSection("my");
## Key types
-| Type | Purpose |
-|----------------------------------|--------------------------------------------------|
-| `ISquidStdService` | Async start/stop lifecycle for managed services. |
-| `RegisterEventListenerAttribute` | Marks event listeners for generated registration. |
-| `RegisterStdServiceAttribute` | Marks services for generated registration. |
-| `RegisterConfigSectionAttribute` | Marks config sections for generated registration. |
-| `RegisterStdServiceExtension` | `RegisterStdService<,>` container extension. |
-| `RegisterConfigSectionExtension` | `RegisterConfigSection<>` container extension. |
-| `ServiceRegistrationData` | Ordered service registration record. |
-| `ConfigRegistrationData` | Config section registration record. |
+| Type | Purpose |
+|----------------------------------|---------------------------------------------------|
+| `ISquidStdService` | Async start/stop lifecycle for managed services. |
+| `RegisterEventListenerAttribute` | Marks event listeners for generated registration. |
+| `RegisterStdServiceAttribute` | Marks services for generated registration. |
+| `RegisterConfigSectionAttribute` | Marks config sections for generated registration. |
+| `RegisterStdServiceExtension` | `RegisterStdService<,>` container extension. |
+| `RegisterConfigSectionExtension` | `RegisterConfigSection<>` container extension. |
+| `ServiceRegistrationData` | Ordered service registration record. |
+| `ConfigRegistrationData` | Config section registration record. |
## Related
-- Tutorial: [Source generators: registration](https://tgiachi.github.io/squid-std/tutorials/source-generators-registration.html)
+-
+Tutorial: [Source generators: registration](https://tgiachi.github.io/squid-std/tutorials/source-generators-registration.html)
## License
diff --git a/src/SquidStd.Actors/Actor.cs b/src/SquidStd.Actors/Actor.cs
index 23cd542e..872dd9c4 100644
--- a/src/SquidStd.Actors/Actor.cs
+++ b/src/SquidStd.Actors/Actor.cs
@@ -9,9 +9,9 @@
namespace SquidStd.Actors;
///
-/// Base class for an actor: a single-consumer mailbox that processes messages in FIFO order on one
-/// logical thread, so handler state is mutated without locks. Send fire-and-forget messages with
-/// and request/response messages with .
+/// Base class for an actor: a single-consumer mailbox that processes messages in FIFO order on one
+/// logical thread, so handler state is mutated without locks. Send fire-and-forget messages with
+/// and request/response messages with .
///
/// The base type of every message this actor accepts.
public abstract class Actor : IAsyncDisposable
@@ -24,18 +24,15 @@ public abstract class Actor : IAsyncDisposable
private int _disposed;
/// Number of messages waiting in the mailbox.
- public int PendingCount
- {
- get { return _mailbox.InputCount; }
- }
+ public int PendingCount => _mailbox.InputCount;
/// Initializes the actor and starts its mailbox consumer.
/// Mailbox options; defaults are used when null.
protected Actor(ActorOptions? options = null)
{
_options = options ?? new ActorOptions();
- _shutdown = new CancellationTokenSource();
- _outstanding = new ConcurrentDictionary();
+ _shutdown = new();
+ _outstanding = new();
_logger = Log.ForContext(GetType());
// The mailbox is deliberately NOT bound to _shutdown.Token: cancelling that token would abort
@@ -46,11 +43,11 @@ protected Actor(ActorOptions? options = null)
MaxDegreeOfParallelism = 1,
EnsureOrdered = true,
BoundedCapacity = _options.OverflowPolicy == ActorOverflowPolicy.Unbounded
- ? DataflowBlockOptions.Unbounded
- : _options.Capacity
+ ? DataflowBlockOptions.Unbounded
+ : _options.Capacity
};
- _mailbox = new ActionBlock(ProcessAsync, blockOptions);
+ _mailbox = new(ProcessAsync, blockOptions);
}
/// Enqueues a fire-and-forget message. Returns false only when dropped (DropNewest).
@@ -76,9 +73,7 @@ public async ValueTask TellAsync(TMessage message, CancellationToken cance
/// The request message type.
/// The reply type.
/// The reply.
- public async Task AskAsync(
- TRequest request, CancellationToken cancellationToken = default
- )
+ public async Task AskAsync(TRequest request, CancellationToken cancellationToken = default)
where TRequest : TMessage, IActorRequest
{
ArgumentNullException.ThrowIfNull(request);
@@ -87,8 +82,7 @@ public async Task AskAsync(
_outstanding[request] = 0;
using var registration =
- cancellationToken.Register(() => request.Fail(new OperationCanceledException(cancellationToken))
- );
+ cancellationToken.Register(() => request.Fail(new OperationCanceledException(cancellationToken)));
try
{
@@ -116,9 +110,7 @@ public async Task AskAsync(
/// The message whose handler threw.
/// The thrown exception.
protected virtual ValueTask OnErrorAsync(TMessage message, Exception error)
- {
- return ValueTask.CompletedTask;
- }
+ => ValueTask.CompletedTask;
private async Task ProcessAsync(TMessage message)
{
@@ -193,8 +185,8 @@ private async Task TryDrainAsync(TimeSpan timeout)
}
///
- /// Completes the mailbox and drains queued work within ,
- /// then cancels any handlers still running and faults requests that never completed.
+ /// Completes the mailbox and drains queued work within ,
+ /// then cancels any handlers still running and faults requests that never completed.
///
public async ValueTask DisposeAsync()
{
diff --git a/src/SquidStd.Actors/ActorRequest.cs b/src/SquidStd.Actors/ActorRequest.cs
index e6eb1fb3..e099eb14 100644
--- a/src/SquidStd.Actors/ActorRequest.cs
+++ b/src/SquidStd.Actors/ActorRequest.cs
@@ -3,9 +3,9 @@
namespace SquidStd.Actors;
///
-/// Base request record that removes the boilerplate.
-/// Derive from it together with your actor's message interface, e.g.
-/// record GetNick : ActorRequest<string?>, ISessionMessage;.
+/// Base request record that removes the boilerplate.
+/// Derive from it together with your actor's message interface, e.g.
+/// record GetNick : ActorRequest<string?>, ISessionMessage;.
///
/// The reply type.
public abstract record ActorRequest : IActorRequest
@@ -14,20 +14,13 @@ public abstract record ActorRequest : IActorRequest
new(TaskCreationOptions.RunContinuationsAsynchronously);
///
- public Task Completion
- {
- get { return _completion.Task; }
- }
+ public Task Completion => _completion.Task;
///
public void Reply(TReply value)
- {
- _completion.TrySetResult(value);
- }
+ => _completion.TrySetResult(value);
///
public void Fail(Exception error)
- {
- _completion.TrySetException(error);
- }
+ => _completion.TrySetException(error);
}
diff --git a/src/SquidStd.Actors/Data/ActorOptions.cs b/src/SquidStd.Actors/Data/ActorOptions.cs
index fefb36da..f4aa0603 100644
--- a/src/SquidStd.Actors/Data/ActorOptions.cs
+++ b/src/SquidStd.Actors/Data/ActorOptions.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Actors.Data;
///
-/// Configuration for an mailbox.
+/// Configuration for an mailbox.
///
public sealed class ActorOptions
{
@@ -17,9 +17,9 @@ public sealed class ActorOptions
public ActorErrorPolicy ErrorPolicy { get; init; } = ActorErrorPolicy.Isolate;
///
- /// How long drains queued messages
- /// before cancelling in-flight handlers. Queued work runs to completion within this budget;
- /// once it elapses, the actor cancels and faults any still-pending requests.
+ /// How long drains queued messages
+ /// before cancelling in-flight handlers. Queued work runs to completion within this budget;
+ /// once it elapses, the actor cancels and faults any still-pending requests.
///
public TimeSpan ShutdownDrainTimeout { get; init; } = TimeSpan.FromSeconds(5);
}
diff --git a/src/SquidStd.Actors/Extensions/ActorEventBusExtensions.cs b/src/SquidStd.Actors/Extensions/ActorEventBusExtensions.cs
index 03e87ef0..98acfa02 100644
--- a/src/SquidStd.Actors/Extensions/ActorEventBusExtensions.cs
+++ b/src/SquidStd.Actors/Extensions/ActorEventBusExtensions.cs
@@ -3,8 +3,8 @@
namespace SquidStd.Actors.Extensions;
///
-/// Bridges the event bus to an actor mailbox: published events are mapped to messages and delivered
-/// in order through the actor's single consumer.
+/// Bridges the event bus to an actor mailbox: published events are mapped to messages and delivered
+/// in order through the actor's single consumer.
///
public static class ActorEventBusExtensions
{
@@ -12,8 +12,8 @@ public static class ActorEventBusExtensions
extension(Actor actor)
{
///
- /// Subscribes the actor to on the bus, mapping each event to a
- /// message and telling it to the mailbox. Dispose the returned token to stop delivery.
+ /// Subscribes the actor to on the bus, mapping each event to a
+ /// message and telling it to the mailbox. Dispose the returned token to stop delivery.
///
/// The event bus to subscribe to.
/// Maps an event to an actor message.
@@ -21,12 +21,11 @@ public static class ActorEventBusExtensions
/// A token that unsubscribes when disposed.
public IDisposable SubscribeToEventBus(IEventBus eventBus, Func map)
where TEvent : IEvent
- {
- return eventBus.Subscribe(async (eventData, cancellationToken) =>
+ => eventBus.Subscribe(
+ async (eventData, cancellationToken) =>
{
await actor.TellAsync(map(eventData), cancellationToken);
}
);
- }
}
}
diff --git a/src/SquidStd.Actors/Interfaces/IActorRequest.cs b/src/SquidStd.Actors/Interfaces/IActorRequest.cs
index abbe1e78..fb35c6ea 100644
--- a/src/SquidStd.Actors/Interfaces/IActorRequest.cs
+++ b/src/SquidStd.Actors/Interfaces/IActorRequest.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Actors.Interfaces;
///
-/// A request message that an actor answers with a single typed reply.
+/// A request message that an actor answers with a single typed reply.
///
/// The reply type.
public interface IActorRequest : IActorRequestCore
diff --git a/src/SquidStd.Actors/Interfaces/IActorRequestCore.cs b/src/SquidStd.Actors/Interfaces/IActorRequestCore.cs
index 522a67ef..8e13e894 100644
--- a/src/SquidStd.Actors/Interfaces/IActorRequestCore.cs
+++ b/src/SquidStd.Actors/Interfaces/IActorRequestCore.cs
@@ -1,8 +1,8 @@
namespace SquidStd.Actors.Interfaces;
///
-/// Non-generic request facet allowing the actor infrastructure to fault a pending request
-/// without knowing its reply type.
+/// Non-generic request facet allowing the actor infrastructure to fault a pending request
+/// without knowing its reply type.
///
public interface IActorRequestCore
{
diff --git a/src/SquidStd.Actors/README.md b/src/SquidStd.Actors/README.md
index c88652e1..a34364b6 100644
--- a/src/SquidStd.Actors/README.md
+++ b/src/SquidStd.Actors/README.md
@@ -55,23 +55,23 @@ using var sub = session.SubscribeToEventBus(eventBus, (UserJoinedEvent e) => new
## Key types
-| Type | Purpose |
-|---------------------------|----------------------------------------------------|
-| `Actor` | Mailbox base class (`TellAsync` / `AskAsync`). |
-| `ActorRequest` | Base record for request/response messages. |
-| `IActorRequest` | Request contract (implement directly if not using the base). |
-| `ActorOptions` | Capacity / overflow / error configuration. |
+| Type | Purpose |
+|-------------------------|--------------------------------------------------------------|
+| `Actor` | Mailbox base class (`TellAsync` / `AskAsync`). |
+| `ActorRequest` | Base record for request/response messages. |
+| `IActorRequest` | Request contract (implement directly if not using the base). |
+| `ActorOptions` | Capacity / overflow / error configuration. |
## Options
`ActorOptions` controls the mailbox:
-| Property | Values | Default |
-|------------------|-------------------------------------|----------|
-| `Capacity` | bounded mailbox size | `1024` |
-| `OverflowPolicy` | `Wait` / `DropNewest` / `Unbounded` | `Wait` |
-| `ErrorPolicy` | `Isolate` / `StopOnError` | `Isolate`|
-| `ShutdownDrainTimeout` | any `TimeSpan` | `5s` |
+| Property | Values | Default |
+|------------------------|-------------------------------------|-----------|
+| `Capacity` | bounded mailbox size | `1024` |
+| `OverflowPolicy` | `Wait` / `DropNewest` / `Unbounded` | `Wait` |
+| `ErrorPolicy` | `Isolate` / `StopOnError` | `Isolate` |
+| `ShutdownDrainTimeout` | any `TimeSpan` | `5s` |
- **Wait**: `TellAsync` awaits until capacity frees (back-pressure).
- **DropNewest**: `TellAsync` returns `false` when full.
diff --git a/src/SquidStd.Actors/Types/ActorErrorPolicy.cs b/src/SquidStd.Actors/Types/ActorErrorPolicy.cs
index ec42b9e9..056c66c7 100644
--- a/src/SquidStd.Actors/Types/ActorErrorPolicy.cs
+++ b/src/SquidStd.Actors/Types/ActorErrorPolicy.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Actors.Types;
///
-/// Behavior when a handler throws while processing a fire-and-forget message.
+/// Behavior when a handler throws while processing a fire-and-forget message.
///
public enum ActorErrorPolicy
{
diff --git a/src/SquidStd.Actors/Types/ActorOverflowPolicy.cs b/src/SquidStd.Actors/Types/ActorOverflowPolicy.cs
index 9f1a1924..d54a777a 100644
--- a/src/SquidStd.Actors/Types/ActorOverflowPolicy.cs
+++ b/src/SquidStd.Actors/Types/ActorOverflowPolicy.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Actors.Types;
///
-/// Behavior when the actor mailbox reaches its bounded capacity.
+/// Behavior when the actor mailbox reaches its bounded capacity.
///
public enum ActorOverflowPolicy
{
diff --git a/src/SquidStd.AspNetCore/Extensions/SquidStdAspNetCoreBuilderExtensions.cs b/src/SquidStd.AspNetCore/Extensions/SquidStdAspNetCoreBuilderExtensions.cs
index c44fd3c9..103c6d55 100644
--- a/src/SquidStd.AspNetCore/Extensions/SquidStdAspNetCoreBuilderExtensions.cs
+++ b/src/SquidStd.AspNetCore/Extensions/SquidStdAspNetCoreBuilderExtensions.cs
@@ -9,7 +9,7 @@
namespace SquidStd.AspNetCore.Extensions;
///
-/// Extension methods for connecting SquidStd to ASP.NET Core Minimal API applications.
+/// Extension methods for connecting SquidStd to ASP.NET Core Minimal API applications.
///
public static class SquidStdAspNetCoreBuilderExtensions
{
@@ -26,17 +26,15 @@ private static void ValidateOptions(SquidStdOptions options)
extension(WebApplicationBuilder builder)
{
///
- /// Registers SquidStd using DryIoc as the ASP.NET Core service provider.
+ /// Registers SquidStd using DryIoc as the ASP.NET Core service provider.
///
/// Optional SquidStd bootstrap options callback.
/// The same builder for chaining.
public WebApplicationBuilder UseSquidStd(Action? configureOptions = null)
- {
- return builder.UseSquidStd(configureOptions, null);
- }
+ => builder.UseSquidStd(configureOptions, null);
///
- /// Registers SquidStd using DryIoc as the ASP.NET Core service provider.
+ /// Registers SquidStd using DryIoc as the ASP.NET Core service provider.
///
/// Optional SquidStd bootstrap options callback.
/// Optional DryIoc registration callback.
diff --git a/src/SquidStd.AspNetCore/Extensions/SquidStdHealthChecksExtensions.cs b/src/SquidStd.AspNetCore/Extensions/SquidStdHealthChecksExtensions.cs
index 6ff1155b..ab54d1ff 100644
--- a/src/SquidStd.AspNetCore/Extensions/SquidStdHealthChecksExtensions.cs
+++ b/src/SquidStd.AspNetCore/Extensions/SquidStdHealthChecksExtensions.cs
@@ -8,7 +8,7 @@
namespace SquidStd.AspNetCore.Extensions;
///
-/// Extension methods that bridge SquidStd health checks into the standard ASP.NET Core health-check system.
+/// Extension methods that bridge SquidStd health checks into the standard ASP.NET Core health-check system.
///
public static class SquidStdHealthChecksExtensions
{
@@ -16,9 +16,9 @@ public static class SquidStdHealthChecksExtensions
extension(WebApplicationBuilder builder)
{
///
- /// Registers each SquidStd IHealthCheck as a standard ASP.NET Core health check (one entry
- /// per check, same name). Call after UseSquidStd; expose them with the standard
- /// app.MapHealthChecks(...). Check names must be unique.
+ /// Registers each SquidStd IHealthCheck as a standard ASP.NET Core health check (one entry
+ /// per check, same name). Call after UseSquidStd; expose them with the standard
+ /// app.MapHealthChecks(...). Check names must be unique.
///
/// The same builder for chaining.
public WebApplicationBuilder AddSquidStdHealthChecks()
@@ -40,7 +40,7 @@ out var value
foreach (var check in checks)
{
healthChecks.Add(
- new HealthCheckRegistration(
+ new(
check.Name,
_ => new SquidStdHealthCheckAdapter(check),
HealthStatus.Unhealthy,
diff --git a/src/SquidStd.AspNetCore/Services/SquidStdHealthCheckAdapter.cs b/src/SquidStd.AspNetCore/Services/SquidStdHealthCheckAdapter.cs
index 037ed264..a9b64d07 100644
--- a/src/SquidStd.AspNetCore/Services/SquidStdHealthCheckAdapter.cs
+++ b/src/SquidStd.AspNetCore/Services/SquidStdHealthCheckAdapter.cs
@@ -5,8 +5,8 @@
namespace SquidStd.AspNetCore.Services;
///
-/// Adapts a SquidStd to the standard ASP.NET Core
-/// contract.
+/// Adapts a SquidStd to the standard ASP.NET Core
+/// contract.
///
internal sealed class SquidStdHealthCheckAdapter : IHealthCheck
{
@@ -25,7 +25,7 @@ public async Task CheckHealthAsync(
var result = await _check.CheckAsync(cancellationToken);
return result.Status == SquidHealthStatus.Unhealthy
- ? HealthCheckResult.Unhealthy(result.Description, result.Exception)
- : HealthCheckResult.Healthy(result.Description);
+ ? HealthCheckResult.Unhealthy(result.Description, result.Exception)
+ : HealthCheckResult.Healthy(result.Description);
}
}
diff --git a/src/SquidStd.AspNetCore/Services/SquidStdHostedService.cs b/src/SquidStd.AspNetCore/Services/SquidStdHostedService.cs
index c2f65da8..b279eb7f 100644
--- a/src/SquidStd.AspNetCore/Services/SquidStdHostedService.cs
+++ b/src/SquidStd.AspNetCore/Services/SquidStdHostedService.cs
@@ -4,14 +4,14 @@
namespace SquidStd.AspNetCore.Services;
///
-/// Bridges the ASP.NET Core host lifecycle to the SquidStd bootstrap lifecycle.
+/// Bridges the ASP.NET Core host lifecycle to the SquidStd bootstrap lifecycle.
///
internal sealed class SquidStdHostedService : IHostedService
{
private readonly ISquidStdBootstrap _bootstrap;
///
- /// Initializes the hosted service.
+ /// Initializes the hosted service.
///
/// SquidStd bootstrap instance started with the ASP.NET host.
public SquidStdHostedService(ISquidStdBootstrap bootstrap)
@@ -21,13 +21,9 @@ public SquidStdHostedService(ISquidStdBootstrap bootstrap)
///
public async Task StartAsync(CancellationToken cancellationToken)
- {
- await _bootstrap.StartAsync(cancellationToken);
- }
+ => await _bootstrap.StartAsync(cancellationToken);
///
public async Task StopAsync(CancellationToken cancellationToken)
- {
- await _bootstrap.StopAsync(cancellationToken);
- }
+ => await _bootstrap.StopAsync(cancellationToken);
}
diff --git a/src/SquidStd.Aws.Abstractions/Data/Config/AwsConfigEntry.cs b/src/SquidStd.Aws.Abstractions/Data/Config/AwsConfigEntry.cs
index 80cc661e..fe5e1f43 100644
--- a/src/SquidStd.Aws.Abstractions/Data/Config/AwsConfigEntry.cs
+++ b/src/SquidStd.Aws.Abstractions/Data/Config/AwsConfigEntry.cs
@@ -1,8 +1,8 @@
namespace SquidStd.Aws.Abstractions.Data.Config;
///
-/// Shared connection configuration for AWS-style services (region, credentials, endpoint override).
-/// A dependency-free POCO: each provider maps it to its own SDK (AWS SDK, MinIO SDK, ...).
+/// Shared connection configuration for AWS-style services (region, credentials, endpoint override).
+/// A dependency-free POCO: each provider maps it to its own SDK (AWS SDK, MinIO SDK, ...).
///
public sealed class AwsConfigEntry
{
diff --git a/src/SquidStd.Aws.Abstractions/README.md b/src/SquidStd.Aws.Abstractions/README.md
index 20cc1518..d849eedf 100644
--- a/src/SquidStd.Aws.Abstractions/README.md
+++ b/src/SquidStd.Aws.Abstractions/README.md
@@ -29,8 +29,8 @@ client at that endpoint instead of the regional AWS endpoint.
## Key types
-| Type | Purpose |
-|------|---------|
+| Type | Purpose |
+|------------------|-----------------------------------------------------------------------------------|
| `AwsConfigEntry` | Region, optional credentials and an optional endpoint override (e.g. LocalStack). |
## License
diff --git a/src/SquidStd.Caching.Abstractions/Data/Config/CacheConnectionString.cs b/src/SquidStd.Caching.Abstractions/Data/Config/CacheConnectionString.cs
index 0d1b9274..3463b840 100644
--- a/src/SquidStd.Caching.Abstractions/Data/Config/CacheConnectionString.cs
+++ b/src/SquidStd.Caching.Abstractions/Data/Config/CacheConnectionString.cs
@@ -4,7 +4,7 @@
namespace SquidStd.Caching.Abstractions.Data.Config;
///
-/// Parsed cache connection string of the form scheme://[user:pass@]host[:port][?params].
+/// Parsed cache connection string of the form scheme://[user:pass@]host[:port][?params].
///
public sealed class CacheConnectionString
{
@@ -62,14 +62,14 @@ public static CacheConnectionString Parse(string connectionString)
var query = HttpUtility.ParseQueryString(uri.Query);
var parameters = query.AllKeys
- .Where(static key => key is not null)
- .ToFrozenDictionary(
- key => key!,
- key => query[key] ?? string.Empty,
- StringComparer.OrdinalIgnoreCase
- );
+ .Where(static key => key is not null)
+ .ToFrozenDictionary(
+ key => key!,
+ key => query[key] ?? string.Empty,
+ StringComparer.OrdinalIgnoreCase
+ );
- return new CacheConnectionString(
+ return new(
uri.Scheme,
uri.Host,
uri.Port > 0 ? uri.Port : null,
@@ -81,13 +81,11 @@ public static CacheConnectionString Parse(string connectionString)
/// Builds from the query parameters.
public CacheOptions ToCacheOptions()
- {
- return new CacheOptions
+ => new()
{
DefaultTtl = Parameters.TryGetValue("defaultTtlSeconds", out var ttl) && int.TryParse(ttl, out var seconds)
- ? TimeSpan.FromSeconds(seconds)
- : null,
+ ? TimeSpan.FromSeconds(seconds)
+ : null,
KeyPrefix = Parameters.TryGetValue("keyPrefix", out var prefix) ? prefix : string.Empty
};
- }
}
diff --git a/src/SquidStd.Caching.Abstractions/Data/Config/CacheOptions.cs b/src/SquidStd.Caching.Abstractions/Data/Config/CacheOptions.cs
index 0f633d4c..68fda982 100644
--- a/src/SquidStd.Caching.Abstractions/Data/Config/CacheOptions.cs
+++ b/src/SquidStd.Caching.Abstractions/Data/Config/CacheOptions.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Caching.Abstractions.Data.Config;
///
-/// Options shared by all cache providers.
+/// Options shared by all cache providers.
///
public sealed class CacheOptions
{
diff --git a/src/SquidStd.Caching.Abstractions/Interfaces/ICacheMetrics.cs b/src/SquidStd.Caching.Abstractions/Interfaces/ICacheMetrics.cs
index c88d4bf2..bb966b18 100644
--- a/src/SquidStd.Caching.Abstractions/Interfaces/ICacheMetrics.cs
+++ b/src/SquidStd.Caching.Abstractions/Interfaces/ICacheMetrics.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Caching.Abstractions.Interfaces;
///
-/// Sink for cache instrumentation events.
+/// Sink for cache instrumentation events.
///
public interface ICacheMetrics
{
diff --git a/src/SquidStd.Caching.Abstractions/Interfaces/ICacheProvider.cs b/src/SquidStd.Caching.Abstractions/Interfaces/ICacheProvider.cs
index dd061219..de8a47ae 100644
--- a/src/SquidStd.Caching.Abstractions/Interfaces/ICacheProvider.cs
+++ b/src/SquidStd.Caching.Abstractions/Interfaces/ICacheProvider.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Caching.Abstractions.Interfaces;
///
-/// Byte-level cache backend. Implemented by each provider (in-memory, Redis, ...).
+/// Byte-level cache backend. Implemented by each provider (in-memory, Redis, ...).
///
public interface ICacheProvider : ISquidStdService
{
diff --git a/src/SquidStd.Caching.Abstractions/Interfaces/ICacheService.cs b/src/SquidStd.Caching.Abstractions/Interfaces/ICacheService.cs
index 46cf2db6..db57782e 100644
--- a/src/SquidStd.Caching.Abstractions/Interfaces/ICacheService.cs
+++ b/src/SquidStd.Caching.Abstractions/Interfaces/ICacheService.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Caching.Abstractions.Interfaces;
///
-/// Typed cache-aside facade over an .
+/// Typed cache-aside facade over an .
///
public interface ICacheService
{
diff --git a/src/SquidStd.Caching.Abstractions/Services/CacheMetricsProvider.cs b/src/SquidStd.Caching.Abstractions/Services/CacheMetricsProvider.cs
index 04695d85..c35ee72f 100644
--- a/src/SquidStd.Caching.Abstractions/Services/CacheMetricsProvider.cs
+++ b/src/SquidStd.Caching.Abstractions/Services/CacheMetricsProvider.cs
@@ -6,7 +6,7 @@
namespace SquidStd.Caching.Abstractions.Services;
///
-/// Accumulates aggregate cache metrics and exposes them to the metrics collection system.
+/// Accumulates aggregate cache metrics and exposes them to the metrics collection system.
///
public sealed class CacheMetricsProvider : ICacheMetrics, IMetricProvider
{
@@ -20,27 +20,19 @@ public sealed class CacheMetricsProvider : ICacheMetrics, IMetricProvider
///
public void OnHit(string key)
- {
- Interlocked.Increment(ref _hits);
- }
+ => Interlocked.Increment(ref _hits);
///
public void OnMiss(string key)
- {
- Interlocked.Increment(ref _misses);
- }
+ => Interlocked.Increment(ref _misses);
///
public void OnRemove(string key)
- {
- Interlocked.Increment(ref _removes);
- }
+ => Interlocked.Increment(ref _removes);
///
public void OnSet(string key)
- {
- Interlocked.Increment(ref _sets);
- }
+ => Interlocked.Increment(ref _sets);
///
public ValueTask> CollectAsync(CancellationToken cancellationToken = default)
diff --git a/src/SquidStd.Caching.Abstractions/Services/CacheService.cs b/src/SquidStd.Caching.Abstractions/Services/CacheService.cs
index e21e6cbb..400c9d9e 100644
--- a/src/SquidStd.Caching.Abstractions/Services/CacheService.cs
+++ b/src/SquidStd.Caching.Abstractions/Services/CacheService.cs
@@ -5,8 +5,8 @@
namespace SquidStd.Caching.Abstractions.Services;
///
-/// Typed cache-aside facade: serializes values, applies the key prefix and default TTL, and
-/// implements once over any .
+/// Typed cache-aside facade: serializes values, applies the key prefix and default TTL, and
+/// implements once over any .
///
public sealed class CacheService : ICacheService
{
@@ -35,9 +35,7 @@ public CacheService(
///
public Task ExistsAsync(string key, CancellationToken cancellationToken = default)
- {
- return _provider.ExistsAsync(Prefixed(key), cancellationToken);
- }
+ => _provider.ExistsAsync(Prefixed(key), cancellationToken);
///
public async Task GetAsync(string key, CancellationToken cancellationToken = default)
@@ -104,7 +102,5 @@ public async Task SetAsync(string key, T value, TimeSpan? ttl = null, Cancell
}
private string Prefixed(string key)
- {
- return _keyPrefix.Length == 0 ? key : _keyPrefix + key;
- }
+ => _keyPrefix.Length == 0 ? key : _keyPrefix + key;
}
diff --git a/src/SquidStd.Caching.Abstractions/Services/NoOpCacheMetrics.cs b/src/SquidStd.Caching.Abstractions/Services/NoOpCacheMetrics.cs
index 4d210305..285be016 100644
--- a/src/SquidStd.Caching.Abstractions/Services/NoOpCacheMetrics.cs
+++ b/src/SquidStd.Caching.Abstractions/Services/NoOpCacheMetrics.cs
@@ -3,26 +3,18 @@
namespace SquidStd.Caching.Abstractions.Services;
///
-/// Metrics sink that ignores all events. Used when no metrics are configured.
+/// Metrics sink that ignores all events. Used when no metrics are configured.
///
public sealed class NoOpCacheMetrics : ICacheMetrics
{
/// Shared instance.
public static NoOpCacheMetrics Instance { get; } = new();
- public void OnHit(string key)
- {
- }
+ public void OnHit(string key) { }
- public void OnMiss(string key)
- {
- }
+ public void OnMiss(string key) { }
- public void OnRemove(string key)
- {
- }
+ public void OnRemove(string key) { }
- public void OnSet(string key)
- {
- }
+ public void OnSet(string key) { }
}
diff --git a/src/SquidStd.Caching.Redis/Data/Config/RedisCacheOptions.cs b/src/SquidStd.Caching.Redis/Data/Config/RedisCacheOptions.cs
index 82bf02f9..30dd72d4 100644
--- a/src/SquidStd.Caching.Redis/Data/Config/RedisCacheOptions.cs
+++ b/src/SquidStd.Caching.Redis/Data/Config/RedisCacheOptions.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Caching.Redis.Data.Config;
///
-/// Connection options for the Redis cache provider.
+/// Connection options for the Redis cache provider.
///
public sealed class RedisCacheOptions
{
diff --git a/src/SquidStd.Caching.Redis/Extensions/RedisCacheRegistrationExtensions.cs b/src/SquidStd.Caching.Redis/Extensions/RedisCacheRegistrationExtensions.cs
index 80798883..78e58210 100644
--- a/src/SquidStd.Caching.Redis/Extensions/RedisCacheRegistrationExtensions.cs
+++ b/src/SquidStd.Caching.Redis/Extensions/RedisCacheRegistrationExtensions.cs
@@ -11,7 +11,7 @@
namespace SquidStd.Caching.Redis.Extensions;
///
-/// DryIoc registration helpers for the Redis cache provider.
+/// DryIoc registration helpers for the Redis cache provider.
///
public static class RedisCacheRegistrationExtensions
{
diff --git a/src/SquidStd.Caching.Redis/Services/RedisCacheProvider.cs b/src/SquidStd.Caching.Redis/Services/RedisCacheProvider.cs
index 6163982c..97bcdb33 100644
--- a/src/SquidStd.Caching.Redis/Services/RedisCacheProvider.cs
+++ b/src/SquidStd.Caching.Redis/Services/RedisCacheProvider.cs
@@ -5,7 +5,7 @@
namespace SquidStd.Caching.Redis.Services;
///
-/// Redis backed by a StackExchange.Redis connection multiplexer.
+/// Redis backed by a StackExchange.Redis connection multiplexer.
///
public sealed class RedisCacheProvider : ICacheProvider, IAsyncDisposable
{
@@ -38,9 +38,7 @@ public async ValueTask DisposeAsync()
///
public Task ExistsAsync(string key, CancellationToken cancellationToken = default)
- {
- return Database.KeyExistsAsync(key);
- }
+ => Database.KeyExistsAsync(key);
///
public async Task?> GetAsync(string key, CancellationToken cancellationToken = default)
@@ -57,9 +55,7 @@ public Task ExistsAsync(string key, CancellationToken cancellationToken =
///
public Task RemoveAsync(string key, CancellationToken cancellationToken = default)
- {
- return Database.KeyDeleteAsync(key);
- }
+ => Database.KeyDeleteAsync(key);
///
public async Task SetAsync(
@@ -69,19 +65,15 @@ public async Task SetAsync(
CancellationToken cancellationToken = default
)
{
- var expiry = ttl is null ? Expiration.Default : new Expiration(ttl.Value);
+ var expiry = ttl is null ? Expiration.Default : new(ttl.Value);
await Database.StringSetAsync(key, value.ToArray(), expiry);
}
///
public async ValueTask StartAsync(CancellationToken cancellationToken = default)
- {
- _connection = await ConnectionMultiplexer.ConnectAsync(_options.Configuration);
- }
+ => _connection = await ConnectionMultiplexer.ConnectAsync(_options.Configuration);
///
public ValueTask StopAsync(CancellationToken cancellationToken = default)
- {
- return DisposeAsync();
- }
+ => DisposeAsync();
}
diff --git a/src/SquidStd.Caching/Extensions/CacheRegistrationExtensions.cs b/src/SquidStd.Caching/Extensions/CacheRegistrationExtensions.cs
index e88685ce..2fb42565 100644
--- a/src/SquidStd.Caching/Extensions/CacheRegistrationExtensions.cs
+++ b/src/SquidStd.Caching/Extensions/CacheRegistrationExtensions.cs
@@ -11,7 +11,7 @@
namespace SquidStd.Caching.Extensions;
///
-/// DryIoc registration helpers for the in-memory cache.
+/// DryIoc registration helpers for the in-memory cache.
///
public static class CacheRegistrationExtensions
{
diff --git a/src/SquidStd.Caching/Services/InMemoryCacheProvider.cs b/src/SquidStd.Caching/Services/InMemoryCacheProvider.cs
index c7b93ccf..d63c2879 100644
--- a/src/SquidStd.Caching/Services/InMemoryCacheProvider.cs
+++ b/src/SquidStd.Caching/Services/InMemoryCacheProvider.cs
@@ -4,7 +4,7 @@
namespace SquidStd.Caching.Services;
///
-/// In-memory backed by .
+/// In-memory backed by .
///
public sealed class InMemoryCacheProvider : ICacheProvider
{
@@ -17,9 +17,7 @@ public InMemoryCacheProvider(IMemoryCache cache)
///
public Task ExistsAsync(string key, CancellationToken cancellationToken = default)
- {
- return Task.FromResult(_cache.TryGetValue(key, out _));
- }
+ => Task.FromResult(_cache.TryGetValue(key, out _));
///
public Task?> GetAsync(string key, CancellationToken cancellationToken = default)
@@ -63,13 +61,9 @@ public Task SetAsync(
///
public ValueTask StartAsync(CancellationToken cancellationToken = default)
- {
- return ValueTask.CompletedTask;
- }
+ => ValueTask.CompletedTask;
///
public ValueTask StopAsync(CancellationToken cancellationToken = default)
- {
- return ValueTask.CompletedTask;
- }
+ => ValueTask.CompletedTask;
}
diff --git a/src/SquidStd.Core/Data/Bootstrap/SquidStdLoggerOptions.cs b/src/SquidStd.Core/Data/Bootstrap/SquidStdLoggerOptions.cs
index bd0dd582..e361a730 100644
--- a/src/SquidStd.Core/Data/Bootstrap/SquidStdLoggerOptions.cs
+++ b/src/SquidStd.Core/Data/Bootstrap/SquidStdLoggerOptions.cs
@@ -3,37 +3,37 @@
namespace SquidStd.Core.Data.Bootstrap;
///
-/// Defines YAML-backed logger options for SquidStd bootstrap.
+/// Defines YAML-backed logger options for SquidStd bootstrap.
///
public sealed class SquidStdLoggerOptions
{
///
- /// Gets or sets the minimum logger level.
+ /// Gets or sets the minimum logger level.
///
public LogLevelType MinimumLevel { get; set; } = LogLevelType.Information;
///
- /// Gets or sets whether console logging is enabled.
+ /// Gets or sets whether console logging is enabled.
///
public bool EnableConsole { get; set; } = true;
///
- /// Gets or sets whether file logging is enabled.
+ /// Gets or sets whether file logging is enabled.
///
public bool EnableFile { get; set; }
///
- /// Gets or sets the file log directory. Relative paths are resolved from the SquidStd root directory.
+ /// Gets or sets the file log directory. Relative paths are resolved from the SquidStd root directory.
///
public string LogDirectory { get; set; } = "logs";
///
- /// Gets or sets the file log name or rolling file pattern.
+ /// Gets or sets the file log name or rolling file pattern.
///
public string FileName { get; set; } = "squidstd-.log";
///
- /// Gets or sets the file log rolling interval.
+ /// Gets or sets the file log rolling interval.
///
public SquidStdLogRollingIntervalType RollingInterval { get; set; } = SquidStdLogRollingIntervalType.Day;
}
diff --git a/src/SquidStd.Core/Data/Bootstrap/SquidStdOptions.cs b/src/SquidStd.Core/Data/Bootstrap/SquidStdOptions.cs
index 24885cde..614508d6 100644
--- a/src/SquidStd.Core/Data/Bootstrap/SquidStdOptions.cs
+++ b/src/SquidStd.Core/Data/Bootstrap/SquidStdOptions.cs
@@ -1,17 +1,17 @@
namespace SquidStd.Core.Data.Bootstrap;
///
-/// Defines bootstrap-only options used to locate SquidStd runtime resources.
+/// Defines bootstrap-only options used to locate SquidStd runtime resources.
///
public sealed class SquidStdOptions
{
///
- /// Gets or sets the root directory for configuration, logs, and runtime data.
+ /// Gets or sets the root directory for configuration, logs, and runtime data.
///
public string RootDirectory { get; set; } = Directory.GetCurrentDirectory();
///
- /// Gets or sets the logical configuration name or YAML file name.
+ /// Gets or sets the logical configuration name or YAML file name.
///
public string ConfigName { get; set; } = "squidstd";
}
diff --git a/src/SquidStd.Core/Data/Commands/CommandDispatchResult.cs b/src/SquidStd.Core/Data/Commands/CommandDispatchResult.cs
index 75f59ffb..1d5c44b5 100644
--- a/src/SquidStd.Core/Data/Commands/CommandDispatchResult.cs
+++ b/src/SquidStd.Core/Data/Commands/CommandDispatchResult.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Core.Data.Commands;
///
-/// The outcome of dispatching a command.
+/// The outcome of dispatching a command.
///
/// True when at least one handler was registered for the command type.
/// The number of handlers invoked.
diff --git a/src/SquidStd.Core/Data/Commands/CommandHandlerError.cs b/src/SquidStd.Core/Data/Commands/CommandHandlerError.cs
index 2c946a2b..90a788eb 100644
--- a/src/SquidStd.Core/Data/Commands/CommandHandlerError.cs
+++ b/src/SquidStd.Core/Data/Commands/CommandHandlerError.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Core.Data.Commands;
///
-/// A handler that threw while processing a dispatched command.
+/// A handler that threw while processing a dispatched command.
///
/// The concrete handler type that failed.
/// The exception thrown by the handler.
diff --git a/src/SquidStd.Core/Data/Config/HealthCheckOptions.cs b/src/SquidStd.Core/Data/Config/HealthCheckOptions.cs
index f578f535..b344fbe1 100644
--- a/src/SquidStd.Core/Data/Config/HealthCheckOptions.cs
+++ b/src/SquidStd.Core/Data/Config/HealthCheckOptions.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Core.Data.Config;
///
-/// Options for the health-check aggregator.
+/// Options for the health-check aggregator.
///
public sealed class HealthCheckOptions
{
diff --git a/src/SquidStd.Core/Data/Events/EventBusOptions.cs b/src/SquidStd.Core/Data/Events/EventBusOptions.cs
index 7893a1dd..c3c2569c 100644
--- a/src/SquidStd.Core/Data/Events/EventBusOptions.cs
+++ b/src/SquidStd.Core/Data/Events/EventBusOptions.cs
@@ -1,12 +1,12 @@
namespace SquidStd.Core.Data.Events;
///
-/// Options controlling event bus dispatch behavior.
+/// Options controlling event bus dispatch behavior.
///
public sealed record EventBusOptions
{
///
- /// Listeners whose handling exceeds this duration are logged as slow. Defaults to 100ms.
+ /// Listeners whose handling exceeds this duration are logged as slow. Defaults to 100ms.
///
public TimeSpan SlowListenerThreshold { get; init; } = TimeSpan.FromMilliseconds(100);
}
diff --git a/src/SquidStd.Core/Data/Files/FileChangedEvent.cs b/src/SquidStd.Core/Data/Files/FileChangedEvent.cs
index f5f7e728..ddb195f2 100644
--- a/src/SquidStd.Core/Data/Files/FileChangedEvent.cs
+++ b/src/SquidStd.Core/Data/Files/FileChangedEvent.cs
@@ -4,7 +4,7 @@
namespace SquidStd.Core.Data.Files;
///
-/// Published on the event bus when a watched file changes, after debouncing.
+/// Published on the event bus when a watched file changes, after debouncing.
///
/// The kind of change observed.
/// The absolute path of the affected file.
diff --git a/src/SquidStd.Core/Data/Health/HealthCheckResult.cs b/src/SquidStd.Core/Data/Health/HealthCheckResult.cs
index 76bba2b0..344b315c 100644
--- a/src/SquidStd.Core/Data/Health/HealthCheckResult.cs
+++ b/src/SquidStd.Core/Data/Health/HealthCheckResult.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Data.Health;
///
-/// Result of a single health check. is stamped by the aggregator.
+/// Result of a single health check. is stamped by the aggregator.
///
public sealed record HealthCheckResult
{
@@ -21,13 +21,9 @@ public sealed record HealthCheckResult
/// Creates a healthy result.
public static HealthCheckResult Healthy(string? description = null)
- {
- return new HealthCheckResult { Status = HealthStatus.Healthy, Description = description };
- }
+ => new() { Status = HealthStatus.Healthy, Description = description };
/// Creates an unhealthy result.
public static HealthCheckResult Unhealthy(string? description = null, Exception? exception = null)
- {
- return new HealthCheckResult { Status = HealthStatus.Unhealthy, Description = description, Exception = exception };
- }
+ => new() { Status = HealthStatus.Unhealthy, Description = description, Exception = exception };
}
diff --git a/src/SquidStd.Core/Data/Health/HealthReport.cs b/src/SquidStd.Core/Data/Health/HealthReport.cs
index e9a8a56f..93c05f8c 100644
--- a/src/SquidStd.Core/Data/Health/HealthReport.cs
+++ b/src/SquidStd.Core/Data/Health/HealthReport.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Data.Health;
///
-/// Aggregated result of running every registered health check.
+/// Aggregated result of running every registered health check.
///
public sealed record HealthReport
{
diff --git a/src/SquidStd.Core/Data/Jobs/JobsConfig.cs b/src/SquidStd.Core/Data/Jobs/JobsConfig.cs
index c83ae3a7..7f91275b 100644
--- a/src/SquidStd.Core/Data/Jobs/JobsConfig.cs
+++ b/src/SquidStd.Core/Data/Jobs/JobsConfig.cs
@@ -1,17 +1,17 @@
namespace SquidStd.Core.Data.Jobs;
///
-/// Configuration for the background job system.
+/// Configuration for the background job system.
///
public sealed class JobsConfig
{
///
- /// Gets or sets the number of worker threads.
+ /// Gets or sets the number of worker threads.
///
public int WorkerThreadCount { get; set; }
///
- /// Gets or sets the seconds to wait for worker shutdown.
+ /// Gets or sets the seconds to wait for worker shutdown.
///
public double ShutdownTimeoutSeconds { get; set; } = 1.0;
}
diff --git a/src/SquidStd.Core/Data/Metrics/MetricSample.cs b/src/SquidStd.Core/Data/Metrics/MetricSample.cs
index 69ba580c..b4612060 100644
--- a/src/SquidStd.Core/Data/Metrics/MetricSample.cs
+++ b/src/SquidStd.Core/Data/Metrics/MetricSample.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Data.Metrics;
///
-/// Represents one collected metric value.
+/// Represents one collected metric value.
///
/// Metric name emitted by the provider.
/// Metric numeric value.
diff --git a/src/SquidStd.Core/Data/Metrics/MetricsCollectedEvent.cs b/src/SquidStd.Core/Data/Metrics/MetricsCollectedEvent.cs
index 38efc0ff..854a3f2b 100644
--- a/src/SquidStd.Core/Data/Metrics/MetricsCollectedEvent.cs
+++ b/src/SquidStd.Core/Data/Metrics/MetricsCollectedEvent.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Data.Metrics;
///
-/// Event published after a metrics snapshot has been collected.
+/// Event published after a metrics snapshot has been collected.
///
/// The collected metrics snapshot.
public sealed record MetricsCollectedEvent(MetricsSnapshot Snapshot) : IEvent;
diff --git a/src/SquidStd.Core/Data/Metrics/MetricsConfig.cs b/src/SquidStd.Core/Data/Metrics/MetricsConfig.cs
index 8c9424eb..531ce7f7 100644
--- a/src/SquidStd.Core/Data/Metrics/MetricsConfig.cs
+++ b/src/SquidStd.Core/Data/Metrics/MetricsConfig.cs
@@ -4,27 +4,27 @@
namespace SquidStd.Core.Data.Metrics;
///
-/// Configuration for periodic metrics collection.
+/// Configuration for periodic metrics collection.
///
public sealed class MetricsConfig : IConfigEntry
{
///
- /// Gets or sets whether metrics collection is enabled.
+ /// Gets or sets whether metrics collection is enabled.
///
public bool Enabled { get; set; } = true;
///
- /// Gets or sets the collection interval in milliseconds.
+ /// Gets or sets the collection interval in milliseconds.
///
public int IntervalMilliseconds { get; set; } = 1000;
///
- /// Gets or sets whether each provider collection is logged.
+ /// Gets or sets whether each provider collection is logged.
///
public bool LogEnabled { get; set; } = true;
///
- /// Gets or sets the log level used for metrics collection logs.
+ /// Gets or sets the log level used for metrics collection logs.
///
public LogLevelType LogLevel { get; set; } = LogLevelType.Trace;
@@ -33,7 +33,5 @@ public sealed class MetricsConfig : IConfigEntry
Type IConfigEntry.ConfigType => typeof(MetricsConfig);
object IConfigEntry.CreateDefault()
- {
- return new MetricsConfig();
- }
+ => new MetricsConfig();
}
diff --git a/src/SquidStd.Core/Data/Metrics/MetricsSnapshot.cs b/src/SquidStd.Core/Data/Metrics/MetricsSnapshot.cs
index 58777768..a325930b 100644
--- a/src/SquidStd.Core/Data/Metrics/MetricsSnapshot.cs
+++ b/src/SquidStd.Core/Data/Metrics/MetricsSnapshot.cs
@@ -1,22 +1,22 @@
namespace SquidStd.Core.Data.Metrics;
///
-/// Stores the last collected metrics batch.
+/// Stores the last collected metrics batch.
///
public sealed class MetricsSnapshot
{
///
- /// Gets the timestamp when the snapshot was collected.
+ /// Gets the timestamp when the snapshot was collected.
///
public DateTimeOffset CollectedAt { get; }
///
- /// Gets metrics keyed by their flattened metric name.
+ /// Gets metrics keyed by their flattened metric name.
///
public IReadOnlyDictionary Metrics { get; }
///
- /// Initializes a metrics snapshot.
+ /// Initializes a metrics snapshot.
///
/// Timestamp when the snapshot was collected.
/// Metrics keyed by their flattened metric name.
diff --git a/src/SquidStd.Core/Data/Scheduling/CronJobInfo.cs b/src/SquidStd.Core/Data/Scheduling/CronJobInfo.cs
index bf45a4b6..860db3fd 100644
--- a/src/SquidStd.Core/Data/Scheduling/CronJobInfo.cs
+++ b/src/SquidStd.Core/Data/Scheduling/CronJobInfo.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Core.Data.Scheduling;
///
-/// Immutable snapshot describing a registered cron job.
+/// Immutable snapshot describing a registered cron job.
///
public sealed class CronJobInfo
{
diff --git a/src/SquidStd.Core/Data/Storage/SecretsConfig.cs b/src/SquidStd.Core/Data/Storage/SecretsConfig.cs
index 1708dc4e..ee471b1a 100644
--- a/src/SquidStd.Core/Data/Storage/SecretsConfig.cs
+++ b/src/SquidStd.Core/Data/Storage/SecretsConfig.cs
@@ -3,17 +3,17 @@
namespace SquidStd.Core.Data.Storage;
///
-/// Configuration for encrypted local secret storage.
+/// Configuration for encrypted local secret storage.
///
public sealed class SecretsConfig : IConfigEntry
{
///
- /// Gets or sets the root directory used by local secret storage.
+ /// Gets or sets the root directory used by local secret storage.
///
public string RootDirectory { get; set; } = "secrets";
///
- /// Gets or sets the environment variable that contains the base64 AES key.
+ /// Gets or sets the environment variable that contains the base64 AES key.
///
public string KeyEnvironmentVariable { get; set; } = "SQUIDSTD_SECRETS_KEY";
@@ -22,7 +22,5 @@ public sealed class SecretsConfig : IConfigEntry
Type IConfigEntry.ConfigType => typeof(SecretsConfig);
object IConfigEntry.CreateDefault()
- {
- return new SecretsConfig();
- }
+ => new SecretsConfig();
}
diff --git a/src/SquidStd.Core/Data/Timing/TimerWheelConfig.cs b/src/SquidStd.Core/Data/Timing/TimerWheelConfig.cs
index 064129b1..a92aa79d 100644
--- a/src/SquidStd.Core/Data/Timing/TimerWheelConfig.cs
+++ b/src/SquidStd.Core/Data/Timing/TimerWheelConfig.cs
@@ -1,17 +1,17 @@
namespace SquidStd.Core.Data.Timing;
///
-/// Configuration for the hashed timer wheel.
+/// Configuration for the hashed timer wheel.
///
public sealed class TimerWheelConfig
{
///
- /// Gets or sets the timer wheel granularity.
+ /// Gets or sets the timer wheel granularity.
///
public TimeSpan TickDuration { get; set; } = TimeSpan.FromMilliseconds(8);
///
- /// Gets or sets the number of slots in the wheel.
+ /// Gets or sets the number of slots in the wheel.
///
public int WheelSize { get; set; } = 512;
}
diff --git a/src/SquidStd.Core/Data/Timing/TimerWheelPumpConfig.cs b/src/SquidStd.Core/Data/Timing/TimerWheelPumpConfig.cs
index 6c12fadb..c106b8f8 100644
--- a/src/SquidStd.Core/Data/Timing/TimerWheelPumpConfig.cs
+++ b/src/SquidStd.Core/Data/Timing/TimerWheelPumpConfig.cs
@@ -1,12 +1,12 @@
namespace SquidStd.Core.Data.Timing;
///
-/// Configuration for the timer wheel pump service.
+/// Configuration for the timer wheel pump service.
///
public sealed class TimerWheelPumpConfig
{
///
- /// Gets or sets how often the pump advances the timer wheel.
+ /// Gets or sets how often the pump advances the timer wheel.
///
public TimeSpan PumpInterval { get; set; } = TimeSpan.FromMilliseconds(250);
}
diff --git a/src/SquidStd.Core/Directories/DirectoriesConfig.cs b/src/SquidStd.Core/Directories/DirectoriesConfig.cs
index a9792945..9cfd74bd 100644
--- a/src/SquidStd.Core/Directories/DirectoriesConfig.cs
+++ b/src/SquidStd.Core/Directories/DirectoriesConfig.cs
@@ -3,33 +3,33 @@
namespace SquidStd.Core.Directories;
///
-/// Configuration for managing directory structures with automatic creation and path resolution
+/// Configuration for managing directory structures with automatic creation and path resolution
///
public class DirectoriesConfig
{
private readonly string[] _directories;
///
- /// Gets the root directory path.
+ /// Gets the root directory path.
///
public string Root { get; }
///
- /// Gets the path for the specified directory type.
+ /// Gets the path for the specified directory type.
///
/// The directory type as string.
/// The path for the directory type.
public string this[string directoryType] => GetPath(directoryType);
///
- /// Gets the path for the specified directory type enum.
+ /// Gets the path for the specified directory type enum.
///
/// The directory type enum.
/// The path for the directory type.
public string this[Enum directoryType] => GetPath(directoryType.ToString());
///
- /// Initializes a new instance of the DirectoriesConfig class.
+ /// Initializes a new instance of the DirectoriesConfig class.
///
/// The root directory path.
/// The array of directory types.
@@ -42,17 +42,15 @@ public DirectoriesConfig(string rootDirectory, string[] directories)
}
///
- /// Gets the path for the specified directory type enum.
+ /// Gets the path for the specified directory type enum.
///
/// The directory type enum value.
/// The path for the directory type.
public string GetPath(TEnum value) where TEnum : struct, Enum
- {
- return GetPath(Enum.GetName(value));
- }
+ => GetPath(Enum.GetName(value));
///
- /// Gets the path for the specified directory type string.
+ /// Gets the path for the specified directory type string.
///
/// The directory type as string.
/// The path for the directory type.
@@ -69,16 +67,14 @@ public string GetPath(string directoryType)
}
///
- /// Returns a string representation of the root directory.
+ /// Returns a string representation of the root directory.
///
/// The root directory path.
public override string ToString()
- {
- return Root;
- }
+ => Root;
///
- /// Initializes the directories configuration.
+ /// Initializes the directories configuration.
///
private void Init()
{
@@ -90,7 +86,7 @@ private void Init()
var directoryTypes = _directories.ToList();
foreach (var path in directoryTypes.Select(GetPath)
- .Where(path => !Directory.Exists(path)))
+ .Where(path => !Directory.Exists(path)))
{
Directory.CreateDirectory(path);
}
diff --git a/src/SquidStd.Core/Extensions/Crypto/EncryptExtensions.cs b/src/SquidStd.Core/Extensions/Crypto/EncryptExtensions.cs
index 4e05eab1..dbaf9b92 100644
--- a/src/SquidStd.Core/Extensions/Crypto/EncryptExtensions.cs
+++ b/src/SquidStd.Core/Extensions/Crypto/EncryptExtensions.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Extensions.Crypto;
///
-/// String convenience helpers for AES-GCM encryption using a base64-encoded key.
+/// String convenience helpers for AES-GCM encryption using a base64-encoded key.
///
public static class EncryptExtensions
{
@@ -11,7 +11,7 @@ public static class EncryptExtensions
extension(string text)
{
///
- /// Encrypts the string with AES-GCM and returns a base64 payload.
+ /// Encrypts the string with AES-GCM and returns a base64 payload.
///
/// The base64-encoded key.
/// The base64-encoded encrypted payload.
@@ -23,7 +23,7 @@ public string EncryptString(string base64Key)
}
///
- /// Decrypts a base64 payload produced by .
+ /// Decrypts a base64 payload produced by .
///
/// The base64-encoded key.
/// The decrypted text.
diff --git a/src/SquidStd.Core/Extensions/Directories/DirectoriesExtension.cs b/src/SquidStd.Core/Extensions/Directories/DirectoriesExtension.cs
index cc1a1a03..0d263937 100644
--- a/src/SquidStd.Core/Extensions/Directories/DirectoriesExtension.cs
+++ b/src/SquidStd.Core/Extensions/Directories/DirectoriesExtension.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Extensions.Directories;
///
-/// Provides extension methods for directory path resolution and environment variable expansion
+/// Provides extension methods for directory path resolution and environment variable expansion
///
public static class DirectoriesExtension
{
@@ -11,7 +11,7 @@ public static class DirectoriesExtension
extension(string path)
{
///
- /// Resolves path by expanding tilde (~) to user home directory and expanding environment variables
+ /// Resolves path by expanding tilde (~) to user home directory and expanding environment variables
///
/// The fully resolved path with expanded environment variables
/// Thrown when path is null or empty
diff --git a/src/SquidStd.Core/Extensions/Env/EnvExtensions.cs b/src/SquidStd.Core/Extensions/Env/EnvExtensions.cs
index 141c896b..c70f81a0 100644
--- a/src/SquidStd.Core/Extensions/Env/EnvExtensions.cs
+++ b/src/SquidStd.Core/Extensions/Env/EnvExtensions.cs
@@ -4,7 +4,7 @@
namespace SquidStd.Core.Extensions.Env;
///
-/// Provides extension methods for expanding environment variables in strings
+/// Provides extension methods for expanding environment variables in strings
///
public static class EnvExtensions
{
@@ -17,7 +17,7 @@ public static class EnvExtensions
extension(string input)
{
///
- /// Expands environment variables in a string using custom $VARIABLE syntax
+ /// Expands environment variables in a string using custom $VARIABLE syntax
///
/// The string with environment variables expanded to their values
public string ExpandEnvironmentVariables()
@@ -38,8 +38,8 @@ public string ExpandEnvironmentVariables()
}
///
- /// Replaces "$VAR" tokens with the matching environment variable value. Unknown variables are
- /// left unchanged.
+ /// Replaces "$VAR" tokens with the matching environment variable value. Unknown variables are
+ /// left unchanged.
///
/// The string with known $VAR tokens substituted.
public string ReplaceEnv()
diff --git a/src/SquidStd.Core/Extensions/Logger/LogLevelExtensions.cs b/src/SquidStd.Core/Extensions/Logger/LogLevelExtensions.cs
index ff272cb5..9c676cfe 100644
--- a/src/SquidStd.Core/Extensions/Logger/LogLevelExtensions.cs
+++ b/src/SquidStd.Core/Extensions/Logger/LogLevelExtensions.cs
@@ -4,7 +4,7 @@
namespace SquidStd.Core.Extensions.Logger;
///
-/// Extension methods for converting log levels between different logging frameworks.
+/// Extension methods for converting log levels between different logging frameworks.
///
public static class LogLevelExtensions
{
@@ -12,12 +12,11 @@ public static class LogLevelExtensions
extension(LogLevelType logLevel)
{
///
- /// Converts a LogLevelType to a Serilog LogEventLevel.
+ /// Converts a LogLevelType to a Serilog LogEventLevel.
///
/// The corresponding Serilog log event level.
public LogEventLevel ToSerilogLogLevel()
- {
- return logLevel switch
+ => logLevel switch
{
LogLevelType.Trace => LogEventLevel.Verbose,
LogLevelType.Debug => LogEventLevel.Debug,
@@ -27,6 +26,5 @@ public LogEventLevel ToSerilogLogLevel()
LogLevelType.Critical => LogEventLevel.Fatal,
_ => LogEventLevel.Information
};
- }
}
}
diff --git a/src/SquidStd.Core/Extensions/Random/RandomExtensions.cs b/src/SquidStd.Core/Extensions/Random/RandomExtensions.cs
index 1867a3d0..3ba2fc8e 100644
--- a/src/SquidStd.Core/Extensions/Random/RandomExtensions.cs
+++ b/src/SquidStd.Core/Extensions/Random/RandomExtensions.cs
@@ -5,7 +5,7 @@
namespace SquidStd.Core.Extensions.Random;
///
-/// Shuffling and random-selection helpers over collections, built on .
+/// Shuffling and random-selection helpers over collections, built on .
///
public static class RandomExtensions
{
@@ -15,16 +15,12 @@ public static class RandomExtensions
/// Shuffles the array in place.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Shuffle()
- {
- BuiltInRng.Generator.Shuffle(array.AsSpan());
- }
+ => BuiltInRng.Generator.Shuffle(array.AsSpan());
/// Returns a random element from the array.
/// A random element, or default when the array is empty.
public T? RandomElement()
- {
- return array.Length == 0 ? default : array[RandomUtils.Random(array.Length)];
- }
+ => array.Length == 0 ? default : array[RandomUtils.Random(array.Length)];
/// Returns a random sample of distinct elements without modifying the source.
/// Number of elements to sample.
@@ -63,9 +59,7 @@ public T[] RandomSample(int count)
/// Shuffles the list in place.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Shuffle()
- {
- BuiltInRng.Generator.Shuffle(CollectionsMarshal.AsSpan(list));
- }
+ => BuiltInRng.Generator.Shuffle(CollectionsMarshal.AsSpan(list));
/// Returns a random sample of distinct elements without modifying the source.
/// Number of elements to sample.
@@ -105,8 +99,6 @@ public List RandomSample(int count)
/// Returns a random element from the list.
/// A random element, or default when the list is empty.
public T? RandomElement()
- {
- return list.Count == 0 ? default : list[RandomUtils.Random(list.Count)];
- }
+ => list.Count == 0 ? default : list[RandomUtils.Random(list.Count)];
}
}
diff --git a/src/SquidStd.Core/Extensions/Strings/Base64Extensions.cs b/src/SquidStd.Core/Extensions/Strings/Base64Extensions.cs
index 36063765..32ecaa4c 100644
--- a/src/SquidStd.Core/Extensions/Strings/Base64Extensions.cs
+++ b/src/SquidStd.Core/Extensions/Strings/Base64Extensions.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Extensions.Strings;
///
-/// Provides base64 conversion helpers for strings and byte arrays.
+/// Provides base64 conversion helpers for strings and byte arrays.
///
public static class Base64Extensions
{
@@ -11,7 +11,7 @@ public static class Base64Extensions
extension(string value)
{
///
- /// Determines whether the string is a well-formed base64 value.
+ /// Determines whether the string is a well-formed base64 value.
///
/// true when the string decodes as base64; otherwise false.
public bool IsBase64String()
@@ -27,43 +27,35 @@ public bool IsBase64String()
}
///
- /// Encodes the UTF-8 bytes of the string as base64.
+ /// Encodes the UTF-8 bytes of the string as base64.
///
/// The base64 representation.
public string ToBase64()
- {
- return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
- }
+ => Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
///
- /// Decodes a base64 string into its UTF-8 text.
+ /// Decodes a base64 string into its UTF-8 text.
///
/// The decoded text.
public string FromBase64()
- {
- return Encoding.UTF8.GetString(Convert.FromBase64String(value));
- }
+ => Encoding.UTF8.GetString(Convert.FromBase64String(value));
///
- /// Decodes a base64 string into its raw bytes.
+ /// Decodes a base64 string into its raw bytes.
///
/// The decoded bytes.
public byte[] FromBase64ToByteArray()
- {
- return Convert.FromBase64String(value);
- }
+ => Convert.FromBase64String(value);
}
/// The bytes to encode.
extension(byte[] value)
{
///
- /// Encodes the bytes as base64.
+ /// Encodes the bytes as base64.
///
/// The base64 representation.
public string ToBase64()
- {
- return Convert.ToBase64String(value);
- }
+ => Convert.ToBase64String(value);
}
}
diff --git a/src/SquidStd.Core/Extensions/Strings/StringMethodExtension.cs b/src/SquidStd.Core/Extensions/Strings/StringMethodExtension.cs
index 41234bf9..2741372c 100644
--- a/src/SquidStd.Core/Extensions/Strings/StringMethodExtension.cs
+++ b/src/SquidStd.Core/Extensions/Strings/StringMethodExtension.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Extensions.Strings;
///
-/// Provides extension methods for string operations, particularly for case conversions.
+/// Provides extension methods for string operations, particularly for case conversions.
///
public static class StringMethodExtension
{
@@ -11,93 +11,73 @@ public static class StringMethodExtension
extension(string text)
{
///
- /// Converts a string to camelCase.
+ /// Converts a string to camelCase.
///
/// A camelCase version of the input string.
public string ToCamelCase()
- {
- return StringUtils.ToCamelCase(text);
- }
+ => StringUtils.ToCamelCase(text);
///
- /// Converts a string to Dot Case.
+ /// Converts a string to Dot Case.
///
/// A Dot Case version of the input string.
public string ToDotCase()
- {
- return StringUtils.ToDotCase(text);
- }
+ => StringUtils.ToDotCase(text);
///
- /// Converts a string to kebab-case.
+ /// Converts a string to kebab-case.
///
/// A kebab-case version of the input string.
public string ToKebabCase()
- {
- return StringUtils.ToKebabCase(text);
- }
+ => StringUtils.ToKebabCase(text);
///
- /// Converts a string to PascalCase.
+ /// Converts a string to PascalCase.
///
/// A PascalCase version of the input string.
public string ToPascalCase()
- {
- return StringUtils.ToPascalCase(text);
- }
+ => StringUtils.ToPascalCase(text);
///
- /// Converts a string to Path Case.
+ /// Converts a string to Path Case.
///
/// A Path Case version of the input string.
public string ToPathCase()
- {
- return StringUtils.ToPathCase(text);
- }
+ => StringUtils.ToPathCase(text);
///
- /// Converts a string to Sentence Case.
+ /// Converts a string to Sentence Case.
///
/// A Sentence Case version of the input string.
public string ToSentenceCase()
- {
- return StringUtils.ToSentenceCase(text);
- }
+ => StringUtils.ToSentenceCase(text);
///
- /// Converts a string to snake_case.
+ /// Converts a string to snake_case.
///
/// A snake_case version of the input string.
public string ToSnakeCase()
- {
- return StringUtils.ToSnakeCase(text);
- }
+ => StringUtils.ToSnakeCase(text);
///
- /// Converts a string to UPPER_SNAKE_CASE.
+ /// Converts a string to UPPER_SNAKE_CASE.
///
/// An UPPER_SNAKE_CASE version of the input string.
public string ToSnakeCaseUpper()
- {
- return StringUtils.ToUpperSnakeCase(text);
- }
+ => StringUtils.ToUpperSnakeCase(text);
///
- /// Converts a string to Title Case.
+ /// Converts a string to Title Case.
///
/// A Title Case version of the input string.
public string ToTitleCase()
- {
- return StringUtils.ToTitleCase(text);
- }
+ => StringUtils.ToTitleCase(text);
///
- /// Converts a string to Train Case.
+ /// Converts a string to Train Case.
///
/// A Train Case version of the input string.
public string ToTrainCase()
- {
- return StringUtils.ToTrainCase(text);
- }
+ => StringUtils.ToTrainCase(text);
}
}
diff --git a/src/SquidStd.Core/Files/FileWatcherService.cs b/src/SquidStd.Core/Files/FileWatcherService.cs
index 837b274a..cbd150bb 100644
--- a/src/SquidStd.Core/Files/FileWatcherService.cs
+++ b/src/SquidStd.Core/Files/FileWatcherService.cs
@@ -9,11 +9,11 @@
namespace SquidStd.Core.Files;
///
-/// Recursive directory watcher that coalesces rapid file-system notifications with a debounce window and
-/// publishes a single per path on the event bus. Each
-/// call adds one recursive watcher with its own glob filter, so several directories (each with a different
-/// pattern, e.g. *.lua and *.json) can be watched at once. The watcher stays decoupled from
-/// any reload logic.
+/// Recursive directory watcher that coalesces rapid file-system notifications with a debounce window and
+/// publishes a single per path on the event bus. Each
+/// call adds one recursive watcher with its own glob filter, so several directories (each with a different
+/// pattern, e.g. *.lua and *.json) can be watched at once. The watcher stays decoupled from
+/// any reload logic.
///
public sealed class FileWatcherService : IFileWatcherService
{
@@ -28,16 +28,14 @@ public sealed class FileWatcherService : IFileWatcherService
private bool _disposed;
///
- /// Initializes the watcher with the default 300ms debounce window.
+ /// Initializes the watcher with the default 300ms debounce window.
///
/// The bus that receives notifications.
public FileWatcherService(IEventBus eventBus)
- : this(eventBus, TimeSpan.FromMilliseconds(300))
- {
- }
+ : this(eventBus, TimeSpan.FromMilliseconds(300)) { }
///
- /// Initializes the watcher with an explicit debounce window.
+ /// Initializes the watcher with an explicit debounce window.
///
/// The bus that receives notifications.
/// How long a path must be quiet before its change is published.
@@ -54,9 +52,7 @@ public FileWatcherService(IEventBus eventBus, TimeSpan debounceDelay)
///
public void Watch(string path)
- {
- Watch(path, "*");
- }
+ => Watch(path, "*");
///
public void Watch(string path, string filter)
@@ -81,7 +77,7 @@ public void Watch(string path, string filter)
return;
}
- watcher = new FileSystemWatcher(fullPath, filter)
+ watcher = new(fullPath, filter)
{
NotifyFilter = NotifyFilters.LastWrite |
NotifyFilters.FileName |
@@ -173,7 +169,7 @@ private void OnFileChanged(object sender, FileSystemEventArgs e)
_ => FileChangeKind.Changed
};
- Schedule(new FileChangedEvent(kind, Path.GetFullPath(e.FullPath)));
+ Schedule(new(kind, Path.GetFullPath(e.FullPath)));
}
private void OnFileRenamed(object sender, RenamedEventArgs e)
@@ -183,9 +179,7 @@ private void OnFileRenamed(object sender, RenamedEventArgs e)
return;
}
- Schedule(
- new FileChangedEvent(FileChangeKind.Renamed, Path.GetFullPath(e.FullPath), Path.GetFullPath(e.OldFullPath))
- );
+ Schedule(new(FileChangeKind.Renamed, Path.GetFullPath(e.FullPath), Path.GetFullPath(e.OldFullPath)));
}
private void Schedule(FileChangedEvent change)
@@ -200,7 +194,7 @@ private void Schedule(FileChangedEvent change)
var timer = _debounceTimers.AddOrUpdate(
key,
- k => new Timer(OnDebounceElapsed, k, _debounce, Timeout.InfiniteTimeSpan),
+ k => new(OnDebounceElapsed, k, _debounce, Timeout.InfiniteTimeSpan),
(_, existing) =>
{
existing.Change(_debounce, Timeout.InfiniteTimeSpan);
@@ -245,9 +239,7 @@ private async Task PublishAsync(FileChangedEvent change)
}
private static string KeyFor(string path, string filter)
- {
- return path + "|" + filter;
- }
+ => path + "|" + filter;
private static void DisposeWatcher(FileSystemWatcher watcher)
{
diff --git a/src/SquidStd.Core/Interfaces/Bootstrap/ISquidStdBootstrap.cs b/src/SquidStd.Core/Interfaces/Bootstrap/ISquidStdBootstrap.cs
index b987f9f2..857851bf 100644
--- a/src/SquidStd.Core/Interfaces/Bootstrap/ISquidStdBootstrap.cs
+++ b/src/SquidStd.Core/Interfaces/Bootstrap/ISquidStdBootstrap.cs
@@ -4,57 +4,57 @@
namespace SquidStd.Core.Interfaces.Bootstrap;
///
-/// Coordinates SquidStd dependency registration, configuration loading, and service lifecycle.
+/// Coordinates SquidStd dependency registration, configuration loading, and service lifecycle.
///
public interface ISquidStdBootstrap : IAsyncDisposable
{
///
- /// Gets the bootstrap options used to configure runtime resources.
+ /// Gets the bootstrap options used to configure runtime resources.
///
SquidStdOptions Options { get; }
///
- /// Gets the owned dependency injection container.
+ /// Gets the owned dependency injection container.
///
IContainer Container { get; }
///
- /// Applies custom service registrations before the bootstrap lifecycle starts.
+ /// Applies custom service registrations before the bootstrap lifecycle starts.
///
/// Callback that receives and returns the container.
/// The same bootstrap instance for chaining.
ISquidStdBootstrap ConfigureService(Func configure);
///
- /// Applies custom service registrations before the bootstrap lifecycle starts.
+ /// Applies custom service registrations before the bootstrap lifecycle starts.
///
/// Callback that receives and returns the container.
/// The same bootstrap instance for chaining.
ISquidStdBootstrap ConfigureServices(Func configure);
///
- /// Resolves a service from the owned dependency injection container.
+ /// Resolves a service from the owned dependency injection container.
///
/// The service type to resolve.
/// The resolved service instance.
TService Resolve();
///
- /// Starts services, waits until cancellation, and then stops services.
+ /// Starts services, waits until cancellation, and then stops services.
///
/// Token that controls the run lifetime.
/// A task that completes after services have stopped.
Task RunAsync(CancellationToken cancellationToken = default);
///
- /// Starts registered lifecycle services in priority order.
+ /// Starts registered lifecycle services in priority order.
///
/// Token used to cancel the start operation.
/// A task that represents the asynchronous start operation.
ValueTask StartAsync(CancellationToken cancellationToken = default);
///
- /// Stops started lifecycle services in reverse priority order.
+ /// Stops started lifecycle services in reverse priority order.
///
/// Token used to cancel the stop operation.
/// A task that represents the asynchronous stop operation.
diff --git a/src/SquidStd.Core/Interfaces/Commands/ICommand.cs b/src/SquidStd.Core/Interfaces/Commands/ICommand.cs
index 71256c51..9d8dd4cc 100644
--- a/src/SquidStd.Core/Interfaces/Commands/ICommand.cs
+++ b/src/SquidStd.Core/Interfaces/Commands/ICommand.cs
@@ -1,8 +1,6 @@
namespace SquidStd.Core.Interfaces.Commands;
///
-/// Marker contract for commands dispatched through an .
+/// Marker contract for commands dispatched through an .
///
-public interface ICommand
-{
-}
+public interface ICommand { }
diff --git a/src/SquidStd.Core/Interfaces/Commands/ICommandContextFactorySeeded.cs b/src/SquidStd.Core/Interfaces/Commands/ICommandContextFactorySeeded.cs
index f9631719..19f021b0 100644
--- a/src/SquidStd.Core/Interfaces/Commands/ICommandContextFactorySeeded.cs
+++ b/src/SquidStd.Core/Interfaces/Commands/ICommandContextFactorySeeded.cs
@@ -1,8 +1,8 @@
namespace SquidStd.Core.Interfaces.Commands;
///
-/// Produces a from a seed (for example the connection a message
-/// arrived on), so a dispatch can carry the context that belongs to that seed.
+/// Produces a from a seed (for example the connection a message
+/// arrived on), so a dispatch can carry the context that belongs to that seed.
///
/// The context type produced.
/// The seed the context is built from.
diff --git a/src/SquidStd.Core/Interfaces/Commands/ICommandDispatcher.cs b/src/SquidStd.Core/Interfaces/Commands/ICommandDispatcher.cs
index 768eb2f9..0214af29 100644
--- a/src/SquidStd.Core/Interfaces/Commands/ICommandDispatcher.cs
+++ b/src/SquidStd.Core/Interfaces/Commands/ICommandDispatcher.cs
@@ -3,8 +3,8 @@
namespace SquidStd.Core.Interfaces.Commands;
///
-/// Dispatches typed commands to registered handlers within an ambient ,
-/// fanning a command out to every handler registered for its type.
+/// Dispatches typed commands to registered handlers within an ambient ,
+/// fanning a command out to every handler registered for its type.
///
/// The ambient context type.
public interface ICommandDispatcher
@@ -28,7 +28,9 @@ public interface ICommandDispatcher
/// The cancellation token.
/// The dispatch result.
Task DispatchAsync(
- TCommand command, TContext context, CancellationToken cancellationToken = default
+ TCommand command,
+ TContext context,
+ CancellationToken cancellationToken = default
)
where TCommand : ICommand;
}
diff --git a/src/SquidStd.Core/Interfaces/Commands/ICommandHandler.cs b/src/SquidStd.Core/Interfaces/Commands/ICommandHandler.cs
index 58d1940c..9a4676cd 100644
--- a/src/SquidStd.Core/Interfaces/Commands/ICommandHandler.cs
+++ b/src/SquidStd.Core/Interfaces/Commands/ICommandHandler.cs
@@ -1,8 +1,8 @@
namespace SquidStd.Core.Interfaces.Commands;
///
-/// Handles a command of type within the ambient
-/// (for example the current session or connection).
+/// Handles a command of type within the ambient
+/// (for example the current session or connection).
///
/// The command type handled.
/// The ambient context type passed to the handler.
diff --git a/src/SquidStd.Core/Interfaces/Commands/ISeededCommandDispatcher.cs b/src/SquidStd.Core/Interfaces/Commands/ISeededCommandDispatcher.cs
index a10511f1..8725f991 100644
--- a/src/SquidStd.Core/Interfaces/Commands/ISeededCommandDispatcher.cs
+++ b/src/SquidStd.Core/Interfaces/Commands/ISeededCommandDispatcher.cs
@@ -3,11 +3,11 @@
namespace SquidStd.Core.Interfaces.Commands;
///
-/// Dispatches commands by first building the from a
-/// (for example the originating connection) through an
-/// , then delegating to the underlying
-/// . Handlers are still registered on the
-/// .
+/// Dispatches commands by first building the from a
+/// (for example the originating connection) through an
+/// , then delegating to the underlying
+/// . Handlers are still registered on the
+/// .
///
/// The ambient context type.
/// The seed the context is built from.
@@ -20,7 +20,9 @@ public interface ISeededCommandDispatcher
/// The cancellation token.
/// The dispatch result.
Task DispatchAsync(
- TCommand command, TSeed seed, CancellationToken cancellationToken = default
+ TCommand command,
+ TSeed seed,
+ CancellationToken cancellationToken = default
)
where TCommand : ICommand;
}
diff --git a/src/SquidStd.Core/Interfaces/Config/IConfigEntry.cs b/src/SquidStd.Core/Interfaces/Config/IConfigEntry.cs
index c5fcdbd8..0b7a7ca7 100644
--- a/src/SquidStd.Core/Interfaces/Config/IConfigEntry.cs
+++ b/src/SquidStd.Core/Interfaces/Config/IConfigEntry.cs
@@ -1,22 +1,22 @@
namespace SquidStd.Core.Interfaces.Config;
///
-/// Describes a configuration section that can be composed into YAML and registered into DI.
+/// Describes a configuration section that can be composed into YAML and registered into DI.
///
public interface IConfigEntry
{
///
- /// Gets the top-level YAML section name.
+ /// Gets the top-level YAML section name.
///
string SectionName { get; }
///
- /// Gets the concrete configuration type for this section.
+ /// Gets the concrete configuration type for this section.
///
Type ConfigType { get; }
///
- /// Creates a default configuration value for this section.
+ /// Creates a default configuration value for this section.
///
/// The default configuration object.
object CreateDefault();
diff --git a/src/SquidStd.Core/Interfaces/Config/IConfigManagerService.cs b/src/SquidStd.Core/Interfaces/Config/IConfigManagerService.cs
index 626620ee..0ae4a387 100644
--- a/src/SquidStd.Core/Interfaces/Config/IConfigManagerService.cs
+++ b/src/SquidStd.Core/Interfaces/Config/IConfigManagerService.cs
@@ -1,50 +1,50 @@
namespace SquidStd.Core.Interfaces.Config;
///
-/// Manages the YAML configuration file and registers loaded sections into DI.
+/// Manages the YAML configuration file and registers loaded sections into DI.
///
public interface IConfigManagerService
{
///
- /// Gets the logical configuration name.
+ /// Gets the logical configuration name.
///
string ConfigName { get; }
///
- /// Gets the directory where the configuration file is searched.
+ /// Gets the directory where the configuration file is searched.
///
string ConfigDirectory { get; }
///
- /// Gets the resolved YAML configuration file path.
+ /// Gets the resolved YAML configuration file path.
///
string ConfigPath { get; }
///
- /// Gets the registered configuration entries.
+ /// Gets the registered configuration entries.
///
IReadOnlyCollection Entries { get; }
///
- /// Composes the currently loaded sections into YAML.
+ /// Composes the currently loaded sections into YAML.
///
/// The composed YAML document.
string Compose();
///
- /// Gets a loaded configuration section from DI.
+ /// Gets a loaded configuration section from DI.
///
/// The configuration type.
/// The loaded configuration section.
TConfig GetConfig() where TConfig : class;
///
- /// Loads or creates the configured YAML file and registers every section into DI.
+ /// Loads or creates the configured YAML file and registers every section into DI.
///
void Load();
///
- /// Saves the currently loaded sections to the configured YAML file.
+ /// Saves the currently loaded sections to the configured YAML file.
///
void Save();
}
diff --git a/src/SquidStd.Core/Interfaces/Events/IEvent.cs b/src/SquidStd.Core/Interfaces/Events/IEvent.cs
index 9dc7bc9e..3b4e0027 100644
--- a/src/SquidStd.Core/Interfaces/Events/IEvent.cs
+++ b/src/SquidStd.Core/Interfaces/Events/IEvent.cs
@@ -1,8 +1,6 @@
namespace SquidStd.Core.Interfaces.Events;
///
-/// Marker contract for events dispatched through the SquidStd event bus.
+/// Marker contract for events dispatched through the SquidStd event bus.
///
-public interface IEvent
-{
-}
+public interface IEvent { }
diff --git a/src/SquidStd.Core/Interfaces/Events/IEventBus.cs b/src/SquidStd.Core/Interfaces/Events/IEventBus.cs
index 879e6344..2f3d8059 100644
--- a/src/SquidStd.Core/Interfaces/Events/IEventBus.cs
+++ b/src/SquidStd.Core/Interfaces/Events/IEventBus.cs
@@ -1,19 +1,19 @@
namespace SquidStd.Core.Interfaces.Events;
///
-/// In-process event bus that dispatches events to registered listeners in parallel.
+/// In-process event bus that dispatches events to registered listeners in parallel.
///
public interface IEventBus
{
///
- /// Publishes an event and blocks until every listener has completed.
+ /// Publishes an event and blocks until every listener has completed.
///
/// The event payload.
/// The event type.
void Publish(TEvent eventData) where TEvent : IEvent;
///
- /// Publishes an event and completes when every listener has finished.
+ /// Publishes an event and completes when every listener has finished.
///
/// The event payload.
/// The cancellation token.
@@ -22,7 +22,7 @@ public interface IEventBus
Task PublishAsync(TEvent eventData, CancellationToken cancellationToken = default) where TEvent : IEvent;
///
- /// Registers a listener for the specified event type. Dispose the returned token to unsubscribe.
+ /// Registers a listener for the specified event type. Dispose the returned token to unsubscribe.
///
/// The listener to register.
/// The event type.
@@ -30,7 +30,7 @@ public interface IEventBus
IDisposable RegisterListener(IEventListener listener) where TEvent : IEvent;
///
- /// Subscribes a delegate handler for the specified event type. Dispose the returned token to unsubscribe.
+ /// Subscribes a delegate handler for the specified event type. Dispose the returned token to unsubscribe.
///
/// The handler invoked for each published event.
/// The event type.
diff --git a/src/SquidStd.Core/Interfaces/Events/IEventListener.cs b/src/SquidStd.Core/Interfaces/Events/IEventListener.cs
index f3a7a3b5..73820859 100644
--- a/src/SquidStd.Core/Interfaces/Events/IEventListener.cs
+++ b/src/SquidStd.Core/Interfaces/Events/IEventListener.cs
@@ -1,13 +1,13 @@
namespace SquidStd.Core.Interfaces.Events;
///
-/// Handles an event published on the SquidStd event bus.
+/// Handles an event published on the SquidStd event bus.
///
/// The event type handled by the listener.
public interface IEventListener where TEvent : IEvent
{
///
- /// Handles a published event.
+ /// Handles a published event.
///
/// The event payload.
/// The cancellation token.
diff --git a/src/SquidStd.Core/Interfaces/Files/IFileWatcherService.cs b/src/SquidStd.Core/Interfaces/Files/IFileWatcherService.cs
index 076d9565..19db2c43 100644
--- a/src/SquidStd.Core/Interfaces/Files/IFileWatcherService.cs
+++ b/src/SquidStd.Core/Interfaces/Files/IFileWatcherService.cs
@@ -1,34 +1,34 @@
namespace SquidStd.Core.Interfaces.Files;
///
-/// Watches directories recursively and publishes debounced file-change events on the event bus.
+/// Watches directories recursively and publishes debounced file-change events on the event bus.
///
public interface IFileWatcherService : IDisposable
{
///
- /// Starts watching a directory and all of its current and future subdirectories, for every file.
- /// The directory is created if it does not exist.
+ /// Starts watching a directory and all of its current and future subdirectories, for every file.
+ /// The directory is created if it does not exist.
///
/// The directory to watch.
void Watch(string path);
///
- /// Starts watching a directory and all of its current and future subdirectories, limited to files
- /// matching the glob filter. The directory is created if it does not exist. Call this once per
- /// directory to watch several at the same time, each with its own filter.
+ /// Starts watching a directory and all of its current and future subdirectories, limited to files
+ /// matching the glob filter. The directory is created if it does not exist. Call this once per
+ /// directory to watch several at the same time, each with its own filter.
///
/// The directory to watch.
/// A glob pattern such as *.lua or * for all files.
void Watch(string path, string filter);
///
- /// Stops watching a directory and its subdirectories.
+ /// Stops watching a directory and its subdirectories.
///
/// The directory to stop watching.
void Unwatch(string path);
///
- /// Stops every watcher and cancels pending debounced notifications.
+ /// Stops every watcher and cancels pending debounced notifications.
///
void Stop();
}
diff --git a/src/SquidStd.Core/Interfaces/Health/IHealthCheck.cs b/src/SquidStd.Core/Interfaces/Health/IHealthCheck.cs
index 8acf796f..1555dad3 100644
--- a/src/SquidStd.Core/Interfaces/Health/IHealthCheck.cs
+++ b/src/SquidStd.Core/Interfaces/Health/IHealthCheck.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Interfaces.Health;
///
-/// A single health check for one component.
+/// A single health check for one component.
///
public interface IHealthCheck
{
diff --git a/src/SquidStd.Core/Interfaces/Health/IHealthCheckService.cs b/src/SquidStd.Core/Interfaces/Health/IHealthCheckService.cs
index 9da3dea7..c04b9042 100644
--- a/src/SquidStd.Core/Interfaces/Health/IHealthCheckService.cs
+++ b/src/SquidStd.Core/Interfaces/Health/IHealthCheckService.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Interfaces.Health;
///
-/// Runs every registered and aggregates the results.
+/// Runs every registered and aggregates the results.
///
public interface IHealthCheckService
{
diff --git a/src/SquidStd.Core/Interfaces/Jobs/IJobSystem.cs b/src/SquidStd.Core/Interfaces/Jobs/IJobSystem.cs
index 2bdd1104..79c5336e 100644
--- a/src/SquidStd.Core/Interfaces/Jobs/IJobSystem.cs
+++ b/src/SquidStd.Core/Interfaces/Jobs/IJobSystem.cs
@@ -1,32 +1,32 @@
namespace SquidStd.Core.Interfaces.Jobs;
///
-/// Schedules work on a fixed-size pool of worker threads.
+/// Schedules work on a fixed-size pool of worker threads.
///
public interface IJobSystem : IDisposable
{
///
- /// Gets the number of worker threads.
+ /// Gets the number of worker threads.
///
int WorkerCount { get; }
///
- /// Gets the number of jobs waiting in the queue.
+ /// Gets the number of jobs waiting in the queue.
///
int PendingCount { get; }
///
- /// Gets the number of jobs currently executing.
+ /// Gets the number of jobs currently executing.
///
int ActiveCount { get; }
///
- /// Gets the number of jobs that completed since startup.
+ /// Gets the number of jobs that completed since startup.
///
long CompletedCount { get; }
///
- /// Schedules work on a worker thread.
+ /// Schedules work on a worker thread.
///
/// Work invoked on a worker thread.
/// Token used to cancel the job before it starts.
@@ -34,7 +34,7 @@ public interface IJobSystem : IDisposable
Task ScheduleAsync(Action work, CancellationToken cancellationToken = default);
///
- /// Schedules work on a worker thread and returns the result.
+ /// Schedules work on a worker thread and returns the result.
///
/// Work invoked on a worker thread.
/// Token used to cancel the job before it starts.
diff --git a/src/SquidStd.Core/Interfaces/Metrics/IMetricProvider.cs b/src/SquidStd.Core/Interfaces/Metrics/IMetricProvider.cs
index a5d02ade..cd13980e 100644
--- a/src/SquidStd.Core/Interfaces/Metrics/IMetricProvider.cs
+++ b/src/SquidStd.Core/Interfaces/Metrics/IMetricProvider.cs
@@ -3,17 +3,17 @@
namespace SquidStd.Core.Interfaces.Metrics;
///
-/// Provides metric samples for one subsystem domain.
+/// Provides metric samples for one subsystem domain.
///
public interface IMetricProvider
{
///
- /// Gets the unique provider name used as metric name prefix.
+ /// Gets the unique provider name used as metric name prefix.
///
string ProviderName { get; }
///
- /// Collects the current metric samples for this provider.
+ /// Collects the current metric samples for this provider.
///
/// Token used to cancel collection.
/// The collected metric samples.
diff --git a/src/SquidStd.Core/Interfaces/Metrics/IMetricsCollectionService.cs b/src/SquidStd.Core/Interfaces/Metrics/IMetricsCollectionService.cs
index c0e0989b..37aef401 100644
--- a/src/SquidStd.Core/Interfaces/Metrics/IMetricsCollectionService.cs
+++ b/src/SquidStd.Core/Interfaces/Metrics/IMetricsCollectionService.cs
@@ -3,24 +3,24 @@
namespace SquidStd.Core.Interfaces.Metrics;
///
-/// Exposes the latest metrics snapshot collected from registered providers.
+/// Exposes the latest metrics snapshot collected from registered providers.
///
public interface IMetricsCollectionService
{
///
- /// Gets all metrics from the latest snapshot.
+ /// Gets all metrics from the latest snapshot.
///
/// Metrics keyed by their flattened metric name.
IReadOnlyDictionary GetAllMetrics();
///
- /// Gets the latest collected metrics snapshot.
+ /// Gets the latest collected metrics snapshot.
///
/// The current metrics snapshot.
MetricsSnapshot GetSnapshot();
///
- /// Gets the current metrics status.
+ /// Gets the current metrics status.
///
/// The current metrics snapshot.
MetricsSnapshot GetStatus();
diff --git a/src/SquidStd.Core/Interfaces/Scheduling/ICronScheduler.cs b/src/SquidStd.Core/Interfaces/Scheduling/ICronScheduler.cs
index 255e6858..a3e6b1d5 100644
--- a/src/SquidStd.Core/Interfaces/Scheduling/ICronScheduler.cs
+++ b/src/SquidStd.Core/Interfaces/Scheduling/ICronScheduler.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Core.Interfaces.Scheduling;
///
-/// Schedules asynchronous jobs on standard 5-field cron expressions (UTC).
+/// Schedules asynchronous jobs on standard 5-field cron expressions (UTC).
///
public interface ICronScheduler
{
@@ -11,7 +11,7 @@ public interface ICronScheduler
IReadOnlyCollection Jobs { get; }
///
- /// Registers a cron job.
+ /// Registers a cron job.
///
/// Logical job name.
/// Standard 5-field cron expression, evaluated in UTC.
diff --git a/src/SquidStd.Core/Interfaces/Secrets/ISecretProtector.cs b/src/SquidStd.Core/Interfaces/Secrets/ISecretProtector.cs
index 382dea52..07fc86cb 100644
--- a/src/SquidStd.Core/Interfaces/Secrets/ISecretProtector.cs
+++ b/src/SquidStd.Core/Interfaces/Secrets/ISecretProtector.cs
@@ -1,19 +1,19 @@
namespace SquidStd.Core.Interfaces.Secrets;
///
-/// Protects and unprotects secret payloads.
+/// Protects and unprotects secret payloads.
///
public interface ISecretProtector
{
///
- /// Protects a plaintext payload.
+ /// Protects a plaintext payload.
///
/// Plaintext bytes to protect.
/// Protected payload bytes.
byte[] Protect(byte[] plaintext);
///
- /// Unprotects a protected payload.
+ /// Unprotects a protected payload.
///
/// Protected payload bytes.
/// Plaintext bytes.
diff --git a/src/SquidStd.Core/Interfaces/Secrets/ISecretStore.cs b/src/SquidStd.Core/Interfaces/Secrets/ISecretStore.cs
index f499b937..6562762e 100644
--- a/src/SquidStd.Core/Interfaces/Secrets/ISecretStore.cs
+++ b/src/SquidStd.Core/Interfaces/Secrets/ISecretStore.cs
@@ -1,12 +1,12 @@
namespace SquidStd.Core.Interfaces.Secrets;
///
-/// Stores encrypted secret values by logical name.
+/// Stores encrypted secret values by logical name.
///
public interface ISecretStore
{
///
- /// Deletes a secret.
+ /// Deletes a secret.
///
/// The secret name.
/// Token used to cancel the operation.
@@ -14,7 +14,7 @@ public interface ISecretStore
ValueTask DeleteAsync(string name, CancellationToken cancellationToken = default);
///
- /// Checks whether a secret exists.
+ /// Checks whether a secret exists.
///
/// The secret name.
/// Token used to cancel the operation.
@@ -22,7 +22,7 @@ public interface ISecretStore
ValueTask ExistsAsync(string name, CancellationToken cancellationToken = default);
///
- /// Gets a secret value.
+ /// Gets a secret value.
///
/// The secret name.
/// Token used to cancel the operation.
@@ -30,7 +30,7 @@ public interface ISecretStore
ValueTask GetAsync(string name, CancellationToken cancellationToken = default);
///
- /// Sets a secret value.
+ /// Sets a secret value.
///
/// The secret name.
/// The secret value.
@@ -38,7 +38,7 @@ public interface ISecretStore
ValueTask SetAsync(string name, string value, CancellationToken cancellationToken = default);
///
- /// Enumerates stored secret names, optionally filtered by prefix.
+ /// Enumerates stored secret names, optionally filtered by prefix.
///
/// Optional name prefix; null or empty returns all names.
/// Token used to cancel the enumeration.
diff --git a/src/SquidStd.Core/Interfaces/Serialization/IDataDeserializer.cs b/src/SquidStd.Core/Interfaces/Serialization/IDataDeserializer.cs
index c8fa8416..0c649821 100644
--- a/src/SquidStd.Core/Interfaces/Serialization/IDataDeserializer.cs
+++ b/src/SquidStd.Core/Interfaces/Serialization/IDataDeserializer.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Core.Interfaces.Serialization;
///
-/// Deserializes bytes to typed values.
+/// Deserializes bytes to typed values.
///
public interface IDataDeserializer
{
diff --git a/src/SquidStd.Core/Interfaces/Serialization/IDataSerializer.cs b/src/SquidStd.Core/Interfaces/Serialization/IDataSerializer.cs
index a216e3be..6b4b140c 100644
--- a/src/SquidStd.Core/Interfaces/Serialization/IDataSerializer.cs
+++ b/src/SquidStd.Core/Interfaces/Serialization/IDataSerializer.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Core.Interfaces.Serialization;
///
-/// Serializes typed values to bytes.
+/// Serializes typed values to bytes.
///
public interface IDataSerializer
{
diff --git a/src/SquidStd.Core/Interfaces/Threading/IMainThreadDispatcher.cs b/src/SquidStd.Core/Interfaces/Threading/IMainThreadDispatcher.cs
index aa9202a1..82fde106 100644
--- a/src/SquidStd.Core/Interfaces/Threading/IMainThreadDispatcher.cs
+++ b/src/SquidStd.Core/Interfaces/Threading/IMainThreadDispatcher.cs
@@ -1,24 +1,24 @@
namespace SquidStd.Core.Interfaces.Threading;
///
-/// Queues callbacks for execution on the caller that drains the queue.
+/// Queues callbacks for execution on the caller that drains the queue.
///
public interface IMainThreadDispatcher
{
///
- /// Gets the number of callbacks waiting to be drained.
+ /// Gets the number of callbacks waiting to be drained.
///
int PendingCount { get; }
///
- /// Executes queued callbacks on the calling thread.
+ /// Executes queued callbacks on the calling thread.
///
/// Optional wall-clock budget in milliseconds.
/// The number of callbacks executed.
int DrainPending(double? budgetMs = null);
///
- /// Queues a callback for later execution.
+ /// Queues a callback for later execution.
///
/// Callback to execute when the queue is drained.
void Post(Action action);
diff --git a/src/SquidStd.Core/Interfaces/Timing/ITimerService.cs b/src/SquidStd.Core/Interfaces/Timing/ITimerService.cs
index 3e8d4a7e..41941238 100644
--- a/src/SquidStd.Core/Interfaces/Timing/ITimerService.cs
+++ b/src/SquidStd.Core/Interfaces/Timing/ITimerService.cs
@@ -1,12 +1,12 @@
namespace SquidStd.Core.Interfaces.Timing;
///
-/// Schedules timer callbacks on a hashed timer wheel.
+/// Schedules timer callbacks on a hashed timer wheel.
///
public interface ITimerService
{
///
- /// Registers a timer.
+ /// Registers a timer.
///
/// Logical timer name.
/// Timer interval.
@@ -23,26 +23,26 @@ string RegisterTimer(
);
///
- /// Removes all registered timers.
+ /// Removes all registered timers.
///
void UnregisterAllTimers();
///
- /// Removes a timer by id.
+ /// Removes a timer by id.
///
/// Timer id to remove.
/// true when a timer was removed; otherwise false.
bool UnregisterTimer(string timerId);
///
- /// Removes all timers with the specified name.
+ /// Removes all timers with the specified name.
///
/// Timer name to remove.
/// The number of removed timers.
int UnregisterTimersByName(string name);
///
- /// Advances the wheel using an absolute timestamp in milliseconds.
+ /// Advances the wheel using an absolute timestamp in milliseconds.
///
/// Absolute monotonic timestamp in milliseconds.
/// The number of processed wheel ticks.
diff --git a/src/SquidStd.Core/Json/JsonContextTypeResolver.cs b/src/SquidStd.Core/Json/JsonContextTypeResolver.cs
index ff0214f6..cf2cf232 100644
--- a/src/SquidStd.Core/Json/JsonContextTypeResolver.cs
+++ b/src/SquidStd.Core/Json/JsonContextTypeResolver.cs
@@ -5,12 +5,12 @@
namespace SquidStd.Core.Json;
///
-/// Utility class to retrieve registered types from JsonSerializerContext at runtime.
+/// Utility class to retrieve registered types from JsonSerializerContext at runtime.
///
public static class JsonContextTypeResolver
{
///
- /// Gets all types registered in the specified JsonSerializerContext.
+ /// Gets all types registered in the specified JsonSerializerContext.
///
/// The JsonSerializerContext to query.
/// A collection of registered Type objects.
@@ -18,10 +18,11 @@ public static IEnumerable GetRegisteredTypes(JsonSerializerContext context
{
// Get all JsonTypeInfo properties from the context
var properties = GetContextType(context)
- .GetProperties()
- .Where(p => p.PropertyType.IsGenericType &&
- p.PropertyType.GetGenericTypeDefinition() == typeof(JsonTypeInfo<>)
- );
+ .GetProperties()
+ .Where(
+ p => p.PropertyType.IsGenericType &&
+ p.PropertyType.GetGenericTypeDefinition() == typeof(JsonTypeInfo<>)
+ );
foreach (var property in properties)
{
@@ -33,19 +34,17 @@ public static IEnumerable GetRegisteredTypes(JsonSerializerContext context
}
///
- /// Gets all registered types that inherit from a specific base type.
+ /// Gets all registered types that inherit from a specific base type.
///
/// The JsonSerializerContext to query.
/// The base type to filter by.
/// A collection of types that inherit from TBase.
public static IEnumerable GetRegisteredTypes(JsonSerializerContext context)
- {
- return GetRegisteredTypes(context)
+ => GetRegisteredTypes(context)
.Where(t => typeof(TBase).IsAssignableFrom(t));
- }
///
- /// Gets all registered types with their corresponding JsonTypeInfo.
+ /// Gets all registered types with their corresponding JsonTypeInfo.
///
/// The JsonSerializerContext to query.
/// A dictionary mapping Type to JsonTypeInfo.
@@ -54,10 +53,11 @@ public static Dictionary GetRegisteredTypesWithInfo(JsonSeri
var result = new Dictionary();
var properties = GetContextType(context)
- .GetProperties()
- .Where(p => p.PropertyType.IsGenericType &&
- p.PropertyType.GetGenericTypeDefinition() == typeof(JsonTypeInfo<>)
- );
+ .GetProperties()
+ .Where(
+ p => p.PropertyType.IsGenericType &&
+ p.PropertyType.GetGenericTypeDefinition() == typeof(JsonTypeInfo<>)
+ );
foreach (var property in properties)
{
@@ -74,7 +74,7 @@ public static Dictionary GetRegisteredTypesWithInfo(JsonSeri
}
///
- /// Gets the JsonTypeInfo for a specific type if registered.
+ /// Gets the JsonTypeInfo for a specific type if registered.
///
/// The JsonSerializerContext to query.
/// The type to get info for.
@@ -90,15 +90,13 @@ public static Dictionary GetRegisteredTypesWithInfo(JsonSeri
}
///
- /// Checks if a specific type is registered in the context.
+ /// Checks if a specific type is registered in the context.
///
/// The JsonSerializerContext to query.
/// The type to check.
/// True if the type is registered, false otherwise.
public static bool IsTypeRegistered(JsonSerializerContext context, Type type)
- {
- return GetRegisteredTypes(context).Contains(type);
- }
+ => GetRegisteredTypes(context).Contains(type);
[UnconditionalSuppressMessage(
"Trimming",
@@ -107,7 +105,5 @@ public static bool IsTypeRegistered(JsonSerializerContext context, Type type)
)]
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)]
private static Type GetContextType(JsonSerializerContext context)
- {
- return context.GetType();
- }
+ => context.GetType();
}
diff --git a/src/SquidStd.Core/Json/JsonDataSerializer.cs b/src/SquidStd.Core/Json/JsonDataSerializer.cs
index 3a2fd7a1..c20a7576 100644
--- a/src/SquidStd.Core/Json/JsonDataSerializer.cs
+++ b/src/SquidStd.Core/Json/JsonDataSerializer.cs
@@ -5,9 +5,9 @@
namespace SquidStd.Core.Json;
///
-/// Default JSON data serializer based on Web defaults
-/// (reflection-based, supports arbitrary types). Implements both
-/// and .
+/// Default JSON data serializer based on Web defaults
+/// (reflection-based, supports arbitrary types). Implements both
+/// and .
///
public sealed class JsonDataSerializer : IDataSerializer, IDataDeserializer
{
@@ -15,21 +15,17 @@ public sealed class JsonDataSerializer : IDataSerializer, IDataDeserializer
public JsonDataSerializer()
{
- _options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
+ _options = new(JsonSerializerDefaults.Web);
}
- [RequiresUnreferencedCode("JSON deserialization may require types that cannot be statically analyzed.")]
- [RequiresDynamicCode("JSON deserialization may require runtime code generation.")]
+ [RequiresUnreferencedCode("JSON deserialization may require types that cannot be statically analyzed."),
+ RequiresDynamicCode("JSON deserialization may require runtime code generation.")]
public T Deserialize(ReadOnlyMemory data)
- {
- return JsonSerializer.Deserialize(data.Span, _options) ??
- throw new InvalidOperationException($"Deserialization returned null for type {typeof(T).Name}.");
- }
+ => JsonSerializer.Deserialize(data.Span, _options) ??
+ throw new InvalidOperationException($"Deserialization returned null for type {typeof(T).Name}.");
- [RequiresUnreferencedCode("JSON serialization may require types that cannot be statically analyzed.")]
- [RequiresDynamicCode("JSON serialization may require runtime code generation.")]
+ [RequiresUnreferencedCode("JSON serialization may require types that cannot be statically analyzed."),
+ RequiresDynamicCode("JSON serialization may require runtime code generation.")]
public ReadOnlyMemory Serialize(T value)
- {
- return JsonSerializer.SerializeToUtf8Bytes(value, _options);
- }
+ => JsonSerializer.SerializeToUtf8Bytes(value, _options);
}
diff --git a/src/SquidStd.Core/Json/JsonUtils.cs b/src/SquidStd.Core/Json/JsonUtils.cs
index 93795587..847a038c 100644
--- a/src/SquidStd.Core/Json/JsonUtils.cs
+++ b/src/SquidStd.Core/Json/JsonUtils.cs
@@ -8,7 +8,7 @@
namespace SquidStd.Core.Json;
///
-/// Provides utility methods for JSON serialization and deserialization.
+/// Provides utility methods for JSON serialization and deserialization.
///
public static class JsonUtils
{
@@ -27,7 +27,7 @@ static JsonUtils()
}
///
- /// Adds a JSON converter to the global converter list. Thread-safe.
+ /// Adds a JSON converter to the global converter list. Thread-safe.
///
/// The converter to add.
public static void AddJsonConverter(JsonConverter converter)
@@ -47,17 +47,18 @@ public static void AddJsonConverter(JsonConverter converter)
}
///
- /// Deserializes a JSON string to an object using global options.
+ /// Deserializes a JSON string to an object using global options.
///
/// The type to deserialize to.
/// The JSON string to deserialize.
/// Deserialized object.
[RequiresUnreferencedCode(
- "JSON deserialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
- )]
- [RequiresDynamicCode(
- "JSON deserialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
- )]
+ "JSON deserialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
+ ),
+ RequiresDynamicCode(
+ "JSON deserialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
+ )]
+
///
/// Deserializes a JSON string to an object using global options.
///
@@ -80,7 +81,7 @@ public static void AddJsonConverter(JsonConverter converter)
}
///
- /// Deserializes a JSON string to an object using a JsonSerializerContext.
+ /// Deserializes a JSON string to an object using a JsonSerializerContext.
///
/// The type to deserialize to.
/// The JSON string to deserialize.
@@ -105,17 +106,18 @@ public static T Deserialize(string json, JsonSerializerContext context)
}
///
- /// Deserializes an object from a JSON file.
+ /// Deserializes an object from a JSON file.
///
/// The type to deserialize to.
/// Path to the JSON file.
/// Deserialized object.
[RequiresUnreferencedCode(
- "JSON deserialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
- )]
- [RequiresDynamicCode(
- "JSON deserialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
- )]
+ "JSON deserialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
+ ),
+ RequiresDynamicCode(
+ "JSON deserialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
+ )]
+
///
/// Deserializes an object from a JSON file.
///
@@ -146,7 +148,7 @@ public static T DeserializeFromFile(string filePath)
}
///
- /// Deserializes an object from a JSON file using a JsonSerializerContext.
+ /// Deserializes an object from a JSON file using a JsonSerializerContext.
///
/// The type to deserialize to.
/// Path to the JSON file.
@@ -169,8 +171,8 @@ public static T DeserializeFromFile(string filePath, JsonSerializerContext co
var json = File.ReadAllText(normalizedPath);
return JsonSerializer.Deserialize(json, context.GetTypeInfo(typeof(T))) is T typedResult
- ? typedResult
- : throw new JsonException($"Deserialization returned null for type {typeof(T).Name}");
+ ? typedResult
+ : throw new JsonException($"Deserialization returned null for type {typeof(T).Name}");
}
catch (JsonException ex)
{
@@ -186,18 +188,19 @@ public static T DeserializeFromFile(string filePath, JsonSerializerContext co
}
///
- /// Deserializes an object from a JSON file asynchronously.
+ /// Deserializes an object from a JSON file asynchronously.
///
/// The type to deserialize to.
/// Path to the JSON file.
/// Cancellation token.
/// Deserialized object.
[RequiresUnreferencedCode(
- "JSON deserialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
- )]
- [RequiresDynamicCode(
- "JSON deserialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
- )]
+ "JSON deserialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
+ ),
+ RequiresDynamicCode(
+ "JSON deserialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
+ )]
+
///
/// Deserializes an object from a JSON file asynchronously.
///
@@ -229,18 +232,19 @@ public static async Task DeserializeFromFileAsync(string filePath, Cancell
}
///
- /// Deserializes an object from a stream asynchronously.
+ /// Deserializes an object from a stream asynchronously.
///
/// The type to deserialize to.
/// The stream containing JSON data.
/// Cancellation token.
/// Deserialized object.
[RequiresUnreferencedCode(
- "JSON deserialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
- )]
- [RequiresDynamicCode(
- "JSON deserialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
- )]
+ "JSON deserialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
+ ),
+ RequiresDynamicCode(
+ "JSON deserialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
+ )]
+
///
/// Deserializes an object from a stream asynchronously.
///
@@ -255,7 +259,7 @@ public static async Task DeserializeFromStreamAsync(Stream stream, Cancell
try
{
var result = await JsonSerializer.DeserializeAsync(stream, GetJsonSerializerOptions(), cancellationToken)
- .ConfigureAwait(false);
+ .ConfigureAwait(false);
return result ?? throw new JsonException($"Deserialization returned null for type {typeof(T).Name}");
}
@@ -266,18 +270,19 @@ public static async Task DeserializeFromStreamAsync(Stream stream, Cancell
}
///
- /// Deserializes a JSON string to an object with fallback value.
+ /// Deserializes a JSON string to an object with fallback value.
///
/// The type to deserialize to.
/// The JSON string to deserialize.
/// Default value if deserialization fails.
/// Deserialized object or default value.
[RequiresUnreferencedCode(
- "JSON deserialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
- )]
- [RequiresDynamicCode(
- "JSON deserialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
- )]
+ "JSON deserialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
+ ),
+ RequiresDynamicCode(
+ "JSON deserialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
+ )]
+
///
/// Deserializes a JSON string to an object with fallback value.
///
@@ -303,7 +308,7 @@ public static async Task DeserializeFromStreamAsync(Stream stream, Cancell
}
///
- /// Gets a read-only view of the current JSON converters.
+ /// Gets a read-only view of the current JSON converters.
///
/// A read-only list of JSON converters.
public static IReadOnlyList GetJsonConverters()
@@ -316,15 +321,13 @@ public static IReadOnlyList GetJsonConverters()
}
///
- /// Gets the current JSON serializer options. Thread-safe.
+ /// Gets the current JSON serializer options. Thread-safe.
///
public static JsonSerializerOptions GetJsonSerializerOptions()
- {
- return _jsonSerializerOptions ?? throw new InvalidOperationException("JsonSerializerOptions not initialized");
- }
+ => _jsonSerializerOptions ?? throw new InvalidOperationException("JsonSerializerOptions not initialized");
///
- /// Gets cached JSON serializer options combined with a context resolver. Thread-safe.
+ /// Gets cached JSON serializer options combined with a context resolver. Thread-safe.
///
public static JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerContext context)
{
@@ -336,7 +339,7 @@ public static JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerConte
{
var baseOptions = GetJsonSerializerOptions();
- return new JsonSerializerOptions(baseOptions)
+ return new(baseOptions)
{
TypeInfoResolver = JsonTypeInfoResolver.Combine(context, baseOptions.TypeInfoResolver)
};
@@ -345,7 +348,7 @@ public static JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerConte
}
///
- /// Generates a schema file name for the given type using snake_case convention.
+ /// Generates a schema file name for the given type using snake_case convention.
///
/// The type to generate a schema name for.
/// A schema file name in the format "type_name.schema.json".
@@ -368,7 +371,7 @@ public static string GetSchemaFileName(Type type)
}
///
- /// Determines if a JSON string represents an array.
+ /// Determines if a JSON string represents an array.
///
/// The JSON string to analyze.
/// True if the JSON represents an array, false otherwise.
@@ -392,7 +395,7 @@ public static bool IsArray(string json)
}
///
- /// Determines if a JSON file contains an array.
+ /// Determines if a JSON file contains an array.
///
/// Path to the JSON file to analyze.
/// True if the JSON file contains an array, false otherwise.
@@ -420,7 +423,7 @@ public static bool IsArrayFile(string filePath)
}
///
- /// Validates if a string is valid JSON without deserializing.
+ /// Validates if a string is valid JSON without deserializing.
///
/// The JSON string to validate.
/// True if valid JSON, false otherwise.
@@ -444,7 +447,7 @@ public static bool IsValidJson(string json)
}
///
- /// Registers a JSON serializer context for source generation. Thread-safe.
+ /// Registers a JSON serializer context for source generation. Thread-safe.
///
/// The context to register.
public static void RegisterJsonContext(JsonSerializerContext context)
@@ -456,7 +459,7 @@ public static void RegisterJsonContext(JsonSerializerContext context)
}
///
- /// Removes all converters of the specified type. Thread-safe.
+ /// Removes all converters of the specified type. Thread-safe.
///
/// The converter type to remove.
/// True if any converters were removed.
@@ -494,17 +497,18 @@ public static bool RemoveJsonConverter() where T : JsonConverter
}
///
- /// Serializes an object to JSON string using global options.
+ /// Serializes an object to JSON string using global options.
///
/// The type to serialize.
/// The object to serialize.
/// JSON string representation.
[RequiresUnreferencedCode(
- "JSON serialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
- )]
- [RequiresDynamicCode(
- "JSON serialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
- )]
+ "JSON serialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
+ ),
+ RequiresDynamicCode(
+ "JSON serialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
+ )]
+
///
/// Serializes an object to JSON string using global options.
///
@@ -526,18 +530,19 @@ public static string Serialize(T obj)
}
///
- /// Serializes an object to JSON string using custom options.
+ /// Serializes an object to JSON string using custom options.
///
/// The type to serialize.
/// The object to serialize.
/// Custom serialization options.
/// JSON string representation.
[RequiresUnreferencedCode(
- "JSON serialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
- )]
- [RequiresDynamicCode(
- "JSON serialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
- )]
+ "JSON serialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
+ ),
+ RequiresDynamicCode(
+ "JSON serialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
+ )]
+
///
/// Serializes an object to JSON string using custom options.
///
@@ -561,17 +566,18 @@ public static string Serialize(T obj, JsonSerializerOptions options)
}
///
- /// Serializes multiple objects to JSON files in a directory.
+ /// Serializes multiple objects to JSON files in a directory.
///
/// The type to serialize.
/// Dictionary of filename to object mappings.
/// Target directory path.
[RequiresUnreferencedCode(
- "JSON serialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
- )]
- [RequiresDynamicCode(
- "JSON serialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
- )]
+ "JSON serialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
+ ),
+ RequiresDynamicCode(
+ "JSON serialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
+ )]
+
///
/// Serializes multiple objects to JSON files in a directory.
///
@@ -604,17 +610,18 @@ public static void SerializeMultipleToDirectory(Dictionary objects
}
///
- /// Serializes an object to a JSON file with directory creation.
+ /// Serializes an object to a JSON file with directory creation.
///
/// The type to serialize.
/// The object to serialize.
/// Path to the output JSON file.
[RequiresUnreferencedCode(
- "JSON serialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
- )]
- [RequiresDynamicCode(
- "JSON serialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
- )]
+ "JSON serialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
+ ),
+ RequiresDynamicCode(
+ "JSON serialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
+ )]
+
///
/// Serializes an object to a JSON file with directory creation.
///
@@ -646,18 +653,19 @@ public static void SerializeToFile(T obj, string filePath)
}
///
- /// Serializes an object to a JSON file asynchronously with directory creation.
+ /// Serializes an object to a JSON file asynchronously with directory creation.
///
/// The type to serialize.
/// The object to serialize.
/// Path to the output JSON file.
/// Cancellation token.
[RequiresUnreferencedCode(
- "JSON serialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
- )]
- [RequiresDynamicCode(
- "JSON serialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
- )]
+ "JSON serialization may require types that cannot be statically analyzed. Use overload with JsonSerializerContext when possible."
+ ),
+ RequiresDynamicCode(
+ "JSON serialization may require dynamic code generation. Use overload with JsonSerializerContext when possible."
+ )]
+
///
/// Serializes an object to a JSON file asynchronously with directory creation.
///
diff --git a/src/SquidStd.Core/Logging/EventSink.cs b/src/SquidStd.Core/Logging/EventSink.cs
index ae2b57ec..0e328a1b 100644
--- a/src/SquidStd.Core/Logging/EventSink.cs
+++ b/src/SquidStd.Core/Logging/EventSink.cs
@@ -4,13 +4,13 @@
namespace SquidStd.Core.Logging;
///
-/// A Serilog sink that raises events when logs are received.
-/// Subscribe to to receive log events.
+/// A Serilog sink that raises events when logs are received.
+/// Subscribe to to receive log events.
///
public class EventSink : ILogEventSink
{
///
- /// Emits a log event to all subscribers.
+ /// Emits a log event to all subscribers.
///
/// The log event to emit.
public void Emit(LogEvent logEvent)
@@ -60,16 +60,14 @@ public void Emit(LogEvent logEvent)
}
///
- /// Clears all event subscribers.
- /// Useful for cleanup or testing.
+ /// Clears all event subscribers.
+ /// Useful for cleanup or testing.
///
public static void ClearSubscribers()
- {
- OnLogReceived = null;
- }
+ => OnLogReceived = null;
///
- /// Event raised when a log event is received.
+ /// Event raised when a log event is received.
///
public static event EventHandler? OnLogReceived;
}
diff --git a/src/SquidStd.Core/Logging/EventSinkExtensions.cs b/src/SquidStd.Core/Logging/EventSinkExtensions.cs
index fbdc1cf5..b89f8244 100644
--- a/src/SquidStd.Core/Logging/EventSinkExtensions.cs
+++ b/src/SquidStd.Core/Logging/EventSinkExtensions.cs
@@ -5,13 +5,13 @@
namespace SquidStd.Core.Logging;
///
-/// Extension methods for configuring the EventSink.
+/// Extension methods for configuring the EventSink.
///
public static class EventSinkExtensions
{
///
- /// Adds the EventSink to the Serilog pipeline.
- /// Subscribe to to receive log events.
+ /// Adds the EventSink to the Serilog pipeline.
+ /// Subscribe to to receive log events.
///
/// The logger sink configuration.
/// The minimum log level to capture. Defaults to Verbose (all logs).
@@ -20,7 +20,5 @@ public static LoggerConfiguration EventSink(
this LoggerSinkConfiguration sinkConfiguration,
LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose
)
- {
- return sinkConfiguration.Sink(new EventSink(), restrictedToMinimumLevel);
- }
+ => sinkConfiguration.Sink(new EventSink(), restrictedToMinimumLevel);
}
diff --git a/src/SquidStd.Core/Logging/LogEventData.cs b/src/SquidStd.Core/Logging/LogEventData.cs
index 57d92a5f..97c25271 100644
--- a/src/SquidStd.Core/Logging/LogEventData.cs
+++ b/src/SquidStd.Core/Logging/LogEventData.cs
@@ -3,37 +3,37 @@
namespace SquidStd.Core.Logging;
///
-/// Contains data for a log event.
+/// Contains data for a log event.
///
public class LogEventData
{
///
- /// Gets the log level.
+ /// Gets the log level.
///
public LogEventLevel Level { get; init; }
///
- /// Gets the timestamp of the log event.
+ /// Gets the timestamp of the log event.
///
public DateTimeOffset Timestamp { get; init; }
///
- /// Gets the formatted log message.
+ /// Gets the formatted log message.
///
public string Message { get; init; } = string.Empty;
///
- /// Gets the exception associated with the log event, if any.
+ /// Gets the exception associated with the log event, if any.
///
public Exception? Exception { get; init; }
///
- /// Gets the properties associated with the log event.
+ /// Gets the properties associated with the log event.
///
public IReadOnlyDictionary Properties { get; init; } = new Dictionary();
///
- /// Gets the source context (usually the logger name/class).
+ /// Gets the source context (usually the logger name/class).
///
public string? SourceContext { get; init; }
}
diff --git a/src/SquidStd.Core/Pool/ObjectPool.cs b/src/SquidStd.Core/Pool/ObjectPool.cs
index 8ad71859..9a4db3a6 100644
--- a/src/SquidStd.Core/Pool/ObjectPool.cs
+++ b/src/SquidStd.Core/Pool/ObjectPool.cs
@@ -3,10 +3,10 @@
namespace SquidStd.Core.Pool;
///
-/// Thread-safe, non-blocking object pool. reuses a retained instance or creates a new
-/// one through the factory; stocks the instance back (up to a bound), optionally
-/// resetting it first. Instances dropped over the bound, and those still pooled on dispose, are disposed
-/// when implements .
+/// Thread-safe, non-blocking object pool. reuses a retained instance or creates a new
+/// one through the factory; stocks the instance back (up to a bound), optionally
+/// resetting it first. Instances dropped over the bound, and those still pooled on dispose, are disposed
+/// when implements .
///
/// The pooled reference type.
public sealed class ObjectPool : IDisposable
@@ -20,12 +20,12 @@ public sealed class ObjectPool : IDisposable
private bool _disposed;
///
- /// Gets the number of instances currently retained for reuse.
+ /// Gets the number of instances currently retained for reuse.
///
public int Count => Volatile.Read(ref _retained);
///
- /// Initializes the pool.
+ /// Initializes the pool.
///
/// Creates a new instance when the pool is empty.
/// Maximum number of instances kept for reuse. Defaults to 1024.
@@ -45,7 +45,7 @@ public ObjectPool(Func factory, int maxRetained = 1024, Action? onReturn =
}
///
- /// Rents an instance from the pool, creating one through the factory when the pool is empty.
+ /// Rents an instance from the pool, creating one through the factory when the pool is empty.
///
/// A pooled or freshly created instance.
public T Get()
@@ -61,7 +61,7 @@ public T Get()
}
///
- /// Returns an instance to the pool. Instances beyond the retained bound are disposed instead of kept.
+ /// Returns an instance to the pool. Instances beyond the retained bound are disposed instead of kept.
///
/// The instance to return.
public void Return(T item)
@@ -82,7 +82,7 @@ public void Return(T item)
}
///
- /// Disposes every retained instance that implements .
+ /// Disposes every retained instance that implements .
///
public void Dispose()
{
diff --git a/src/SquidStd.Core/README.md b/src/SquidStd.Core/README.md
index 356350ad..0a16950c 100644
--- a/src/SquidStd.Core/README.md
+++ b/src/SquidStd.Core/README.md
@@ -49,18 +49,18 @@ pool.Return(builder);
## Key types
-| Type | Purpose |
-|-------------------------|-----------------------------------------------|
-| `IConfigEntry` | A registrable YAML configuration section. |
-| `IConfigManagerService` | Loads YAML config and exposes typed sections. |
-| `IEventBus` | Publish/subscribe in-process event bus. |
-| `IJobSystem` | Background job scheduling/execution. |
-| `ITimerService` | Timer-wheel based scheduling. |
-| `IMetricProvider` | Source of metric samples for collection. |
-| `IStorageService` | File/object storage abstraction. |
-| `IFileWatcherService` | Recursive, debounced file watcher publishing to the event bus. |
-| `ObjectPool` | Thread-safe, non-blocking object pool. |
-| `ICommandDispatcher` | Typed protocol command dispatch with context. |
+| Type | Purpose |
+|--------------------------------|----------------------------------------------------------------|
+| `IConfigEntry` | A registrable YAML configuration section. |
+| `IConfigManagerService` | Loads YAML config and exposes typed sections. |
+| `IEventBus` | Publish/subscribe in-process event bus. |
+| `IJobSystem` | Background job scheduling/execution. |
+| `ITimerService` | Timer-wheel based scheduling. |
+| `IMetricProvider` | Source of metric samples for collection. |
+| `IStorageService` | File/object storage abstraction. |
+| `IFileWatcherService` | Recursive, debounced file watcher publishing to the event bus. |
+| `ObjectPool` | Thread-safe, non-blocking object pool. |
+| `ICommandDispatcher` | Typed protocol command dispatch with context. |
## Related
diff --git a/src/SquidStd.Core/SquidStd.Core.csproj b/src/SquidStd.Core/SquidStd.Core.csproj
index ed893826..33720bd9 100644
--- a/src/SquidStd.Core/SquidStd.Core.csproj
+++ b/src/SquidStd.Core/SquidStd.Core.csproj
@@ -15,7 +15,7 @@
all
runtime; build; native; contentfiles; analyzers
-
+
diff --git a/src/SquidStd.Core/Types/Files/FileChangeKind.cs b/src/SquidStd.Core/Types/Files/FileChangeKind.cs
index 256da868..fc24c5f8 100644
--- a/src/SquidStd.Core/Types/Files/FileChangeKind.cs
+++ b/src/SquidStd.Core/Types/Files/FileChangeKind.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Core.Types.Files;
///
-/// The kind of change observed on a watched file.
+/// The kind of change observed on a watched file.
///
public enum FileChangeKind
{
diff --git a/src/SquidStd.Core/Types/Health/HealthStatus.cs b/src/SquidStd.Core/Types/Health/HealthStatus.cs
index 9dc66aed..d005a10e 100644
--- a/src/SquidStd.Core/Types/Health/HealthStatus.cs
+++ b/src/SquidStd.Core/Types/Health/HealthStatus.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Core.Types.Health;
///
-/// Overall health state of a check or report.
+/// Overall health state of a check or report.
///
public enum HealthStatus
{
diff --git a/src/SquidStd.Core/Types/LogLevelType.cs b/src/SquidStd.Core/Types/LogLevelType.cs
index 6133c86c..43ef7f77 100644
--- a/src/SquidStd.Core/Types/LogLevelType.cs
+++ b/src/SquidStd.Core/Types/LogLevelType.cs
@@ -1,42 +1,42 @@
namespace SquidStd.Core.Types;
///
-/// public enum LogLevelType : byte.
+/// public enum LogLevelType : byte.
///
public enum LogLevelType : byte
{
///
- /// No logging.
+ /// No logging.
///
None = 0,
///
- /// Trace level logging.
+ /// Trace level logging.
///
Trace = 1,
///
- /// Debug level logging.
+ /// Debug level logging.
///
Debug = 2,
///
- /// Information level logging.
+ /// Information level logging.
///
Information = 3,
///
- /// Warning level logging.
+ /// Warning level logging.
///
Warning = 4,
///
- /// Error level logging.
+ /// Error level logging.
///
Error = 5,
///
- /// Critical level logging.
+ /// Critical level logging.
///
Critical = 6
}
diff --git a/src/SquidStd.Core/Types/Metrics/MetricType.cs b/src/SquidStd.Core/Types/Metrics/MetricType.cs
index 6202e72a..f59560ff 100644
--- a/src/SquidStd.Core/Types/Metrics/MetricType.cs
+++ b/src/SquidStd.Core/Types/Metrics/MetricType.cs
@@ -1,22 +1,22 @@
namespace SquidStd.Core.Types.Metrics;
///
-/// Defines the semantic type of a metric sample.
+/// Defines the semantic type of a metric sample.
///
public enum MetricType
{
///
- /// A value that can go up or down.
+ /// A value that can go up or down.
///
Gauge,
///
- /// A cumulative value that only increases.
+ /// A cumulative value that only increases.
///
Counter,
///
- /// A value that represents a distribution bucket or aggregate.
+ /// A value that represents a distribution bucket or aggregate.
///
Histogram
}
diff --git a/src/SquidStd.Core/Types/PlatformType.cs b/src/SquidStd.Core/Types/PlatformType.cs
index 56571088..21f3f66c 100644
--- a/src/SquidStd.Core/Types/PlatformType.cs
+++ b/src/SquidStd.Core/Types/PlatformType.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Core.Types;
///
-/// Enumerates the supported platform types.
+/// Enumerates the supported platform types.
///
public enum PlatformType : byte
{
diff --git a/src/SquidStd.Core/Types/SquidStdLogRollingIntervalType.cs b/src/SquidStd.Core/Types/SquidStdLogRollingIntervalType.cs
index 7584213a..9aa4830c 100644
--- a/src/SquidStd.Core/Types/SquidStdLogRollingIntervalType.cs
+++ b/src/SquidStd.Core/Types/SquidStdLogRollingIntervalType.cs
@@ -1,37 +1,37 @@
namespace SquidStd.Core.Types;
///
-/// Defines file log rolling intervals.
+/// Defines file log rolling intervals.
///
public enum SquidStdLogRollingIntervalType
{
///
- /// Does not roll log files automatically.
+ /// Does not roll log files automatically.
///
Infinite = 0,
///
- /// Rolls log files every year.
+ /// Rolls log files every year.
///
Year = 1,
///
- /// Rolls log files every month.
+ /// Rolls log files every month.
///
Month = 2,
///
- /// Rolls log files every day.
+ /// Rolls log files every day.
///
Day = 3,
///
- /// Rolls log files every hour.
+ /// Rolls log files every hour.
///
Hour = 4,
///
- /// Rolls log files every minute.
+ /// Rolls log files every minute.
///
Minute = 5
}
diff --git a/src/SquidStd.Core/Utils/BuiltInRng.cs b/src/SquidStd.Core/Utils/BuiltInRng.cs
index ad4d0580..7de1ccbf 100644
--- a/src/SquidStd.Core/Utils/BuiltInRng.cs
+++ b/src/SquidStd.Core/Utils/BuiltInRng.cs
@@ -3,8 +3,8 @@
namespace SquidStd.Core.Utils;
///
-/// Ambient pseudo-random generator. Call with a fixed seed for reproducible
-/// sequences (useful for deterministic simulations and game logic).
+/// Ambient pseudo-random generator. Call with a fixed seed for reproducible
+/// sequences (useful for deterministic simulations and game logic).
///
public static class BuiltInRng
{
@@ -13,77 +13,57 @@ public static class BuiltInRng
/// Replaces the generator with a new, non-deterministically seeded instance.
public static void Reset()
- {
- Generator = new Random();
- }
+ => Generator = new();
/// Replaces the generator with one seeded for reproducible sequences.
/// The seed value.
public static void Reset(int seed)
- {
- Generator = new Random(seed);
- }
+ => Generator = new(seed);
/// Returns a non-negative random integer.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Next()
- {
- return Generator.Next();
- }
+ => Generator.Next();
/// Returns a non-negative random integer below .
/// Exclusive upper bound.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Next(int maxValue)
- {
- return Generator.Next(maxValue);
- }
+ => Generator.Next(maxValue);
/// Returns a random integer in [minValue, minValue + count).
/// Inclusive lower bound.
/// Number of distinct values.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Next(int minValue, int count)
- {
- return minValue + Generator.Next(count);
- }
+ => minValue + Generator.Next(count);
/// Returns a non-negative random long below .
/// Exclusive upper bound.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long Next(long maxValue)
- {
- return Generator.NextInt64(maxValue);
- }
+ => Generator.NextInt64(maxValue);
/// Returns a random long in [minValue, minValue + count).
/// Inclusive lower bound.
/// Number of distinct values.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long Next(long minValue, long count)
- {
- return minValue + Generator.NextInt64(count);
- }
+ => minValue + Generator.NextInt64(count);
/// Returns a non-negative random long.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long NextLong()
- {
- return Generator.NextInt64();
- }
+ => Generator.NextInt64();
/// Returns a random double in [0, 1).
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double NextDouble()
- {
- return Generator.NextDouble();
- }
+ => Generator.NextDouble();
/// Fills the buffer with random bytes.
/// The buffer to fill.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void NextBytes(Span buffer)
- {
- Generator.NextBytes(buffer);
- }
+ => Generator.NextBytes(buffer);
}
diff --git a/src/SquidStd.Core/Utils/CryptoUtils.cs b/src/SquidStd.Core/Utils/CryptoUtils.cs
index 431faa5c..7c78ea7d 100644
--- a/src/SquidStd.Core/Utils/CryptoUtils.cs
+++ b/src/SquidStd.Core/Utils/CryptoUtils.cs
@@ -4,8 +4,8 @@
namespace SquidStd.Core.Utils;
///
-/// Authenticated symmetric encryption helpers built on AES-GCM. Produced payloads are laid out as
-/// nonce (12 bytes) | tag (16 bytes) | ciphertext.
+/// Authenticated symmetric encryption helpers built on AES-GCM. Produced payloads are laid out as
+/// nonce (12 bytes) | tag (16 bytes) | ciphertext.
///
public static class CryptoUtils
{
@@ -13,7 +13,7 @@ public static class CryptoUtils
private const int TagSize = 16;
///
- /// Generates a random symmetric key and returns it as a base64 string.
+ /// Generates a random symmetric key and returns it as a base64 string.
///
/// Key length in bytes; must be 16, 24, or 32.
/// The base64-encoded key.
@@ -28,7 +28,7 @@ public static string GenerateKey(int sizeInBytes = 32)
}
///
- /// Encrypts a UTF-8 string with AES-GCM under the supplied key.
+ /// Encrypts a UTF-8 string with AES-GCM under the supplied key.
///
/// The text to encrypt.
/// The 16, 24, or 32 byte key.
@@ -55,7 +55,7 @@ public static byte[] Encrypt(string plaintext, byte[] key)
}
///
- /// Decrypts a payload produced by back into its UTF-8 string.
+ /// Decrypts a payload produced by back into its UTF-8 string.
///
/// The nonce | tag | ciphertext payload.
/// The key used to encrypt the payload.
diff --git a/src/SquidStd.Core/Utils/DirectoriesUtils.cs b/src/SquidStd.Core/Utils/DirectoriesUtils.cs
index ffd8612b..7fd8e34a 100644
--- a/src/SquidStd.Core/Utils/DirectoriesUtils.cs
+++ b/src/SquidStd.Core/Utils/DirectoriesUtils.cs
@@ -1,23 +1,21 @@
namespace SquidStd.Core.Utils;
///
-/// Utility methods for working with directories and file system operations
+/// Utility methods for working with directories and file system operations
///
public class DirectoriesUtils
{
///
- /// Gets files from the specified path recursively with optional extension filtering
+ /// Gets files from the specified path recursively with optional extension filtering
///
/// Directory path to search
/// File extensions to filter by (e.g., "*.txt", "*.json")
/// Array of file paths matching the criteria
public static string[] GetFiles(string path, params string[] extensions)
- {
- return GetFiles(path, true, extensions);
- }
+ => GetFiles(path, true, extensions);
///
- /// Gets files from the specified path with configurable recursion and extension filtering
+ /// Gets files from the specified path with configurable recursion and extension filtering
///
/// Directory path to search
/// Whether to search subdirectories recursively
diff --git a/src/SquidStd.Core/Utils/HashUtils.cs b/src/SquidStd.Core/Utils/HashUtils.cs
index 786a1215..7c63ae4e 100644
--- a/src/SquidStd.Core/Utils/HashUtils.cs
+++ b/src/SquidStd.Core/Utils/HashUtils.cs
@@ -4,7 +4,7 @@
namespace SquidStd.Core.Utils;
///
-/// Provides password hashing and verification helpers using PBKDF2-SHA256.
+/// Provides password hashing and verification helpers using PBKDF2-SHA256.
///
public static class HashUtils
{
@@ -14,7 +14,7 @@ public static class HashUtils
private const int DefaultSaltSize = 16;
///
- /// Hashes a password using PBKDF2-SHA256 and returns a serialized payload.
+ /// Hashes a password using PBKDF2-SHA256 and returns a serialized payload.
///
/// Plain password.
/// Serialized hash payload.
@@ -41,7 +41,7 @@ public static string HashPassword(string password)
}
///
- /// Verifies a plain password against a serialized PBKDF2-SHA256 payload.
+ /// Verifies a plain password against a serialized PBKDF2-SHA256 payload.
///
/// Plain password.
/// Serialized hash payload.
diff --git a/src/SquidStd.Core/Utils/NetworkUtils.cs b/src/SquidStd.Core/Utils/NetworkUtils.cs
index 7d0258b5..e32c695e 100644
--- a/src/SquidStd.Core/Utils/NetworkUtils.cs
+++ b/src/SquidStd.Core/Utils/NetworkUtils.cs
@@ -4,12 +4,12 @@
namespace SquidStd.Core.Utils;
///
-/// Utility methods for network configuration parsing.
+/// Utility methods for network configuration parsing.
///
public static class NetworkUtils
{
///
- /// Enumerates local unicast endpoints matching the supplied endpoint address family.
+ /// Enumerates local unicast endpoints matching the supplied endpoint address family.
///
/// The template endpoint supplying address family and port.
/// The matching local endpoints.
@@ -18,16 +18,17 @@ public static IEnumerable GetListeningAddresses(IPEndPoint endPoint)
ArgumentNullException.ThrowIfNull(endPoint);
return NetworkInterface.GetAllNetworkInterfaces()
- .SelectMany(adapter =>
- adapter.GetIPProperties()
- .UnicastAddresses
- .Where(unicast => endPoint.AddressFamily == unicast.Address.AddressFamily)
- .Select(unicast => new IPEndPoint(unicast.Address, endPoint.Port))
- );
+ .SelectMany(
+ adapter =>
+ adapter.GetIPProperties()
+ .UnicastAddresses
+ .Where(unicast => endPoint.AddressFamily == unicast.Address.AddressFamily)
+ .Select(unicast => new IPEndPoint(unicast.Address, endPoint.Port))
+ );
}
///
- /// Parses an IP address, treating "*" as every IPv4 interface.
+ /// Parses an IP address, treating "*" as every IPv4 interface.
///
/// The IP address or "*".
/// The parsed IP address.
@@ -39,7 +40,7 @@ public static IPAddress ParseIpAddress(string ipAddress)
}
///
- /// Parses a comma-separated port list with optional ranges.
+ /// Parses a comma-separated port list with optional ranges.
///
/// The ports string, such as "6666-6668,6669,8000".
/// The parsed ports.
diff --git a/src/SquidStd.Core/Utils/PlatformUtils.cs b/src/SquidStd.Core/Utils/PlatformUtils.cs
index 2debaa05..29c7583c 100644
--- a/src/SquidStd.Core/Utils/PlatformUtils.cs
+++ b/src/SquidStd.Core/Utils/PlatformUtils.cs
@@ -3,12 +3,12 @@
namespace SquidStd.Core.Utils;
///
-/// Provides utilities for detecting the current platform.
+/// Provides utilities for detecting the current platform.
///
public static class PlatformUtils
{
///
- /// Gets the current platform type.
+ /// Gets the current platform type.
///
/// The detected platform type.
public static PlatformType GetCurrentPlatform()
@@ -27,29 +27,23 @@ public static PlatformType GetCurrentPlatform()
}
///
- /// Checks if the application is running on Linux.
+ /// Checks if the application is running on Linux.
///
/// True if running on Linux, otherwise false.
public static bool IsRunningOnLinux()
- {
- return OperatingSystem.IsLinux();
- }
+ => OperatingSystem.IsLinux();
///
- /// Checks if the application is running on macOS.
+ /// Checks if the application is running on macOS.
///
/// True if running on macOS, otherwise false.
public static bool IsRunningOnMacOS()
- {
- return OperatingSystem.IsMacOS();
- }
+ => OperatingSystem.IsMacOS();
///
- /// Checks if the application is running on Windows.
+ /// Checks if the application is running on Windows.
///
/// True if running on Windows, otherwise false.
public static bool IsRunningOnWindows()
- {
- return OperatingSystem.IsWindows();
- }
+ => OperatingSystem.IsWindows();
}
diff --git a/src/SquidStd.Core/Utils/RandomUtils.cs b/src/SquidStd.Core/Utils/RandomUtils.cs
index db77417c..c2e63eff 100644
--- a/src/SquidStd.Core/Utils/RandomUtils.cs
+++ b/src/SquidStd.Core/Utils/RandomUtils.cs
@@ -4,7 +4,7 @@
namespace SquidStd.Core.Utils;
///
-/// Random value helpers built on , including dice and coin-flip mechanics.
+/// Random value helpers built on , including dice and coin-flip mechanics.
///
public static class RandomUtils
{
@@ -13,53 +13,41 @@ public static class RandomUtils
/// Number of distinct values.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Random(int from, int count)
- {
- return BuiltInRng.Next(from, count);
- }
+ => BuiltInRng.Next(from, count);
/// Returns a random integer below (sign-preserving).
/// Exclusive bound; negative values mirror the range.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Random(int count)
- {
- return count < 0 ? -BuiltInRng.Next(-count) : BuiltInRng.Next(count);
- }
+ => count < 0 ? -BuiltInRng.Next(-count) : BuiltInRng.Next(count);
/// Returns a random long in [from, from + count).
/// Inclusive lower bound.
/// Number of distinct values.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long Random(long from, long count)
- {
- return BuiltInRng.Next(from, count);
- }
+ => BuiltInRng.Next(from, count);
/// Returns a random long below (sign-preserving).
/// Exclusive bound; negative values mirror the range.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long Random(long count)
- {
- return count < 0 ? -BuiltInRng.Next(-count) : BuiltInRng.Next(count);
- }
+ => count < 0 ? -BuiltInRng.Next(-count) : BuiltInRng.Next(count);
/// Fills the buffer with random bytes.
/// The buffer to fill.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RandomBytes(Span buffer)
- {
- BuiltInRng.NextBytes(buffer);
- }
+ => BuiltInRng.NextBytes(buffer);
/// Returns a random double in [0, 1).
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double RandomDouble()
- {
- return BuiltInRng.NextDouble();
- }
+ => BuiltInRng.NextDouble();
///
- /// Counts heads across coin flips, stopping early once
- /// heads are reached.
+ /// Counts heads across coin flips, stopping early once
+ /// heads are reached.
///
/// Number of coins to flip.
/// Cap on the number of heads to count.
@@ -71,8 +59,8 @@ public static int CoinFlips(int amount, int maximum)
while (amount > 0)
{
var num = amount >= 62
- ? (ulong)BuiltInRng.NextLong()
- : (ulong)BuiltInRng.Next(1L << amount);
+ ? (ulong)BuiltInRng.NextLong()
+ : (ulong)BuiltInRng.Next(1L << amount);
heads += BitOperations.PopCount(num);
@@ -97,8 +85,8 @@ public static int CoinFlips(int amount)
while (amount > 0)
{
var num = amount >= 62
- ? (ulong)BuiltInRng.NextLong()
- : (ulong)BuiltInRng.Next(1L << amount);
+ ? (ulong)BuiltInRng.NextLong()
+ : (ulong)BuiltInRng.Next(1L << amount);
heads += BitOperations.PopCount(num);
diff --git a/src/SquidStd.Core/Utils/ResourceUtils.cs b/src/SquidStd.Core/Utils/ResourceUtils.cs
index 55fb52f8..2559ba47 100644
--- a/src/SquidStd.Core/Utils/ResourceUtils.cs
+++ b/src/SquidStd.Core/Utils/ResourceUtils.cs
@@ -3,12 +3,12 @@
namespace SquidStd.Core.Utils;
///
-/// Provides utilities for working with embedded resources.
+/// Provides utilities for working with embedded resources.
///
public static class ResourceUtils
{
///
- /// Converts a resource name to a file path format.
+ /// Converts a resource name to a file path format.
///
/// The resource name to convert.
/// The base namespace to remove.
@@ -38,7 +38,7 @@ public static string ConvertResourceNameToPath(string resourceName, string baseN
}
///
- /// Copies all embedded resources from an assembly to a destination directory
+ /// Copies all embedded resources from an assembly to a destination directory
///
/// The assembly containing the embedded resources
/// The directory where resources will be copied
@@ -72,7 +72,7 @@ public static void CopyEmbeddedToDirectory(Assembly assembly, string destination
}
///
- /// Converts an embedded resource name to a file path format
+ /// Converts an embedded resource name to a file path format
///
/// The full embedded resource name
/// The assembly prefix to remove from the resource name
@@ -88,7 +88,7 @@ public static string EmbeddedNameToPath(string resourceName, string assemblyPref
}
///
- /// Converts an embedded resource name to a directory path structure
+ /// Converts an embedded resource name to a directory path structure
///
/// The embedded resource name (e.g., "Assets.Fonts.DefaultUiFont.ttf")
/// Optional base namespace to remove from the beginning
@@ -128,7 +128,7 @@ public static string GetDirectoryPathFromResourceName(string resourceName, strin
}
///
- /// Gets an embedded resource as a byte array wrapped in Memory
+ /// Gets an embedded resource as a byte array wrapped in Memory
///
/// The assembly containing the resource
/// The full resource name
@@ -145,7 +145,8 @@ public static Memory GetEmbeddedResourceByteArray(Assembly assembly, strin
{
// Try to find a partial match
var resourceNames = assembly.GetManifestResourceNames();
- var matchingResource = resourceNames.FirstOrDefault(n => n.EndsWith(
+ var matchingResource = resourceNames.FirstOrDefault(
+ n => n.EndsWith(
resourceName.Replace('/', '.').Replace('\\', '.'),
StringComparison.Ordinal
)
@@ -167,12 +168,12 @@ public static Memory GetEmbeddedResourceByteArray(Assembly assembly, strin
using var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
- return new Memory(memoryStream.ToArray());
+ return new(memoryStream.ToArray());
}
}
///
- /// Reads the content of an embedded resource as a byte array
+ /// Reads the content of an embedded resource as a byte array
///
/// Resource path (e.g. "Assets/Templates/welcome.scriban")
/// The assembly to search in (if null, uses current assembly)
@@ -220,7 +221,7 @@ public static byte[] GetEmbeddedResourceContent(string resourcePath, Assembly as
}
///
- /// Gets a list of all files in a specific embedded directory
+ /// Gets a list of all files in a specific embedded directory
///
/// The assembly to search in (if null, uses current assembly)
/// Directory path to search (e.g. "Assets/Templates")
@@ -255,7 +256,7 @@ public static List GetEmbeddedResourceFileNames(
}
///
- /// Gets a list of all embedded resources that match a given pattern
+ /// Gets a list of all embedded resources that match a given pattern
///
/// The assembly to search in (if null, uses current assembly)
/// Directory path to search (e.g. "Assets.Templates")
@@ -288,19 +289,17 @@ public static string[] GetEmbeddedResourceNames(Assembly assembly = null, string
}
///
- /// Gets a stream for an embedded resource, inferring the assembly from .
+ /// Gets a stream for an embedded resource, inferring the assembly from .
///
/// Any type defined in the target assembly.
/// The full resource name or a path-style suffix.
/// A stream for the resource.
/// Thrown when the resource cannot be found.
public static Stream GetEmbeddedResourceStream(string resourceName)
- {
- return GetEmbeddedResourceStream(typeof(TClass).Assembly, resourceName);
- }
+ => GetEmbeddedResourceStream(typeof(TClass).Assembly, resourceName);
///
- /// Gets a stream for an embedded resource.
+ /// Gets a stream for an embedded resource.
///
/// The assembly containing the resource.
/// The full resource name.
@@ -317,7 +316,8 @@ public static Stream GetEmbeddedResourceStream(Assembly assembly, string resourc
{
// Try to find a partial match
var resourceNames = assembly.GetManifestResourceNames();
- var matchingResource = resourceNames.FirstOrDefault(n => n.EndsWith(
+ var matchingResource = resourceNames.FirstOrDefault(
+ n => n.EndsWith(
resourceName.Replace('/', '.').Replace('\\', '.'),
StringComparison.Ordinal
)
@@ -350,8 +350,8 @@ public static string GetEmbeddedResourceString(Assembly assembly, string resourc
}
///
- /// Converts an embedded resource name to a proper file name by extracting the last part after the final dot
- /// and treating everything before it as directory structure
+ /// Converts an embedded resource name to a proper file name by extracting the last part after the final dot
+ /// and treating everything before it as directory structure
///
/// The embedded resource name (e.g., "Assets.Fonts.DefaultUiFont.ttf")
/// The file name with extension (e.g., "DefaultUiFont.ttf")
@@ -380,7 +380,7 @@ public static string GetFileNameFromResourceName(string resourceName)
}
///
- /// Extracts the file name from an embedded resource path
+ /// Extracts the file name from an embedded resource path
///
/// Full resource name
/// File name without path
@@ -395,23 +395,23 @@ public static string GetFileNameFromResourcePath(string resourceName)
}
///
- /// Reads the content of an embedded resource as a string.
+ /// Reads the content of an embedded resource as a string.
///
/// The name of the resource to read.
/// The assembly containing the resource.
/// The content of the resource as a string.
/// Thrown when the resource cannot be found in the specified assembly.
///
- /// This method handles resource names that may contain either forward slashes (/) or
- /// backslashes (\) by converting them to dots, which is the standard separator for
- /// resource names in .NET assemblies.
+ /// This method handles resource names that may contain either forward slashes (/) or
+ /// backslashes (\) by converting them to dots, which is the standard separator for
+ /// resource names in .NET assemblies.
///
public static string? ReadEmbeddedResource(string resourceName, Assembly assembly)
{
var resourcePath = resourceName.Replace('/', '.').Replace('\\', '.');
var fullResourceName = assembly.GetManifestResourceNames()
- .FirstOrDefault(name => name.EndsWith(resourcePath, StringComparison.Ordinal));
+ .FirstOrDefault(name => name.EndsWith(resourcePath, StringComparison.Ordinal));
if (fullResourceName == null)
{
diff --git a/src/SquidStd.Core/Utils/SslUtils.cs b/src/SquidStd.Core/Utils/SslUtils.cs
index 37d7dcaf..c22e1333 100644
--- a/src/SquidStd.Core/Utils/SslUtils.cs
+++ b/src/SquidStd.Core/Utils/SslUtils.cs
@@ -3,12 +3,12 @@
namespace SquidStd.Core.Utils;
///
-/// Helpers for loading X.509 certificates used to secure TLS endpoints.
+/// Helpers for loading X.509 certificates used to secure TLS endpoints.
///
public static class SslUtils
{
///
- /// Loads a certificate from a PEM file, optionally combining it with a separate private-key PEM.
+ /// Loads a certificate from a PEM file, optionally combining it with a separate private-key PEM.
///
/// Path to the certificate PEM file.
/// Optional path to the private-key PEM file.
@@ -21,7 +21,7 @@ public static X509Certificate2 LoadFromPem(string certificatePath, string? priva
}
///
- /// Loads a certificate (with its private key) from a PKCS#12 / PFX file.
+ /// Loads a certificate (with its private key) from a PKCS#12 / PFX file.
///
/// Path to the PFX file.
/// Optional password protecting the PFX file.
diff --git a/src/SquidStd.Core/Utils/StringUtils.cs b/src/SquidStd.Core/Utils/StringUtils.cs
index 591f1d27..33c29575 100644
--- a/src/SquidStd.Core/Utils/StringUtils.cs
+++ b/src/SquidStd.Core/Utils/StringUtils.cs
@@ -5,22 +5,22 @@
namespace SquidStd.Core.Utils;
///
-/// Provides utility methods for string operations, including various case conversion methods.
+/// Provides utility methods for string operations, including various case conversion methods.
///
public static partial class StringUtils
{
private static readonly Regex WordSplitterRegex = WordSplitter();
///
- /// Converts a string to camelCase.
+ /// Converts a string to camelCase.
///
/// The string to convert to camelCase.
/// A camelCase version of the input string.
/// Thrown when the input text is null or empty.
///
- /// "HelloWorld" becomes "helloWorld"
- /// "API_RESPONSE" becomes "apiResponse"
- /// "user-id" becomes "userId"
+ /// "HelloWorld" becomes "helloWorld"
+ /// "API_RESPONSE" becomes "apiResponse"
+ /// "user-id" becomes "userId"
///
public static string ToCamelCase(string text)
{
@@ -51,13 +51,13 @@ public static string ToCamelCase(string text)
}
///
- /// Converts a string to Dot Case.
+ /// Converts a string to Dot Case.
///
/// The string to convert to Dot Case.
/// A Dot Case version of the input string.
///
- /// "HelloWorld" becomes "hello.world"
- /// "API_RESPONSE" becomes "api.response"
+ /// "HelloWorld" becomes "hello.world"
+ /// "API_RESPONSE" becomes "api.response"
///
public static string ToDotCase(string text)
{
@@ -96,15 +96,15 @@ public static string ToDotCase(string text)
}
///
- /// Converts a string to kebab-case.
+ /// Converts a string to kebab-case.
///
/// The string to convert to kebab-case.
/// A kebab-case version of the input string.
/// Thrown when the input text is null or empty.
///
- /// "HelloWorld" becomes "hello-world"
- /// "API_RESPONSE" becomes "api-response"
- /// "userId" becomes "user-id"
+ /// "HelloWorld" becomes "hello-world"
+ /// "API_RESPONSE" becomes "api-response"
+ /// "userId" becomes "user-id"
///
public static string ToKebabCase(string text)
{
@@ -143,15 +143,15 @@ public static string ToKebabCase(string text)
}
///
- /// Converts a string to PascalCase.
+ /// Converts a string to PascalCase.
///
/// The string to convert to PascalCase.
/// A PascalCase version of the input string.
/// Thrown when the input text is null or empty.
///
- /// "hello_world" becomes "HelloWorld"
- /// "api-response" becomes "ApiResponse"
- /// "userId" becomes "UserId"
+ /// "hello_world" becomes "HelloWorld"
+ /// "api-response" becomes "ApiResponse"
+ /// "userId" becomes "UserId"
///
public static string ToPascalCase(string text)
{
@@ -182,13 +182,13 @@ public static string ToPascalCase(string text)
}
///
- /// Converts a string to Path Case.
+ /// Converts a string to Path Case.
///
/// The string to convert to Path Case.
/// A Path Case version of the input string.
///
- /// "HelloWorld" becomes "hello/world"
- /// "API_RESPONSE" becomes "api/response"
+ /// "HelloWorld" becomes "hello/world"
+ /// "API_RESPONSE" becomes "api/response"
///
public static string ToPathCase(string text)
{
@@ -227,13 +227,13 @@ public static string ToPathCase(string text)
}
///
- /// Converts a string to Sentence Case.
+ /// Converts a string to Sentence Case.
///
/// The string to convert to Sentence Case.
/// A Sentence Case version of the input string.
///
- /// "hello world" becomes "Hello world"
- /// "API_RESPONSE" becomes "Api response"
+ /// "hello world" becomes "Hello world"
+ /// "API_RESPONSE" becomes "Api response"
///
public static string ToSentenceCase(string text)
{
@@ -284,15 +284,15 @@ public static string ToSentenceCase(string text)
}
///
- /// Converts a string from camelCase or PascalCase to snake_case.
+ /// Converts a string from camelCase or PascalCase to snake_case.
///
/// The string to convert to snake_case.
/// A snake_case version of the input string.
/// Thrown when the input text is null or empty.
///
- /// "HelloWorld" becomes "hello_world"
- /// "APIResponse" becomes "api_response"
- /// "userId" becomes "user_id"
+ /// "HelloWorld" becomes "hello_world"
+ /// "APIResponse" becomes "api_response"
+ /// "userId" becomes "user_id"
///
public static string ToSnakeCase(string text)
{
@@ -331,15 +331,15 @@ public static string ToSnakeCase(string text)
}
///
- /// Converts a string to Title Case.
+ /// Converts a string to Title Case.
///
/// The string to convert to Title Case.
/// A Title Case version of the input string.
/// Thrown when the input text is null or empty.
///
- /// "hello_world" becomes "Hello World"
- /// "API_RESPONSE" becomes "Api Response"
- /// "user-id" becomes "User Id"
+ /// "hello_world" becomes "Hello World"
+ /// "API_RESPONSE" becomes "Api Response"
+ /// "user-id" becomes "User Id"
///
public static string ToTitleCase(string text)
{
@@ -373,13 +373,13 @@ public static string ToTitleCase(string text)
}
///
- /// Converts a string to Train Case (Pascal Case with hyphens).
+ /// Converts a string to Train Case (Pascal Case with hyphens).
///
/// The string to convert to Train Case.
/// A Train Case version of the input string.
///
- /// "hello_world" becomes "Hello-World"
- /// "apiResponse" becomes "Api-Response"
+ /// "hello_world" becomes "Hello-World"
+ /// "apiResponse" becomes "Api-Response"
///
public static string ToTrainCase(string text)
{
@@ -418,20 +418,18 @@ public static string ToTrainCase(string text)
}
///
- /// Converts a string to UPPER_SNAKE_CASE (screaming snake case).
+ /// Converts a string to UPPER_SNAKE_CASE (screaming snake case).
///
/// The string to convert to UPPER_SNAKE_CASE.
/// An UPPER_SNAKE_CASE version of the input string.
/// Thrown when the input text is null or empty.
///
- /// "HelloWorld" becomes "HELLO_WORLD"
- /// "apiResponse" becomes "API_RESPONSE"
- /// "user-id" becomes "USER_ID"
+ /// "HelloWorld" becomes "HELLO_WORLD"
+ /// "apiResponse" becomes "API_RESPONSE"
+ /// "user-id" becomes "USER_ID"
///
public static string ToUpperSnakeCase(string text)
- {
- return ToSnakeCase(text).ToUpperInvariant();
- }
+ => ToSnakeCase(text).ToUpperInvariant();
[GeneratedRegex(@"[\s_-]|(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", RegexOptions.Compiled)]
private static partial Regex WordSplitter();
diff --git a/src/SquidStd.Core/Utils/VersionUtils.cs b/src/SquidStd.Core/Utils/VersionUtils.cs
index 45938b01..60af9eb1 100644
--- a/src/SquidStd.Core/Utils/VersionUtils.cs
+++ b/src/SquidStd.Core/Utils/VersionUtils.cs
@@ -3,21 +3,19 @@
namespace SquidStd.Core.Utils;
///
-/// Provides utility methods for reading assembly version metadata.
+/// Provides utility methods for reading assembly version metadata.
///
public static class VersionUtils
{
///
- /// Gets the informational version for the LyLy.Core assembly.
+ /// Gets the informational version for the LyLy.Core assembly.
///
/// The package version declared for LyLy.Core.
public static string GetVersion()
- {
- return GetVersion(typeof(VersionUtils).Assembly);
- }
+ => GetVersion(typeof(VersionUtils).Assembly);
///
- /// Gets the informational version for the specified assembly.
+ /// Gets the informational version for the specified assembly.
///
/// The assembly to read version metadata from.
/// The assembly informational version, or the assembly version when informational metadata is unavailable.
@@ -26,7 +24,7 @@ public static string GetVersion(Assembly assembly)
ArgumentNullException.ThrowIfNull(assembly);
var informationalVersion = assembly.GetCustomAttribute()
- ?.InformationalVersion;
+ ?.InformationalVersion;
if (!string.IsNullOrWhiteSpace(informationalVersion))
{
diff --git a/src/SquidStd.Core/Yaml/YamlUtils.cs b/src/SquidStd.Core/Yaml/YamlUtils.cs
index 7fd5e36f..1e8dd7ca 100644
--- a/src/SquidStd.Core/Yaml/YamlUtils.cs
+++ b/src/SquidStd.Core/Yaml/YamlUtils.cs
@@ -3,21 +3,21 @@
namespace SquidStd.Core.Yaml;
///
-/// Provides YAML serialization helpers.
+/// Provides YAML serialization helpers.
///
public static class YamlUtils
{
private static readonly ISerializer Serializer = new SerializerBuilder()
- .DisableAliases()
- .WithIndentedSequences()
- .Build();
+ .DisableAliases()
+ .WithIndentedSequences()
+ .Build();
private static readonly IDeserializer Deserializer = new DeserializerBuilder()
- .IgnoreUnmatchedProperties()
- .Build();
+ .IgnoreUnmatchedProperties()
+ .Build();
///
- /// Deserializes YAML text using reflection-based metadata.
+ /// Deserializes YAML text using reflection-based metadata.
///
/// The YAML text to deserialize.
/// The target type.
@@ -31,7 +31,7 @@ public static T Deserialize(string yaml)
}
///
- /// Deserializes YAML text to the specified runtime type.
+ /// Deserializes YAML text to the specified runtime type.
///
/// The YAML text to deserialize.
/// The target type.
@@ -46,7 +46,7 @@ public static object Deserialize(string yaml, Type type)
}
///
- /// Deserializes YAML from a file using reflection-based metadata.
+ /// Deserializes YAML from a file using reflection-based metadata.
///
/// The YAML file path.
/// The target type.
@@ -61,7 +61,7 @@ public static T DeserializeFromFile(string filePath)
}
///
- /// Deserializes a top-level YAML section to the specified runtime type.
+ /// Deserializes a top-level YAML section to the specified runtime type.
///
/// The YAML document.
/// The top-level section name.
@@ -84,7 +84,7 @@ public static T DeserializeFromFile(string filePath)
}
///
- /// Serializes an object to YAML using reflection-based metadata.
+ /// Serializes an object to YAML using reflection-based metadata.
///
/// The object to serialize.
/// The source type.
@@ -97,7 +97,7 @@ public static string Serialize(T obj)
}
///
- /// Serializes top-level YAML sections.
+ /// Serializes top-level YAML sections.
///
/// The section map to serialize.
/// The serialized YAML document.
@@ -109,7 +109,7 @@ public static string SerializeSections(IReadOnlyDictionary secti
}
///
- /// Serializes an object to a YAML file using reflection-based metadata.
+ /// Serializes an object to a YAML file using reflection-based metadata.
///
/// The object to serialize.
/// The output YAML file path.
diff --git a/src/SquidStd.Crypto/Pgp/Data/PgpDecryptionResult.cs b/src/SquidStd.Crypto/Pgp/Data/PgpDecryptionResult.cs
index 417836b4..16d2eee8 100644
--- a/src/SquidStd.Crypto/Pgp/Data/PgpDecryptionResult.cs
+++ b/src/SquidStd.Crypto/Pgp/Data/PgpDecryptionResult.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Crypto.Pgp.Data;
///
-/// Outcome of decrypt-and-verify: the recovered plaintext, whether the message carried a signature, and
-/// whether that signature validated against a keyring public key.
+/// Outcome of decrypt-and-verify: the recovered plaintext, whether the message carried a signature, and
+/// whether that signature validated against a keyring public key.
///
public sealed record PgpDecryptionResult(byte[] Data, bool IsSigned, bool IsValid);
diff --git a/src/SquidStd.Crypto/Pgp/Data/PgpKey.cs b/src/SquidStd.Crypto/Pgp/Data/PgpKey.cs
index 2fd65dcd..114e6e00 100644
--- a/src/SquidStd.Crypto/Pgp/Data/PgpKey.cs
+++ b/src/SquidStd.Crypto/Pgp/Data/PgpKey.cs
@@ -3,8 +3,8 @@
namespace SquidStd.Crypto.Pgp.Data;
///
-/// An OpenPGP key as held in the keyring: identity, key id, fingerprint, the armored public block, and
-/// optionally the armored secret block. Metadata is derived from the public key material.
+/// An OpenPGP key as held in the keyring: identity, key id, fingerprint, the armored public block, and
+/// optionally the armored secret block. Metadata is derived from the public key material.
///
public sealed record PgpKey(
string Identity,
diff --git a/src/SquidStd.Crypto/Pgp/Data/PgpKeyOptions.cs b/src/SquidStd.Crypto/Pgp/Data/PgpKeyOptions.cs
index 69f62e86..8a1bd2bf 100644
--- a/src/SquidStd.Crypto/Pgp/Data/PgpKeyOptions.cs
+++ b/src/SquidStd.Crypto/Pgp/Data/PgpKeyOptions.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Crypto.Pgp.Data;
///
-/// Options controlling key generation: algorithm, key size, and an optional validity period.
+/// Options controlling key generation: algorithm, key size, and an optional validity period.
///
public sealed class PgpKeyOptions
{
diff --git a/src/SquidStd.Crypto/Pgp/Data/PgpVerificationResult.cs b/src/SquidStd.Crypto/Pgp/Data/PgpVerificationResult.cs
index 7fe6fc3d..612b5dde 100644
--- a/src/SquidStd.Crypto/Pgp/Data/PgpVerificationResult.cs
+++ b/src/SquidStd.Crypto/Pgp/Data/PgpVerificationResult.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Crypto.Pgp.Data;
///
-/// Outcome of verifying a signed message: whether the signature validated against a keyring public key,
-/// plus the recovered content. PgpCore reports pass/fail only — no signer attribution is exposed.
+/// Outcome of verifying a signed message: whether the signature validated against a keyring public key,
+/// plus the recovered content. PgpCore reports pass/fail only — no signer attribution is exposed.
///
public sealed record PgpVerificationResult(bool IsValid, byte[] Data);
diff --git a/src/SquidStd.Crypto/Pgp/Extensions/RegisterPgpExtensions.cs b/src/SquidStd.Crypto/Pgp/Extensions/RegisterPgpExtensions.cs
index 56153d0b..cb57b89c 100644
--- a/src/SquidStd.Crypto/Pgp/Extensions/RegisterPgpExtensions.cs
+++ b/src/SquidStd.Crypto/Pgp/Extensions/RegisterPgpExtensions.cs
@@ -11,8 +11,8 @@ public static class RegisterPgpExtensions
extension(IContainer container)
{
///
- /// Registers the PGP keyring, service, and the chosen key store (all singletons). The keyring is not
- /// auto-loaded; call at startup if persistence is desired.
+ /// Registers the PGP keyring, service, and the chosen key store (all singletons). The keyring is not
+ /// auto-loaded; call at startup if persistence is desired.
///
/// Builds the from the resolver.
/// The same container for chaining.
diff --git a/src/SquidStd.Crypto/Pgp/Interfaces/IPgpKeyStore.cs b/src/SquidStd.Crypto/Pgp/Interfaces/IPgpKeyStore.cs
index b5f4ebbb..1fcecefc 100644
--- a/src/SquidStd.Crypto/Pgp/Interfaces/IPgpKeyStore.cs
+++ b/src/SquidStd.Crypto/Pgp/Interfaces/IPgpKeyStore.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Crypto.Pgp.Interfaces;
///
-/// Persistence backend for a set of PGP keys. Implementations decide the on-disk representation.
+/// Persistence backend for a set of PGP keys. Implementations decide the on-disk representation.
///
public interface IPgpKeyStore
{
diff --git a/src/SquidStd.Crypto/Pgp/Interfaces/IPgpKeyring.cs b/src/SquidStd.Crypto/Pgp/Interfaces/IPgpKeyring.cs
index bd2917f6..bdcc4a9c 100644
--- a/src/SquidStd.Crypto/Pgp/Interfaces/IPgpKeyring.cs
+++ b/src/SquidStd.Crypto/Pgp/Interfaces/IPgpKeyring.cs
@@ -3,8 +3,8 @@
namespace SquidStd.Crypto.Pgp.Interfaces;
///
-/// In-memory collection of PGP keys, indexed by identity, key id, and fingerprint. Crypto operations look
-/// recipients and signers up here by identity.
+/// In-memory collection of PGP keys, indexed by identity, key id, and fingerprint. Crypto operations look
+/// recipients and signers up here by identity.
///
public interface IPgpKeyring
{
diff --git a/src/SquidStd.Crypto/Pgp/Interfaces/IPgpService.cs b/src/SquidStd.Crypto/Pgp/Interfaces/IPgpService.cs
index cdf07fcc..07b249c1 100644
--- a/src/SquidStd.Crypto/Pgp/Interfaces/IPgpService.cs
+++ b/src/SquidStd.Crypto/Pgp/Interfaces/IPgpService.cs
@@ -3,8 +3,8 @@
namespace SquidStd.Crypto.Pgp.Interfaces;
///
-/// OpenPGP operations over the keyring: key generation, encrypt/decrypt, sign/verify, and the combined
-/// encrypt+sign / decrypt+verify flows. Recipients and signers are resolved from the keyring by identity.
+/// OpenPGP operations over the keyring: key generation, encrypt/decrypt, sign/verify, and the combined
+/// encrypt+sign / decrypt+verify flows. Recipients and signers are resolved from the keyring by identity.
///
public interface IPgpService
{
@@ -16,7 +16,10 @@ public interface IPgpService
/// Encrypts a stream for the recipient, writing an armored message to .
Task EncryptForAsync(
- string recipientIdentity, Stream input, Stream output, CancellationToken cancellationToken = default
+ string recipientIdentity,
+ Stream input,
+ Stream output,
+ CancellationToken cancellationToken = default
);
/// Decrypts an armored message using the matching keyring secret key and passphrase.
@@ -27,24 +30,36 @@ Task EncryptForAsync(
/// Encrypts for the recipient and signs it with the signer's secret key.
Task EncryptAndSignForAsync(
- string recipientIdentity, byte[] data, string signerIdentity, string signerPassphrase,
+ string recipientIdentity,
+ byte[] data,
+ string signerIdentity,
+ string signerPassphrase,
CancellationToken cancellationToken = default
);
/// Encrypts and signs a stream for the recipient.
Task EncryptAndSignForAsync(
- string recipientIdentity, Stream input, Stream output, string signerIdentity, string signerPassphrase,
+ string recipientIdentity,
+ Stream input,
+ Stream output,
+ string signerIdentity,
+ string signerPassphrase,
CancellationToken cancellationToken = default
);
/// Decrypts an armored message and reports whether it was signed and whether the signature validated.
Task DecryptAndVerifyAsync(
- string armored, string passphrase, CancellationToken cancellationToken = default
+ string armored,
+ string passphrase,
+ CancellationToken cancellationToken = default
);
/// Produces an armored signed message that embeds .
Task SignAsync(
- byte[] data, string signerIdentity, string passphrase, CancellationToken cancellationToken = default
+ byte[] data,
+ string signerIdentity,
+ string passphrase,
+ CancellationToken cancellationToken = default
);
/// Verifies an armored signed message against the keyring, recovering the embedded content.
diff --git a/src/SquidStd.Crypto/Pgp/Internal/PgpKeyFactory.cs b/src/SquidStd.Crypto/Pgp/Internal/PgpKeyFactory.cs
index 5838b962..082c3dd5 100644
--- a/src/SquidStd.Crypto/Pgp/Internal/PgpKeyFactory.cs
+++ b/src/SquidStd.Crypto/Pgp/Internal/PgpKeyFactory.cs
@@ -8,8 +8,8 @@
namespace SquidStd.Crypto.Pgp.Internal;
///
-/// Builds a from armored key material by reading metadata off the public master key.
-/// Shared by key generation, keyring import, and key-store loading.
+/// Builds a from armored key material by reading metadata off the public master key.
+/// Shared by key generation, keyring import, and key-store loading.
///
internal static class PgpKeyFactory
{
@@ -25,7 +25,7 @@ public static PgpKey FromArmored(string publicArmored, string? privateArmored)
var validSeconds = master.GetValidSeconds();
DateTimeOffset? expiresUtc = validSeconds > 0 ? createdUtc.AddSeconds(validSeconds) : null;
- return new PgpKey(
+ return new(
identity,
keyId,
fingerprint,
@@ -51,12 +51,10 @@ private static string FirstUserId(PgpPublicKey master)
}
private static PgpKeyAlgorithm MapAlgorithm(PublicKeyAlgorithmTag tag)
- {
- return tag switch
+ => tag switch
{
PublicKeyAlgorithmTag.RsaGeneral or PublicKeyAlgorithmTag.RsaEncrypt or PublicKeyAlgorithmTag.RsaSign =>
PgpKeyAlgorithm.Rsa,
_ => PgpKeyAlgorithm.Rsa
};
- }
}
diff --git a/src/SquidStd.Crypto/Pgp/Internal/PgpKeyStoreCodec.cs b/src/SquidStd.Crypto/Pgp/Internal/PgpKeyStoreCodec.cs
index 24d3fcad..83054767 100644
--- a/src/SquidStd.Crypto/Pgp/Internal/PgpKeyStoreCodec.cs
+++ b/src/SquidStd.Crypto/Pgp/Internal/PgpKeyStoreCodec.cs
@@ -4,8 +4,8 @@
namespace SquidStd.Crypto.Pgp.Internal;
///
-/// Encodes a set of keys into a single byte blob (one base64 record per line) and back. Only armored
-/// material is stored; metadata is re-derived on load.
+/// Encodes a set of keys into a single byte blob (one base64 record per line) and back. Only armored
+/// material is stored; metadata is re-derived on load.
///
internal static class PgpKeyStoreCodec
{
@@ -17,8 +17,8 @@ public static byte[] Encode(IReadOnlyCollection keys)
{
var pub = Convert.ToBase64String(Encoding.UTF8.GetBytes(key.PublicArmored));
var sec = key.PrivateArmored is null
- ? string.Empty
- : Convert.ToBase64String(Encoding.UTF8.GetBytes(key.PrivateArmored));
+ ? string.Empty
+ : Convert.ToBase64String(Encoding.UTF8.GetBytes(key.PrivateArmored));
builder.Append(pub).Append('\t').Append(sec).Append('\n');
}
@@ -34,9 +34,9 @@ public static IReadOnlyList Decode(byte[] blob)
{
var parts = line.Split('\t');
var publicArmored = Encoding.UTF8.GetString(Convert.FromBase64String(parts[0]));
- string? privateArmored = parts.Length > 1 && parts[1].Length > 0
- ? Encoding.UTF8.GetString(Convert.FromBase64String(parts[1]))
- : null;
+ var privateArmored = parts.Length > 1 && parts[1].Length > 0
+ ? Encoding.UTF8.GetString(Convert.FromBase64String(parts[1]))
+ : null;
result.Add(PgpKeyFactory.FromArmored(publicArmored, privateArmored));
}
diff --git a/src/SquidStd.Crypto/Pgp/Services/AesGcmPgpKeyStore.cs b/src/SquidStd.Crypto/Pgp/Services/AesGcmPgpKeyStore.cs
index f595a789..7090f1cf 100644
--- a/src/SquidStd.Crypto/Pgp/Services/AesGcmPgpKeyStore.cs
+++ b/src/SquidStd.Crypto/Pgp/Services/AesGcmPgpKeyStore.cs
@@ -6,8 +6,8 @@
namespace SquidStd.Crypto.Pgp.Services;
///
-/// Key store that serializes the keyring to a single file encrypted at rest with the application key via
-/// .
+/// Key store that serializes the keyring to a single file encrypted at rest with the application key via
+/// .
///
public sealed class AesGcmPgpKeyStore : IPgpKeyStore
{
@@ -30,6 +30,7 @@ public async Task SaveAsync(IReadOnlyCollection keys, CancellationToken
var protectedBytes = _protector.Protect(plaintext);
var directory = Path.GetDirectoryName(_path);
+
if (!string.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
diff --git a/src/SquidStd.Crypto/Pgp/Services/FilePgpKeyStore.cs b/src/SquidStd.Crypto/Pgp/Services/FilePgpKeyStore.cs
index e71d2c1c..55568d23 100644
--- a/src/SquidStd.Crypto/Pgp/Services/FilePgpKeyStore.cs
+++ b/src/SquidStd.Crypto/Pgp/Services/FilePgpKeyStore.cs
@@ -6,8 +6,8 @@
namespace SquidStd.Crypto.Pgp.Services;
///
-/// Key store backed by a directory of armored .asc files (one public, optionally one secret, per
-/// key). gpg-interoperable.
+/// Key store backed by a directory of armored .asc files (one public, optionally one secret, per
+/// key). gpg-interoperable.
///
public sealed class FilePgpKeyStore : IPgpKeyStore
{
@@ -31,20 +31,20 @@ public async Task SaveAsync(IReadOnlyCollection keys, CancellationToken
{
var stem = Stem(key);
await File.WriteAllTextAsync(
- Path.Combine(_directory, stem + PublicSuffix),
- key.PublicArmored,
- cancellationToken
- )
- .ConfigureAwait(false);
+ Path.Combine(_directory, stem + PublicSuffix),
+ key.PublicArmored,
+ cancellationToken
+ )
+ .ConfigureAwait(false);
if (key.PrivateArmored is not null)
{
await File.WriteAllTextAsync(
- Path.Combine(_directory, stem + SecretSuffix),
- key.PrivateArmored,
- cancellationToken
- )
- .ConfigureAwait(false);
+ Path.Combine(_directory, stem + SecretSuffix),
+ key.PrivateArmored,
+ cancellationToken
+ )
+ .ConfigureAwait(false);
}
}
}
@@ -65,9 +65,9 @@ public async Task> LoadAsync(CancellationToken cancellatio
var publicArmored = await File.ReadAllTextAsync(publicPath, cancellationToken).ConfigureAwait(false);
var secretPath = Path.Combine(_directory, stem + SecretSuffix);
- string? secretArmored = File.Exists(secretPath)
- ? await File.ReadAllTextAsync(secretPath, cancellationToken).ConfigureAwait(false)
- : null;
+ var secretArmored = File.Exists(secretPath)
+ ? await File.ReadAllTextAsync(secretPath, cancellationToken).ConfigureAwait(false)
+ : null;
result.Add(PgpKeyFactory.FromArmored(publicArmored, secretArmored));
}
@@ -78,6 +78,7 @@ public async Task> LoadAsync(CancellationToken cancellatio
private static string Stem(PgpKey key)
{
var safeIdentity = new StringBuilder(key.Identity.Length);
+
foreach (var ch in key.Identity)
{
safeIdentity.Append(char.IsLetterOrDigit(ch) ? ch : '_');
diff --git a/src/SquidStd.Crypto/Pgp/Services/PgpKeyring.cs b/src/SquidStd.Crypto/Pgp/Services/PgpKeyring.cs
index 8d258635..efc8ce14 100644
--- a/src/SquidStd.Crypto/Pgp/Services/PgpKeyring.cs
+++ b/src/SquidStd.Crypto/Pgp/Services/PgpKeyring.cs
@@ -9,7 +9,7 @@
namespace SquidStd.Crypto.Pgp.Services;
///
-/// Thread-safe in-memory keyring indexed by identity, key id, and fingerprint.
+/// Thread-safe in-memory keyring indexed by identity, key id, and fingerprint.
///
public sealed class PgpKeyring : IPgpKeyring
{
@@ -25,8 +25,8 @@ public PgpKey Import(string armored)
ArgumentException.ThrowIfNullOrWhiteSpace(armored);
var key = armored.Contains(SecretHeader, StringComparison.Ordinal)
- ? PgpKeyFactory.FromArmored(ExportPublic(armored), armored)
- : PgpKeyFactory.FromArmored(armored, null);
+ ? PgpKeyFactory.FromArmored(ExportPublic(armored), armored)
+ : PgpKeyFactory.FromArmored(armored, null);
_byKeyId[key.KeyId] = key;
@@ -67,9 +67,7 @@ public bool Remove(string identityOrKeyIdOrFingerprint)
///
public bool Contains(string identityOrKeyIdOrFingerprint)
- {
- return Find(identityOrKeyIdOrFingerprint) is not null;
- }
+ => Find(identityOrKeyIdOrFingerprint) is not null;
///
public async Task LoadAsync(IPgpKeyStore store, CancellationToken cancellationToken = default)
@@ -95,15 +93,14 @@ public Task SaveAsync(IPgpKeyStore store, CancellationToken cancellationToken =
private static string ExportPublic(string secretArmored)
{
- using var input = PgpUtilities.GetDecoderStream(
- new MemoryStream(Encoding.UTF8.GetBytes(secretArmored))
- );
- var ring = new PgpSecretKeyRingBundle(input).GetKeyRings().Cast().First();
+ using var input = PgpUtilities.GetDecoderStream(new MemoryStream(Encoding.UTF8.GetBytes(secretArmored)));
+ var ring = new PgpSecretKeyRingBundle(input).GetKeyRings().First();
using var output = new MemoryStream();
+
using (var armor = new ArmoredOutputStream(output))
{
- foreach (PgpSecretKey secretKey in ring.GetSecretKeys())
+ foreach (var secretKey in ring.GetSecretKeys())
{
secretKey.PublicKey.Encode(armor);
}
diff --git a/src/SquidStd.Crypto/Pgp/Services/PgpService.cs b/src/SquidStd.Crypto/Pgp/Services/PgpService.cs
index 6838551f..5ff2d6ff 100644
--- a/src/SquidStd.Crypto/Pgp/Services/PgpService.cs
+++ b/src/SquidStd.Crypto/Pgp/Services/PgpService.cs
@@ -9,8 +9,8 @@
namespace SquidStd.Crypto.Pgp.Services;
///
-/// OpenPGP operations over a keyring, implemented with PgpCore. Every byte/armored-string operation
-/// round-trips through so binary payloads survive intact.
+/// OpenPGP operations over a keyring, implemented with PgpCore. Every byte/armored-string operation
+/// round-trips through so binary payloads survive intact.
///
public sealed class PgpService : IPgpService
{
@@ -51,7 +51,9 @@ public PgpKey GenerateKey(string identity, string passphrase, PgpKeyOptions? opt
///
public async Task EncryptForAsync(
- string recipientIdentity, byte[] data, CancellationToken cancellationToken = default
+ string recipientIdentity,
+ byte[] data,
+ CancellationToken cancellationToken = default
)
{
ArgumentNullException.ThrowIfNull(data);
@@ -68,7 +70,10 @@ public async Task EncryptForAsync(
///
public async Task EncryptForAsync(
- string recipientIdentity, Stream input, Stream output, CancellationToken cancellationToken = default
+ string recipientIdentity,
+ Stream input,
+ Stream output,
+ CancellationToken cancellationToken = default
)
{
ArgumentNullException.ThrowIfNull(input);
@@ -96,7 +101,10 @@ public async Task DecryptAsync(string armored, string passphrase, Cancel
///
public async Task DecryptAsync(
- Stream input, Stream output, string passphrase, CancellationToken cancellationToken = default
+ Stream input,
+ Stream output,
+ string passphrase,
+ CancellationToken cancellationToken = default
)
{
ArgumentNullException.ThrowIfNull(input);
@@ -116,7 +124,10 @@ public async Task DecryptAsync(
///
public async Task EncryptAndSignForAsync(
- string recipientIdentity, byte[] data, string signerIdentity, string signerPassphrase,
+ string recipientIdentity,
+ byte[] data,
+ string signerIdentity,
+ string signerPassphrase,
CancellationToken cancellationToken = default
)
{
@@ -133,7 +144,11 @@ public async Task EncryptAndSignForAsync(
///
public async Task EncryptAndSignForAsync(
- string recipientIdentity, Stream input, Stream output, string signerIdentity, string signerPassphrase,
+ string recipientIdentity,
+ Stream input,
+ Stream output,
+ string signerIdentity,
+ string signerPassphrase,
CancellationToken cancellationToken = default
)
{
@@ -146,7 +161,9 @@ public async Task EncryptAndSignForAsync(
///
public async Task DecryptAndVerifyAsync(
- string armored, string passphrase, CancellationToken cancellationToken = default
+ string armored,
+ string passphrase,
+ CancellationToken cancellationToken = default
)
{
ArgumentException.ThrowIfNullOrWhiteSpace(armored);
@@ -161,7 +178,7 @@ public async Task DecryptAndVerifyAsync(
{
var plain = await DecryptWith(pgp, armored).ConfigureAwait(false);
- return new PgpDecryptionResult(plain, false, false);
+ return new(plain, false, false);
}
try
@@ -170,19 +187,22 @@ public async Task DecryptAndVerifyAsync(
using var output = new MemoryStream();
await pgp.DecryptAndVerifyAsync(input, output).ConfigureAwait(false);
- return new PgpDecryptionResult(output.ToArray(), true, true);
+ return new(output.ToArray(), true, true);
}
catch (Exception ex) when (ex is BcPgpException or InvalidOperationException or ArgumentException or IOException)
{
var plain = await DecryptWith(pgp, armored).ConfigureAwait(false);
- return new PgpDecryptionResult(plain, true, false);
+ return new(plain, true, false);
}
}
///
public async Task SignAsync(
- byte[] data, string signerIdentity, string passphrase, CancellationToken cancellationToken = default
+ byte[] data,
+ string signerIdentity,
+ string passphrase,
+ CancellationToken cancellationToken = default
)
{
ArgumentNullException.ThrowIfNull(data);
@@ -211,6 +231,7 @@ public async Task VerifyAsync(string signedMessage, Cance
var pgp = new PGP(new EncryptionKeys(key.PublicArmored));
bool ok;
+
try
{
ok = await pgp.VerifyAsync(input, output).ConfigureAwait(false);
@@ -227,11 +248,11 @@ public async Task VerifyAsync(string signedMessage, Cance
if (ok)
{
- return new PgpVerificationResult(true, recovered);
+ return new(true, recovered);
}
}
- return new PgpVerificationResult(false, recovered);
+ return new(false, recovered);
}
private PGP BuildEncryptAndSign(string recipientIdentity, string signerIdentity, string signerPassphrase)
@@ -239,7 +260,7 @@ private PGP BuildEncryptAndSign(string recipientIdentity, string signerIdentity,
var recipient = RequireKey(recipientIdentity);
var signer = RequireKey(signerIdentity);
- return new PGP(new EncryptionKeys(recipient.PublicArmored, signer.PrivateArmored!, signerPassphrase));
+ return new(new EncryptionKeys(recipient.PublicArmored, signer.PrivateArmored!, signerPassphrase));
}
private static async Task DecryptWith(PGP pgp, string armored)
@@ -255,8 +276,8 @@ private PgpKey RequireKey(string identity)
{
ArgumentException.ThrowIfNullOrWhiteSpace(identity);
- return _keyring.Find(identity)
- ?? throw new KeyNotFoundException($"No key for identity '{identity}' in the keyring.");
+ return _keyring.Find(identity) ??
+ throw new KeyNotFoundException($"No key for identity '{identity}' in the keyring.");
}
private PgpKey RequireSecretFor(string armored)
@@ -275,12 +296,8 @@ private PgpKey RequireSecretFor(string armored)
}
private static long ParseKeyId(string keyId)
- {
- return long.Parse(keyId, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
- }
+ => long.Parse(keyId, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
private static string ReadAll(MemoryStream stream)
- {
- return Encoding.UTF8.GetString(stream.ToArray());
- }
+ => Encoding.UTF8.GetString(stream.ToArray());
}
diff --git a/src/SquidStd.Crypto/Pgp/Types/PgpKeyAlgorithm.cs b/src/SquidStd.Crypto/Pgp/Types/PgpKeyAlgorithm.cs
index f98a5288..ed52ffa2 100644
--- a/src/SquidStd.Crypto/Pgp/Types/PgpKeyAlgorithm.cs
+++ b/src/SquidStd.Crypto/Pgp/Types/PgpKeyAlgorithm.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Crypto.Pgp.Types;
///
-/// OpenPGP public-key algorithm family for a generated key. Extensible (ECC may be added later).
+/// OpenPGP public-key algorithm family for a generated key. Extensible (ECC may be added later).
///
public enum PgpKeyAlgorithm
{
diff --git a/src/SquidStd.Crypto/README.md b/src/SquidStd.Crypto/README.md
index 27216f17..cd5d8436 100644
--- a/src/SquidStd.Crypto/README.md
+++ b/src/SquidStd.Crypto/README.md
@@ -52,14 +52,14 @@ await keyring.LoadAsync(container.Resolve());
## Key types
-| Type | Purpose |
-|------|---------|
-| `IPgpService` | Key generation, encrypt/decrypt, sign/verify, and combined encrypt+sign / decrypt+verify. |
-| `IPgpKeyring` | Stateful, indexed keyring: import keys and save/load via an `IPgpKeyStore`. |
-| `IPgpKeyStore` | Pluggable keyring persistence backend. |
-| `FilePgpKeyStore` | One armored `.asc` per key (gpg-interoperable). |
-| `AesGcmPgpKeyStore` | The whole keyring serialized to a single file, encrypted at rest via `ISecretProtector`. |
-| `CryptoFileSystem` | `ILockableFileSystem` that encrypts content and names over any `IVirtualFileSystem`. |
+| Type | Purpose |
+|---------------------|-------------------------------------------------------------------------------------------|
+| `IPgpService` | Key generation, encrypt/decrypt, sign/verify, and combined encrypt+sign / decrypt+verify. |
+| `IPgpKeyring` | Stateful, indexed keyring: import keys and save/load via an `IPgpKeyStore`. |
+| `IPgpKeyStore` | Pluggable keyring persistence backend. |
+| `FilePgpKeyStore` | One armored `.asc` per key (gpg-interoperable). |
+| `AesGcmPgpKeyStore` | The whole keyring serialized to a single file, encrypted at rest via `ISecretProtector`. |
+| `CryptoFileSystem` | `ILockableFileSystem` that encrypts content and names over any `IVirtualFileSystem`. |
## Key stores
diff --git a/src/SquidStd.Crypto/Vfs/Extensions/RegisterCryptoVaultExtensions.cs b/src/SquidStd.Crypto/Vfs/Extensions/RegisterCryptoVaultExtensions.cs
index d87faadd..df8f116a 100644
--- a/src/SquidStd.Crypto/Vfs/Extensions/RegisterCryptoVaultExtensions.cs
+++ b/src/SquidStd.Crypto/Vfs/Extensions/RegisterCryptoVaultExtensions.cs
@@ -13,8 +13,8 @@ public static class RegisterCryptoVaultExtensions
extension(IContainer container)
{
///
- /// Registers an singleton: a crypto vault over a single-file zip at
- /// . The consumer calls at runtime.
+ /// Registers an singleton: a crypto vault over a single-file zip at
+ /// . The consumer calls at runtime.
///
public IContainer RegisterCryptoVault(string path, CryptoVaultOptions? options = null)
{
diff --git a/src/SquidStd.Crypto/Vfs/Internal/EntryCipher.cs b/src/SquidStd.Crypto/Vfs/Internal/EntryCipher.cs
index 03ce8db0..1cda677d 100644
--- a/src/SquidStd.Crypto/Vfs/Internal/EntryCipher.cs
+++ b/src/SquidStd.Crypto/Vfs/Internal/EntryCipher.cs
@@ -13,7 +13,7 @@ internal sealed class EntryCipher : IDisposable
public EntryCipher(byte[] key, int chunkSize)
{
- _aes = new AesGcm(key, TagSize);
+ _aes = new(key, TagSize);
_chunkSize = chunkSize;
}
@@ -58,6 +58,7 @@ public async Task DecryptAsync(Stream input, Stream output, CancellationToken ca
if (length == 0)
{
_aes.Decrypt(nonce.Span, ReadOnlySpan.Empty, tag, Span.Empty);
+
break;
}
@@ -120,7 +121,5 @@ private static async Task ReadExactAsync(Stream stream, byte[] buffer, Cancellat
}
public void Dispose()
- {
- _aes.Dispose();
- }
+ => _aes.Dispose();
}
diff --git a/src/SquidStd.Crypto/Vfs/Internal/VaultHeader.cs b/src/SquidStd.Crypto/Vfs/Internal/VaultHeader.cs
index 289a9867..884939ce 100644
--- a/src/SquidStd.Crypto/Vfs/Internal/VaultHeader.cs
+++ b/src/SquidStd.Crypto/Vfs/Internal/VaultHeader.cs
@@ -14,13 +14,9 @@ int ChunkSize
)
{
public byte[] Serialize()
- {
- return JsonSerializer.SerializeToUtf8Bytes(this);
- }
+ => JsonSerializer.SerializeToUtf8Bytes(this);
public static VaultHeader Parse(byte[] data)
- {
- return JsonSerializer.Deserialize(data)
- ?? throw new InvalidDataException("Vault header is empty or invalid.");
- }
+ => JsonSerializer.Deserialize(data) ??
+ throw new InvalidDataException("Vault header is empty or invalid.");
}
diff --git a/src/SquidStd.Crypto/Vfs/Internal/VaultIndex.cs b/src/SquidStd.Crypto/Vfs/Internal/VaultIndex.cs
index fcd2c56e..cb6c6905 100644
--- a/src/SquidStd.Crypto/Vfs/Internal/VaultIndex.cs
+++ b/src/SquidStd.Crypto/Vfs/Internal/VaultIndex.cs
@@ -25,7 +25,7 @@ public IReadOnlyDictionary Entries
public VaultIndex()
{
- _entries = new Dictionary(StringComparer.Ordinal);
+ _entries = new(StringComparer.Ordinal);
}
private VaultIndex(Dictionary entries)
@@ -67,9 +67,9 @@ public byte[] Serialize()
public static VaultIndex Parse(byte[] data)
{
- var map = JsonSerializer.Deserialize>(data)
- ?? new Dictionary(StringComparer.Ordinal);
+ var map = JsonSerializer.Deserialize>(data) ??
+ new Dictionary(StringComparer.Ordinal);
- return new VaultIndex(new Dictionary(map, StringComparer.Ordinal));
+ return new(new(map, StringComparer.Ordinal));
}
}
diff --git a/src/SquidStd.Crypto/Vfs/Internal/VaultKeyDerivation.cs b/src/SquidStd.Crypto/Vfs/Internal/VaultKeyDerivation.cs
index abb5212a..9be8c299 100644
--- a/src/SquidStd.Crypto/Vfs/Internal/VaultKeyDerivation.cs
+++ b/src/SquidStd.Crypto/Vfs/Internal/VaultKeyDerivation.cs
@@ -12,12 +12,12 @@ internal static class VaultKeyDerivation
public static byte[] DeriveMasterKey(string passphrase, byte[] salt, CryptoVaultOptions options)
{
var parameters = new Argon2Parameters.Builder(Argon2Parameters.Argon2id)
- .WithVersion(Argon2Parameters.Version13)
- .WithSalt(salt)
- .WithIterations(options.Argon2Iterations)
- .WithMemoryAsKB(options.Argon2MemoryKib)
- .WithParallelism(options.Argon2Parallelism)
- .Build();
+ .WithVersion(Argon2Parameters.Version13)
+ .WithSalt(salt)
+ .WithIterations(options.Argon2Iterations)
+ .WithMemoryAsKB(options.Argon2MemoryKib)
+ .WithParallelism(options.Argon2Parallelism)
+ .Build();
var generator = new Argon2BytesGenerator();
generator.Init(parameters);
diff --git a/src/SquidStd.Crypto/Vfs/Services/CryptoFileSystem.cs b/src/SquidStd.Crypto/Vfs/Services/CryptoFileSystem.cs
index 078fca26..920ecfd1 100644
--- a/src/SquidStd.Crypto/Vfs/Services/CryptoFileSystem.cs
+++ b/src/SquidStd.Crypto/Vfs/Services/CryptoFileSystem.cs
@@ -2,9 +2,9 @@
using System.Security.Cryptography;
using SquidStd.Crypto.Vfs.Data;
using SquidStd.Crypto.Vfs.Internal;
+using SquidStd.Vfs.Abstractions;
using SquidStd.Vfs.Abstractions.Data;
using SquidStd.Vfs.Abstractions.Interfaces;
-using SquidStd.Vfs.Abstractions;
namespace SquidStd.Crypto.Vfs.Services;
@@ -35,7 +35,7 @@ public void Unlock(string passphrase)
if (headerBytes is null)
{
- header = new VaultHeader(
+ header = new(
"SQVFS1",
1,
RandomNumberGenerator.GetBytes(16),
@@ -62,8 +62,8 @@ public void Unlock(string passphrase)
var indexBytes = _inner.ReadAllBytesAsync(IndexPath).AsTask().GetAwaiter().GetResult();
_index = indexBytes is null
- ? new VaultIndex()
- : VaultIndex.Parse(VaultBlob.Decrypt(VaultKeyDerivation.DeriveSubKey(master, "index"), indexBytes));
+ ? new()
+ : VaultIndex.Parse(VaultBlob.Decrypt(VaultKeyDerivation.DeriveSubKey(master, "index"), indexBytes));
_masterKey = master;
}
@@ -98,8 +98,8 @@ public ValueTask ExistsAsync(string path, CancellationToken cancellationTo
return null;
}
- var blob = await _inner.ReadAllBytesAsync(entry!.BlobId, cancellationToken).ConfigureAwait(false)
- ?? throw new InvalidDataException($"Backing blob '{entry.BlobId}' is missing.");
+ var blob = await _inner.ReadAllBytesAsync(entry!.BlobId, cancellationToken).ConfigureAwait(false) ??
+ throw new InvalidDataException($"Backing blob '{entry.BlobId}' is missing.");
using var cipher = NewCipher(entry.BlobId);
using var input = new MemoryStream(blob);
@@ -110,7 +110,9 @@ public ValueTask ExistsAsync(string path, CancellationToken cancellationTo
}
public async ValueTask WriteAllBytesAsync(
- string path, ReadOnlyMemory data, CancellationToken cancellationToken = default
+ string path,
+ ReadOnlyMemory data,
+ CancellationToken cancellationToken = default
)
{
EnsureUnlocked();
@@ -124,15 +126,15 @@ public async ValueTask WriteAllBytesAsync(
await cipher.EncryptAsync(input, output, cancellationToken).ConfigureAwait(false);
await _inner.WriteAllBytesAsync(blobId, output.ToArray(), cancellationToken).ConfigureAwait(false);
- _index.Set(normalized, new VaultIndexEntry(blobId, data.Length, DateTimeOffset.UtcNow));
+ _index.Set(normalized, new(blobId, data.Length, DateTimeOffset.UtcNow));
}
public async Task OpenReadAsync(string path, CancellationToken cancellationToken = default)
{
- var data = await ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false)
- ?? throw new FileNotFoundException($"No file at '{path}'.", path);
+ var data = await ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false) ??
+ throw new FileNotFoundException($"No file at '{path}'.", path);
- return new MemoryStream(data, writable: false);
+ return new MemoryStream(data, false);
}
public Task OpenWriteAsync(string path, CancellationToken cancellationToken = default)
@@ -157,7 +159,8 @@ public async ValueTask DeleteAsync(string path, CancellationToken cancella
}
public async IAsyncEnumerable ListAsync(
- string? prefix = null, [EnumeratorCancellation] CancellationToken cancellationToken = default
+ string? prefix = null,
+ [EnumeratorCancellation] CancellationToken cancellationToken = default
)
{
EnsureUnlocked();
@@ -170,21 +173,17 @@ public async IAsyncEnumerable ListAsync(
continue;
}
- yield return new VfsEntry(logicalPath, entry.Size, entry.ModifiedUtc);
+ yield return new(logicalPath, entry.Size, entry.ModifiedUtc);
await Task.CompletedTask;
}
}
private EntryCipher NewCipher(string blobId)
- {
- return new EntryCipher(VaultKeyDerivation.DeriveSubKey(_masterKey!, "entry:" + blobId), _options.ChunkSize);
- }
+ => new(VaultKeyDerivation.DeriveSubKey(_masterKey!, "entry:" + blobId), _options.ChunkSize);
private static string NewBlobId()
- {
- return Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16));
- }
+ => Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16));
private void FlushIndex()
{
@@ -203,6 +202,7 @@ private void PruneOrphans()
var paths = new List();
var enumerator = _inner.ListAsync().GetAsyncEnumerator();
+
try
{
while (enumerator.MoveNextAsync().AsTask().GetAwaiter().GetResult())
@@ -239,9 +239,11 @@ public void Dispose()
{
case IDisposable disposable:
disposable.Dispose();
+
break;
case IAsyncDisposable asyncDisposable:
asyncDisposable.DisposeAsync().AsTask().GetAwaiter().GetResult();
+
break;
}
}
diff --git a/src/SquidStd.Database.Abstractions/Data/Database/DatabaseConfig.cs b/src/SquidStd.Database.Abstractions/Data/Database/DatabaseConfig.cs
index d386fd1b..39fdc203 100644
--- a/src/SquidStd.Database.Abstractions/Data/Database/DatabaseConfig.cs
+++ b/src/SquidStd.Database.Abstractions/Data/Database/DatabaseConfig.cs
@@ -3,18 +3,18 @@
namespace SquidStd.Database.Abstractions.Data.Database;
///
-/// Database connection configuration.
+/// Database connection configuration.
///
public sealed class DatabaseConfig : IConfigEntry
{
///
- /// Gets or sets the URI-style connection string (e.g. "sqlite://squidstd.db",
- /// "postgres://user:pass@host:5432/db"). The scheme selects the provider.
+ /// Gets or sets the URI-style connection string (e.g. "sqlite://squidstd.db",
+ /// "postgres://user:pass@host:5432/db"). The scheme selects the provider.
///
public string ConnectionString { get; set; } = "sqlite://squidstd.db";
///
- /// Gets or sets a value indicating whether the schema is auto-synchronized on startup.
+ /// Gets or sets a value indicating whether the schema is auto-synchronized on startup.
///
public bool AutoMigrate { get; set; } = true;
@@ -23,7 +23,5 @@ public sealed class DatabaseConfig : IConfigEntry
Type IConfigEntry.ConfigType => typeof(DatabaseConfig);
object IConfigEntry.CreateDefault()
- {
- return new DatabaseConfig();
- }
+ => new DatabaseConfig();
}
diff --git a/src/SquidStd.Database.Abstractions/Data/Entities/BaseEntity.cs b/src/SquidStd.Database.Abstractions/Data/Entities/BaseEntity.cs
index 85dc2da7..aee115e9 100644
--- a/src/SquidStd.Database.Abstractions/Data/Entities/BaseEntity.cs
+++ b/src/SquidStd.Database.Abstractions/Data/Entities/BaseEntity.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Database.Abstractions.Data.Entities;
///
-/// Base class for all persisted entities: a Guid identity plus UTC create/update timestamps.
+/// Base class for all persisted entities: a Guid identity plus UTC create/update timestamps.
///
public abstract class BaseEntity
{
diff --git a/src/SquidStd.Database.Abstractions/Data/PagedResultData.cs b/src/SquidStd.Database.Abstractions/Data/PagedResultData.cs
index cd16c889..a259ad19 100644
--- a/src/SquidStd.Database.Abstractions/Data/PagedResultData.cs
+++ b/src/SquidStd.Database.Abstractions/Data/PagedResultData.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Database.Abstractions.Data;
///
-/// A paginated result set with paging metadata.
+/// A paginated result set with paging metadata.
///
/// The item type.
public sealed class PagedResultData
@@ -28,7 +28,7 @@ public sealed class PagedResultData
public bool HasPrevious => Page > 1 && TotalPages > 0;
///
- /// Creates a paged result.
+ /// Creates a paged result.
///
/// The current page items.
/// The 1-based page number.
@@ -36,13 +36,11 @@ public sealed class PagedResultData
/// The total matching row count.
/// The paged result.
public static PagedResultData Create(IReadOnlyList items, int page, int pageSize, long totalCount)
- {
- return new PagedResultData
+ => new()
{
Items = items,
Page = page,
PageSize = pageSize,
TotalCount = totalCount
};
- }
}
diff --git a/src/SquidStd.Database.Abstractions/Interfaces/Data/IDataAccess.cs b/src/SquidStd.Database.Abstractions/Interfaces/Data/IDataAccess.cs
index 8ba1f9ee..a5d8e020 100644
--- a/src/SquidStd.Database.Abstractions/Interfaces/Data/IDataAccess.cs
+++ b/src/SquidStd.Database.Abstractions/Interfaces/Data/IDataAccess.cs
@@ -6,7 +6,7 @@
namespace SquidStd.Database.Abstractions.Interfaces.Data;
///
-/// Generic data access for a type: CRUD, bulk, and querying.
+/// Generic data access for a type: CRUD, bulk, and querying.
///
/// The entity type.
public interface IDataAccess
diff --git a/src/SquidStd.Database.Abstractions/Types/Data/DatabaseProviderType.cs b/src/SquidStd.Database.Abstractions/Types/Data/DatabaseProviderType.cs
index 530fe8ed..81955055 100644
--- a/src/SquidStd.Database.Abstractions/Types/Data/DatabaseProviderType.cs
+++ b/src/SquidStd.Database.Abstractions/Types/Data/DatabaseProviderType.cs
@@ -1,7 +1,7 @@
namespace SquidStd.Database.Abstractions.Types.Data;
///
-/// Supported database providers.
+/// Supported database providers.
///
public enum DatabaseProviderType
{
diff --git a/src/SquidStd.Database/Connection/ConnectionStringParser.cs b/src/SquidStd.Database/Connection/ConnectionStringParser.cs
index 2eb883cc..1559f0c0 100644
--- a/src/SquidStd.Database/Connection/ConnectionStringParser.cs
+++ b/src/SquidStd.Database/Connection/ConnectionStringParser.cs
@@ -4,12 +4,12 @@
namespace SquidStd.Database.Connection;
///
-/// Parses URI-style connection strings ("scheme://...") into a provider and native connection string.
+/// Parses URI-style connection strings ("scheme://...") into a provider and native connection string.
///
public static class ConnectionStringParser
{
///
- /// Parses the given URI connection string.
+ /// Parses the given URI connection string.
///
/// The URI connection string.
/// The parsed provider and native connection string.
@@ -29,10 +29,10 @@ public static ParsedConnection Parse(string connectionString)
var provider = ResolveProvider(scheme);
var native = provider == DatabaseProviderType.Sqlite
- ? BuildSqlite(remainder)
- : BuildServer(provider, remainder);
+ ? BuildSqlite(remainder)
+ : BuildServer(provider, remainder);
- return new ParsedConnection(provider, native);
+ return new(provider, native);
}
private static string BuildServer(DatabaseProviderType provider, string remainder)
@@ -87,8 +87,7 @@ private static string BuildSqlite(string remainder)
}
private static DatabaseProviderType ResolveProvider(string scheme)
- {
- return scheme switch
+ => scheme switch
{
"sqlite" => DatabaseProviderType.Sqlite,
"postgres" or "postgresql" => DatabaseProviderType.Postgres,
@@ -96,7 +95,6 @@ private static DatabaseProviderType ResolveProvider(string scheme)
"mysql" => DatabaseProviderType.MySql,
_ => throw new NotSupportedException($"Unsupported database scheme '{scheme}'.")
};
- }
private static (string User, string Password, string HostPort) SplitAuthority(string authority)
{
diff --git a/src/SquidStd.Database/Connection/ParsedConnection.cs b/src/SquidStd.Database/Connection/ParsedConnection.cs
index 6603c3fd..b03c0d84 100644
--- a/src/SquidStd.Database/Connection/ParsedConnection.cs
+++ b/src/SquidStd.Database/Connection/ParsedConnection.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Database.Connection;
///
-/// The result of parsing a URI connection string: the provider and the native connection string.
+/// The result of parsing a URI connection string: the provider and the native connection string.
///
/// The resolved database provider.
/// The provider-native connection string for FreeSql.
diff --git a/src/SquidStd.Database/Data/FreeSqlDataAccess.cs b/src/SquidStd.Database/Data/FreeSqlDataAccess.cs
index 65a9dec0..b1fe240e 100644
--- a/src/SquidStd.Database/Data/FreeSqlDataAccess.cs
+++ b/src/SquidStd.Database/Data/FreeSqlDataAccess.cs
@@ -10,7 +10,7 @@
namespace SquidStd.Database.Data;
///
-/// FreeSql-backed . Writes run inside a unit of work with rollback.
+/// FreeSql-backed . Writes run inside a unit of work with rollback.
///
/// The entity type.
public sealed class FreeSqlDataAccess : IDataAccess
@@ -21,7 +21,7 @@ public sealed class FreeSqlDataAccess : IDataAccess
private readonly IFreeSql _orm;
///
- /// Initializes the data access over the shared FreeSql instance.
+ /// Initializes the data access over the shared FreeSql instance.
///
/// The database service that owns the FreeSql instance.
public FreeSqlDataAccess(IDatabaseService databaseService)
@@ -34,17 +34,15 @@ public Task BulkDeleteAsync(
Expression> predicate,
CancellationToken cancellationToken = default
)
- {
- return RunInTransactionAsync(
+ => RunInTransactionAsync(
transaction => _orm.Delete()
- .Where(predicate)
- .WithTransaction(transaction)
- .ExecuteAffrowsAsync(cancellationToken),
+ .Where(predicate)
+ .WithTransaction(transaction)
+ .ExecuteAffrowsAsync(cancellationToken),
"BulkDelete",
null,
cancellationToken
);
- }
///
public Task BulkInsertAsync(IEnumerable entities, CancellationToken cancellationToken = default)
@@ -72,9 +70,9 @@ public Task BulkUpdateAsync(IEnumerable entities, CancellationToke
return RunInTransactionAsync(
transaction => _orm.Update()
- .SetSource(list)
- .WithTransaction(transaction)
- .ExecuteAffrowsAsync(cancellationToken),
+ .SetSource(list)
+ .WithTransaction(transaction)
+ .ExecuteAffrowsAsync(cancellationToken),
"BulkUpdate",
list.Count,
cancellationToken
@@ -101,35 +99,29 @@ public Task CountAsync(
public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default)
{
var affected = await RunInTransactionAsync(
- transaction => _orm.Delete()
- .Where(e => e.Id == id)
- .WithTransaction(transaction)
- .ExecuteAffrowsAsync(cancellationToken),
- "Delete",
- null,
- cancellationToken
- );
+ transaction => _orm.Delete()
+ .Where(e => e.Id == id)
+ .WithTransaction(transaction)
+ .ExecuteAffrowsAsync(cancellationToken),
+ "Delete",
+ null,
+ cancellationToken
+ );
return affected > 0;
}
///
public Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default)
- {
- return DeleteAsync(entity.Id, cancellationToken);
- }
+ => DeleteAsync(entity.Id, cancellationToken);
///
public Task ExistsAsync(Expression> predicate, CancellationToken cancellationToken = default)
- {
- return _orm.Select().Where(predicate).AnyAsync(cancellationToken);
- }
+ => _orm.Select().Where(predicate).AnyAsync(cancellationToken);
///
public Task GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
- {
- return _orm.Select().Where(e => e.Id == id).FirstAsync(cancellationToken)!;
- }
+ => _orm.Select().Where(e => e.Id == id).FirstAsync(cancellationToken)!;
///
public async Task> GetPagedAsync(
@@ -185,9 +177,7 @@ await RunInTransactionAsync(
///
public ISelect Query()
- {
- return _orm.Select();
- }
+ => _orm.Select();
///
public async Task> QueryAsync(
@@ -212,9 +202,9 @@ public async Task UpdateAsync(TEntity entity, CancellationToken cancell
await RunInTransactionAsync(
transaction => _orm.Update()
- .SetSource(entity)
- .WithTransaction(transaction)
- .ExecuteAffrowsAsync(cancellationToken),
+ .SetSource(entity)
+ .WithTransaction(transaction)
+ .ExecuteAffrowsAsync(cancellationToken),
"Update",
1,
cancellationToken
diff --git a/src/SquidStd.Database/Extensions/RegisterDatabaseExtension.cs b/src/SquidStd.Database/Extensions/RegisterDatabaseExtension.cs
index abb91982..a357e873 100644
--- a/src/SquidStd.Database/Extensions/RegisterDatabaseExtension.cs
+++ b/src/SquidStd.Database/Extensions/RegisterDatabaseExtension.cs
@@ -10,7 +10,7 @@
namespace SquidStd.Database.Extensions;
///
-/// DI registration for the database subsystem.
+/// DI registration for the database subsystem.
///
public static class RegisterDatabaseExtension
{
@@ -18,7 +18,7 @@ public static class RegisterDatabaseExtension
extension(IContainer container)
{
///
- /// Registers the database config section, the database service, and the open-generic data access.
+ /// Registers the database config section, the database service, and the open-generic data access.
///
/// The same container for chaining.
public IContainer RegisterDatabase()
diff --git a/src/SquidStd.Database/Extensions/ZLinqResultExtensions.cs b/src/SquidStd.Database/Extensions/ZLinqResultExtensions.cs
index 16922587..5985a19a 100644
--- a/src/SquidStd.Database/Extensions/ZLinqResultExtensions.cs
+++ b/src/SquidStd.Database/Extensions/ZLinqResultExtensions.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Database.Extensions;
///
-/// Zero-allocation, in-memory helpers (ZLinq) over already-materialized result lists.
+/// Zero-allocation, in-memory helpers (ZLinq) over already-materialized result lists.
///
public static class ZLinqResultExtensions
{
@@ -11,25 +11,21 @@ public static class ZLinqResultExtensions
extension(IReadOnlyList source)
{
///
- /// Projects each materialized item to a new form using ZLinq, returning a list.
+ /// Projects each materialized item to a new form using ZLinq, returning a list.
///
/// The source item type.
/// The projected item type.
/// The projection.
/// The projected list.
- public List MapToList(
- Func selector
- )
- {
- return source.AsValueEnumerable().Select(selector).ToList();
- }
+ public List MapToList(Func selector)
+ => source.AsValueEnumerable().Select(selector).ToList();
}
/// The materialized source items.
extension(IReadOnlyList source)
{
///
- /// Takes an in-memory page of a materialized list using ZLinq (no SQL involved).
+ /// Takes an in-memory page of a materialized list using ZLinq (no SQL involved).
///
/// The item type.
/// The 1-based page number.
diff --git a/src/SquidStd.Database/Interfaces/Services/IDatabaseService.cs b/src/SquidStd.Database/Interfaces/Services/IDatabaseService.cs
index 1662dde7..0ce04e6d 100644
--- a/src/SquidStd.Database/Interfaces/Services/IDatabaseService.cs
+++ b/src/SquidStd.Database/Interfaces/Services/IDatabaseService.cs
@@ -3,7 +3,7 @@
namespace SquidStd.Database.Interfaces.Services;
///
-/// Owns the application's singleton FreeSql instance and its lifecycle.
+/// Owns the application's singleton FreeSql instance and its lifecycle.
///
public interface IDatabaseService : ISquidStdService
{
diff --git a/src/SquidStd.Database/Services/DatabaseService.cs b/src/SquidStd.Database/Services/DatabaseService.cs
index e9a7512c..7b606ea2 100644
--- a/src/SquidStd.Database/Services/DatabaseService.cs
+++ b/src/SquidStd.Database/Services/DatabaseService.cs
@@ -8,7 +8,7 @@
namespace SquidStd.Database.Services;
///
-/// Builds and owns the singleton FreeSql instance, logging SQL and migrations verbosely.
+/// Builds and owns the singleton FreeSql instance, logging SQL and migrations verbosely.
///
public sealed class DatabaseService : IDatabaseService
{
@@ -22,7 +22,7 @@ public sealed class DatabaseService : IDatabaseService
public IFreeSql Orm => _orm ?? throw new InvalidOperationException("Database service is not started.");
///
- /// Initializes the database service.
+ /// Initializes the database service.
///
/// The database configuration section.
public DatabaseService(DatabaseConfig config)
@@ -44,13 +44,13 @@ public ValueTask StartAsync(CancellationToken cancellationToken = default)
Logger.Verbose("Building FreeSql for provider {Provider}", parsed.Provider);
var builder = new FreeSqlBuilder()
- .UseConnectionString(MapDataType(parsed.Provider), parsed.NativeConnectionString)
- .UseAutoSyncStructure(_config.AutoMigrate)
- .UseMonitorCommand(cmd => Logger.Verbose("SQL {Sql}", cmd.CommandText));
+ .UseConnectionString(MapDataType(parsed.Provider), parsed.NativeConnectionString)
+ .UseAutoSyncStructure(_config.AutoMigrate)
+ .UseMonitorCommand(cmd => Logger.Verbose("SQL {Sql}", cmd.CommandText));
_orm = builder.Build();
_orm.Aop.SyncStructureAfter += (_, e) =>
- Logger.Verbose("Migrated {Entities} -> {Sql}", e.EntityTypes, e.Sql);
+ Logger.Verbose("Migrated {Entities} -> {Sql}", e.EntityTypes, e.Sql);
Logger.Information(
"Database service started ({Provider}, autoMigrate={AutoMigrate})",
@@ -73,8 +73,7 @@ public ValueTask StopAsync(CancellationToken cancellationToken = default)
}
private static DataType MapDataType(DatabaseProviderType provider)
- {
- return provider switch
+ => provider switch
{
DatabaseProviderType.Sqlite => DataType.Sqlite,
DatabaseProviderType.Postgres => DataType.PostgreSQL,
@@ -82,5 +81,4 @@ private static DataType MapDataType(DatabaseProviderType provider)
DatabaseProviderType.MySql => DataType.MySql,
_ => throw new NotSupportedException($"Unsupported provider {provider}.")
};
- }
}
diff --git a/src/SquidStd.Generators/AnalyzerReleases.Unshipped.md b/src/SquidStd.Generators/AnalyzerReleases.Unshipped.md
index 8dd9d9fb..822e1d6d 100644
--- a/src/SquidStd.Generators/AnalyzerReleases.Unshipped.md
+++ b/src/SquidStd.Generators/AnalyzerReleases.Unshipped.md
@@ -3,10 +3,10 @@
### New Rules
-Rule ID | Category | Severity | Notes
---------|----------|----------|------
-SQDGEN001 | SquidStd.Generators | Warning | Event listener cannot be generated
-SQDGEN002 | SquidStd.Generators | Warning | Standard service cannot be generated
-SQDGEN003 | SquidStd.Generators | Warning | Config section cannot be generated
-SQDGEN004 | SquidStd.Generators | Warning | Job handler cannot be generated
-SQDGEN005 | SquidStd.Generators | Warning | Script module cannot be generated
+ Rule ID | Category | Severity | Notes
+-----------|---------------------|----------|--------------------------------------
+ SQDGEN001 | SquidStd.Generators | Warning | Event listener cannot be generated
+ SQDGEN002 | SquidStd.Generators | Warning | Standard service cannot be generated
+ SQDGEN003 | SquidStd.Generators | Warning | Config section cannot be generated
+ SQDGEN004 | SquidStd.Generators | Warning | Job handler cannot be generated
+ SQDGEN005 | SquidStd.Generators | Warning | Script module cannot be generated
diff --git a/src/SquidStd.Generators/Common/GeneratorSymbolHelpers.cs b/src/SquidStd.Generators/Common/GeneratorSymbolHelpers.cs
index 6f10a228..10108900 100644
--- a/src/SquidStd.Generators/Common/GeneratorSymbolHelpers.cs
+++ b/src/SquidStd.Generators/Common/GeneratorSymbolHelpers.cs
@@ -5,24 +5,16 @@ namespace SquidStd.Generators.Common;
internal static class GeneratorSymbolHelpers
{
public static string FullyQualified(ITypeSymbol symbol)
- {
- return symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
- }
+ => symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
public static string DisplayName(ISymbol symbol)
- {
- return symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat);
- }
+ => symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat);
public static Location? PrimaryLocation(ISymbol symbol)
- {
- return symbol.Locations.FirstOrDefault();
- }
+ => symbol.Locations.FirstOrDefault();
public static bool IsConcreteNonGenericClass(INamedTypeSymbol type)
- {
- return type.TypeKind == TypeKind.Class && !type.IsAbstract && !type.IsGenericType;
- }
+ => type.TypeKind == TypeKind.Class && !type.IsAbstract && !type.IsGenericType;
public static bool IsAccessibleFromGeneratedSource(INamedTypeSymbol type)
{
@@ -42,16 +34,15 @@ public static bool IsAccessibleFromGeneratedSource(INamedTypeSymbol type)
}
public static bool ImplementsInterface(INamedTypeSymbol type, string metadataName, string namespaceName)
- {
- return type.AllInterfaces.Any(interfaceType =>
+ => type.AllInterfaces.Any(
+ interfaceType =>
{
var originalDefinition = interfaceType.OriginalDefinition;
- return originalDefinition.MetadataName == metadataName
- && originalDefinition.ContainingNamespace.ToDisplayString() == namespaceName;
+ return originalDefinition.MetadataName == metadataName &&
+ originalDefinition.ContainingNamespace.ToDisplayString() == namespaceName;
}
);
- }
public static bool IsAssignableTo(INamedTypeSymbol implementationType, INamedTypeSymbol serviceType)
{
@@ -68,15 +59,15 @@ public static bool IsAssignableTo(INamedTypeSymbol implementationType, INamedTyp
}
}
- return implementationType.AllInterfaces.Any(interfaceType =>
- SymbolEqualityComparer.Default.Equals(interfaceType, serviceType)
+ return implementationType.AllInterfaces.Any(
+ interfaceType =>
+ SymbolEqualityComparer.Default.Equals(interfaceType, serviceType)
);
}
public static bool HasPublicParameterlessConstructor(INamedTypeSymbol type)
- {
- return type.InstanceConstructors.Any(constructor =>
- constructor.Parameters.Length == 0 && constructor.DeclaredAccessibility == Accessibility.Public
+ => type.InstanceConstructors.Any(
+ constructor =>
+ constructor.Parameters.Length == 0 && constructor.DeclaredAccessibility == Accessibility.Public
);
- }
}
diff --git a/src/SquidStd.Generators/Config/ConfigSectionRegistrationGenerator.cs b/src/SquidStd.Generators/Config/ConfigSectionRegistrationGenerator.cs
index c45894b8..ec82ca29 100644
--- a/src/SquidStd.Generators/Config/ConfigSectionRegistrationGenerator.cs
+++ b/src/SquidStd.Generators/Config/ConfigSectionRegistrationGenerator.cs
@@ -35,12 +35,12 @@ CancellationToken cancellationToken
var sectionName = GetSectionName(attribute);
var priority = GetIntNamedArgument(attribute, "Priority");
- var isSupported = !string.IsNullOrWhiteSpace(sectionName)
- && GeneratorSymbolHelpers.IsConcreteNonGenericClass(configType)
- && GeneratorSymbolHelpers.IsAccessibleFromGeneratedSource(configType)
- && GeneratorSymbolHelpers.HasPublicParameterlessConstructor(configType);
+ var isSupported = !string.IsNullOrWhiteSpace(sectionName) &&
+ GeneratorSymbolHelpers.IsConcreteNonGenericClass(configType) &&
+ GeneratorSymbolHelpers.IsAccessibleFromGeneratedSource(configType) &&
+ GeneratorSymbolHelpers.HasPublicParameterlessConstructor(configType);
- return new ConfigSectionRegistrationCandidate(
+ return new(
GeneratorSymbolHelpers.FullyQualified(configType),
sectionName ?? string.Empty,
GeneratorSymbolHelpers.DisplayName(configType),
@@ -97,19 +97,21 @@ ImmutableArray candidates
}
var key = candidate.SectionName + "|" + candidate.ConfigTypeName;
+
if (seenKeys.Add(key))
{
supported.Add(candidate);
}
}
- supported.Sort(static (left, right) =>
+ supported.Sort(
+ static (left, right) =>
{
var sectionComparison = string.Compare(left.SectionName, right.SectionName, StringComparison.Ordinal);
return sectionComparison != 0
- ? sectionComparison
- : string.Compare(left.ConfigTypeName, right.ConfigTypeName, StringComparison.Ordinal);
+ ? sectionComparison
+ : string.Compare(left.ConfigTypeName, right.ConfigTypeName, StringComparison.Ordinal);
}
);
diff --git a/src/SquidStd.Generators/Config/ConfigSectionSourceBuilder.cs b/src/SquidStd.Generators/Config/ConfigSectionSourceBuilder.cs
index d145ddd8..75db280b 100644
--- a/src/SquidStd.Generators/Config/ConfigSectionSourceBuilder.cs
+++ b/src/SquidStd.Generators/Config/ConfigSectionSourceBuilder.cs
@@ -43,7 +43,5 @@ public static string Build(IReadOnlyList can
}
private static string FormatStringLiteral(string value)
- {
- return "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
- }
+ => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
}
diff --git a/src/SquidStd.Generators/Events/EventListenerRegistrationGenerator.cs b/src/SquidStd.Generators/Events/EventListenerRegistrationGenerator.cs
index 3556912a..df4b7844 100644
--- a/src/SquidStd.Generators/Events/EventListenerRegistrationGenerator.cs
+++ b/src/SquidStd.Generators/Events/EventListenerRegistrationGenerator.cs
@@ -51,6 +51,7 @@ CancellationToken cancellationToken
for (var i = 0; i < listenerType.AllInterfaces.Length; i++)
{
var interfaceType = listenerType.AllInterfaces[i];
+
if (!IsEventListenerInterface(interfaceType))
{
continue;
@@ -61,12 +62,12 @@ CancellationToken cancellationToken
continue;
}
- var isSupported = !listenerType.IsGenericType
- && IsAccessibleFromGeneratedSource(listenerType)
- && IsAccessibleFromGeneratedSource(eventType);
+ var isSupported = !listenerType.IsGenericType &&
+ IsAccessibleFromGeneratedSource(listenerType) &&
+ IsAccessibleFromGeneratedSource(eventType);
candidates.Add(
- new EventListenerCandidate(
+ new(
eventType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
listenerType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
listenerType.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat),
@@ -83,8 +84,8 @@ private static bool IsEventListenerInterface(INamedTypeSymbol interfaceType)
{
var originalDefinition = interfaceType.OriginalDefinition;
- return originalDefinition.MetadataName == EventListenerMetadataName
- && originalDefinition.ContainingNamespace.ToDisplayString() == EventListenerNamespace;
+ return originalDefinition.MetadataName == EventListenerMetadataName &&
+ originalDefinition.ContainingNamespace.ToDisplayString() == EventListenerNamespace;
}
private static bool IsAccessibleFromGeneratedSource(INamedTypeSymbol type)
@@ -134,6 +135,7 @@ ImmutableArray> candidateGroups
}
var key = candidate.EventTypeName + "|" + candidate.ListenerTypeName;
+
if (seenKeys.Add(key))
{
candidates.Add(candidate);
@@ -141,7 +143,8 @@ ImmutableArray> candidateGroups
}
}
- candidates.Sort(static (left, right) => string.Compare(
+ candidates.Sort(
+ static (left, right) => string.Compare(
left.ListenerTypeName,
right.ListenerTypeName,
StringComparison.Ordinal
diff --git a/src/SquidStd.Generators/README.md b/src/SquidStd.Generators/README.md
index 405eb948..4cf86aa9 100644
--- a/src/SquidStd.Generators/README.md
+++ b/src/SquidStd.Generators/README.md
@@ -10,7 +10,8 @@ dotnet add package SquidStd.Generators
## Usage
-The event listener generator discovers concrete `IEventListener` implementations marked with `[RegisterEventListener]` and generates a DryIoc registration extension:
+The event listener generator discovers concrete `IEventListener` implementations marked with
+`[RegisterEventListener]` and generates a DryIoc registration extension:
```csharp
using SquidStd.Abstractions.Attributes;
@@ -26,22 +27,27 @@ public sealed class PingListener : IEventListener
container.RegisterGeneratedEventListeners();
```
-The generated method reuses the normal `RegisterEventListener()` runtime path, so listener activation stays compatible with `SquidStd.Services.Core`. Each registration family has its own marker attribute and generated extension method, all calling the same runtime APIs as manual registration (`RegisterStdService`, `RegisterConfigSection`, `AddJobHandler`, `RegisterScriptModule`).
+The generated method reuses the normal `RegisterEventListener()` runtime path, so listener activation stays
+compatible with `SquidStd.Services.Core`. Each registration family has its own marker attribute and generated extension
+method, all calling the same runtime APIs as manual registration (`RegisterStdService`, `RegisterConfigSection`,
+`AddJobHandler`, `RegisterScriptModule`).
## Key types
-| Marker attribute | Generated method |
-|------------------|------------------|
-| `[RegisterEventListener]` | `RegisterGeneratedEventListeners()` |
-| `[RegisterStdService(typeof(IMyService), Priority = 10)]` | `RegisterGeneratedStdServices()` |
-| `[RegisterConfigSection("workers", Priority = -50)]` | `RegisterGeneratedConfigSections()` |
-| `[RegisterJobHandler]` | `RegisterGeneratedJobHandlers()` |
-| `[RegisterScriptModule]` with `[ScriptModule("name")]` | `RegisterGeneratedScriptModules()` |
+| Marker attribute | Generated method |
+|-----------------------------------------------------------|-------------------------------------|
+| `[RegisterEventListener]` | `RegisterGeneratedEventListeners()` |
+| `[RegisterStdService(typeof(IMyService), Priority = 10)]` | `RegisterGeneratedStdServices()` |
+| `[RegisterConfigSection("workers", Priority = -50)]` | `RegisterGeneratedConfigSections()` |
+| `[RegisterJobHandler]` | `RegisterGeneratedJobHandlers()` |
+| `[RegisterScriptModule]` with `[ScriptModule("name")]` | `RegisterGeneratedScriptModules()` |
## Related
-- Tutorial: [Source generators: event listeners](https://tgiachi.github.io/squid-std/tutorials/source-generators-event-listeners.html)
-- Tutorial: [Source generators: registration](https://tgiachi.github.io/squid-std/tutorials/source-generators-registration.html)
+-
+Tutorial: [Source generators: event listeners](https://tgiachi.github.io/squid-std/tutorials/source-generators-event-listeners.html)
+-
+Tutorial: [Source generators: registration](https://tgiachi.github.io/squid-std/tutorials/source-generators-registration.html)
## License
diff --git a/src/SquidStd.Generators/Scripting/Lua/ScriptModuleRegistrationGenerator.cs b/src/SquidStd.Generators/Scripting/Lua/ScriptModuleRegistrationGenerator.cs
index 5a4a0427..cafde2d0 100644
--- a/src/SquidStd.Generators/Scripting/Lua/ScriptModuleRegistrationGenerator.cs
+++ b/src/SquidStd.Generators/Scripting/Lua/ScriptModuleRegistrationGenerator.cs
@@ -33,11 +33,11 @@ CancellationToken cancellationToken
cancellationToken.ThrowIfCancellationRequested();
var scriptModuleType = (INamedTypeSymbol)context.TargetSymbol;
- var isSupported = GeneratorSymbolHelpers.IsConcreteNonGenericClass(scriptModuleType)
- && GeneratorSymbolHelpers.IsAccessibleFromGeneratedSource(scriptModuleType)
- && HasScriptModuleAttribute(scriptModuleType);
+ var isSupported = GeneratorSymbolHelpers.IsConcreteNonGenericClass(scriptModuleType) &&
+ GeneratorSymbolHelpers.IsAccessibleFromGeneratedSource(scriptModuleType) &&
+ HasScriptModuleAttribute(scriptModuleType);
- return new ScriptModuleRegistrationCandidate(
+ return new(
GeneratorSymbolHelpers.FullyQualified(scriptModuleType),
GeneratorSymbolHelpers.DisplayName(scriptModuleType),
GeneratorSymbolHelpers.PrimaryLocation(scriptModuleType),
@@ -46,18 +46,17 @@ CancellationToken cancellationToken
}
private static bool HasScriptModuleAttribute(INamedTypeSymbol type)
- {
- return type.GetAttributes()
- .Any(attribute =>
- {
- var attributeClass = attribute.AttributeClass;
+ => type.GetAttributes()
+ .Any(
+ attribute =>
+ {
+ var attributeClass = attribute.AttributeClass;
- return attributeClass is not null
- && attributeClass.MetadataName == ScriptModuleAttributeMetadataName
- && attributeClass.ContainingNamespace.ToDisplayString() == ScriptModuleAttributeNamespace;
- }
- );
- }
+ return attributeClass is not null &&
+ attributeClass.MetadataName == ScriptModuleAttributeMetadataName &&
+ attributeClass.ContainingNamespace.ToDisplayString() == ScriptModuleAttributeNamespace;
+ }
+ );
private static void Execute(
SourceProductionContext context,
@@ -88,7 +87,8 @@ ImmutableArray candidates
}
}
- supported.Sort(static (left, right) => string.Compare(
+ supported.Sort(
+ static (left, right) => string.Compare(
left.ScriptModuleTypeName,
right.ScriptModuleTypeName,
StringComparison.Ordinal
diff --git a/src/SquidStd.Generators/Services/StdServiceRegistrationGenerator.cs b/src/SquidStd.Generators/Services/StdServiceRegistrationGenerator.cs
index 2fd7aae3..890ed61c 100644
--- a/src/SquidStd.Generators/Services/StdServiceRegistrationGenerator.cs
+++ b/src/SquidStd.Generators/Services/StdServiceRegistrationGenerator.cs
@@ -35,13 +35,13 @@ CancellationToken cancellationToken
var serviceType = GetServiceType(attribute);
var priority = GetIntNamedArgument(attribute, "Priority");
- var isSupported = serviceType is not null
- && GeneratorSymbolHelpers.IsConcreteNonGenericClass(implementationType)
- && GeneratorSymbolHelpers.IsAccessibleFromGeneratedSource(implementationType)
- && GeneratorSymbolHelpers.IsAccessibleFromGeneratedSource(serviceType)
- && GeneratorSymbolHelpers.IsAssignableTo(implementationType, serviceType);
+ var isSupported = serviceType is not null &&
+ GeneratorSymbolHelpers.IsConcreteNonGenericClass(implementationType) &&
+ GeneratorSymbolHelpers.IsAccessibleFromGeneratedSource(implementationType) &&
+ GeneratorSymbolHelpers.IsAccessibleFromGeneratedSource(serviceType) &&
+ GeneratorSymbolHelpers.IsAssignableTo(implementationType, serviceType);
- return new StdServiceRegistrationCandidate(
+ return new(
serviceType is null ? string.Empty : GeneratorSymbolHelpers.FullyQualified(serviceType),
GeneratorSymbolHelpers.FullyQualified(implementationType),
GeneratorSymbolHelpers.DisplayName(implementationType),
@@ -95,13 +95,15 @@ private static void Execute(SourceProductionContext context, ImmutableArray string.Compare(
+ supported.Sort(
+ static (left, right) => string.Compare(
left.ImplementationTypeName,
right.ImplementationTypeName,
StringComparison.Ordinal
diff --git a/src/SquidStd.Generators/SquidStd.Generators.csproj b/src/SquidStd.Generators/SquidStd.Generators.csproj
index e931f201..f9d941dc 100644
--- a/src/SquidStd.Generators/SquidStd.Generators.csproj
+++ b/src/SquidStd.Generators/SquidStd.Generators.csproj
@@ -14,8 +14,8 @@
-
-
+
+
diff --git a/src/SquidStd.Generators/Workers/JobHandlerRegistrationGenerator.cs b/src/SquidStd.Generators/Workers/JobHandlerRegistrationGenerator.cs
index 59ccd643..d3c01708 100644
--- a/src/SquidStd.Generators/Workers/JobHandlerRegistrationGenerator.cs
+++ b/src/SquidStd.Generators/Workers/JobHandlerRegistrationGenerator.cs
@@ -31,15 +31,15 @@ CancellationToken cancellationToken
cancellationToken.ThrowIfCancellationRequested();
var handlerType = (INamedTypeSymbol)context.TargetSymbol;
- var isSupported = GeneratorSymbolHelpers.IsConcreteNonGenericClass(handlerType)
- && GeneratorSymbolHelpers.IsAccessibleFromGeneratedSource(handlerType)
- && GeneratorSymbolHelpers.ImplementsInterface(
+ var isSupported = GeneratorSymbolHelpers.IsConcreteNonGenericClass(handlerType) &&
+ GeneratorSymbolHelpers.IsAccessibleFromGeneratedSource(handlerType) &&
+ GeneratorSymbolHelpers.ImplementsInterface(
handlerType,
"IJobHandler",
"SquidStd.Workers.Interfaces"
);
- return new JobHandlerRegistrationCandidate(
+ return new(
GeneratorSymbolHelpers.FullyQualified(handlerType),
GeneratorSymbolHelpers.DisplayName(handlerType),
GeneratorSymbolHelpers.PrimaryLocation(handlerType),
@@ -76,7 +76,8 @@ ImmutableArray candidates
}
}
- supported.Sort(static (left, right) => string.Compare(
+ supported.Sort(
+ static (left, right) => string.Compare(
left.HandlerTypeName,
right.HandlerTypeName,
StringComparison.Ordinal
diff --git a/src/SquidStd.Mail.Abstractions/Exceptions/MailSendException.cs b/src/SquidStd.Mail.Abstractions/Exceptions/MailSendException.cs
index b7b4c6e7..d640d699 100644
--- a/src/SquidStd.Mail.Abstractions/Exceptions/MailSendException.cs
+++ b/src/SquidStd.Mail.Abstractions/Exceptions/MailSendException.cs
@@ -5,7 +5,5 @@ public sealed class MailSendException : Exception
{
/// Initializes the exception with a message and the underlying cause.
public MailSendException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
+ : base(message, innerException) { }
}
diff --git a/src/SquidStd.Mail.Abstractions/Interfaces/IMailReader.cs b/src/SquidStd.Mail.Abstractions/Interfaces/IMailReader.cs
index 4ba210f8..3038bfb5 100644
--- a/src/SquidStd.Mail.Abstractions/Interfaces/IMailReader.cs
+++ b/src/SquidStd.Mail.Abstractions/Interfaces/IMailReader.cs
@@ -6,8 +6,8 @@ namespace SquidStd.Mail.Abstractions.Interfaces;
public interface IMailReader
{
///
- /// Connects, fetches the new (unseen) messages, marks them seen / deletes them per options, disconnects,
- /// and returns the parsed messages.
+ /// Connects, fetches the new (unseen) messages, marks them seen / deletes them per options, disconnects,
+ /// and returns the parsed messages.
///
Task> FetchNewAsync(CancellationToken cancellationToken = default);
}
diff --git a/src/SquidStd.Mail.MailKit/Extensions/MailRegistrationExtensions.cs b/src/SquidStd.Mail.MailKit/Extensions/MailRegistrationExtensions.cs
index 7faf1e79..9189363f 100644
--- a/src/SquidStd.Mail.MailKit/Extensions/MailRegistrationExtensions.cs
+++ b/src/SquidStd.Mail.MailKit/Extensions/MailRegistrationExtensions.cs
@@ -16,8 +16,8 @@ public static class MailRegistrationExtensions
extension(IContainer container)
{
///