diff --git a/src/Nexus.UI/Charts/Chart.razor.cs b/src/Nexus.UI/Charts/Chart.razor.cs index 0e9d358d..1f6e80dc 100644 --- a/src/Nexus.UI/Charts/Chart.razor.cs +++ b/src/Nexus.UI/Charts/Chart.razor.cs @@ -54,8 +54,8 @@ public Chart() { _dotNetHelper = DotNetObjectReference.Create(this); - _timeAxisConfigs = new[] - { + _timeAxisConfigs = + [ /* nanoseconds */ new TimeAxisConfig(TimeSpan.FromSeconds(100e-9), ".fffffff", TriggerPeriod.Second, "HH:mm.ss", "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss.fffffff"), @@ -101,11 +101,11 @@ public Chart() /* years */ new TimeAxisConfig(TimeSpan.FromDays(365), "yyyy", TriggerPeriod.Year, default, default, "yyyy-MM-dd"), - }; + ]; _timeAxisConfig = _timeAxisConfigs.First(); - _colors = new[] { + _colors = [ new SKColor(0, 114, 189), new SKColor(217, 83, 25), new SKColor(237, 177, 32), @@ -113,7 +113,7 @@ public Chart() new SKColor(119, 172, 48), new SKColor(77, 190, 238), new SKColor(162, 20, 47) - }; + ]; } [Inject] diff --git a/src/Nexus.UI/Core/AppState.cs b/src/Nexus.UI/Core/AppState.cs index 11f26866..945c98b7 100644 --- a/src/Nexus.UI/Core/AppState.cs +++ b/src/Nexus.UI/Core/AppState.cs @@ -17,8 +17,8 @@ public class AppState : INotifyPropertyChanged private ViewState _viewState = ViewState.Normal; private ExportParameters _exportParameters = default!; private readonly INexusClient _client; - private readonly List<(DateTime, Exception)> _errors = new(); - private readonly Dictionary> _editModeCatalogMap = new(); + private readonly List<(DateTime, Exception)> _errors = []; + private readonly Dictionary> _editModeCatalogMap = []; private bool _beginAtZero; private string? _searchString; private const string GROUP_KEY = "groups"; @@ -176,7 +176,7 @@ public string? SearchString } } - public ObservableCollection Jobs { get; set; } = new ObservableCollection(); + public ObservableCollection Jobs { get; set; } = []; public void AddJob(JobViewModel job) { @@ -232,7 +232,7 @@ public void AddError(Exception error, ISnackbar? snackbar) public void AddEditModeCatalog(string catalogId) { - _editModeCatalogMap.Add(catalogId, new Dictionary()); + _editModeCatalogMap.Add(catalogId, []); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(EditModeCatalogMap))); } @@ -258,7 +258,7 @@ public async Task SaveAndRemoveEditModeCatalogAsync(string catalogId, ISnackbar resources = resourcesNode.AsArray(); else - resources = new JsonArray(); + resources = []; overrides["Resources"] = resources; @@ -283,7 +283,7 @@ public async Task SaveAndRemoveEditModeCatalogAsync(string catalogId, ISnackbar properties = propertiesNode.AsObject(); else - properties = new JsonObject(); + properties = []; resource["Properties"] = properties; @@ -351,7 +351,7 @@ public async Task SaveAndRemoveEditModeCatalogAsync(string catalogId, ISnackbar if (!success) { - group = new List(); + group = []; catalogItemsMap[groupName] = group; } diff --git a/src/Nexus.UI/Core/NexusDemoClient.cs b/src/Nexus.UI/Core/NexusDemoClient.cs index a58f72c2..9faf40b7 100644 --- a/src/Nexus.UI/Core/NexusDemoClient.cs +++ b/src/Nexus.UI/Core/NexusDemoClient.cs @@ -72,7 +72,7 @@ public Task GetAsync(string catalogId, CancellationToken cancel var resource1 = new Resource( Id: "temperature", Properties: properties1, - Representations: new List() { new Representation(NexusDataType.FLOAT64, TimeSpan.FromMinutes(1), default) } + Representations: new List() { new(NexusDataType.FLOAT64, TimeSpan.FromMinutes(1), default) } ); var properties2 = new Dictionary() @@ -85,7 +85,7 @@ public Task GetAsync(string catalogId, CancellationToken cancel var resource2 = new Resource( Id: "wind_speed", Properties: properties2, - Representations: new List() { new Representation(NexusDataType.FLOAT64, TimeSpan.FromMinutes(1), default) } + Representations: new List() { new(NexusDataType.FLOAT64, TimeSpan.FromMinutes(1), default) } ); var resources = new List() { resource1, resource2 }; @@ -188,12 +188,12 @@ We hope you enjoy it! PackageReferenceId: Guid.NewGuid() ); - return Task.FromResult((IReadOnlyList)new List() { catalogInfo }); + return Task.FromResult((IReadOnlyList)[catalogInfo]); } else { - return Task.FromResult((IReadOnlyList)new List() { }); + return Task.FromResult((IReadOnlyList)[]); } } @@ -539,6 +539,6 @@ public Task> GetDescriptionsAsync(Cancellati AdditionalInformation: additionalInformation ); - return Task.FromResult((IReadOnlyList)new List() { description }); + return Task.FromResult((IReadOnlyList)[description]); } } \ No newline at end of file diff --git a/src/Nexus.UI/Core/Utilities.cs b/src/Nexus.UI/Core/Utilities.cs index 52a1d7e7..5fccc74e 100644 --- a/src/Nexus.UI/Core/Utilities.cs +++ b/src/Nexus.UI/Core/Utilities.cs @@ -16,7 +16,7 @@ public record ResourcePathParseResult( TimeSpan? BasePeriod ); -public static class Utilities +public static partial class Utilities { public static string ToSpaceFilledCatalogId(string catalogId) => catalogId.TrimStart('/').Replace("/", " / "); @@ -26,11 +26,11 @@ public static string EscapeDataString(string catalogId) // keep in sync with DataModelExtensions ... private const int NS_PER_TICK = 100; - private static readonly long[] _nanoseconds = new[] { (long)1e0, (long)1e3, (long)1e6, (long)1e9, (long)60e9, (long)3600e9, (long)86400e9 }; - private static readonly int[] _quotients = new[] { 1000, 1000, 1000, 60, 60, 24, 1 }; - private static readonly string[] _postFixes = new[] { "ns", "us", "ms", "s", "min", "h", "d" }; + private static readonly long[] _nanoseconds = [(long)1e0, (long)1e3, (long)1e6, (long)1e9, (long)60e9, (long)3600e9, (long)86400e9]; + private static readonly int[] _quotients = [1000, 1000, 1000, 60, 60, 24, 1]; + private static readonly string[] _postFixes = ["ns", "us", "ms", "s", "min", "h", "d"]; // ... except this line - private static readonly Regex _unitStringEvaluator = new(@"^\s*([0-9]+)[\s_]*([a-zA-Z]+)\s*$", RegexOptions.Compiled); + private static readonly Regex _unitStringEvaluator = UnitStringEvaluator(); public static string ToUnitString(this TimeSpan samplePeriod, bool withUnderScore = false) { @@ -155,7 +155,7 @@ public static void ParseResourcePath( var matches = _matchSingleParametersExpression .Matches(parseResult.Parameters); - if (matches.Any()) + if (matches.Count != 0) { parameters = new ReadOnlyDictionary(matches .Select(match => (match.Groups[1].Value, match.Groups[2].Value)) @@ -331,4 +331,7 @@ private static JsonElement GetJsonObjectFromPath(this JsonElement root, Span value / 4.0).ToArray()), - new LineSeries( + new( "Temperature", "°C", TimeSpan.FromSeconds(1), Enumerable.Range(0, 60).Select(value => random.NextDouble() * 10 - 5).ToArray()), - new LineSeries( + new( "Pressure", "mbar", TimeSpan.FromSeconds(1), diff --git a/src/Nexus.UI/Services/NexusAuthenticationStateProvider.cs b/src/Nexus.UI/Services/NexusAuthenticationStateProvider.cs index 07f2753e..28e5188d 100644 --- a/src/Nexus.UI/Services/NexusAuthenticationStateProvider.cs +++ b/src/Nexus.UI/Services/NexusAuthenticationStateProvider.cs @@ -4,14 +4,9 @@ namespace Nexus.UI.Services; -public class NexusAuthenticationStateProvider : AuthenticationStateProvider +public class NexusAuthenticationStateProvider(INexusClient client) : AuthenticationStateProvider { - private readonly INexusClient _client; - - public NexusAuthenticationStateProvider(INexusClient client) - { - _client = client; - } + private readonly INexusClient _client = client; public override async Task GetAuthenticationStateAsync() { @@ -26,7 +21,7 @@ public override async Task GetAuthenticationStateAsync() var claims = new List { - new Claim(NAME_CLAIM, meResponse.User.Name) + new(NAME_CLAIM, meResponse.User.Name) }; if (meResponse.IsAdmin) diff --git a/src/Nexus.UI/Services/TypeFaceService.cs b/src/Nexus.UI/Services/TypeFaceService.cs index 9144d19d..a625af5c 100644 --- a/src/Nexus.UI/Services/TypeFaceService.cs +++ b/src/Nexus.UI/Services/TypeFaceService.cs @@ -8,12 +8,12 @@ namespace Nexus.UI.Services; public class TypeFaceService { - private readonly Dictionary _typeFaces = new(); + private readonly Dictionary _typeFaces = []; public SKTypeface GetTTF(string ttfName) { - if (_typeFaces.ContainsKey(ttfName)) - return _typeFaces[ttfName]; + if (_typeFaces.TryGetValue(ttfName, out var value)) + return value; else if (LoadTypeFace(ttfName)) return _typeFaces[ttfName]; diff --git a/src/Nexus.UI/ViewModels/CatalogItemSelectionViewModel.cs b/src/Nexus.UI/ViewModels/CatalogItemSelectionViewModel.cs index 81f6d86f..2f96b370 100644 --- a/src/Nexus.UI/ViewModels/CatalogItemSelectionViewModel.cs +++ b/src/Nexus.UI/ViewModels/CatalogItemSelectionViewModel.cs @@ -2,19 +2,13 @@ namespace Nexus.UI.ViewModels; -public class CatalogItemSelectionViewModel +public class CatalogItemSelectionViewModel( + CatalogItemViewModel baseItem, + IDictionary? parameters) { - public CatalogItemSelectionViewModel( - CatalogItemViewModel baseItem, - IDictionary? parameters) - { - BaseItem = baseItem; - Parameters = parameters; - } - - public CatalogItemViewModel BaseItem { get; } - public IDictionary? Parameters { get; } - public List Kinds { get; } = new List(); + public CatalogItemViewModel BaseItem { get; } = baseItem; + public IDictionary? Parameters { get; } = parameters; + public List Kinds { get; } = []; public string GetResourcePath(RepresentationKind kind, TimeSpan samplePeriod) { diff --git a/src/Nexus.UI/ViewModels/SettingsViewModel.cs b/src/Nexus.UI/ViewModels/SettingsViewModel.cs index db3a4056..353f6916 100644 --- a/src/Nexus.UI/ViewModels/SettingsViewModel.cs +++ b/src/Nexus.UI/ViewModels/SettingsViewModel.cs @@ -14,7 +14,7 @@ public class SettingsViewModel : INotifyPropertyChanged private readonly AppState _appState; private readonly INexusClient _client; private readonly IJSInProcessRuntime _jsRuntime; - private List _selectedCatalogItems = new(); + private List _selectedCatalogItems = []; public SettingsViewModel(AppState appState, IJSInProcessRuntime jsRuntime, INexusClient client) { @@ -209,7 +209,7 @@ public void ToggleCatalogItemSelection(CatalogItemSelectionViewModel selection) if (reference is null) { - if (CanModifySamplePeriod && !_selectedCatalogItems.Any()) + if (CanModifySamplePeriod && _selectedCatalogItems.Count == 0) SamplePeriod = new Period(selection.BaseItem.Representation.SamplePeriod); EnsureDefaultRepresentationKind(selection); @@ -244,7 +244,7 @@ private void EnsureDefaultRepresentationKind(CatalogItemSelectionViewModel selec var baseItem = selectedItem.BaseItem; var baseSamplePeriod = baseItem.Representation.SamplePeriod; - if (!selectedItem.Kinds.Any()) + if (selectedItem.Kinds.Count == 0) { if (SamplePeriod.Value < baseSamplePeriod) selectedItem.Kinds.Add(RepresentationKind.Resampled); @@ -268,7 +268,7 @@ private async Task InitializeAsync() .Where(description => description.AdditionalInformation.GetStringValue(Constants.DATA_WRITER_LABEL_KEY) is not null) .ToList(); - if (writerDescriptions.Any()) + if (writerDescriptions.Count != 0) { string? actualFileType = default; diff --git a/src/Nexus/API/ArtifactsController.cs b/src/Nexus/API/ArtifactsController.cs index e04aea59..447f9a3c 100644 --- a/src/Nexus/API/ArtifactsController.cs +++ b/src/Nexus/API/ArtifactsController.cs @@ -11,17 +11,12 @@ namespace Nexus.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] -internal class ArtifactsController : ControllerBase +internal class ArtifactsController( + IDatabaseService databaseService) : ControllerBase { // GET /api/artifacts/{artifactId} - public IDatabaseService _databaseService; - - public ArtifactsController( - IDatabaseService databaseService) - { - _databaseService = databaseService; - } + public IDatabaseService _databaseService = databaseService; /// /// Gets the specified artifact. diff --git a/src/Nexus/API/CatalogsController.cs b/src/Nexus/API/CatalogsController.cs index 8e50f36c..c1e24c4b 100644 --- a/src/Nexus/API/CatalogsController.cs +++ b/src/Nexus/API/CatalogsController.cs @@ -22,7 +22,10 @@ namespace Nexus.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] -internal class CatalogsController : ControllerBase +internal class CatalogsController( + AppState appState, + IDatabaseService databaseService, + IDataControllerService dataControllerService) : ControllerBase { // POST /api/catalogs/search-items // GET /api/catalogs/{catalogId} @@ -38,19 +41,9 @@ internal class CatalogsController : ControllerBase // GET /api/catalogs/{catalogId}/metadata // PUT /api/catalogs/{catalogId}/metadata - private readonly AppState _appState; - private readonly IDatabaseService _databaseService; - private readonly IDataControllerService _dataControllerService; - - public CatalogsController( - AppState appState, - IDatabaseService databaseService, - IDataControllerService dataControllerService) - { - _appState = appState; - _databaseService = databaseService; - _dataControllerService = dataControllerService; - } + private readonly AppState _appState = appState; + private readonly IDatabaseService _databaseService = databaseService; + private readonly IDataControllerService _dataControllerService = dataControllerService; /// /// Searches for the given resource paths and returns the corresponding catalog items. diff --git a/src/Nexus/API/DataController.cs b/src/Nexus/API/DataController.cs index 23b4969e..1ce32ff7 100644 --- a/src/Nexus/API/DataController.cs +++ b/src/Nexus/API/DataController.cs @@ -14,17 +14,12 @@ namespace Nexus.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] -internal class DataController : ControllerBase +internal class DataController( + IDataService dataService) : ControllerBase { // GET /api/data - private readonly IDataService _dataService; - - public DataController( - IDataService dataService) - { - _dataService = dataService; - } + private readonly IDataService _dataService = dataService; /// /// Gets the requested data. diff --git a/src/Nexus/API/JobsController.cs b/src/Nexus/API/JobsController.cs index 99e09471..3280452f 100644 --- a/src/Nexus/API/JobsController.cs +++ b/src/Nexus/API/JobsController.cs @@ -15,7 +15,12 @@ namespace Nexus.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] -internal class JobsController : ControllerBase +internal class JobsController( + AppStateManager appStateManager, + IJobService jobService, + IServiceProvider serviceProvider, + Serilog.IDiagnosticContext diagnosticContext, + ILogger logger) : ControllerBase { // GET /jobs // DELETE /jobs{jobId} @@ -24,25 +29,11 @@ internal class JobsController : ControllerBase // POST /jobs/load-packages // POST /jobs/clear-cache - private readonly AppStateManager _appStateManager; - private readonly ILogger _logger; - private readonly IServiceProvider _serviceProvider; - private readonly Serilog.IDiagnosticContext _diagnosticContext; - private readonly IJobService _jobService; - - public JobsController( - AppStateManager appStateManager, - IJobService jobService, - IServiceProvider serviceProvider, - Serilog.IDiagnosticContext diagnosticContext, - ILogger logger) - { - _appStateManager = appStateManager; - _jobService = jobService; - _serviceProvider = serviceProvider; - _diagnosticContext = diagnosticContext; - _logger = logger; - } + private readonly AppStateManager _appStateManager = appStateManager; + private readonly ILogger _logger = logger; + private readonly IServiceProvider _serviceProvider = serviceProvider; + private readonly Serilog.IDiagnosticContext _diagnosticContext = diagnosticContext; + private readonly IJobService _jobService = jobService; #region Jobs Management @@ -54,11 +45,7 @@ public JobsController( public ActionResult> GetJobs() { var isAdmin = User.IsInRole(NexusRoles.ADMINISTRATOR); - var username = User.Identity?.Name; - - if (username is null) - throw new Exception("This should never happen."); - + var username = (User.Identity?.Name) ?? throw new Exception("This should never happen."); var result = _jobService .GetJobs() .Select(jobControl => jobControl.Job) @@ -79,11 +66,7 @@ public ActionResult CancelJob(Guid jobId) if (_jobService.TryGetJob(jobId, out var jobControl)) { var isAdmin = User.IsInRole(NexusRoles.ADMINISTRATOR); - var username = User.Identity?.Name; - - if (username is null) - throw new Exception("This should never happen."); - + var username = (User.Identity?.Name) ?? throw new Exception("This should never happen."); if (jobControl.Job.Owner == username || isAdmin) { jobControl.CancellationTokenSource.Cancel(); @@ -113,11 +96,7 @@ public async Task> GetJobStatusAsync(Guid jobId) if (_jobService.TryGetJob(jobId, out var jobControl)) { var isAdmin = User.IsInRole(NexusRoles.ADMINISTRATOR); - var username = User.Identity?.Name; - - if (username is null) - throw new Exception("This should never happen."); - + var username = (User.Identity?.Name) ?? throw new Exception("This should never happen."); if (jobControl.Job.Owner == username || isAdmin) { var status = new JobStatus( @@ -180,11 +159,7 @@ public async Task> ExportAsync( { catalogItemRequests = await Task.WhenAll(parameters.ResourcePaths.Select(async resourcePath => { - var catalogItemRequest = await root.TryFindAsync(resourcePath, cancellationToken); - - if (catalogItemRequest is null) - throw new ValidationException($"Could not find resource path {resourcePath}."); - + var catalogItemRequest = await root.TryFindAsync(resourcePath, cancellationToken) ?? throw new ValidationException($"Could not find resource path {resourcePath}."); return catalogItemRequest; })); } diff --git a/src/Nexus/API/PackageReferencesController.cs b/src/Nexus/API/PackageReferencesController.cs index 022d801e..7fa458ac 100644 --- a/src/Nexus/API/PackageReferencesController.cs +++ b/src/Nexus/API/PackageReferencesController.cs @@ -12,26 +12,19 @@ namespace Nexus.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] -internal class PackageReferencesController : ControllerBase +internal class PackageReferencesController( + AppState appState, + AppStateManager appStateManager, + IExtensionHive extensionHive) : ControllerBase { // GET /api/packagereferences // POST /api/packagereferences // DELETE /api/packagereferences/{packageReferenceId} // GET /api/packagereferences/{packageReferenceId}/versions - private readonly AppState _appState; - private readonly AppStateManager _appStateManager; - private readonly IExtensionHive _extensionHive; - - public PackageReferencesController( - AppState appState, - AppStateManager appStateManager, - IExtensionHive extensionHive) - { - _appState = appState; - _appStateManager = appStateManager; - _extensionHive = extensionHive; - } + private readonly AppState _appState = appState; + private readonly AppStateManager _appStateManager = appStateManager; + private readonly IExtensionHive _extensionHive = extensionHive; /// /// Gets the list of package references. diff --git a/src/Nexus/API/SourcesController.cs b/src/Nexus/API/SourcesController.cs index 9f3954ec..5ccd9ff5 100644 --- a/src/Nexus/API/SourcesController.cs +++ b/src/Nexus/API/SourcesController.cs @@ -17,26 +17,19 @@ namespace Nexus.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] -internal class SourcesController : ControllerBase +internal class SourcesController( + AppState appState, + AppStateManager appStateManager, + IExtensionHive extensionHive) : ControllerBase { // GET /api/sources/descriptions // GET /api/sources/registrations // POST /api/sources/registrations // DELETE /api/sources/registrations/{registrationId} - private readonly AppState _appState; - private readonly AppStateManager _appStateManager; - private readonly IExtensionHive _extensionHive; - - public SourcesController( - AppState appState, - AppStateManager appStateManager, - IExtensionHive extensionHive) - { - _appState = appState; - _appStateManager = appStateManager; - _extensionHive = extensionHive; - } + private readonly AppState _appState = appState; + private readonly AppStateManager _appStateManager = appStateManager; + private readonly IExtensionHive _extensionHive = extensionHive; /// /// Gets the list of source descriptions. diff --git a/src/Nexus/API/SystemController.cs b/src/Nexus/API/SystemController.cs index 064f37a7..151f3872 100644 --- a/src/Nexus/API/SystemController.cs +++ b/src/Nexus/API/SystemController.cs @@ -14,7 +14,10 @@ namespace Nexus.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] -internal class SystemController : ControllerBase +internal class SystemController( + AppState appState, + AppStateManager appStateManager, + IOptions generalOptions) : ControllerBase { // [authenticated] // GET /api/system/configuration @@ -24,19 +27,9 @@ internal class SystemController : ControllerBase // [privileged] // PUT /api/system/configuration - private readonly AppState _appState; - private readonly AppStateManager _appStateManager; - private readonly GeneralOptions _generalOptions; - - public SystemController( - AppState appState, - AppStateManager appStateManager, - IOptions generalOptions) - { - _generalOptions = generalOptions.Value; - _appState = appState; - _appStateManager = appStateManager; - } + private readonly AppState _appState = appState; + private readonly AppStateManager _appStateManager = appStateManager; + private readonly GeneralOptions _generalOptions = generalOptions.Value; /// /// Gets the default file type. diff --git a/src/Nexus/API/UsersController.cs b/src/Nexus/API/UsersController.cs index 12b39cea..d27df9e9 100644 --- a/src/Nexus/API/UsersController.cs +++ b/src/Nexus/API/UsersController.cs @@ -22,7 +22,11 @@ namespace Nexus.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] -internal class UsersController : ControllerBase +internal class UsersController( + IDBService dBService, + ITokenService tokenService, + IOptions securityOptions, + ILogger logger) : ControllerBase { // [anonymous] // GET /api/users/authenticate @@ -46,22 +50,10 @@ internal class UsersController : ControllerBase // GET /api/users/{userId}/tokens - private readonly IDBService _dbService; - private readonly ITokenService _tokenService; - private readonly SecurityOptions _securityOptions; - private readonly ILogger _logger; - - public UsersController( - IDBService dBService, - ITokenService tokenService, - IOptions securityOptions, - ILogger logger) - { - _dbService = dBService; - _tokenService = tokenService; - _securityOptions = securityOptions.Value; - _logger = logger; - } + private readonly IDBService _dbService = dBService; + private readonly ITokenService _tokenService = tokenService; + private readonly SecurityOptions _securityOptions = securityOptions.Value; + private readonly ILogger _logger = logger; #region Anonymous diff --git a/src/Nexus/API/WritersController.cs b/src/Nexus/API/WritersController.cs index 3c2aeb12..fe4e9dd4 100644 --- a/src/Nexus/API/WritersController.cs +++ b/src/Nexus/API/WritersController.cs @@ -11,17 +11,12 @@ namespace Nexus.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]")] -internal class WritersController : ControllerBase +internal class WritersController( + AppState appState) : ControllerBase { // GET /api/writers/descriptions - private readonly AppState _appState; - - public WritersController( - AppState appState) - { - _appState = appState; - } + private readonly AppState _appState = appState; /// /// Gets the list of writer descriptions. diff --git a/src/Nexus/Core/CatalogContainer.cs b/src/Nexus/Core/CatalogContainer.cs index 1e342805..1b66682a 100644 --- a/src/Nexus/Core/CatalogContainer.cs +++ b/src/Nexus/Core/CatalogContainer.cs @@ -99,11 +99,8 @@ public async Task GetLazyCatalogInfoAsync(CancellationToken can { await EnsureLazyCatalogInfoAsync(cancellationToken); - var lazyCatalogInfo = _lazyCatalogInfo; - - if (lazyCatalogInfo is null) - throw new Exception("this should never happen"); - + var lazyCatalogInfo = _lazyCatalogInfo + ?? throw new Exception("this should never happen"); return lazyCatalogInfo; } finally diff --git a/src/Nexus/Core/CustomExtensions.cs b/src/Nexus/Core/CustomExtensions.cs index 10aef6de..d69fda53 100644 --- a/src/Nexus/Core/CustomExtensions.cs +++ b/src/Nexus/Core/CustomExtensions.cs @@ -33,8 +33,7 @@ internal static class CustomExtensions public static byte[] Hash(this string value) { - var md5 = MD5.Create(); // compute hash is not thread safe! - var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(value)); // + var hash = MD5.HashData(Encoding.UTF8.GetBytes(value)); return hash; } diff --git a/src/Nexus/Core/Models_Public.cs b/src/Nexus/Core/Models_Public.cs index b4c0c887..dbc2a958 100644 --- a/src/Nexus/Core/Models_Public.cs +++ b/src/Nexus/Core/Models_Public.cs @@ -8,35 +8,24 @@ namespace Nexus.Core; /// /// Represents a user. /// -public class NexusUser +public class NexusUser( + string id, + string name) { -#pragma warning disable CS1591 - - public NexusUser( - string id, - string name) - { - Id = id; - Name = name; - - Claims = new(); - } - + /// [JsonIgnore] [ValidateNever] - public string Id { get; set; } = default!; - -#pragma warning restore CS1591 + public string Id { get; set; } = id; /// /// The user name. /// - public string Name { get; set; } = default!; + public string Name { get; set; } = name; #pragma warning disable CS1591 [JsonIgnore] - public List Claims { get; set; } = default!; + public List Claims { get; set; } = []; #pragma warning restore CS1591 @@ -45,32 +34,22 @@ public NexusUser( /// /// Represents a claim. /// -public class NexusClaim +public class NexusClaim(Guid id, string type, string value) { -#pragma warning disable CS1591 - - public NexusClaim(Guid id, string type, string value) - { - Id = id; - Type = type; - Value = value; - } - + /// [JsonIgnore] [ValidateNever] - public Guid Id { get; set; } - -#pragma warning restore CS1591 + public Guid Id { get; set; } = id; /// /// The claim type. /// - public string Type { get; init; } + public string Type { get; init; } = type; /// /// The claim value. /// - public string Value { get; init; } + public string Value { get; init; } = value; #pragma warning disable CS1591 diff --git a/src/Nexus/Core/NexusAuthExtensions.cs b/src/Nexus/Core/NexusAuthExtensions.cs index ec167506..11702a02 100644 --- a/src/Nexus/Core/NexusAuthExtensions.cs +++ b/src/Nexus/Core/NexusAuthExtensions.cs @@ -56,7 +56,7 @@ public static IServiceCollection AddNexusAuth( var providers = securityOptions.OidcProviders.Any() ? securityOptions.OidcProviders - : new List() { DefaultProvider }; + : [DefaultProvider]; foreach (var provider in providers) { @@ -131,11 +131,8 @@ public static IServiceCollection AddNexusAuth( // scopes // https://openid.net/specs/openid-connect-basic-1_0.html#Scopes - var principal = context.Principal; - - if (principal is null) - throw new Exception("The principal is null. This should never happen."); - + var principal = context.Principal + ?? throw new Exception("The principal is null. This should never happen."); var userId = principal.FindFirstValue(Claims.Subject) ?? throw new Exception("The subject claim is missing. This should never happen."); @@ -208,19 +205,15 @@ public static IServiceCollection AddNexusAuth( PersonalAccessTokenAuthenticationDefaults.AuthenticationScheme }; - services.AddAuthorization(options => - { - options.DefaultPolicy = new AuthorizationPolicyBuilder() + services.AddAuthorizationBuilder() + .SetDefaultPolicy(new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .RequireRole(NexusRoles.USER) .AddAuthenticationSchemes(authenticationSchemes) - .Build(); - - options - .AddPolicy(NexusPolicies.RequireAdmin, policy => policy + .Build()) + .AddPolicy(NexusPolicies.RequireAdmin, policy => policy .RequireRole(NexusRoles.ADMINISTRATOR) .AddAuthenticationSchemes(authenticationSchemes)); - }); return services; } diff --git a/src/Nexus/Core/NexusIdentityProviderExtensions.cs b/src/Nexus/Core/NexusIdentityProviderExtensions.cs index 24697d6d..6fe9f017 100644 --- a/src/Nexus/Core/NexusIdentityProviderExtensions.cs +++ b/src/Nexus/Core/NexusIdentityProviderExtensions.cs @@ -182,14 +182,9 @@ public static WebApplication UseNexusIdentityProvider( } } -internal class HostedService : IHostedService +internal class HostedService(IServiceProvider serviceProvider) : IHostedService { - private readonly IServiceProvider _serviceProvider; - - public HostedService(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } + private readonly IServiceProvider _serviceProvider = serviceProvider; public async Task StartAsync(CancellationToken cancellationToken) { diff --git a/src/Nexus/Core/NexusOptions.cs b/src/Nexus/Core/NexusOptions.cs index 8b52aad1..85d9ac21 100644 --- a/src/Nexus/Core/NexusOptions.cs +++ b/src/Nexus/Core/NexusOptions.cs @@ -100,5 +100,5 @@ internal partial record SecurityOptions() : NexusOptionsBase public const string Section = "Security"; public TimeSpan CookieLifetime { get; set; } = TimeSpan.FromDays(30); - public List OidcProviders { get; set; } = new(); + public List OidcProviders { get; set; } = []; } \ No newline at end of file diff --git a/src/Nexus/Core/PersonalAccessTokenAuthenticationHandler.cs b/src/Nexus/Core/PersonalAccessTokenAuthenticationHandler.cs index c68b4e60..900811cc 100644 --- a/src/Nexus/Core/PersonalAccessTokenAuthenticationHandler.cs +++ b/src/Nexus/Core/PersonalAccessTokenAuthenticationHandler.cs @@ -13,22 +13,16 @@ internal static class PersonalAccessTokenAuthenticationDefaults public const string AuthenticationScheme = "pat"; } -internal class PersonalAccessTokenAuthHandler : AuthenticationHandler +internal class PersonalAccessTokenAuthHandler( + ITokenService tokenService, + IDBService dbService, + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder) : AuthenticationHandler(options, logger, encoder) { - private readonly ITokenService _tokenService; + private readonly ITokenService _tokenService = tokenService; - private readonly IDBService _dbService; - - public PersonalAccessTokenAuthHandler( - ITokenService tokenService, - IDBService dbService, - IOptionsMonitor options, - ILoggerFactory logger, - UrlEncoder encoder) : base(options, logger, encoder) - { - _tokenService = tokenService; - _dbService = dbService; - } + private readonly IDBService _dbService = dbService; protected async override Task HandleAuthenticateAsync() { @@ -79,8 +73,7 @@ protected async override Task HandleAuthenticateAsync() nameType: Claims.Name, roleType: Claims.Role); - if (principal is null) - principal = new ClaimsPrincipal(); + principal ??= new ClaimsPrincipal(); principal.AddIdentity(identity); } diff --git a/src/Nexus/Core/UserDbContext.cs b/src/Nexus/Core/UserDbContext.cs index 0c8f1fd3..49d6e6fa 100644 --- a/src/Nexus/Core/UserDbContext.cs +++ b/src/Nexus/Core/UserDbContext.cs @@ -2,14 +2,9 @@ namespace Nexus.Core; -internal class UserDbContext : DbContext +internal class UserDbContext(DbContextOptions options) + : DbContext(options) { - public UserDbContext(DbContextOptions options) - : base(options) - { - // - } - protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder diff --git a/src/Nexus/Extensibility/DataSource/DataSourceController.cs b/src/Nexus/Extensibility/DataSource/DataSourceController.cs index b5c86123..52991946 100644 --- a/src/Nexus/Extensibility/DataSource/DataSourceController.cs +++ b/src/Nexus/Extensibility/DataSource/DataSourceController.cs @@ -53,43 +53,30 @@ Task ReadAsync( CancellationToken cancellationToken); } -internal class DataSourceController : IDataSourceController +internal class DataSourceController( + IDataSource dataSource, + InternalDataSourceRegistration registration, + IReadOnlyDictionary? systemConfiguration, + IReadOnlyDictionary? requestConfiguration, + IProcessingService processingService, + ICacheService cacheService, + DataOptions dataOptions, + ILogger logger) : IDataSourceController { - private readonly IProcessingService _processingService; - private readonly ICacheService _cacheService; - private readonly DataOptions _dataOptions; + private readonly IProcessingService _processingService = processingService; + private readonly ICacheService _cacheService = cacheService; + private readonly DataOptions _dataOptions = dataOptions; private ConcurrentDictionary _catalogCache = default!; - public DataSourceController( - IDataSource dataSource, - InternalDataSourceRegistration registration, - IReadOnlyDictionary? systemConfiguration, - IReadOnlyDictionary? requestConfiguration, - IProcessingService processingService, - ICacheService cacheService, - DataOptions dataOptions, - ILogger logger) - { - DataSource = dataSource; - DataSourceRegistration = registration; - SystemConfiguration = systemConfiguration; - RequestConfiguration = requestConfiguration; - Logger = logger; - - _processingService = processingService; - _cacheService = cacheService; - _dataOptions = dataOptions; - } - - private IDataSource DataSource { get; } + private IDataSource DataSource { get; } = dataSource; - private InternalDataSourceRegistration DataSourceRegistration { get; } + private InternalDataSourceRegistration DataSourceRegistration { get; } = registration; - private IReadOnlyDictionary? SystemConfiguration { get; } + private IReadOnlyDictionary? SystemConfiguration { get; } = systemConfiguration; - internal IReadOnlyDictionary? RequestConfiguration { get; } + internal IReadOnlyDictionary? RequestConfiguration { get; } = requestConfiguration; - private ILogger Logger { get; } + private ILogger Logger { get; } = logger; public async Task InitializeAsync( ConcurrentDictionary catalogCache, @@ -239,7 +226,7 @@ public async Task GetCatalogAsync( .RepositoryUrl; var newResourceProperties = catalogProperties is null - ? new Dictionary() + ? [] : catalogProperties.ToDictionary(entry => entry.Key, entry => entry.Value); var originJsonObject = new JsonObject() @@ -564,7 +551,7 @@ private async Task ReadAggregatedAsync( if (disableCache) { - uncachedIntervals = new List { new Interval(begin, end) }; + uncachedIntervals = [new Interval(begin, end)]; } else @@ -607,7 +594,7 @@ private async Task ReadAggregatedAsync( await DataSource.ReadAsync( interval.Begin, interval.End, - new[] { slicedReadRequest }, + [slicedReadRequest], readDataHandler, progress, cancellationToken); @@ -721,7 +708,7 @@ private async Task ReadResampledAsync( await DataSource.ReadAsync( roundedBegin, roundedEnd, - new[] { readRequest }, + [readRequest], readDataHandler, progress, cancellationToken); @@ -779,7 +766,7 @@ private ReadUnit[] PrepareReadUnits( } } - return readUnits.ToArray(); + return [.. readUnits]; } public static async Task ReadAsync( diff --git a/src/Nexus/Extensibility/DataSource/DataSourceControllerExtensions.cs b/src/Nexus/Extensibility/DataSource/DataSourceControllerExtensions.cs index 5c42cb69..97649103 100644 --- a/src/Nexus/Extensibility/DataSource/DataSourceControllerExtensions.cs +++ b/src/Nexus/Extensibility/DataSource/DataSourceControllerExtensions.cs @@ -75,16 +75,16 @@ public static Task ReadSingleAsync( { var samplePeriod = request.Item.Representation.SamplePeriod; - var readingGroup = new DataReadingGroup(controller, new CatalogItemRequestPipeWriter[] - { + var readingGroup = new DataReadingGroup(controller, + [ new CatalogItemRequestPipeWriter(request, dataWriter) - }); + ]); return DataSourceController.ReadAsync( begin, end, samplePeriod, - new DataReadingGroup[] { readingGroup }, + [readingGroup], readDataHandler, memoryTracker, progress, diff --git a/src/Nexus/Extensibility/DataSource/DataSourceDoubleStream.cs b/src/Nexus/Extensibility/DataSource/DataSourceDoubleStream.cs index d9958d74..62fe7662 100644 --- a/src/Nexus/Extensibility/DataSource/DataSourceDoubleStream.cs +++ b/src/Nexus/Extensibility/DataSource/DataSourceDoubleStream.cs @@ -2,20 +2,14 @@ namespace Nexus.Extensibility; -internal class DataSourceDoubleStream : Stream +internal class DataSourceDoubleStream(long length, PipeReader reader) + : Stream { private readonly CancellationTokenSource _cts = new(); private long _position; - private readonly long _length; - private readonly PipeReader _reader; - private readonly Stream _stream; - - public DataSourceDoubleStream(long length, PipeReader reader) - { - _length = length; - _reader = reader; - _stream = reader.AsStream(); - } + private readonly long _length = length; + private readonly PipeReader _reader = reader; + private readonly Stream _stream = reader.AsStream(); public override bool CanRead => true; diff --git a/src/Nexus/Extensibility/DataWriter/DataWriterController.cs b/src/Nexus/Extensibility/DataWriter/DataWriterController.cs index 201e8f88..079a0e1c 100644 --- a/src/Nexus/Extensibility/DataWriter/DataWriterController.cs +++ b/src/Nexus/Extensibility/DataWriter/DataWriterController.cs @@ -24,31 +24,22 @@ Task WriteAsync( // TODO: Add "CheckFileSize" method (e.g. for Famos). -internal class DataWriterController : IDataWriterController +internal class DataWriterController( + IDataWriter dataWriter, + Uri resourceLocator, + IReadOnlyDictionary? systemConfiguration, + IReadOnlyDictionary? requestConfiguration, + ILogger logger) : IDataWriterController { - public DataWriterController( - IDataWriter dataWriter, - Uri resourceLocator, - IReadOnlyDictionary? systemConfiguration, - IReadOnlyDictionary? requestConfiguration, - ILogger logger) - { - DataWriter = dataWriter; - ResourceLocator = resourceLocator; - SystemConfiguration = systemConfiguration; - RequestConfiguration = requestConfiguration; - Logger = logger; - } - - private IReadOnlyDictionary? SystemConfiguration { get; } + private IReadOnlyDictionary? SystemConfiguration { get; } = systemConfiguration; - private IReadOnlyDictionary? RequestConfiguration { get; } + private IReadOnlyDictionary? RequestConfiguration { get; } = requestConfiguration; - private IDataWriter DataWriter { get; } + private IDataWriter DataWriter { get; } = dataWriter; - private Uri ResourceLocator { get; } + private Uri ResourceLocator { get; } = resourceLocator; - private ILogger Logger { get; } + private ILogger Logger { get; } = logger; public async Task InitializeAsync( ILogger logger, diff --git a/src/Nexus/Extensions/Sources/Sample.cs b/src/Nexus/Extensions/Sources/Sample.cs index 93624630..e2fdc776 100644 --- a/src/Nexus/Extensions/Sources/Sample.cs +++ b/src/Nexus/Extensions/Sources/Sample.cs @@ -103,8 +103,8 @@ public Task GetCatalogRegistrationsAsync( if (path == "/") return Task.FromResult(new CatalogRegistration[] { - new CatalogRegistration(LocalCatalogId, LocalCatalogTitle), - new CatalogRegistration(RemoteCatalogId, RemoteCatalogTitle), + new(LocalCatalogId, LocalCatalogTitle), + new(RemoteCatalogId, RemoteCatalogTitle), }); else @@ -200,7 +200,7 @@ public async Task ReadAsync( var finishedTasks = 0; - while (tasks.Any()) + while (tasks.Count != 0) { var task = await Task.WhenAny(tasks); cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/Nexus/Extensions/Writers/Csv.cs b/src/Nexus/Extensions/Writers/Csv.cs index 702e6ec9..efc4a2fd 100644 --- a/src/Nexus/Extensions/Writers/Csv.cs +++ b/src/Nexus/Extensions/Writers/Csv.cs @@ -69,7 +69,7 @@ internal class Csv : IDataWriter, IDisposable private double _excelStart; private DateTime _lastFileBegin; private TimeSpan _lastSamplePeriod; - private readonly Dictionary _resourceMap = new(); + private readonly Dictionary _resourceMap = []; private DataWriterContext Context { get; set; } = default!; @@ -123,7 +123,7 @@ public async Task OpenAsync( var layout = new Layout() { - HeaderRows = new[] { 4 } + HeaderRows = [4] }; var fields = new[] { timestampField }.Concat(catalogItemGroup.Select(catalogItem => @@ -150,7 +150,7 @@ public async Task OpenAsync( Name: resourceFileNameWithoutExtension.ToLower(), Profile: "tabular-data-resource", Scheme: "multipart", - Path: new List(), + Path: [], Layout: layout, Schema: schema); diff --git a/src/Nexus/PackageManagement/PackageController.cs b/src/Nexus/PackageManagement/PackageController.cs index cb550618..fe55505f 100644 --- a/src/Nexus/PackageManagement/PackageController.cs +++ b/src/Nexus/PackageManagement/PackageController.cs @@ -12,7 +12,9 @@ namespace Nexus.PackageManagement; -internal partial class PackageController +internal partial class PackageController( + InternalPackageReference packageReference, + ILogger logger) { public static Guid BUILTIN_ID = new("97d297d2-df6f-4c85-9d07-86bc64a041a6"); public const string BUILTIN_PROVIDER = "nexus"; @@ -22,16 +24,10 @@ internal partial class PackageController private static readonly HttpClient _httpClient = new(); - private readonly ILogger _logger; + private readonly ILogger _logger = logger; private PackageLoadContext? _loadContext; - public PackageController(InternalPackageReference packageReference, ILogger logger) - { - PackageReference = packageReference; - _logger = logger; - } - - public InternalPackageReference PackageReference { get; } + public InternalPackageReference PackageReference { get; } = packageReference; public async Task DiscoverAsync(CancellationToken cancellationToken) { @@ -73,16 +69,8 @@ public async Task LoadAsync(string restoreRoot, CancellationToken canc var depsJsonFilePath = Directory .EnumerateFiles(restoreFolderPath, $"*{depsJsonExtension}", SearchOption.AllDirectories) - .SingleOrDefault(); - - if (depsJsonFilePath is null) - throw new Exception($"Could not determine the location of the .deps.json file in folder {restoreFolderPath}."); - - var entryDllPath = depsJsonFilePath[..^depsJsonExtension.Length] + ".dll"; - - if (entryDllPath is null) - throw new Exception($"Could not determine the location of the entry DLL file in folder {restoreFolderPath}."); - + .SingleOrDefault() ?? throw new Exception($"Could not determine the location of the .deps.json file in folder {restoreFolderPath}."); + var entryDllPath = depsJsonFilePath[..^depsJsonExtension.Length] + ".dll" ?? throw new Exception($"Could not determine the location of the entry DLL file in folder {restoreFolderPath}."); _loadContext = new PackageLoadContext(entryDllPath); var assemblyName = new AssemblyName(Path.GetFileNameWithoutExtension(entryDllPath)); @@ -280,11 +268,7 @@ private async Task DiscoverGitTagsAsync(CancellationToken cancellation RedirectStandardError = true }; - using var process = Process.Start(startInfo); - - if (process is null) - throw new Exception("Process is null."); - + using var process = Process.Start(startInfo) ?? throw new Exception("Process is null."); while (!process.StandardOutput.EndOfStream) { var refLine = await process.StandardOutput.ReadLineAsync(cancellationToken); @@ -326,7 +310,7 @@ private async Task DiscoverGitTagsAsync(CancellationToken cancellation result.Reverse(); - return result.ToArray(); + return [.. result]; } private async Task RestoreGitTagAsync(string restoreRoot, CancellationToken cancellationToken) @@ -365,11 +349,7 @@ private async Task RestoreGitTagAsync(string restoreRoot, CancellationTo RedirectStandardError = true }; - using var process1 = Process.Start(startInfo1); - - if (process1 is null) - throw new Exception("Process is null."); - + using var process1 = Process.Start(startInfo1) ?? throw new Exception("Process is null."); await process1.WaitForExitAsync(cancellationToken); if (process1.ExitCode != 0) @@ -400,11 +380,7 @@ private async Task RestoreGitTagAsync(string restoreRoot, CancellationTo RedirectStandardError = true }; - using var process2 = Process.Start(startInfo2); - - if (process2 is null) - throw new Exception("Process is null."); - + using var process2 = Process.Start(startInfo2) ?? throw new Exception("Process is null."); await process2.WaitForExitAsync(cancellationToken); if (process2.ExitCode != 0) @@ -518,7 +494,7 @@ private async Task DiscoverGithubReleasesAsync(CancellationToken cance continue; } - return result.ToArray(); + return [.. result]; } private async Task RestoreGitHubReleasesAsync(string restoreRoot, CancellationToken cancellationToken) @@ -633,7 +609,7 @@ private async Task DiscoverGitLabPackagesGenericAsync(CancellationToke result.Reverse(); - return result.ToArray(); + return [.. result]; } private async Task RestoreGitLabPackagesGenericAsync(string restoreRoot, CancellationToken cancellationToken) diff --git a/src/Nexus/PackageManagement/PackageLoadContext.cs b/src/Nexus/PackageManagement/PackageLoadContext.cs index ec18b297..dd4720c4 100644 --- a/src/Nexus/PackageManagement/PackageLoadContext.cs +++ b/src/Nexus/PackageManagement/PackageLoadContext.cs @@ -3,14 +3,10 @@ namespace Nexus.PackageManagement; -internal class PackageLoadContext : AssemblyLoadContext +internal class PackageLoadContext(string entryDllPath) + : AssemblyLoadContext(isCollectible: true) { - private readonly AssemblyDependencyResolver _resolver; - - public PackageLoadContext(string entryDllPath) : base(isCollectible: true) - { - _resolver = new AssemblyDependencyResolver(entryDllPath); - } + private readonly AssemblyDependencyResolver _resolver = new(entryDllPath); protected override Assembly? Load(AssemblyName assemblyName) { diff --git a/src/Nexus/Program.cs b/src/Nexus/Program.cs index 5709ad20..82f0180e 100644 --- a/src/Nexus/Program.cs +++ b/src/Nexus/Program.cs @@ -238,7 +238,7 @@ void ConfigurePipeline(WebApplication app) app.UseAuthorization(); // endpoints - + /* REST API */ app.MapControllers(); diff --git a/src/Nexus/Services/AppStateManager.cs b/src/Nexus/Services/AppStateManager.cs index 2823a0f5..d83f0847 100644 --- a/src/Nexus/Services/AppStateManager.cs +++ b/src/Nexus/Services/AppStateManager.cs @@ -7,30 +7,21 @@ namespace Nexus.Services; -internal class AppStateManager +internal class AppStateManager( + AppState appState, + IExtensionHive extensionHive, + ICatalogManager catalogManager, + IDatabaseService databaseService, + ILogger logger) { - private readonly IExtensionHive _extensionHive; - private readonly ICatalogManager _catalogManager; - private readonly IDatabaseService _databaseService; - private readonly ILogger _logger; + private readonly IExtensionHive _extensionHive = extensionHive; + private readonly ICatalogManager _catalogManager = catalogManager; + private readonly IDatabaseService _databaseService = databaseService; + private readonly ILogger _logger = logger; private readonly SemaphoreSlim _refreshDatabaseSemaphore = new(initialCount: 1, maxCount: 1); private readonly SemaphoreSlim _projectSemaphore = new(initialCount: 1, maxCount: 1); - public AppStateManager( - AppState appState, - IExtensionHive extensionHive, - ICatalogManager catalogManager, - IDatabaseService databaseService, - ILogger logger) - { - AppState = appState; - _extensionHive = extensionHive; - _catalogManager = catalogManager; - _databaseService = databaseService; - _logger = logger; - } - - public AppState AppState { get; } + public AppState AppState { get; } = appState; public async Task RefreshDatabaseAsync( IProgress progress, @@ -250,11 +241,7 @@ private void LoadDataWriters() } var additionalInformation = attribute.Description; - var label = additionalInformation?.GetStringValue(Nexus.UI.Core.Constants.DATA_WRITER_LABEL_KEY); - - if (label is null) - throw new Exception($"The description of data writer {fullName} has no label property"); - + var label = (additionalInformation?.GetStringValue(Nexus.UI.Core.Constants.DATA_WRITER_LABEL_KEY)) ?? throw new Exception($"The description of data writer {fullName} has no label property"); var version = dataWriterType.Assembly .GetCustomAttribute()! .InformationalVersion; diff --git a/src/Nexus/Services/CacheService.cs b/src/Nexus/Services/CacheService.cs index 12464a50..16d8e748 100644 --- a/src/Nexus/Services/CacheService.cs +++ b/src/Nexus/Services/CacheService.cs @@ -28,17 +28,12 @@ Task ClearAsync( CancellationToken cancellationToken); } -internal class CacheService : ICacheService +internal class CacheService( + IDatabaseService databaseService) : ICacheService { - private readonly IDatabaseService _databaseService; + private readonly IDatabaseService _databaseService = databaseService; private readonly TimeSpan _largestSamplePeriod = TimeSpan.FromDays(1); - public CacheService( - IDatabaseService databaseService) - { - _databaseService = databaseService; - } - public async Task> ReadAsync( CatalogItem catalogItem, DateTime begin, diff --git a/src/Nexus/Services/CatalogManager.cs b/src/Nexus/Services/CatalogManager.cs index f4031714..44e4feb3 100644 --- a/src/Nexus/Services/CatalogManager.cs +++ b/src/Nexus/Services/CatalogManager.cs @@ -16,7 +16,13 @@ Task GetCatalogContainersAsync( CancellationToken cancellationToken); } -internal class CatalogManager : ICatalogManager +internal class CatalogManager( + AppState appState, + IDataControllerService dataControllerService, + IDatabaseService databaseService, + IServiceProvider serviceProvider, + IExtensionHive extensionHive, + ILogger logger) : ICatalogManager { record CatalogPrototype( CatalogRegistration Registration, @@ -25,28 +31,12 @@ record CatalogPrototype( CatalogMetadata Metadata, ClaimsPrincipal? Owner); - private readonly AppState _appState; - private readonly IDataControllerService _dataControllerService; - private readonly IDatabaseService _databaseService; - private readonly IServiceProvider _serviceProvider; - private readonly IExtensionHive _extensionHive; - private readonly ILogger _logger; - - public CatalogManager( - AppState appState, - IDataControllerService dataControllerService, - IDatabaseService databaseService, - IServiceProvider serviceProvider, - IExtensionHive extensionHive, - ILogger logger) - { - _appState = appState; - _dataControllerService = dataControllerService; - _databaseService = databaseService; - _serviceProvider = serviceProvider; - _extensionHive = extensionHive; - _logger = logger; - } + private readonly AppState _appState = appState; + private readonly IDataControllerService _dataControllerService = dataControllerService; + private readonly IDatabaseService _databaseService = databaseService; + private readonly IServiceProvider _serviceProvider = serviceProvider; + private readonly IExtensionHive _extensionHive = extensionHive; + private readonly ILogger _logger = logger; public async Task GetCatalogContainersAsync( CatalogContainer parent, @@ -65,7 +55,7 @@ public async Task GetCatalogContainersAsync( /* load builtin data source */ var builtinDataSourceRegistrations = new InternalDataSourceRegistration[] { - new InternalDataSourceRegistration( + new( Id: Sample.RegistrationId, Type: typeof(Sample).FullName!, ResourceLocator: default, @@ -195,7 +185,7 @@ public async Task GetCatalogContainersAsync( catch (Exception ex) { _logger.LogWarning(ex, "Unable to get or process child data source registrations"); - catalogContainers = Array.Empty(); + catalogContainers = []; } } @@ -301,6 +291,6 @@ private CatalogPrototype[] EnsureNoHierarchy( } } - return catalogPrototypesToKeep.ToArray(); + return [.. catalogPrototypesToKeep]; } } diff --git a/src/Nexus/Services/DataControllerService.cs b/src/Nexus/Services/DataControllerService.cs index 36eeb7ec..7d9c7d6e 100644 --- a/src/Nexus/Services/DataControllerService.cs +++ b/src/Nexus/Services/DataControllerService.cs @@ -19,38 +19,26 @@ Task GetDataWriterControllerAsync( CancellationToken cancellationToken); } -internal class DataControllerService : IDataControllerService +internal class DataControllerService( + AppState appState, + IHttpContextAccessor httpContextAccessor, + IExtensionHive extensionHive, + IProcessingService processingService, + ICacheService cacheService, + IOptions dataOptions, + ILogger logger, + ILoggerFactory loggerFactory) : IDataControllerService { public const string NexusConfigurationHeaderKey = "Nexus-Configuration"; - private readonly AppState _appState; - private readonly DataOptions _dataOptions; - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IExtensionHive _extensionHive; - private readonly IProcessingService _processingService; - private readonly ICacheService _cacheService; - private readonly ILogger _logger; - private readonly ILoggerFactory _loggerFactory; - - public DataControllerService( - AppState appState, - IHttpContextAccessor httpContextAccessor, - IExtensionHive extensionHive, - IProcessingService processingService, - ICacheService cacheService, - IOptions dataOptions, - ILogger logger, - ILoggerFactory loggerFactory) - { - _appState = appState; - _httpContextAccessor = httpContextAccessor; - _extensionHive = extensionHive; - _processingService = processingService; - _cacheService = cacheService; - _dataOptions = dataOptions.Value; - _logger = logger; - _loggerFactory = loggerFactory; - } + private readonly AppState _appState = appState; + private readonly DataOptions _dataOptions = dataOptions.Value; + private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; + private readonly IExtensionHive _extensionHive = extensionHive; + private readonly IProcessingService _processingService = processingService; + private readonly ICacheService _cacheService = cacheService; + private readonly ILogger _logger = logger; + private readonly ILoggerFactory _loggerFactory = loggerFactory; public async Task GetDataSourceControllerAsync( InternalDataSourceRegistration registration, diff --git a/src/Nexus/Services/DataService.cs b/src/Nexus/Services/DataService.cs index e76ede98..eee4c8dd 100644 --- a/src/Nexus/Services/DataService.cs +++ b/src/Nexus/Services/DataService.cs @@ -34,40 +34,26 @@ Task ExportAsync( CancellationToken cancellationToken); } -internal class DataService : IDataService +internal class DataService( + AppState appState, + ClaimsPrincipal user, + IDataControllerService dataControllerService, + IDatabaseService databaseService, + IMemoryTracker memoryTracker, + ILogger logger, + ILoggerFactory loggerFactory) : IDataService { - private readonly AppState _appState; - private readonly IMemoryTracker _memoryTracker; - private readonly ClaimsPrincipal _user; - private readonly ILogger _logger; - private readonly ILoggerFactory _loggerFactory; - private readonly IDatabaseService _databaseService; - private readonly IDataControllerService _dataControllerService; - - public DataService( - AppState appState, - ClaimsPrincipal user, - IDataControllerService dataControllerService, - IDatabaseService databaseService, - IMemoryTracker memoryTracker, - ILogger logger, - ILoggerFactory loggerFactory) - { - _user = user; - _appState = appState; - _dataControllerService = dataControllerService; - _databaseService = databaseService; - _memoryTracker = memoryTracker; - _logger = logger; - _loggerFactory = loggerFactory; - - ReadProgress = new Progress(); - WriteProgress = new Progress(); - } + private readonly AppState _appState = appState; + private readonly IMemoryTracker _memoryTracker = memoryTracker; + private readonly ClaimsPrincipal _user = user; + private readonly ILogger _logger = logger; + private readonly ILoggerFactory _loggerFactory = loggerFactory; + private readonly IDatabaseService _databaseService = databaseService; + private readonly IDataControllerService _dataControllerService = dataControllerService; - public Progress ReadProgress { get; } + public Progress ReadProgress { get; } = new Progress(); - public Progress WriteProgress { get; } + public Progress WriteProgress { get; } = new Progress(); public async Task ReadAsStreamAsync( string resourcePath, @@ -80,11 +66,7 @@ public async Task ReadAsStreamAsync( // find representation var root = _appState.CatalogState.Root; - var catalogItemRequest = await root.TryFindAsync(resourcePath, cancellationToken); - - if (catalogItemRequest is null) - throw new Exception($"Could not find resource path {resourcePath}."); - + var catalogItemRequest = await root.TryFindAsync(resourcePath, cancellationToken) ?? throw new Exception($"Could not find resource path {resourcePath}."); var catalogContainer = catalogItemRequest.Container; // security check diff --git a/src/Nexus/Services/DatabaseService.cs b/src/Nexus/Services/DatabaseService.cs index 53ba88dd..e18ab825 100644 --- a/src/Nexus/Services/DatabaseService.cs +++ b/src/Nexus/Services/DatabaseService.cs @@ -41,7 +41,8 @@ Stream WriteTokenMap( string userId); } -internal class DatabaseService : IDatabaseService +internal class DatabaseService(IOptions pathsOptions) + : IDatabaseService { // generated, small files: // @@ -57,12 +58,7 @@ internal class DatabaseService : IDatabaseService // /export // /.nexus/packages - private readonly PathsOptions _pathsOptions; - - public DatabaseService(IOptions pathsOptions) - { - _pathsOptions = pathsOptions.Value; - } + private readonly PathsOptions _pathsOptions = pathsOptions.Value; /* /config/catalogs/catalog_id.json */ public bool TryReadCatalogMetadata(string catalogId, [NotNullWhen(true)] out string? catalogMetadata) diff --git a/src/Nexus/Services/DbService.cs b/src/Nexus/Services/DbService.cs index 61007328..3ab8645a 100644 --- a/src/Nexus/Services/DbService.cs +++ b/src/Nexus/Services/DbService.cs @@ -14,15 +14,10 @@ internal interface IDBService Task SaveChangesAsync(); } -internal class DbService : IDBService +internal class DbService( + UserDbContext context) : IDBService { - private readonly UserDbContext _context; - - public DbService( - UserDbContext context) - { - _context = context; - } + private readonly UserDbContext _context = context; public IQueryable GetUsers() { diff --git a/src/Nexus/Services/ExtensionHive.cs b/src/Nexus/Services/ExtensionHive.cs index 0147fcdd..42cf0253 100644 --- a/src/Nexus/Services/ExtensionHive.cs +++ b/src/Nexus/Services/ExtensionHive.cs @@ -29,24 +29,17 @@ Task GetVersionsAsync( CancellationToken cancellationToken); } -internal class ExtensionHive : IExtensionHive +internal class ExtensionHive( + IOptions pathsOptions, + ILogger logger, + ILoggerFactory loggerFactory) : IExtensionHive { - private readonly ILogger _logger; - private readonly ILoggerFactory _loggerFactory; - private readonly PathsOptions _pathsOptions; + private readonly ILogger _logger = logger; + private readonly ILoggerFactory _loggerFactory = loggerFactory; + private readonly PathsOptions _pathsOptions = pathsOptions.Value; private Dictionary>? _packageControllerMap = default!; - public ExtensionHive( - IOptions pathsOptions, - ILogger logger, - ILoggerFactory loggerFactory) - { - _logger = logger; - _loggerFactory = loggerFactory; - _pathsOptions = pathsOptions.Value; - } - public async Task LoadPackagesAsync( IEnumerable packageReferences, IProgress progress, @@ -68,7 +61,7 @@ public async Task LoadPackagesAsync( var nexusPackageReference = new InternalPackageReference( Id: PackageController.BUILTIN_ID, Provider: PackageController.BUILTIN_PROVIDER, - Configuration: new Dictionary() + Configuration: [] ); packageReferences = new List() { nexusPackageReference }.Concat(packageReferences); diff --git a/src/Nexus/Services/MemoryTracker.cs b/src/Nexus/Services/MemoryTracker.cs index 8339d4ec..7224d5c6 100644 --- a/src/Nexus/Services/MemoryTracker.cs +++ b/src/Nexus/Services/MemoryTracker.cs @@ -3,18 +3,14 @@ namespace Nexus.Services; -internal class AllocationRegistration : IDisposable +internal class AllocationRegistration( + IMemoryTracker tracker, + long actualByteCount) : IDisposable { private bool _disposedValue; - private readonly IMemoryTracker _tracker; + private readonly IMemoryTracker _tracker = tracker; - public AllocationRegistration(IMemoryTracker tracker, long actualByteCount) - { - _tracker = tracker; - ActualByteCount = actualByteCount; - } - - public long ActualByteCount { get; } + public long ActualByteCount { get; } = actualByteCount; public void Dispose() { @@ -36,7 +32,7 @@ internal class MemoryTracker : IMemoryTracker { private long _consumedBytes; private readonly DataOptions _dataOptions; - private readonly List _retrySemaphores = new(); + private readonly List _retrySemaphores = []; private readonly ILogger _logger; public MemoryTracker(IOptions dataOptions, ILogger logger) diff --git a/src/Nexus/Services/ProcessingService.cs b/src/Nexus/Services/ProcessingService.cs index 54ccf4c8..8488b705 100644 --- a/src/Nexus/Services/ProcessingService.cs +++ b/src/Nexus/Services/ProcessingService.cs @@ -28,14 +28,10 @@ void Aggregate( int blockSize); } -internal class ProcessingService : IProcessingService +internal class ProcessingService(IOptions dataOptions) + : IProcessingService { - private readonly double _nanThreshold; - - public ProcessingService(IOptions dataOptions) - { - _nanThreshold = dataOptions.Value.AggregationNaNThreshold; - } + private readonly double _nanThreshold = dataOptions.Value.AggregationNaNThreshold; public void Resample( NexusDataType dataType, @@ -46,7 +42,7 @@ public void Resample( int offset) { using var memoryOwner = MemoryPool.Shared.Rent(status.Length); - var doubleData = memoryOwner.Memory.Slice(0, status.Length); + var doubleData = memoryOwner.Memory[..status.Length]; BufferUtilities.ApplyRepresentationStatusByDataType( dataType, @@ -103,7 +99,7 @@ private void GenericProcess( using (var memoryOwner = MemoryPool.Shared.Rent(Tdata.Length)) { - var doubleData2 = memoryOwner.Memory.Slice(0, Tdata.Length); + var doubleData2 = memoryOwner.Memory[..Tdata.Length]; BufferUtilities.ApplyRepresentationStatus(Tdata, status, target: doubleData2); ApplyAggregationFunction(kind, blockSize, doubleData2, targetBuffer); @@ -152,8 +148,8 @@ private void ApplyAggregationFunction( using (var memoryOwner_sin = MemoryPool.Shared.Rent(targetBuffer.Length)) using (var memoryOwner_cos = MemoryPool.Shared.Rent(targetBuffer.Length)) { - var sinBuffer = memoryOwner_sin.Memory.Slice(0, targetBuffer.Length); - var cosBuffer = memoryOwner_cos.Memory.Slice(0, targetBuffer.Length); + var sinBuffer = memoryOwner_sin.Memory[..targetBuffer.Length]; + var cosBuffer = memoryOwner_cos.Memory[..targetBuffer.Length]; var limit = 360; var factor = 2 * Math.PI / limit; diff --git a/src/Nexus/Services/TokenService.cs b/src/Nexus/Services/TokenService.cs index 343bc0ac..21195cf2 100644 --- a/src/Nexus/Services/TokenService.cs +++ b/src/Nexus/Services/TokenService.cs @@ -27,20 +27,16 @@ bool TryGet( Task> GetAllAsync(string userId); } -internal class TokenService : ITokenService +internal class TokenService(IDatabaseService databaseService) + : ITokenService { private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create(); - private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim _semaphoreSlim = new(1, 1); private readonly ConcurrentDictionary> _cache = new(); - private readonly IDatabaseService _databaseService; - - public TokenService(IDatabaseService databaseService) - { - _databaseService = databaseService; - } + private readonly IDatabaseService _databaseService = databaseService; public Task CreateAsync( string userId, diff --git a/src/Nexus/Utilities/MemoryManager.cs b/src/Nexus/Utilities/MemoryManager.cs index af2eab65..cad24e75 100644 --- a/src/Nexus/Utilities/MemoryManager.cs +++ b/src/Nexus/Utilities/MemoryManager.cs @@ -5,13 +5,11 @@ namespace Nexus.Utilities; // TODO: Validate against this: https://github.com/windows-toolkit/WindowsCommunityToolkit/pull/3520/files -internal class CastMemoryManager : MemoryManager +internal class CastMemoryManager(Memory from) : MemoryManager where TFrom : struct where TTo : struct { - private readonly Memory _from; - - public CastMemoryManager(Memory from) => _from = from; + private readonly Memory _from = from; public override Span GetSpan() => MemoryMarshal.Cast(_from.Span); diff --git a/src/Nexus/Utilities/NexusUtilities.cs b/src/Nexus/Utilities/NexusUtilities.cs index 729de5ea..561388d3 100644 --- a/src/Nexus/Utilities/NexusUtilities.cs +++ b/src/Nexus/Utilities/NexusUtilities.cs @@ -6,7 +6,7 @@ namespace Nexus.Utilities; -internal static class NexusUtilities +internal static partial class NexusUtilities { private static string? _defaultBaseUrl; @@ -21,7 +21,7 @@ public static string DefaultBaseUrl if (aspnetcoreEnvVar is not null) { - var match = Regex.Match(aspnetcoreEnvVar, ":([0-9]+)"); + var match = AspNetCoreEnvVarRegex().Match(aspnetcoreEnvVar); if (match.Success && int.TryParse(match.Groups[1].Value, out var parsedPort)) port = parsedPort; @@ -105,7 +105,7 @@ public static async ValueTask WhenAll(params ValueTask[] tasks) public static async Task WhenAllFailFastAsync(List tasks, CancellationToken cancellationToken) { - while (tasks.Any()) + while (tasks.Count != 0) { var task = await Task .WhenAny(tasks) @@ -148,4 +148,7 @@ public static IEnumerable GetCustomAttributes(this Type type) where T : At { return type.GetCustomAttributes(false).OfType(); } + + [GeneratedRegex(":([0-9]+)")] + private static partial Regex AspNetCoreEnvVarRegex(); } \ No newline at end of file diff --git a/src/extensibility/dotnet-extensibility/DataModel/DataModelExtensions.cs b/src/extensibility/dotnet-extensibility/DataModel/DataModelExtensions.cs index c5338556..6192dd9f 100644 --- a/src/extensibility/dotnet-extensibility/DataModel/DataModelExtensions.cs +++ b/src/extensibility/dotnet-extensibility/DataModel/DataModelExtensions.cs @@ -6,7 +6,7 @@ namespace Nexus.DataModel; /// /// Contains extension methods to make life easier working with the data model types. /// -public static class DataModelExtensions +public static partial class DataModelExtensions { #region Fluent API @@ -133,11 +133,11 @@ public static string ToPath(this Uri url) // keep in sync with Nexus.UI.Utilities ... private const int NS_PER_TICK = 100; - private static readonly long[] _nanoseconds = new[] { (long)1e0, (long)1e3, (long)1e6, (long)1e9, (long)60e9, (long)3600e9, (long)86400e9 }; - private static readonly int[] _quotients = new[] { 1000, 1000, 1000, 60, 60, 24, 1 }; - private static readonly string[] _postFixes = new[] { "ns", "us", "ms", "s", "min", "h", "d" }; + private static readonly long[] _nanoseconds = [(long)1e0, (long)1e3, (long)1e6, (long)1e9, (long)60e9, (long)3600e9, (long)86400e9]; + private static readonly int[] _quotients = [1000, 1000, 1000, 60, 60, 24, 1]; + private static readonly string[] _postFixes = ["ns", "us", "ms", "s", "min", "h", "d"]; // ... except this line - private static readonly Regex _unitStringEvaluator = new(@"^([0-9]+)_([a-z]+)$", RegexOptions.Compiled); + private static readonly Regex _unitStringEvaluator = UnitStringEvaluator(); /// /// Converts period into a human readable number string with unit. @@ -185,5 +185,8 @@ internal static TimeSpan ToSamplePeriod(string unitString) return new TimeSpan(ticks); } + [GeneratedRegex(@"^([0-9]+)_([a-z]+)$", RegexOptions.Compiled)] + private static partial Regex UnitStringEvaluator(); + #endregion } diff --git a/src/extensibility/dotnet-extensibility/DataModel/DataModelUtilities.cs b/src/extensibility/dotnet-extensibility/DataModel/DataModelUtilities.cs index bbcf8de7..996c5562 100644 --- a/src/extensibility/dotnet-extensibility/DataModel/DataModelUtilities.cs +++ b/src/extensibility/dotnet-extensibility/DataModel/DataModelUtilities.cs @@ -5,7 +5,7 @@ namespace Nexus.DataModel; -internal static class DataModelUtilities +internal static partial class DataModelUtilities { /* Example resource paths: * @@ -18,7 +18,7 @@ internal static class DataModelUtilities * /a/b/c/T1/600_s_mean(abc=456)#base=1s */ // keep in sync with Nexus.UI.Core.Utilities - private static readonly Regex _resourcePathEvaluator = new(@"^(?'catalog'.*)\/(?'resource'.*)\/(?'sample_period'[0-9]+_[a-zA-Z]+)(?:_(?'kind'[^\(#\s]+))?(?:\((?'parameters'.*)\))?(?:#(?'fragment'.*))?$", RegexOptions.Compiled); + private static readonly Regex _resourcePathEvaluator = ResourcePathEvaluator(); private static string ToPascalCase(string input) { @@ -285,4 +285,7 @@ private static void MergeArrays(JsonArray currentArray, JsonElement root1, JsonE _ => JsonValue.Create(element) }; } + + [GeneratedRegex(@"^(?'catalog'.*)\/(?'resource'.*)\/(?'sample_period'[0-9]+_[a-zA-Z]+)(?:_(?'kind'[^\(#\s]+))?(?:\((?'parameters'.*)\))?(?:#(?'fragment'.*))?$", RegexOptions.Compiled)] + private static partial Regex ResourcePathEvaluator(); } \ No newline at end of file diff --git a/src/extensibility/dotnet-extensibility/DataModel/Representation.cs b/src/extensibility/dotnet-extensibility/DataModel/Representation.cs index 7dd6ebfa..48a63b67 100644 --- a/src/extensibility/dotnet-extensibility/DataModel/Representation.cs +++ b/src/extensibility/dotnet-extensibility/DataModel/Representation.cs @@ -9,9 +9,9 @@ namespace Nexus.DataModel; /// A representation is part of a resource. /// [DebuggerDisplay("{Id,nq}")] -public record Representation +public partial record Representation { - private static readonly Regex _snakeCaseEvaluator = new("(?<=[a-z])([A-Z])", RegexOptions.Compiled); + private static readonly Regex _snakeCaseEvaluator = SnakeCaseEvaluator(); private static readonly HashSet _nexusDataTypeValues = new(Enum.GetValues()); private IReadOnlyDictionary? _parameters; @@ -136,4 +136,7 @@ private static void ValidateParameters(IReadOnlyDictionary throw new Exception("The representation argument identifier is not valid."); } } + + [GeneratedRegex("(?<=[a-z])([A-Z])", RegexOptions.Compiled)] + private static partial Regex SnakeCaseEvaluator(); } \ No newline at end of file diff --git a/src/extensibility/dotnet-extensibility/DataModel/Resource.cs b/src/extensibility/dotnet-extensibility/DataModel/Resource.cs index 29bf620a..eec1667c 100644 --- a/src/extensibility/dotnet-extensibility/DataModel/Resource.cs +++ b/src/extensibility/dotnet-extensibility/DataModel/Resource.cs @@ -9,7 +9,7 @@ namespace Nexus.DataModel; /// A resource is part of a resource catalog and holds a list of representations. /// [DebuggerDisplay("{Id,nq}")] -public record Resource +public partial record Resource { private string _id = default!; private IReadOnlyList? _representations; @@ -36,7 +36,7 @@ public Resource( /// [JsonIgnore] #warning Remove this when https://github.com/RicoSuter/NSwag/issues/4681 is solved - public static Regex ValidIdExpression { get; } = new Regex(@"^[a-zA-Z_][a-zA-Z_0-9]*$"); + public static Regex ValidIdExpression { get; } = ValidExpression(); /// /// Gets a regular expression to find invalid characters in a resource identifier. @@ -129,4 +129,7 @@ private static void ValidateRepresentations(IReadOnlyList repres if (uniqueIds.Count() != representations.Count) throw new ArgumentException("There are multiple representations with the same identifier."); } + + [GeneratedRegex(@"^[a-zA-Z_][a-zA-Z_0-9]*$")] + private static partial Regex ValidExpression(); } \ No newline at end of file diff --git a/src/extensibility/dotnet-extensibility/DataModel/ResourceBuilder.cs b/src/extensibility/dotnet-extensibility/DataModel/ResourceBuilder.cs index ac1fdaa4..24f8b5cd 100644 --- a/src/extensibility/dotnet-extensibility/DataModel/ResourceBuilder.cs +++ b/src/extensibility/dotnet-extensibility/DataModel/ResourceBuilder.cs @@ -30,7 +30,7 @@ public ResourceBuilder(string id) /// The resource builder. public ResourceBuilder WithProperty(string key, object value) { - _properties ??= new(); + _properties ??= []; _properties[key] = JsonSerializer.SerializeToElement(value); @@ -44,7 +44,7 @@ public ResourceBuilder WithProperty(string key, object value) /// The resource builder. public ResourceBuilder AddRepresentation(Representation representation) { - _representations ??= new List(); + _representations ??= []; _representations.Add(representation); @@ -68,7 +68,7 @@ public ResourceBuilder AddRepresentations(params Representation[] representation /// The resource builder. public ResourceBuilder AddRepresentations(IEnumerable representations) { - _representations ??= new List(); + _representations ??= []; _representations.AddRange(representations); diff --git a/src/extensibility/dotnet-extensibility/DataModel/ResourceCatalog.cs b/src/extensibility/dotnet-extensibility/DataModel/ResourceCatalog.cs index 43d6824d..8e50d701 100644 --- a/src/extensibility/dotnet-extensibility/DataModel/ResourceCatalog.cs +++ b/src/extensibility/dotnet-extensibility/DataModel/ResourceCatalog.cs @@ -11,7 +11,7 @@ namespace Nexus.DataModel; /// A catalog is a top level element and holds a list of resources. /// [DebuggerDisplay("{Id,nq}")] -public record ResourceCatalog +public partial record ResourceCatalog { private string _id = default!; private IReadOnlyList? _resources; @@ -38,7 +38,7 @@ public ResourceCatalog( /// [JsonIgnore] #warning Remove this when https://github.com/RicoSuter/NSwag/issues/4681 is solved - public static Regex ValidIdExpression { get; } = new Regex(@"^(?:\/[a-zA-Z_][a-zA-Z_0-9]*)+$", RegexOptions.Compiled); + public static Regex ValidIdExpression { get; } = ValidIdExpressionRegex(); [JsonIgnore] #warning Remove this when https://github.com/RicoSuter/NSwag/issues/4681 is solved @@ -202,4 +202,7 @@ private static void ValidateResources(IReadOnlyList resources) if (uniqueIds.Count() != resources.Count) throw new ArgumentException("There are multiple resources with the same identifier."); } + + [GeneratedRegex(@"^(?:\/[a-zA-Z_][a-zA-Z_0-9]*)+$", RegexOptions.Compiled)] + private static partial Regex ValidIdExpressionRegex(); } diff --git a/src/extensibility/dotnet-extensibility/DataModel/ResourceCatalogBuilder.cs b/src/extensibility/dotnet-extensibility/DataModel/ResourceCatalogBuilder.cs index 0a7b588c..f22f567a 100644 --- a/src/extensibility/dotnet-extensibility/DataModel/ResourceCatalogBuilder.cs +++ b/src/extensibility/dotnet-extensibility/DataModel/ResourceCatalogBuilder.cs @@ -28,7 +28,7 @@ public ResourceCatalogBuilder(string id) /// The resource catalog builder. public ResourceCatalogBuilder WithProperty(string key, JsonElement value) { - _properties ??= new(); + _properties ??= []; _properties[key] = value; @@ -43,7 +43,7 @@ public ResourceCatalogBuilder WithProperty(string key, JsonElement value) /// The resource catalog builder. public ResourceCatalogBuilder WithProperty(string key, object value) { - _properties ??= new(); + _properties ??= []; _properties[key] = JsonSerializer.SerializeToElement(value); @@ -57,7 +57,7 @@ public ResourceCatalogBuilder WithProperty(string key, object value) /// The resource catalog builder. public ResourceCatalogBuilder AddResource(Resource resource) { - _resources ??= new List(); + _resources ??= []; _resources.Add(resource); @@ -81,7 +81,7 @@ public ResourceCatalogBuilder AddResources(params Resource[] resources) /// The resource catalog builder. public ResourceCatalogBuilder AddResources(IEnumerable resources) { - _resources ??= new List(); + _resources ??= []; _resources.AddRange(resources); diff --git a/src/extensibility/dotnet-extensibility/Extensibility/DataWriter/DataWriterTypes.cs b/src/extensibility/dotnet-extensibility/Extensibility/DataWriter/DataWriterTypes.cs index 8afc214c..c1dffc37 100644 --- a/src/extensibility/dotnet-extensibility/Extensibility/DataWriter/DataWriterTypes.cs +++ b/src/extensibility/dotnet-extensibility/Extensibility/DataWriter/DataWriterTypes.cs @@ -26,17 +26,10 @@ public record WriteRequest( /// /// An attribute to provide additional information about the data writer. /// +/// The data writer description including the data writer format label and UI options. [AttributeUsage(AttributeTargets.Class)] -public class DataWriterDescriptionAttribute : Attribute +public class DataWriterDescriptionAttribute(string description) : Attribute { - /// - /// Initializes a new instance of the . - /// - /// The data writer description including the data writer format label and UI options. - public DataWriterDescriptionAttribute(string description) - { - Description = JsonSerializer.Deserialize?>(description); - } - - internal IReadOnlyDictionary? Description { get; } + internal IReadOnlyDictionary? Description { get; } + = JsonSerializer.Deserialize?>(description); } diff --git a/src/extensibility/dotnet-extensibility/Extensibility/ExtensionDescriptionAttribute.cs b/src/extensibility/dotnet-extensibility/Extensibility/ExtensionDescriptionAttribute.cs index b37bf615..3687aca8 100644 --- a/src/extensibility/dotnet-extensibility/Extensibility/ExtensionDescriptionAttribute.cs +++ b/src/extensibility/dotnet-extensibility/Extensibility/ExtensionDescriptionAttribute.cs @@ -3,34 +3,25 @@ /// /// An attribute to identify the extension. /// +/// The extension description. +/// An optional project website URL. +/// An optional source repository URL. [AttributeUsage(validOn: AttributeTargets.Class, AllowMultiple = false)] -public class ExtensionDescriptionAttribute : Attribute +public class ExtensionDescriptionAttribute(string description, string projectUrl, string repositoryUrl) : Attribute { - /// - /// Initializes a new instance of the . - /// - /// The extension description. - /// An optional project website URL. - /// An optional source repository URL. - public ExtensionDescriptionAttribute(string description, string projectUrl, string repositoryUrl) - { - Description = description; - ProjectUrl = projectUrl; - RepositoryUrl = repositoryUrl; - } /// /// Gets the extension description. /// - public string Description { get; } + public string Description { get; } = description; /// /// Gets the project website URL. /// - public string ProjectUrl { get; } + public string ProjectUrl { get; } = projectUrl; /// /// Gets the source repository URL. /// - public string RepositoryUrl { get; } + public string RepositoryUrl { get; } = repositoryUrl; } \ No newline at end of file diff --git a/tests/Nexus.Tests/DataSource/DataSourceControllerTests.cs b/tests/Nexus.Tests/DataSource/DataSourceControllerTests.cs index d05e5347..e1a61d55 100644 --- a/tests/Nexus.Tests/DataSource/DataSourceControllerTests.cs +++ b/tests/Nexus.Tests/DataSource/DataSourceControllerTests.cs @@ -12,14 +12,10 @@ namespace DataSource; -public class DataSourceControllerTests : IClassFixture +public class DataSourceControllerTests(DataSourceControllerFixture fixture) + : IClassFixture { - private readonly DataSourceControllerFixture _fixture; - - public DataSourceControllerTests(DataSourceControllerFixture fixture) - { - _fixture = fixture; - } + private readonly DataSourceControllerFixture _fixture = fixture; [Fact] internal async Task CanGetAvailability() @@ -132,13 +128,13 @@ public async Task CanRead() // combine var catalogItemRequestPipeWriters = new CatalogItemRequestPipeWriter[] { - new CatalogItemRequestPipeWriter(catalogItemRequest1, dataWriter1), - new CatalogItemRequestPipeWriter(catalogItemRequest2, dataWriter2) + new(catalogItemRequest1, dataWriter1), + new(catalogItemRequest2, dataWriter2) }; var readingGroups = new DataReadingGroup[] { - new DataReadingGroup(controller, catalogItemRequestPipeWriters) + new(controller, catalogItemRequestPipeWriters) }; var result1 = new double[86401]; @@ -458,8 +454,8 @@ public async Task CanReadCached() /* ICacheService */ var uncachedIntervals = new List { - new Interval(begin, new DateTime(2020, 01, 02, 0, 0, 0, DateTimeKind.Utc)), - new Interval(new DateTime(2020, 01, 03, 0, 0, 0, DateTimeKind.Utc), end) + new(begin, new DateTime(2020, 01, 02, 0, 0, 0, DateTimeKind.Utc)), + new(new DateTime(2020, 01, 03, 0, 0, 0, DateTimeKind.Utc), end) }; var cacheService = new Mock(); diff --git a/tests/Nexus.Tests/DataSource/SampleDataSourceTests.cs b/tests/Nexus.Tests/DataSource/SampleDataSourceTests.cs index 02cd9589..f9fd885a 100644 --- a/tests/Nexus.Tests/DataSource/SampleDataSourceTests.cs +++ b/tests/Nexus.Tests/DataSource/SampleDataSourceTests.cs @@ -29,7 +29,7 @@ public async Task ProvidesCatalog() // assert var actualIds = actual.Resources!.Select(resource => resource.Id).ToList(); var actualUnits = actual.Resources!.Select(resource => resource.Properties?.GetStringValue("unit")).ToList(); - var actualGroups = actual.Resources!.SelectMany(resource => resource.Properties?.GetStringArray("groups") ?? Array.Empty()); + var actualGroups = actual.Resources!.SelectMany(resource => resource.Properties?.GetStringArray("groups") ?? []); var actualDataTypes = actual.Resources!.SelectMany(resource => resource.Representations!.Select(representation => representation.DataType)).ToList(); var expectedIds = new List() { "T1", "V1", "unix_time1", "unix_time2" }; @@ -110,7 +110,7 @@ public async Task CanReadFullDay() await dataSource.ReadAsync( begin, end, - new[] { request }, + [request], default!, new Progress(), CancellationToken.None); diff --git a/tests/Nexus.Tests/DataWriter/CsvDataWriterTests.cs b/tests/Nexus.Tests/DataWriter/CsvDataWriterTests.cs index 4cb0eb2a..f6a4e489 100644 --- a/tests/Nexus.Tests/DataWriter/CsvDataWriterTests.cs +++ b/tests/Nexus.Tests/DataWriter/CsvDataWriterTests.cs @@ -10,14 +10,10 @@ namespace DataWriter; -public class CsvDataWriterTests : IClassFixture +public class CsvDataWriterTests(DataWriterFixture fixture) + : IClassFixture { - private readonly DataWriterFixture _fixture; - - public CsvDataWriterTests(DataWriterFixture fixture) - { - _fixture = fixture; - } + private readonly DataWriterFixture _fixture = fixture; [Theory] [InlineData("index")] diff --git a/tests/Nexus.Tests/DataWriter/DataWriterControllerTests.cs b/tests/Nexus.Tests/DataWriter/DataWriterControllerTests.cs index c08ef818..026db497 100644 --- a/tests/Nexus.Tests/DataWriter/DataWriterControllerTests.cs +++ b/tests/Nexus.Tests/DataWriter/DataWriterControllerTests.cs @@ -8,14 +8,10 @@ namespace DataWriter; -public class DataWriterControllerTests : IClassFixture +public class DataWriterControllerTests(DataWriterFixture fixture) + : IClassFixture { - private readonly DataWriterFixture _fixture; - - public DataWriterControllerTests(DataWriterFixture fixture) - { - _fixture = fixture; - } + private readonly DataWriterFixture _fixture = fixture; [Fact] public async Task CanWrite() diff --git a/tests/Nexus.Tests/DataWriter/DataWriterFixture.cs b/tests/Nexus.Tests/DataWriter/DataWriterFixture.cs index 12decb9d..e6b9abcc 100644 --- a/tests/Nexus.Tests/DataWriter/DataWriterFixture.cs +++ b/tests/Nexus.Tests/DataWriter/DataWriterFixture.cs @@ -4,15 +4,15 @@ namespace DataWriter; public class DataWriterFixture : IDisposable { - readonly List _targetFolders = new(); + readonly List _targetFolders = []; public DataWriterFixture() { // catalog 1 var representations1 = new List() { - new Representation(dataType: NexusDataType.FLOAT32, samplePeriod: TimeSpan.FromSeconds(1)), - new Representation(dataType: NexusDataType.FLOAT64, samplePeriod: TimeSpan.FromSeconds(10)), + new(dataType: NexusDataType.FLOAT32, samplePeriod: TimeSpan.FromSeconds(1)), + new(dataType: NexusDataType.FLOAT64, samplePeriod: TimeSpan.FromSeconds(10)), }; var resourceBuilder1 = new ResourceBuilder(id: "resource1") @@ -37,7 +37,7 @@ public DataWriterFixture() .WithProperty("my-custom-parameter3", "my-custom-value3") .AddResource(resourceBuilder2.Build()); - Catalogs = new[] { catalogBuilder1.Build(), catalogBuilder2.Build() }; + Catalogs = [catalogBuilder1.Build(), catalogBuilder2.Build()]; } public ResourceCatalog[] Catalogs { get; } diff --git a/tests/Nexus.Tests/Other/CatalogContainersExtensionsTests.cs b/tests/Nexus.Tests/Other/CatalogContainersExtensionsTests.cs index c230b240..c27cc1f0 100644 --- a/tests/Nexus.Tests/Other/CatalogContainersExtensionsTests.cs +++ b/tests/Nexus.Tests/Other/CatalogContainersExtensionsTests.cs @@ -25,29 +25,29 @@ public async Task CanTryFindCatalogContainer() { "/" => new CatalogContainer[] { - new CatalogContainer(new CatalogRegistration("/A", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!), + new(new CatalogRegistration("/A", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!), }, - "/A" => new CatalogContainer[] - { + "/A" => + [ new CatalogContainer(new CatalogRegistration("/A/C", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!), new CatalogContainer(new CatalogRegistration("/A/B", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!), new CatalogContainer(new CatalogRegistration("/A/D", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!) - }, - "/A/B" => new CatalogContainer[] - { + ], + "/A/B" => + [ new CatalogContainer(new CatalogRegistration("/A/B/D", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!), new CatalogContainer(new CatalogRegistration("/A/B/C", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!) - }, - "/A/D" => new CatalogContainer[] - { + ], + "/A/D" => + [ new CatalogContainer(new CatalogRegistration("/A/D/F", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!), new CatalogContainer(new CatalogRegistration("/A/D/E", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!), new CatalogContainer(new CatalogRegistration("/A/D/E2", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!) - }, - "/A/F" => new CatalogContainer[] - { + ], + "/A/F" => + [ new CatalogContainer(new CatalogRegistration("/A/F/H", string.Empty), default!, default!, default!, default!, catalogManager, default!, default!) - }, + ], _ => throw new Exception($"Unsupported combination {container.Id}.") }); }); @@ -123,7 +123,7 @@ public async Task CanTryFind() { "/" => new CatalogContainer[] { - new CatalogContainer(new CatalogRegistration("/A/B/C", string.Empty), default!, default!, default!, default!, default!, default!, dataControllerService), + new(new CatalogRegistration("/A/B/C", string.Empty), default!, default!, default!, default!, default!, default!, dataControllerService), }, _ => throw new Exception("Unsupported combination.") }); diff --git a/tests/Nexus.Tests/Other/LoggingTests.cs b/tests/Nexus.Tests/Other/LoggingTests.cs index 21db804c..a8c4bac8 100644 --- a/tests/Nexus.Tests/Other/LoggingTests.cs +++ b/tests/Nexus.Tests/Other/LoggingTests.cs @@ -46,7 +46,7 @@ public void CanSerilog() Environment.SetEnvironmentVariable("NEXUS_SERILOG__ENRICH__1", "WithMachineName"); // 2. Build the configuration - var configuration = NexusOptionsBase.BuildConfiguration(Array.Empty()); + var configuration = NexusOptionsBase.BuildConfiguration([]); var serilogger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) diff --git a/tests/Nexus.Tests/Other/OptionsTests.cs b/tests/Nexus.Tests/Other/OptionsTests.cs index d5094696..ae051772 100644 --- a/tests/Nexus.Tests/Other/OptionsTests.cs +++ b/tests/Nexus.Tests/Other/OptionsTests.cs @@ -16,7 +16,7 @@ public class OptionsTests public void CanBindOptions(string section, Type optionsType) { var configuration = NexusOptionsBase - .BuildConfiguration(Array.Empty()); + .BuildConfiguration([]); var options = (NexusOptionsBase)configuration .GetSection(section) @@ -29,7 +29,7 @@ public void CanBindOptions(string section, Type optionsType) public void CanReadAppsettingsJson() { var configuration = NexusOptionsBase - .BuildConfiguration(Array.Empty()); + .BuildConfiguration([]); var options = configuration .GetSection(DataOptions.Section) @@ -46,7 +46,7 @@ public void CanOverrideAppsettingsJson_With_Json() Environment.SetEnvironmentVariable("NEXUS_PATHS__SETTINGS", "myappsettings.json"); var configuration = NexusOptionsBase - .BuildConfiguration(Array.Empty()); + .BuildConfiguration([]); var options = configuration .GetSection(DataOptions.Section) @@ -66,7 +66,7 @@ public void CanOverrideIni_With_EnvironmentVariable() Environment.SetEnvironmentVariable("NEXUS_PATHS__SETTINGS", "myappsettings.ini"); var configuration1 = NexusOptionsBase - .BuildConfiguration(Array.Empty()); + .BuildConfiguration([]); var options1 = configuration1 .GetSection(DataOptions.Section) @@ -75,7 +75,7 @@ public void CanOverrideIni_With_EnvironmentVariable() Environment.SetEnvironmentVariable("NEXUS_DATA__AGGREGATIONNANTHRESHOLD", "0.90"); var configuration2 = NexusOptionsBase - .BuildConfiguration(Array.Empty()); + .BuildConfiguration([]); var options2 = configuration2 .GetSection(DataOptions.Section) @@ -105,7 +105,7 @@ public void CanOverrideEnvironmentVariable_With_CommandLineParameter(string arg) Environment.SetEnvironmentVariable("NEXUS_DATA__AGGREGATIONNANTHRESHOLD", "0.90"); var configuration = NexusOptionsBase - .BuildConfiguration(new string[] { arg }); + .BuildConfiguration([arg]); var options = configuration .GetSection(DataOptions.Section) diff --git a/tests/Nexus.Tests/Other/PackageControllerTests.cs b/tests/Nexus.Tests/Other/PackageControllerTests.cs index 473324bf..4df84647 100644 --- a/tests/Nexus.Tests/Other/PackageControllerTests.cs +++ b/tests/Nexus.Tests/Other/PackageControllerTests.cs @@ -195,10 +195,8 @@ private async Task Load_Run_and_Unload_Async( var dataSourceType = assembly .ExportedTypes - .First(type => typeof(IDataSource).IsAssignableFrom(type)); - - if (dataSourceType is null) - throw new Exception("data source type is null"); + .First(type => typeof(IDataSource).IsAssignableFrom(type)) + ?? throw new Exception("data source type is null"); // run diff --git a/tests/Nexus.Tests/Services/CacheServiceTests.cs b/tests/Nexus.Tests/Services/CacheServiceTests.cs index 548ab419..eb0cd801 100644 --- a/tests/Nexus.Tests/Services/CacheServiceTests.cs +++ b/tests/Nexus.Tests/Services/CacheServiceTests.cs @@ -130,8 +130,8 @@ public async Task CanUpdateCache() var expected = new DateTime[] { - new DateTime(2020, 01, 01, 0, 0, 0, DateTimeKind.Utc), - new DateTime(2020, 01, 02, 0, 0, 0, DateTimeKind.Utc) + new(2020, 01, 01, 0, 0, 0, DateTimeKind.Utc), + new(2020, 01, 02, 0, 0, 0, DateTimeKind.Utc) }; var databaseService = Mock.Of(); @@ -167,7 +167,7 @@ public async Task CanUpdateCache() var uncachedIntervals = new List { - new Interval(new DateTime(2020, 01, 01, 15, 0, 0, DateTimeKind.Utc), new DateTime(2020, 01, 02, 03, 0, 0, DateTimeKind.Utc)) + new(new DateTime(2020, 01, 01, 15, 0, 0, DateTimeKind.Utc), new DateTime(2020, 01, 02, 03, 0, 0, DateTimeKind.Utc)) }; var begin = new DateTime(2020, 01, 01, 0, 0, 0, DateTimeKind.Utc); diff --git a/tests/Nexus.Tests/Services/CatalogManagerTests.cs b/tests/Nexus.Tests/Services/CatalogManagerTests.cs index c474bf3f..f548d716 100644 --- a/tests/Nexus.Tests/Services/CatalogManagerTests.cs +++ b/tests/Nexus.Tests/Services/CatalogManagerTests.cs @@ -44,10 +44,10 @@ public async Task CanCreateCatalogHierarchy() return (type, path) switch { - ("A", "/") => Task.FromResult(new CatalogRegistration[] { new CatalogRegistration("/A", string.Empty), new CatalogRegistration("/B/A", string.Empty) }), - ("A", "/A/") => Task.FromResult(new CatalogRegistration[] { new CatalogRegistration("/A/B", string.Empty), new CatalogRegistration("/A/B/C", string.Empty), new CatalogRegistration("/A/C/A", string.Empty) }), - ("B", "/") => Task.FromResult(new CatalogRegistration[] { new CatalogRegistration("/A", string.Empty), new CatalogRegistration("/B/B", string.Empty), new CatalogRegistration("/B/B2", string.Empty) }), - ("C", "/") => Task.FromResult(new CatalogRegistration[] { new CatalogRegistration("/C/A", string.Empty) }), + ("A", "/") => Task.FromResult(new CatalogRegistration[] { new("/A", string.Empty), new("/B/A", string.Empty) }), + ("A", "/A/") => Task.FromResult(new CatalogRegistration[] { new("/A/B", string.Empty), new("/A/B/C", string.Empty), new("/A/C/A", string.Empty) }), + ("B", "/") => Task.FromResult(new CatalogRegistration[] { new("/A", string.Empty), new("/B/B", string.Empty), new("/B/B2", string.Empty) }), + ("C", "/") => Task.FromResult(new CatalogRegistration[] { new("/C/A", string.Empty) }), ("Nexus.Sources." + nameof(Sample), "/") => Task.FromResult(Array.Empty()), _ => throw new Exception("Unsupported combination.") }; @@ -119,8 +119,8 @@ public async Task CanCreateCatalogHierarchy() var userAClaims = new List { - new NexusClaim(Guid.NewGuid(), Claims.Name, usernameA), - new NexusClaim(Guid.NewGuid(), Claims.Role, NexusRoles.ADMINISTRATOR) + new(Guid.NewGuid(), Claims.Name, usernameA), + new(Guid.NewGuid(), Claims.Role, NexusRoles.ADMINISTRATOR) }; var userA = new NexusUser( @@ -135,7 +135,7 @@ public async Task CanCreateCatalogHierarchy() var userBClaims = new List { - new NexusClaim(Guid.NewGuid(), Claims.Name, usernameB), + new(Guid.NewGuid(), Claims.Name, usernameB), }; var userB = new NexusUser( diff --git a/tests/Nexus.Tests/Services/DataServiceTests.cs b/tests/Nexus.Tests/Services/DataServiceTests.cs index 4462b94b..a21dda98 100644 --- a/tests/Nexus.Tests/Services/DataServiceTests.cs +++ b/tests/Nexus.Tests/Services/DataServiceTests.cs @@ -125,7 +125,7 @@ public async Task CanExportAsync() End: end, FilePeriod: TimeSpan.FromSeconds(10), Type: "A", - ResourcePaths: new[] { catalogItem1.ToPath(), catalogItem2.ToPath() }, + ResourcePaths: [catalogItem1.ToPath(), catalogItem2.ToPath()], Configuration: default); // data service diff --git a/tests/Nexus.Tests/Services/MemoryTrackerTests.cs b/tests/Nexus.Tests/Services/MemoryTrackerTests.cs index 157a90ad..aba4e810 100644 --- a/tests/Nexus.Tests/Services/MemoryTrackerTests.cs +++ b/tests/Nexus.Tests/Services/MemoryTrackerTests.cs @@ -32,8 +32,8 @@ public async Task CanHandleMultipleRequests() var firstWaitingTask = memoryTracker.RegisterAllocationAsync(minimumByteCount: 70, maximumByteCount: 70, CancellationToken.None); var secondWaitingTask = memoryTracker.RegisterAllocationAsync(minimumByteCount: 80, maximumByteCount: 80, CancellationToken.None); - Assert.True(firstWaitingTask.Status != TaskStatus.RanToCompletion); - Assert.True(secondWaitingTask.Status != TaskStatus.RanToCompletion); + Assert.NotEqual(TaskStatus.RanToCompletion, firstWaitingTask.Status); + Assert.NotEqual(TaskStatus.RanToCompletion, secondWaitingTask.Status); // dispose first registration weAreWaiting.Set(); diff --git a/tests/Nexus.Tests/Services/TokenServiceTests.cs b/tests/Nexus.Tests/Services/TokenServiceTests.cs index 651deaf0..e95f7aa8 100644 --- a/tests/Nexus.Tests/Services/TokenServiceTests.cs +++ b/tests/Nexus.Tests/Services/TokenServiceTests.cs @@ -16,7 +16,7 @@ public async Task CanCreateToken() { // Arrange var filePath = Path.GetTempFileName(); - var tokenService = GetTokenService(filePath, new()); + var tokenService = GetTokenService(filePath, []); var description = "The description."; var expires = new DateTime(2020, 01, 01); var claim1Type = "claim1"; @@ -31,8 +31,8 @@ await tokenService.CreateAsync( expires, new List { - new TokenClaim(claim1Type, claim1Value), - new TokenClaim(claim2Type, claim2Value), + new(claim1Type, claim1Value), + new(claim2Type, claim2Value), } ); @@ -40,24 +40,20 @@ await tokenService.CreateAsync( var jsonString = File.ReadAllText(filePath); var actualTokenMap = JsonSerializer.Deserialize>(jsonString)!; - Assert.Collection( - actualTokenMap, - entry1 => + var entry1 = Assert.Single(actualTokenMap); + Assert.Equal(description, entry1.Value.Description); + Assert.Equal(expires, entry1.Value.Expires); + + Assert.Collection(entry1.Value.Claims, + entry1_1 => + { + Assert.Equal(claim1Type, entry1_1.Type); + Assert.Equal(claim1Value, entry1_1.Value); + }, + entry1_2 => { - Assert.Equal(description, entry1.Value.Description); - Assert.Equal(expires, entry1.Value.Expires); - - Assert.Collection(entry1.Value.Claims, - entry1_1 => - { - Assert.Equal(claim1Type, entry1_1.Type); - Assert.Equal(claim1Value, entry1_1.Value); - }, - entry1_2 => - { - Assert.Equal(claim2Type, entry1_2.Type); - Assert.Equal(claim2Value, entry1_2.Value); - }); + Assert.Equal(claim2Type, entry1_2.Type); + Assert.Equal(claim2Value, entry1_2.Value); }); } @@ -202,7 +198,7 @@ public async Task CanGetAllTokens() Assert.Equal(expected, actual); } - private ITokenService GetTokenService(string filePath, Dictionary tokenMap) + private static ITokenService GetTokenService(string filePath, Dictionary tokenMap) { var databaseService = Mock.Of(); diff --git a/tests/clients/dotnet-client-tests/ClientTests.cs b/tests/clients/dotnet-client-tests/ClientTests.cs index 914a8565..5fdcd9fe 100644 --- a/tests/clients/dotnet-client-tests/ClientTests.cs +++ b/tests/clients/dotnet-client-tests/ClientTests.cs @@ -75,7 +75,8 @@ public async Task CanAddConfigurationAsync() headers => { Assert.NotNull(headers); - Assert.Collection(headers, header => Assert.Equal(encodedJson, header)); + var header = Assert.Single(headers); + Assert.Equal(encodedJson, header); }, Assert.Null); } diff --git a/tests/extensibility/dotnet-extensibility-tests/DataModelTests.cs b/tests/extensibility/dotnet-extensibility-tests/DataModelTests.cs index 03607a61..763ec25f 100644 --- a/tests/extensibility/dotnet-extensibility-tests/DataModelTests.cs +++ b/tests/extensibility/dotnet-extensibility-tests/DataModelTests.cs @@ -4,14 +4,10 @@ namespace Nexus.Extensibility.Tests; -public class DataModelTests : IClassFixture +public class DataModelTests(DataModelFixture fixture) + : IClassFixture { - private readonly DataModelFixture _fixture; - - public DataModelTests(DataModelFixture fixture) - { - _fixture = fixture; - } + private readonly DataModelFixture _fixture = fixture; [Theory] @@ -200,9 +196,9 @@ static void action() id: "/C", resources: new List() { - new Resource(id: "R1"), - new Resource(id: "R2"), - new Resource(id: "R2") + new(id: "R1"), + new(id: "R2"), + new(id: "R2") }); } @@ -218,16 +214,16 @@ public void ResourceMergeThrowsForNonEqualRepresentations() id: "myresource", representations: new List() { - new Representation(dataType: NexusDataType.FLOAT32, samplePeriod: TimeSpan.FromSeconds(1)) + new(dataType: NexusDataType.FLOAT32, samplePeriod: TimeSpan.FromSeconds(1)) }); var resource2 = new Resource( id: "myresource", representations: new List() { - new Representation(dataType: NexusDataType.FLOAT64, samplePeriod: TimeSpan.FromSeconds(1)), - new Representation(dataType: NexusDataType.FLOAT32, samplePeriod: TimeSpan.FromSeconds(2)), - new Representation(dataType: NexusDataType.FLOAT32, samplePeriod: TimeSpan.FromSeconds(3)) + new(dataType: NexusDataType.FLOAT64, samplePeriod: TimeSpan.FromSeconds(1)), + new(dataType: NexusDataType.FLOAT32, samplePeriod: TimeSpan.FromSeconds(2)), + new(dataType: NexusDataType.FLOAT32, samplePeriod: TimeSpan.FromSeconds(3)) }); // Act @@ -262,8 +258,8 @@ public void CanFindCatalogItem() var catalog = new ResourceCatalog(id: "/A/B/C", resources: new List() { resource }); var catalogItem = new CatalogItem( - catalog with { Resources = default }, - resource with { Representations = default }, + catalog, + resource, representation, Parameters: default);