From d2490c8806bac7405d7608d6b30553cf2dcc2beb Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Fri, 26 Jan 2024 13:27:22 +0000 Subject: [PATCH] style: format code with dotnet-format This commit fixes the style issues introduced in 7dcb415 according to the output from dotnet-format. Details: None --- ...reCommunicationServicesAutoConfigurator.cs | 194 ++++++------ src/Communication/Email/EmailSenderOptions.cs | 88 +++--- src/Communication/Sms/SmsSender.cs | 74 ++--- src/Configuration/MultiServiceCollection.cs | 50 +-- .../DownstreamApiOptionsConfigurator.cs | 14 +- src/Http/ResponseCodes/ResponseCode.cs | 12 +- src/Mvc/ApiControllerBase.cs | 8 +- .../Produces405ErrorAttribute.cs | 3 +- src/Mvc/Result.cs | 3 +- src/Mvc/ViewControllerBase.cs | 8 +- .../Attributes/GenerateIdAttribute.cs | 14 +- .../AuthorizeResourceTagHelper.cs | 120 ++++---- .../Authorization/AuthorizeTagHelper.cs | 78 ++--- .../Bootstrap/ActiveAnchorTagHelper.cs | 120 ++++---- .../Bootstrap/FooterNavlinkTagHelper.cs | 104 +++---- src/TagHelpers/Bootstrap/InputTagHelper.cs | 170 +++++------ .../Navigation.No/NavDropdownLink.cs | 38 +-- .../Navigation.No/NavbarDropdownDivider.cs | 14 +- .../Navigation.No/NavbarDropdownTagHelper.cs | 60 ++-- .../Navigation.No/NavbarFormTagHelper.cs | 10 +- .../Navigation.No/NavbarLinkTagHelper.cs | 274 ++++++++--------- .../Bootstrap/Navigation.No/NavbarNavRight.cs | 14 +- .../Navigation.No/NavbarNavTagHelper.cs | 24 +- .../Navigation.No/NavbarTagHelper.cs | 284 +++++++++--------- .../Navigation.No/NavbarTextTagHelper.cs | 20 +- .../Bootstrap/PageElements/Footer.cs | 62 ++-- .../PageElements/FooterNavLinkHelper.cs | 94 +++--- .../Bootstrap/PageElements/PageHeader.cs | 44 +-- src/TagHelpers/Card/CardImageTagHelper.cs | 56 ++-- .../Carousel/CarouselItemTagHelper.cs | 114 +++---- src/TagHelpers/Components/FigureTagHelper.cs | 124 ++++---- src/TagHelpers/DgmjrTagHelperBase.cs | 190 ++++++------ .../Extensions/ColorInfoExtensions.cs | 14 +- .../Extensions/ContextAttributeExtensions.cs | 6 +- .../ConvertUrlAttributeExtensions.cs | 6 +- .../Extensions/CopyToOutputExtensions.cs | 6 +- src/TagHelpers/Extensions/InitExtensions.cs | 2 +- .../MandatoryPropertiesExtensions.cs | 6 +- .../MinimizableAttributeExtensions.cs | 6 +- .../Extensions/ProcessTagHelperExtensions.cs | 2 +- .../Extensions/TagHelperOutputExtensions.cs | 6 +- src/TagHelpers/Media/MediaImageTagHelper.cs | 80 ++--- 42 files changed, 1310 insertions(+), 1306 deletions(-) diff --git a/src/Communication/AzureCommunicationServicesAutoConfigurator.cs b/src/Communication/AzureCommunicationServicesAutoConfigurator.cs index 3de996e6..910d3b0e 100644 --- a/src/Communication/AzureCommunicationServicesAutoConfigurator.cs +++ b/src/Communication/AzureCommunicationServicesAutoConfigurator.cs @@ -24,101 +24,101 @@ public class AzureCommunicationServicesAutoConfigurator( ILogger logger ) : IConfigureIHostApplicationBuilder, IConfigureIApplicationBuilder, ILog { - public ConfigurationOrder Order => ConfigurationOrder.AnyTime; - - public ILogger Logger => logger; - - public void Configure(IApplicationBuilder builder) - { - var emailSenderOptions = builder.ApplicationServices.GetService< - IOptions - >(); - if (emailSenderOptions is null) - { - Logger.LogWarning( - "Azure Email Communication Services options are not configured. Please configure them in your appsettings.json file." - ); - } - var smsSenderOptions = builder.ApplicationServices.GetService>(); - if (smsSenderOptions is null) - { - Logger.LogWarning( - "Azure SMS Communication Services options are not configured. Please configure them in your appsettings.json file." - ); - } - } - - public void Configure(IHostApplicationBuilder builder) - { - var optionsSection = builder.Configuration.GetSection( - AzureCommunicationServicesOptionsBase.ConfigurationSectionName - ); - if (!optionsSection.Exists()) - { - Logger.LogWarning( - "Azure Communication Services options are not configured. Please configure them in your appsettings.json file." - ); - } - else - { - builder.Services.Configure(optionsSection); - - var emailCommunicationSection = builder.Configuration.GetSection( - EmailSenderOptions.ConfigurationSectionName - ); - if (!emailCommunicationSection.Exists()) - { - Logger.LogWarning( - "Azure Email Communication Services options are not configured. Please configure them in your appsettings.json file." - ); - builder.Services.AddSingleton( - y => - throw new KeyNotFoundException( - $"The {nameof(EmailSenderOptions)} configuration section was not found in the appsettings.json file." - ) - ); - } - else - { - builder.Services.Configure(emailCommunicationSection); - builder.Services.AddSingleton( - y => - new EmailSender( - y.GetService>() - ?? throw new KeyNotFoundException( - $"The {nameof(EmailSenderOptions)} configuration section was not found in the appsettings.json file." - ) - ) - ); - } - var smsCommunicationSection = builder.Configuration.GetSection( - SmsSenderOptions.ConfigurationSectionName - ); - if (!smsCommunicationSection.Exists()) - { - Logger.LogWarning( - "Azure SMS Communication Services options are not configured. Please configure them in your appsettings.json file." - ); - builder.Services.AddSingleton( - y => - throw new KeyNotFoundException( - $"The {nameof(SmsSenderOptions)} configuration section was not found in the appsettings.json file." - ) - ); - } - else - { - builder.Services.Configure(smsCommunicationSection); - builder.Services.AddSingleton( - y => - new SmsSender( - y.GetService>() - ?? throw new KeyNotFoundException( - $"The {nameof(SmsSenderOptions)} configuration section was not found in the appsettings.json file." - ) - ) - ); - } - } - } + public ConfigurationOrder Order => ConfigurationOrder.AnyTime; + +public ILogger Logger => logger; + +public void Configure(IApplicationBuilder builder) +{ + var emailSenderOptions = builder.ApplicationServices.GetService< + IOptions + >(); + if (emailSenderOptions is null) + { + Logger.LogWarning( + "Azure Email Communication Services options are not configured. Please configure them in your appsettings.json file." + ); + } + var smsSenderOptions = builder.ApplicationServices.GetService>(); + if (smsSenderOptions is null) + { + Logger.LogWarning( + "Azure SMS Communication Services options are not configured. Please configure them in your appsettings.json file." + ); + } +} + +public void Configure(IHostApplicationBuilder builder) +{ + var optionsSection = builder.Configuration.GetSection( + AzureCommunicationServicesOptionsBase.ConfigurationSectionName + ); + if (!optionsSection.Exists()) + { + Logger.LogWarning( + "Azure Communication Services options are not configured. Please configure them in your appsettings.json file." + ); + } + else + { + builder.Services.Configure(optionsSection); + + var emailCommunicationSection = builder.Configuration.GetSection( + EmailSenderOptions.ConfigurationSectionName + ); + if (!emailCommunicationSection.Exists()) + { + Logger.LogWarning( + "Azure Email Communication Services options are not configured. Please configure them in your appsettings.json file." + ); + builder.Services.AddSingleton( + y => + throw new KeyNotFoundException( + $"The {nameof(EmailSenderOptions)} configuration section was not found in the appsettings.json file." + ) + ); + } + else + { + builder.Services.Configure(emailCommunicationSection); + builder.Services.AddSingleton( + y => + new EmailSender( + y.GetService>() + ?? throw new KeyNotFoundException( + $"The {nameof(EmailSenderOptions)} configuration section was not found in the appsettings.json file." + ) + ) + ); + } + var smsCommunicationSection = builder.Configuration.GetSection( + SmsSenderOptions.ConfigurationSectionName + ); + if (!smsCommunicationSection.Exists()) + { + Logger.LogWarning( + "Azure SMS Communication Services options are not configured. Please configure them in your appsettings.json file." + ); + builder.Services.AddSingleton( + y => + throw new KeyNotFoundException( + $"The {nameof(SmsSenderOptions)} configuration section was not found in the appsettings.json file." + ) + ); + } + else + { + builder.Services.Configure(smsCommunicationSection); + builder.Services.AddSingleton( + y => + new SmsSender( + y.GetService>() + ?? throw new KeyNotFoundException( + $"The {nameof(SmsSenderOptions)} configuration section was not found in the appsettings.json file." + ) + ) + ); + } + } +} } diff --git a/src/Communication/Email/EmailSenderOptions.cs b/src/Communication/Email/EmailSenderOptions.cs index 018258d7..06d68b0c 100644 --- a/src/Communication/Email/EmailSenderOptions.cs +++ b/src/Communication/Email/EmailSenderOptions.cs @@ -22,48 +22,48 @@ public record class EmailSenderOptions : AzureCommunicationServicesOptions.Parse(connectionString); - return new EmailSenderOptions(options); - } - - [SetsRequiredMembers] - public EmailSenderOptions( - AzureCommunicationServicesOptionsBase options, - EmailAddress? defaultFrom = null - ) - { - DefaultFrom = defaultFrom ?? EmailAddress.Empty; - Endpoint = options.Endpoint; - AccessKey = options.AccessKey; - } - - [SetsRequiredMembers] - public EmailSenderOptions(AzureCommunicationServicesOptions options) - : base(options) - { - DefaultFrom = options.DefaultFrom; - AdminFrom = options.AdminFrom; - MassDistributionFrom = options.MassDistributionFrom; - SecurityFrom = options.SecurityFrom; - } - - [SetsRequiredMembers] - public EmailSenderOptions(string connectionString, EmailAddress? defaultFrom = null) - : this(Parse(connectionString) with { DefaultFrom = defaultFrom ?? EmailAddress.Empty }) { } - - [SetsRequiredMembers] - public EmailSenderOptions(string endpoint, string accessKey, EmailAddress? defaultFrom = null) - { - DefaultFrom = defaultFrom ?? EmailAddress.Empty; - Endpoint = endpoint; - AccessKey = accessKey; - } - - [SetsRequiredMembers] - public EmailSenderOptions() - : this(EmptyValue) { } + public override required EmailAddress DefaultFrom { get; set; } + +public static new EmailSenderOptions Parse(string connectionString) +{ + var options = AzureCommunicationServicesOptions.Parse(connectionString); + return new EmailSenderOptions(options); +} + +[SetsRequiredMembers] +public EmailSenderOptions( + AzureCommunicationServicesOptionsBase options, + EmailAddress? defaultFrom = null +) +{ + DefaultFrom = defaultFrom ?? EmailAddress.Empty; + Endpoint = options.Endpoint; + AccessKey = options.AccessKey; +} + +[SetsRequiredMembers] +public EmailSenderOptions(AzureCommunicationServicesOptions options) + : base(options) +{ + DefaultFrom = options.DefaultFrom; + AdminFrom = options.AdminFrom; + MassDistributionFrom = options.MassDistributionFrom; + SecurityFrom = options.SecurityFrom; +} + +[SetsRequiredMembers] +public EmailSenderOptions(string connectionString, EmailAddress? defaultFrom = null) + : this(Parse(connectionString) with { DefaultFrom = defaultFrom ?? EmailAddress.Empty }) { } + +[SetsRequiredMembers] +public EmailSenderOptions(string endpoint, string accessKey, EmailAddress? defaultFrom = null) +{ + DefaultFrom = defaultFrom ?? EmailAddress.Empty; + Endpoint = endpoint; + AccessKey = accessKey; +} + +[SetsRequiredMembers] +public EmailSenderOptions() + : this(EmptyValue) { } } diff --git a/src/Communication/Sms/SmsSender.cs b/src/Communication/Sms/SmsSender.cs index 17a85d46..329b9905 100644 --- a/src/Communication/Sms/SmsSender.cs +++ b/src/Communication/Sms/SmsSender.cs @@ -33,41 +33,41 @@ public class SmsSender(SmsSenderOptions? options) : ISmsSender /// /// The options. /// - private readonly SmsSenderOptions _options = options; - - /// - /// Initializes a new instance of the class. - /// - /// The options. - public SmsSender(IOptions options) - : this(options?.Value) { } - - /// - /// Creates the client. - /// - /// An . - protected SmsClient CreateClient() => new(_options.ConnectionString); - - private SmsClient _client; - - /// - /// Gets the client. - /// - protected SmsClient Client => _client ??= CreateClient(); - - /// - /// Sends the sms asynchronously. - /// - /// The number of the recipient. - /// The message. - /// A ]]> - public async Task SendSmsAsync(PhoneNumber @to, string message) - { - return new SmsSendResult( - (await Client.SendAsync(from: _options.DefaultFrom, to: @to, message: message)).Value - ); - } - - public Task SendSmsAsync(string to, string message) => - SendSmsAsync(PhoneNumber.From(to), message); + private readonly SmsSenderOptions _options = options; + +/// +/// Initializes a new instance of the class. +/// +/// The options. +public SmsSender(IOptions options) + : this(options?.Value) { } + +/// +/// Creates the client. +/// +/// An . +protected SmsClient CreateClient() => new(_options.ConnectionString); + +private SmsClient _client; + +/// +/// Gets the client. +/// +protected SmsClient Client => _client ??= CreateClient(); + +/// +/// Sends the sms asynchronously. +/// +/// The number of the recipient. +/// The message. +/// A ]]> +public async Task SendSmsAsync(PhoneNumber @to, string message) +{ + return new SmsSendResult( + (await Client.SendAsync(from: _options.DefaultFrom, to: @to, message: message)).Value + ); +} + +public Task SendSmsAsync(string to, string message) => + SendSmsAsync(PhoneNumber.From(to), message); } diff --git a/src/Configuration/MultiServiceCollection.cs b/src/Configuration/MultiServiceCollection.cs index 7e5c9e60..a24dc252 100644 --- a/src/Configuration/MultiServiceCollection.cs +++ b/src/Configuration/MultiServiceCollection.cs @@ -6,29 +6,29 @@ public class MultiServiceCollection(params IServiceCollection[] collections) : MultiCollection(collections), IServiceCollection { - private readonly IServiceCollection[] _collections; - - public ServiceDescriptor this[int index] - { - get => _collections[0][index]; - set => throw new NotImplementedException(); - } - - public int IndexOf(ServiceDescriptor item) => _collections[0].IndexOf(item); - - public void Insert(int index, ServiceDescriptor item) - { - foreach (var collection in _collections) - { - collection.Insert(index, item); - } - } - - public void RemoveAt(int index) - { - foreach (var collection in _collections) - { - collection.RemoveAt(index); - } - } + private readonly IServiceCollection[] _collections; + +public ServiceDescriptor this[int index] +{ + get => _collections[0][index]; + set => throw new NotImplementedException(); +} + +public int IndexOf(ServiceDescriptor item) => _collections[0].IndexOf(item); + +public void Insert(int index, ServiceDescriptor item) +{ + foreach (var collection in _collections) + { + collection.Insert(index, item); + } +} + +public void RemoveAt(int index) +{ + foreach (var collection in _collections) + { + collection.RemoveAt(index); + } +} } diff --git a/src/DownstreamApis/DownstreamApiOptionsConfigurator.cs b/src/DownstreamApis/DownstreamApiOptionsConfigurator.cs index 4b4d916b..1e4c5e9e 100644 --- a/src/DownstreamApis/DownstreamApiOptionsConfigurator.cs +++ b/src/DownstreamApis/DownstreamApiOptionsConfigurator.cs @@ -6,11 +6,11 @@ namespace Dgmjr.Web.DownstreamApis; public class DownstreamApiOptionsConfigurator(IOptions jsonOptions) : IConfigureOptions { - private readonly Jso _jso = jsonOptions?.Value?.JsonSerializerOptions; - - public void Configure(DownstreamApiOptions options) - { - options.Serializer = requestObject => - new StringContent(Serialize(requestObject, _jso), UTF8, Application.Json.DisplayName); - } + private readonly Jso _jso = jsonOptions?.Value?.JsonSerializerOptions; + +public void Configure(DownstreamApiOptions options) +{ + options.Serializer = requestObject => + new StringContent(Serialize(requestObject, _jso), UTF8, Application.Json.DisplayName); +} } diff --git a/src/Http/ResponseCodes/ResponseCode.cs b/src/Http/ResponseCodes/ResponseCode.cs index 084abc39..1935c477 100644 --- a/src/Http/ResponseCodes/ResponseCode.cs +++ b/src/Http/ResponseCodes/ResponseCode.cs @@ -51,8 +51,8 @@ public enum StatusCode : ushort /// 200 /// [Display( - Name = "OK", - // Description = "The request has succeeded. The meaning of the success depends on the HTTP method:" + Name = "OK", + // Description = "The request has succeeded. The meaning of the success depends on the HTTP method:" Description = "Yay! You didn't fuck up!" )] [Uri($"{UriBase}200")] @@ -63,8 +63,8 @@ public enum StatusCode : ushort /// 201 /// [Display( - Name = "Created", - // Description = "The request has succeeded and a new resource has been created as a result. This is typically the response sent after a PUT request." + Name = "Created", + // Description = "The request has succeeded and a new resource has been created as a result. This is typically the response sent after a PUT request." Description = "I created the thing for you." )] [Uri($"{UriBase}201")] @@ -75,8 +75,8 @@ public enum StatusCode : ushort /// 202 /// [Display( - Name = "Accepted", - // Description = "The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing." + Name = "Accepted", + // Description = "The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing." Description = "I got it and you can go do other stuff while I work on it for you." )] [Uri($"{UriBase}202")] diff --git a/src/Mvc/ApiControllerBase.cs b/src/Mvc/ApiControllerBase.cs index f8a7d04c..a915ca41 100644 --- a/src/Mvc/ApiControllerBase.cs +++ b/src/Mvc/ApiControllerBase.cs @@ -20,8 +20,8 @@ namespace Dgmjr.AspNetCore.Mvc; public class ApiControllerBase(ILogger? logger = null) : ControllerBase, ILog { - public ILogger Logger => logger ?? new NullLogger(); - - public IActionResult Result(T value, string contentType) => - ControllerExtensions.Result(this, value, contentType); + public ILogger Logger => logger ?? new NullLogger(); + +public IActionResult Result(T value, string contentType) => + ControllerExtensions.Result(this, value, contentType); } diff --git a/src/Mvc/ProducesErrorAttributes/Produces405ErrorAttribute.cs b/src/Mvc/ProducesErrorAttributes/Produces405ErrorAttribute.cs index f195fae9..4d36e75b 100644 --- a/src/Mvc/ProducesErrorAttributes/Produces405ErrorAttribute.cs +++ b/src/Mvc/ProducesErrorAttributes/Produces405ErrorAttribute.cs @@ -25,5 +25,6 @@ public Produces405ErrorAttribute() Http.StatusCode.MethodNotAllowed.Description, typeof(MethodNotAllowedProblemDetails), ApplicationMediaTypeNames.ProblemJson - ) { } + ) + { } } diff --git a/src/Mvc/Result.cs b/src/Mvc/Result.cs index e71a7f68..21f5496b 100644 --- a/src/Mvc/Result.cs +++ b/src/Mvc/Result.cs @@ -23,7 +23,8 @@ public class Result : OneOfBase, IConvertToActio { public Result(T value, string contentType) : base(value is string ? new ContentResult { Content = value as string, ContentType = contentType, StatusCode = Status200OK } : - new ObjectResult(value) { ContentTypes = [contentType], StatusCode = Status200OK, DeclaredType = typeof(T) }) { } + new ObjectResult(value) { ContentTypes = [contentType], StatusCode = Status200OK, DeclaredType = typeof(T) }) + { } protected Result(ContentResult contentResult) : base(contentResult) { } protected Result(ObjectResult contentResult) : base(contentResult) { } diff --git a/src/Mvc/ViewControllerBase.cs b/src/Mvc/ViewControllerBase.cs index bb6c443b..ff1930ea 100644 --- a/src/Mvc/ViewControllerBase.cs +++ b/src/Mvc/ViewControllerBase.cs @@ -21,8 +21,8 @@ namespace Dgmjr.AspNetCore.Mvc; public class ViewControllerBase(ILogger? logger = null) : Controller, ILog { - public ILogger Logger => logger ?? new NullLogger(); - - public IActionResult Result(T value, string contentType) => - ControllerExtensions.Result(this, value, contentType); + public ILogger Logger => logger ?? new NullLogger(); + +public IActionResult Result(T value, string contentType) => + ControllerExtensions.Result(this, value, contentType); } diff --git a/src/TagHelpers/Attributes/GenerateIdAttribute.cs b/src/TagHelpers/Attributes/GenerateIdAttribute.cs index cabc9f58..447f7037 100644 --- a/src/TagHelpers/Attributes/GenerateIdAttribute.cs +++ b/src/TagHelpers/Attributes/GenerateIdAttribute.cs @@ -15,11 +15,11 @@ namespace Dgmjr.AspNetCore.TagHelpers.Attributes; [AttributeUsage(AttributeTargets.Class)] public class GenerateIdAttribute(string prefix, bool renderIdAttribute = true) : Attribute { - private string _id; - - public string Prefix { get; set; } = prefix; - - public bool RenderIdAttribute { get; set; } = renderIdAttribute; - - public string Id => _id ??= Prefix + guid.NewGuid().ToString("N"); + private string _id; + +public string Prefix { get; set; } = prefix; + +public bool RenderIdAttribute { get; set; } = renderIdAttribute; + +public string Id => _id ??= Prefix + guid.NewGuid().ToString("N"); } diff --git a/src/TagHelpers/Authorization/AuthorizeResourceTagHelper.cs b/src/TagHelpers/Authorization/AuthorizeResourceTagHelper.cs index 0a5d4bfd..0195d1da 100644 --- a/src/TagHelpers/Authorization/AuthorizeResourceTagHelper.cs +++ b/src/TagHelpers/Authorization/AuthorizeResourceTagHelper.cs @@ -22,64 +22,64 @@ IAuthorizationService authorizationService /// /// Gets or sets the policy name that determines access to the HTML block. /// - [HtmlAttributeName("asp-policy")] - public string Policy { get; set; } - - /// - /// Gets or sets a comma delimited list of roles that are allowed to access the HTML block. - /// - [HtmlAttributeName("asp-requirement")] - public IAuthorizationRequirement Requirement { get; set; } - - /// - /// Gets or sets the resource to be authorized against a particular policy - /// - [HtmlAttributeName("asp-authorize-resource")] - public object Resource { get; set; } - - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - if (Resource == null) - { - throw new ArgumentException("Resource cannot be null"); - } - if (IsNullOrWhiteSpace(Policy) && Requirement == null) - { - throw new ArgumentException("Either Policy or Requirement must be specified"); - } - if (!IsNullOrWhiteSpace(Policy) && Requirement != null) - { - throw new ArgumentException( - "Policy and Requirement cannot be specified at the same time" - ); - } - - AuthorizationResult authorizeResult; - - if (!IsNullOrWhiteSpace(Policy)) - { - authorizeResult = await authorizationService.AuthorizeAsync( - httpContextAccessor.HttpContext.User, - Resource, - Policy - ); - } - else if (Requirement != null) - { - authorizeResult = await authorizationService.AuthorizeAsync( - httpContextAccessor.HttpContext.User, - Resource, - Requirement - ); - } - else - { - throw new ArgumentException("Either Policy or Requirement must be specified"); - } - - if (!authorizeResult.Succeeded) - { - output.SuppressOutput(); - } - } + [HtmlAttributeName("asp-policy")] +public string Policy { get; set; } + +/// +/// Gets or sets a comma delimited list of roles that are allowed to access the HTML block. +/// +[HtmlAttributeName("asp-requirement")] +public IAuthorizationRequirement Requirement { get; set; } + +/// +/// Gets or sets the resource to be authorized against a particular policy +/// +[HtmlAttributeName("asp-authorize-resource")] +public object Resource { get; set; } + +public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + if (Resource == null) + { + throw new ArgumentException("Resource cannot be null"); + } + if (IsNullOrWhiteSpace(Policy) && Requirement == null) + { + throw new ArgumentException("Either Policy or Requirement must be specified"); + } + if (!IsNullOrWhiteSpace(Policy) && Requirement != null) + { + throw new ArgumentException( + "Policy and Requirement cannot be specified at the same time" + ); + } + + AuthorizationResult authorizeResult; + + if (!IsNullOrWhiteSpace(Policy)) + { + authorizeResult = await authorizationService.AuthorizeAsync( + httpContextAccessor.HttpContext.User, + Resource, + Policy + ); + } + else if (Requirement != null) + { + authorizeResult = await authorizationService.AuthorizeAsync( + httpContextAccessor.HttpContext.User, + Resource, + Requirement + ); + } + else + { + throw new ArgumentException("Either Policy or Requirement must be specified"); + } + + if (!authorizeResult.Succeeded) + { + output.SuppressOutput(); + } +} } diff --git a/src/TagHelpers/Authorization/AuthorizeTagHelper.cs b/src/TagHelpers/Authorization/AuthorizeTagHelper.cs index 989c73f2..c9ed35f0 100644 --- a/src/TagHelpers/Authorization/AuthorizeTagHelper.cs +++ b/src/TagHelpers/Authorization/AuthorizeTagHelper.cs @@ -14,43 +14,43 @@ IPolicyEvaluator policyEvaluator /// /// Gets or sets the policy name that determines access to the HTML block. /// - [HtmlAttributeName("asp-policy")] - public string Policy { get; set; } - - /// - /// Gets or sets a comma delimited list of roles that are allowed to access the HTML block. - /// - [HtmlAttributeName("asp-roles")] - public string Roles { get; set; } - - /// - /// Gets or sets a comma delimited list of schemes from which user information is constructed. - /// - [HtmlAttributeName("asp-authentication-schemes")] - public string AuthenticationSchemes { get; set; } - - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - var policy = await AuthorizationPolicy.CombineAsync(policyProvider, new[] { this }); - - var authenticateResult = await policyEvaluator.AuthenticateAsync( - policy, - httpContextAccessor.HttpContext - ); - - var authorizeResult = await policyEvaluator.AuthorizeAsync( - policy, - authenticateResult, - httpContextAccessor.HttpContext, - null - ); - - if (!authorizeResult.Succeeded) - { - output.SuppressOutput(); - } - - if (output.Attributes.TryGetAttribute("asp-authorize", out TagHelperAttribute attribute)) - output.Attributes.Remove(attribute); - } + [HtmlAttributeName("asp-policy")] +public string Policy { get; set; } + +/// +/// Gets or sets a comma delimited list of roles that are allowed to access the HTML block. +/// +[HtmlAttributeName("asp-roles")] +public string Roles { get; set; } + +/// +/// Gets or sets a comma delimited list of schemes from which user information is constructed. +/// +[HtmlAttributeName("asp-authentication-schemes")] +public string AuthenticationSchemes { get; set; } + +public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + var policy = await AuthorizationPolicy.CombineAsync(policyProvider, new[] { this }); + + var authenticateResult = await policyEvaluator.AuthenticateAsync( + policy, + httpContextAccessor.HttpContext + ); + + var authorizeResult = await policyEvaluator.AuthorizeAsync( + policy, + authenticateResult, + httpContextAccessor.HttpContext, + null + ); + + if (!authorizeResult.Succeeded) + { + output.SuppressOutput(); + } + + if (output.Attributes.TryGetAttribute("asp-authorize", out TagHelperAttribute attribute)) + output.Attributes.Remove(attribute); +} } diff --git a/src/TagHelpers/Bootstrap/ActiveAnchorTagHelper.cs b/src/TagHelpers/Bootstrap/ActiveAnchorTagHelper.cs index b8b369e5..ba5f1d9b 100644 --- a/src/TagHelpers/Bootstrap/ActiveAnchorTagHelper.cs +++ b/src/TagHelpers/Bootstrap/ActiveAnchorTagHelper.cs @@ -15,64 +15,64 @@ namespace Dgmjr.AspNetCore.TagHelpers.Bootstrap; public class ActiveAnchorTagHelper(IHtmlGenerator generator) : Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper(generator) { - private bool? _isActive; - public bool IsActive - { - get => _isActive ?? ShouldBeActive(); - set => _isActive = value; - } - - public override int Order => int.MaxValue; - - public override void Process(TagHelperContext context, TagHelperOutput output) - { - // base.Process(context, output); - - if (IsActive) - { - var activeClass = output.Attributes.FirstOrDefault(a => a.Name == "class"); - if (activeClass != null) - { - output.Attributes.SetAttribute( - AttributeNames.Class, - activeClass.Value + " " + CssClasses.Active - ); - } - else - { - output.Attributes.SetAttribute(AttributeNames.Class, CssClasses.Active); - } - } - } - - private bool ShouldBeActive() - { - var currentController = ViewContext.RouteData.Values["Controller"]?.ToString(); - var currentAction = ViewContext.RouteData.Values["Action"]?.ToString(); - - if ( - !IsNullOrWhiteSpace(Controller) && Controller?.ToLower() != currentController?.ToLower() - ) - { - return false; - } - - if (!IsNullOrWhiteSpace(Action) && Action?.ToLower() != currentAction?.ToLower()) - { - return false; - } - - foreach (var routeValue in RouteValues) - { - if ( - !ViewContext.RouteData.Values.ContainsKey(routeValue.Key) - || ViewContext.RouteData.Values[routeValue.Key].ToString() != routeValue.Value - ) - { - return false; - } - } - - return true; - } + private bool? _isActive; +public bool IsActive +{ + get => _isActive ?? ShouldBeActive(); + set => _isActive = value; +} + +public override int Order => int.MaxValue; + +public override void Process(TagHelperContext context, TagHelperOutput output) +{ + // base.Process(context, output); + + if (IsActive) + { + var activeClass = output.Attributes.FirstOrDefault(a => a.Name == "class"); + if (activeClass != null) + { + output.Attributes.SetAttribute( + AttributeNames.Class, + activeClass.Value + " " + CssClasses.Active + ); + } + else + { + output.Attributes.SetAttribute(AttributeNames.Class, CssClasses.Active); + } + } +} + +private bool ShouldBeActive() +{ + var currentController = ViewContext.RouteData.Values["Controller"]?.ToString(); + var currentAction = ViewContext.RouteData.Values["Action"]?.ToString(); + + if ( + !IsNullOrWhiteSpace(Controller) && Controller?.ToLower() != currentController?.ToLower() + ) + { + return false; + } + + if (!IsNullOrWhiteSpace(Action) && Action?.ToLower() != currentAction?.ToLower()) + { + return false; + } + + foreach (var routeValue in RouteValues) + { + if ( + !ViewContext.RouteData.Values.ContainsKey(routeValue.Key) + || ViewContext.RouteData.Values[routeValue.Key].ToString() != routeValue.Value + ) + { + return false; + } + } + + return true; +} } diff --git a/src/TagHelpers/Bootstrap/FooterNavlinkTagHelper.cs b/src/TagHelpers/Bootstrap/FooterNavlinkTagHelper.cs index 2d4d2023..9e4b994c 100644 --- a/src/TagHelpers/Bootstrap/FooterNavlinkTagHelper.cs +++ b/src/TagHelpers/Bootstrap/FooterNavlinkTagHelper.cs @@ -17,56 +17,56 @@ namespace Dgmjr.AspNetCore.TagHelpers.Bootstrap; [HtmlTargetElement(TagNames.NavLink)] public class NavLinkTagHelper(IHtmlGenerator generator) : AnchorTagHelper(generator) { - protected IServiceProvider Services => ViewContext.HttpContext.RequestServices; - - private IUrlHelper _urlHelper; - - [HtmlAttributeNotBound] - public IUrlHelper UrlHelper - { - get => - _urlHelper ??= Services - .GetRequiredService() - .GetUrlHelper(ViewContext); - set => _urlHelper = value; - } - - private bool ShouldBeActive() - { - var currentController = ViewContext.RouteData.Values["Controller"]?.ToString(); - var currentAction = ViewContext.RouteData.Values["Action"]?.ToString(); - - if ( - !IsNullOrWhiteSpace(Controller) && Controller?.ToLower() != currentController?.ToLower() - ) - { - return false; - } - - if (!IsNullOrWhiteSpace(Action) && Action?.ToLower() != currentAction?.ToLower()) - { - return false; - } - - foreach (var routeValue in RouteValues) - { - if ( - !ViewContext.RouteData.Values.ContainsKey(routeValue.Key) - || ViewContext.RouteData.Values[routeValue.Key].ToString() != routeValue.Value - ) - { - return false; - } - } - - return true; - } - - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - if (ShouldBeActive()) - { - output.AddCssClass(CssClasses.Active); - } - } + protected IServiceProvider Services => ViewContext.HttpContext.RequestServices; + +private IUrlHelper _urlHelper; + +[HtmlAttributeNotBound] +public IUrlHelper UrlHelper +{ + get => + _urlHelper ??= Services + .GetRequiredService() + .GetUrlHelper(ViewContext); + set => _urlHelper = value; +} + +private bool ShouldBeActive() +{ + var currentController = ViewContext.RouteData.Values["Controller"]?.ToString(); + var currentAction = ViewContext.RouteData.Values["Action"]?.ToString(); + + if ( + !IsNullOrWhiteSpace(Controller) && Controller?.ToLower() != currentController?.ToLower() + ) + { + return false; + } + + if (!IsNullOrWhiteSpace(Action) && Action?.ToLower() != currentAction?.ToLower()) + { + return false; + } + + foreach (var routeValue in RouteValues) + { + if ( + !ViewContext.RouteData.Values.ContainsKey(routeValue.Key) + || ViewContext.RouteData.Values[routeValue.Key].ToString() != routeValue.Value + ) + { + return false; + } + } + + return true; +} + +public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + if (ShouldBeActive()) + { + output.AddCssClass(CssClasses.Active); + } +} } diff --git a/src/TagHelpers/Bootstrap/InputTagHelper.cs b/src/TagHelpers/Bootstrap/InputTagHelper.cs index 8534662a..83137556 100644 --- a/src/TagHelpers/Bootstrap/InputTagHelper.cs +++ b/src/TagHelpers/Bootstrap/InputTagHelper.cs @@ -11,89 +11,89 @@ namespace Dgmjr.AspNetCore.TagHelpers.Bootstrap; public abstract class InputTagHelper(IHtmlGenerator generator) : Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper(generator) { - [HtmlAttributeName(AttributeNames.Type)] - public virtual InputType InputType - { - get => Enum.TryParse(InputTypeName, out var value) ? value : InputType.Text; - set => InputTypeName = value.ToString().ToLower(); - } - - [HtmlAttributeName(AttributeNames.Placeholder)] - public string? Placeholder { get; set; } - - [HtmlAttributeName(AttributeNames.MarginBottom)] - public int? MarginBottom { get; set; } = 3; - - protected string MarginBottomCssClass => - MarginBottom.HasValue ? $"mb-{MarginBottom}" : string.Empty; - - [HtmlAttributeName(AttributeNames.Label)] - public string? Label { get; set; } - - [HtmlAttributeName(AttributeNames.TextBefore)] - public string? TextBefore { get; set; } - - [HtmlAttributeName(AttributeNames.TextAfter)] - public string? TextAfter { get; set; } - - [HtmlAttributeName(AttributeNames.BsLabelPosition)] - public LabelPosition LabelPosition { get; set; } = - Dgmjr.AspNetCore.TagHelpers.Enumerations.LabelPosition.Default; - - [HtmlAttributeName(AttributeNames.Id)] - public string Id - { - get => _id ??= guid.NewGuid().ToString(); - set => _id = value; - } - private string? _id; - - public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - output.AddCssClass("form-control"); - - var divTagBuilder = new TagBuilder(TagNames.Div); - - divTagBuilder.AddCssClass("form-group"); - divTagBuilder.AddCssClass(MarginBottomCssClass); - - if (Placeholder is not null) - { - output.Attributes.SetAttribute(AttributeNames.Placeholder, Placeholder); - } - - if (Label is not null) - { - output.PreElement.AppendHtmlLine($"
"); - switch (LabelPosition) - { - case LabelPosition.Default: - output.PreElement.AppendHtmlLine($"{Label}"); - break; - case LabelPosition.Left: - output.PreElement.AppendHtmlLine( - $"{Label}" - ); - break; - case LabelPosition.Right: - output.PostElement.AppendHtmlLine( - $"{Label}" - ); - break; - case LabelPosition.Floating: - output.PostElement.AppendHtmlLine( - $"" - ); - break; - } - output.PreElement.AppendHtml( - $"" - ); - } - - output.PreElement.SetHtmlContent($"
"); - output.PostElement.SetHtmlContent("
"); - - return base.ProcessAsync(context, output); - } + [HtmlAttributeName(AttributeNames.Type)] +public virtual InputType InputType +{ + get => Enum.TryParse(InputTypeName, out var value) ? value : InputType.Text; + set => InputTypeName = value.ToString().ToLower(); +} + +[HtmlAttributeName(AttributeNames.Placeholder)] +public string? Placeholder { get; set; } + +[HtmlAttributeName(AttributeNames.MarginBottom)] +public int? MarginBottom { get; set; } = 3; + +protected string MarginBottomCssClass => + MarginBottom.HasValue ? $"mb-{MarginBottom}" : string.Empty; + +[HtmlAttributeName(AttributeNames.Label)] +public string? Label { get; set; } + +[HtmlAttributeName(AttributeNames.TextBefore)] +public string? TextBefore { get; set; } + +[HtmlAttributeName(AttributeNames.TextAfter)] +public string? TextAfter { get; set; } + +[HtmlAttributeName(AttributeNames.BsLabelPosition)] +public LabelPosition LabelPosition { get; set; } = + Dgmjr.AspNetCore.TagHelpers.Enumerations.LabelPosition.Default; + +[HtmlAttributeName(AttributeNames.Id)] +public string Id +{ + get => _id ??= guid.NewGuid().ToString(); + set => _id = value; +} +private string? _id; + +public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + output.AddCssClass("form-control"); + + var divTagBuilder = new TagBuilder(TagNames.Div); + + divTagBuilder.AddCssClass("form-group"); + divTagBuilder.AddCssClass(MarginBottomCssClass); + + if (Placeholder is not null) + { + output.Attributes.SetAttribute(AttributeNames.Placeholder, Placeholder); + } + + if (Label is not null) + { + output.PreElement.AppendHtmlLine($"
"); + switch (LabelPosition) + { + case LabelPosition.Default: + output.PreElement.AppendHtmlLine($"{Label}"); + break; + case LabelPosition.Left: + output.PreElement.AppendHtmlLine( + $"{Label}" + ); + break; + case LabelPosition.Right: + output.PostElement.AppendHtmlLine( + $"{Label}" + ); + break; + case LabelPosition.Floating: + output.PostElement.AppendHtmlLine( + $"" + ); + break; + } + output.PreElement.AppendHtml( + $"" + ); + } + + output.PreElement.SetHtmlContent($"
"); + output.PostElement.SetHtmlContent("
"); + + return base.ProcessAsync(context, output); +} } diff --git a/src/TagHelpers/Bootstrap/Navigation.No/NavDropdownLink.cs b/src/TagHelpers/Bootstrap/Navigation.No/NavDropdownLink.cs index 14dd1c2c..52d96dc2 100644 --- a/src/TagHelpers/Bootstrap/Navigation.No/NavDropdownLink.cs +++ b/src/TagHelpers/Bootstrap/Navigation.No/NavDropdownLink.cs @@ -16,23 +16,23 @@ namespace No.Dgmjr.AspNetCore.TagHelpers.Bootstrap; public class NavDropdownLink(IHtmlGenerator generator) : AnchorTagHelper(generator) { #region --- Attribute Names --- - - private const string TitleAttributeName = "title"; - - #endregion - - #region --- Properties --- - - [HtmlAttributeName(TitleAttributeName)] - public string Title { get; set; } - - #endregion - - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - var childContent = await output.GetChildContentAsync(); - - output.TagName = TagNames.Anchor; - output.AddCssClass("dropdown-item"); - } + +private const string TitleAttributeName = "title"; + +#endregion + +#region --- Properties --- + +[HtmlAttributeName(TitleAttributeName)] +public string Title { get; set; } + +#endregion + +public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + var childContent = await output.GetChildContentAsync(); + + output.TagName = TagNames.Anchor; + output.AddCssClass("dropdown-item"); +} } diff --git a/src/TagHelpers/Bootstrap/Navigation.No/NavbarDropdownDivider.cs b/src/TagHelpers/Bootstrap/Navigation.No/NavbarDropdownDivider.cs index 4cb5fffa..23bf410f 100644 --- a/src/TagHelpers/Bootstrap/Navigation.No/NavbarDropdownDivider.cs +++ b/src/TagHelpers/Bootstrap/Navigation.No/NavbarDropdownDivider.cs @@ -14,11 +14,11 @@ namespace No.Dgmjr.AspNetCore.TagHelpers.Bootstrap; public class NavbarDropdownDividerTagHelper() : DgmjrTagHelperBase(TagNames.Divider) { - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - await base.ProcessAsync(context, output); - output.TagName = TagNames.Divider; - output.AddCssClass(CssClasses.DropdownDivider); - output.WrapOutside($"<{TagNames.Li}>", $""); - } + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + await base.ProcessAsync(context, output); + output.TagName = TagNames.Divider; + output.AddCssClass(CssClasses.DropdownDivider); + output.WrapOutside($"<{TagNames.Li}>", $""); +} }; diff --git a/src/TagHelpers/Bootstrap/Navigation.No/NavbarDropdownTagHelper.cs b/src/TagHelpers/Bootstrap/Navigation.No/NavbarDropdownTagHelper.cs index becc024b..88b95961 100644 --- a/src/TagHelpers/Bootstrap/Navigation.No/NavbarDropdownTagHelper.cs +++ b/src/TagHelpers/Bootstrap/Navigation.No/NavbarDropdownTagHelper.cs @@ -20,34 +20,34 @@ namespace No.Dgmjr.AspNetCore.TagHelpers.Bootstrap; public class NavbarDropdownTagHelper() : DgmjrTagHelperBase(TagNames.Li) { #region --- Attribute Names --- - - private const string TitleAttributeName = "title"; - - #endregion - - #region --- Properties --- - - [HtmlAttributeName(TitleAttributeName)] - public string Title { get; set; } - - #endregion - - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - await output.GetChildContentAsync(); - - output.TagName = "li"; - output.AddCssClass("nav-item dropdown"); - - // Dropdown Button - output.PreContent.AppendHtml( - $"" - ); - - // Dropdown Items - output.PreContent.AppendHtml( - $"
" - ); - output.PostContent.AppendHtml("
"); - } + +private const string TitleAttributeName = "title"; + +#endregion + +#region --- Properties --- + +[HtmlAttributeName(TitleAttributeName)] +public string Title { get; set; } + +#endregion + +public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + await output.GetChildContentAsync(); + + output.TagName = "li"; + output.AddCssClass("nav-item dropdown"); + + // Dropdown Button + output.PreContent.AppendHtml( + $"" + ); + + // Dropdown Items + output.PreContent.AppendHtml( + $"
" + ); + output.PostContent.AppendHtml("
"); +} } diff --git a/src/TagHelpers/Bootstrap/Navigation.No/NavbarFormTagHelper.cs b/src/TagHelpers/Bootstrap/Navigation.No/NavbarFormTagHelper.cs index 103fd2e2..8d6280d7 100644 --- a/src/TagHelpers/Bootstrap/Navigation.No/NavbarFormTagHelper.cs +++ b/src/TagHelpers/Bootstrap/Navigation.No/NavbarFormTagHelper.cs @@ -4,9 +4,9 @@ [HtmlTargetElement(TagNames.NavForm, ParentTag = TagNames.Navbar)] public class NavbarFormTagHelper() : DgmjrTagHelperBase(TagNames.Form) { - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - output.TagName = "form"; - output.AddCssClass("form-inline"); - } + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + output.TagName = "form"; + output.AddCssClass("form-inline"); +} } diff --git a/src/TagHelpers/Bootstrap/Navigation.No/NavbarLinkTagHelper.cs b/src/TagHelpers/Bootstrap/Navigation.No/NavbarLinkTagHelper.cs index e0a2b22a..b9742831 100644 --- a/src/TagHelpers/Bootstrap/Navigation.No/NavbarLinkTagHelper.cs +++ b/src/TagHelpers/Bootstrap/Navigation.No/NavbarLinkTagHelper.cs @@ -11,141 +11,141 @@ namespace No.Dgmjr.AspNetCore.TagHelpers.Bootstrap; public class NavbarLinkTagHelper(IHtmlGenerator generator) : AnchorTagHelper(generator) { #region --- Attribute Names --- - - private const string ActiveAttributeName = "active"; - private const string DisableAttributeName = "disable"; - - #endregion - - #region --- Properties --- - - private bool? _active; - - [HtmlAttributeName(ActiveAttributeName)] - public bool Active - { - get => _active ?? ShouldBeActive(); - set => _active = value; - } - - [HtmlAttributeName(DisableAttributeName)] - public bool IsDisabled { get; set; } - - // [HtmlAttributeName("href")] - // public string Href { get; set; } = string.Empty; - - // [HtmlAttributeName("asp-action")] - // public string Action { get; set; } = string.Empty; - - // [HtmlAttributeName("asp-controller")] - // public string Controller { get; set; } = string.Empty; - - // [HtmlAttributeName("asp-area")] - // public string Area { get; set; } = string.Empty; - - // [HtmlAttributeName("asp-route-")] - // public IStringDictionary RouteValues { get; set; } = new StringDictionary(); - protected IServiceProvider Services => ViewContext.HttpContext.RequestServices; - - private IUrlHelper _urlHelper; - - [HtmlAttributeNotBound] - public IUrlHelper UrlHelper - { - get => - _urlHelper ??= Services - .GetRequiredService() - .GetUrlHelper(ViewContext); - set => _urlHelper = value; - } - #endregion - - private bool ShouldBeActive() - { - var currentController = ViewContext.RouteData.Values["Controller"]?.ToString(); - var currentAction = ViewContext.RouteData.Values["Action"]?.ToString(); - - if ( - !IsNullOrWhiteSpace(Controller) && Controller?.ToLower() != currentController?.ToLower() - ) - { - return false; - } - - if (!IsNullOrWhiteSpace(Action) && Action?.ToLower() != currentAction?.ToLower()) - { - return false; - } - - foreach (var routeValue in RouteValues) - { - if ( - !ViewContext.RouteData.Values.ContainsKey(routeValue.Key) - || ViewContext.RouteData.Values[routeValue.Key].ToString() != routeValue.Value - ) - { - return false; - } - } - - return true; - } - - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - output.TagName = "a"; - output.AddCssClass( - !context.HasContextItem() ? "nav-link" : "dropdown-item" - ); - - // Href - if (!IsNullOrEmpty(Route)) - { - output.Attributes.Add(AttributeNames.Href, Route); - } - else - { - var url = UrlHelper.ActionLink(Action, Controller, new { area = Area }); - output.Attributes.Add(AttributeNames.Href, url); - } - - // Disabled - if (IsDisabled) - { - output.AddCssClass("disabled"); - } - - // Active - if (Active && context.HasContextItem()) - { - output.AddCssClass("active"); - output.PostContent.AppendHtml( - $"(current)" - ); - } - else if (Active && !context.HasContextItem()) - { - output.PostContent.AppendHtml( - $"(current)" - ); - output.WrapHtmlOutside($"
  • ", "
  • "); - } - else if (!context.HasContextItem()) - { - output.WrapHtmlOutside($"
  • ", "
  • "); - } - } - - // private bool IsActive() - // { - // var path = ViewContext.HttpContext.Request.Path; - // var href = Href; - - // if (href == "/") - // { - // return path == href; - // } - - // return path.StartsWithSegments(href); - // } + +private const string ActiveAttributeName = "active"; +private const string DisableAttributeName = "disable"; + +#endregion + +#region --- Properties --- + +private bool? _active; + +[HtmlAttributeName(ActiveAttributeName)] +public bool Active +{ + get => _active ?? ShouldBeActive(); + set => _active = value; +} + +[HtmlAttributeName(DisableAttributeName)] +public bool IsDisabled { get; set; } + +// [HtmlAttributeName("href")] +// public string Href { get; set; } = string.Empty; + +// [HtmlAttributeName("asp-action")] +// public string Action { get; set; } = string.Empty; + +// [HtmlAttributeName("asp-controller")] +// public string Controller { get; set; } = string.Empty; + +// [HtmlAttributeName("asp-area")] +// public string Area { get; set; } = string.Empty; + +// [HtmlAttributeName("asp-route-")] +// public IStringDictionary RouteValues { get; set; } = new StringDictionary(); +protected IServiceProvider Services => ViewContext.HttpContext.RequestServices; + +private IUrlHelper _urlHelper; + +[HtmlAttributeNotBound] +public IUrlHelper UrlHelper +{ + get => + _urlHelper ??= Services + .GetRequiredService() + .GetUrlHelper(ViewContext); + set => _urlHelper = value; +} +#endregion + +private bool ShouldBeActive() +{ + var currentController = ViewContext.RouteData.Values["Controller"]?.ToString(); + var currentAction = ViewContext.RouteData.Values["Action"]?.ToString(); + + if ( + !IsNullOrWhiteSpace(Controller) && Controller?.ToLower() != currentController?.ToLower() + ) + { + return false; + } + + if (!IsNullOrWhiteSpace(Action) && Action?.ToLower() != currentAction?.ToLower()) + { + return false; + } + + foreach (var routeValue in RouteValues) + { + if ( + !ViewContext.RouteData.Values.ContainsKey(routeValue.Key) + || ViewContext.RouteData.Values[routeValue.Key].ToString() != routeValue.Value + ) + { + return false; + } + } + + return true; +} + +public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + output.TagName = "a"; + output.AddCssClass( + !context.HasContextItem() ? "nav-link" : "dropdown-item" + ); + + // Href + if (!IsNullOrEmpty(Route)) + { + output.Attributes.Add(AttributeNames.Href, Route); + } + else + { + var url = UrlHelper.ActionLink(Action, Controller, new { area = Area }); + output.Attributes.Add(AttributeNames.Href, url); + } + + // Disabled + if (IsDisabled) + { + output.AddCssClass("disabled"); + } + + // Active + if (Active && context.HasContextItem()) + { + output.AddCssClass("active"); + output.PostContent.AppendHtml( + $"(current)" + ); + } + else if (Active && !context.HasContextItem()) + { + output.PostContent.AppendHtml( + $"(current)" + ); + output.WrapHtmlOutside($"
  • ", "
  • "); + } + else if (!context.HasContextItem()) + { + output.WrapHtmlOutside($"
  • ", "
  • "); + } +} + +// private bool IsActive() +// { +// var path = ViewContext.HttpContext.Request.Path; +// var href = Href; + +// if (href == "/") +// { +// return path == href; +// } + +// return path.StartsWithSegments(href); +// } } diff --git a/src/TagHelpers/Bootstrap/Navigation.No/NavbarNavRight.cs b/src/TagHelpers/Bootstrap/Navigation.No/NavbarNavRight.cs index 320459e1..82b2a4c9 100644 --- a/src/TagHelpers/Bootstrap/Navigation.No/NavbarNavRight.cs +++ b/src/TagHelpers/Bootstrap/Navigation.No/NavbarNavRight.cs @@ -18,11 +18,11 @@ namespace No.Dgmjr.AspNetCore.TagHelpers.Bootstrap; public class NavbarNavRightTagHelper(IActionContextAccessor actionContextAccessor) : NavbarNavTagHelper(actionContextAccessor) { - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - await base.ProcessAsync(context, output); - output.AddCssClass(CssClasses.Nav); - output.AddCssClass(CssClasses.NavbarNav); - output.AddCssClass(CssClasses.NavRight); - } + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + await base.ProcessAsync(context, output); + output.AddCssClass(CssClasses.Nav); + output.AddCssClass(CssClasses.NavbarNav); + output.AddCssClass(CssClasses.NavRight); +} } diff --git a/src/TagHelpers/Bootstrap/Navigation.No/NavbarNavTagHelper.cs b/src/TagHelpers/Bootstrap/Navigation.No/NavbarNavTagHelper.cs index 2780dc87..4b9165d2 100644 --- a/src/TagHelpers/Bootstrap/Navigation.No/NavbarNavTagHelper.cs +++ b/src/TagHelpers/Bootstrap/Navigation.No/NavbarNavTagHelper.cs @@ -10,16 +10,16 @@ public class NavbarNavTagHelper(IActionContextAccessor actionContextAccessor) IHaveAnActionContextAccessor, IIdentifiable { - public IActionContextAccessor ActionContextAccessor => actionContextAccessor; - - [CopyToOutput] - public string Id { get; set; } = guid.NewGuid().ToString()[..8]; - - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - await base.ProcessAsync(context, output); - output.TagName = "ul"; - output.AddCssClass(CssClasses.Nav); - output.AddCssClass(CssClasses.NavbarNav); - } + public IActionContextAccessor ActionContextAccessor => actionContextAccessor; + +[CopyToOutput] +public string Id { get; set; } = guid.NewGuid().ToString()[..8]; + +public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + await base.ProcessAsync(context, output); + output.TagName = "ul"; + output.AddCssClass(CssClasses.Nav); + output.AddCssClass(CssClasses.NavbarNav); +} } diff --git a/src/TagHelpers/Bootstrap/Navigation.No/NavbarTagHelper.cs b/src/TagHelpers/Bootstrap/Navigation.No/NavbarTagHelper.cs index be2a3c06..fdf02f55 100644 --- a/src/TagHelpers/Bootstrap/Navigation.No/NavbarTagHelper.cs +++ b/src/TagHelpers/Bootstrap/Navigation.No/NavbarTagHelper.cs @@ -27,146 +27,146 @@ public class NavbarTagHelper(IActionContextAccessor actionContextAccessor) + "," + ThemeAttributeName + "," - + BackgroundAttributeName; - private const string BrandTextAttributeName = "brand-text"; - private const string BrandImageAttributeName = "brand-image"; - private const string BrandHrefAttributeName = "brand-href"; - private const string BrandAreaAttributeName = "brand-area"; - private const string BrandControllerAttributeName = "brand-controller"; - private const string BrandActionAttributeName = "brand-action"; - private const string ThemeAttributeName = "theme"; - private const string BackgroundAttributeName = "background"; - #endregion - - #region --- Properties --- - - public IActionContextAccessor ActionContextAccessor => actionContextAccessor; - - [HtmlAttributeName(BrandHrefAttributeName)] - public string BrandHref { get; set; } = "#"; - - [HtmlAttributeName(BrandAreaAttributeName)] - public string BrandArea { get; set; } = string.Empty; - - [HtmlAttributeName(BrandControllerAttributeName)] - public string BrandController { get; set; } = string.Empty; - - [HtmlAttributeName(BrandActionAttributeName)] - public string BrandAction { get; set; } = string.Empty; - - [HtmlAttributeName(BrandTextAttributeName)] - public string BrandText { get; set; } - - [HtmlAttributeName(BrandImageAttributeName)] - [ConvertVirtualUrl] - public string BrandImage { get; set; } - - [HtmlAttributeName(ThemeAttributeName)] - public Theme Theme { get; set; } = Theme.Light; - - [HtmlAttributeName(BackgroundAttributeName)] - public Color Background { get; set; } = Color.Light; - - [ViewContext] - [HtmlAttributeNotBound] - public ViewContext ViewContext { get; set; } - - [CopyToOutput] - public string Id { get; set; } = guid.NewGuid().ToString()[..8]; - - #endregion - - // public override void Init(TagHelperContext context) - // { - // this.Init(context, ActionContextAccessor); - // base.Init(context); - // } - - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - await output.GetChildContentAsync(); - - output.TagName = TagNames.Nav; - output.AddCssClass( - $"{CssClasses.Navbar} {CssClasses.NavbarExpandLg} {CssClasses.BgPrimary}" - ); - - // Theme - if (Theme != Theme.Default) - { - output.AddCssClass( - $"navbar-{Theme.GetEnumInfo().Name} data-bs-theme-{Theme.GetEnumInfo().Name}" - ); - - // Set background to valid color - Background = Theme == Theme.Dark && Background == Color.Light ? Color.Dark : Background; - } - else - { - output.AddCssClass(CssClasses.NavBarLight); - } - - // Background - output.AddCssClass(Background.GetColorInfo().BackgroundCssClass); - - // Brand - if (!IsNullOrEmpty(BrandText) || !IsNullOrEmpty(BrandImage)) - { - output.PreContent.AppendHtml(GenerateBrand()); - } - - // Toggler - output.PreContent.AppendHtml( - $"" - ); - - // Wrapper - output.WrapHtmlContentInside( - $"
    ", - "
    " - ); - } - - private string GetBrandHref() - { - // Href - if (!IsNullOrEmpty(BrandHref)) - { - return BrandHref; - } - else - { - var urlHelper = new UrlHelper(ViewContext); - return urlHelper.Action(BrandAction, BrandController, new { area = BrandArea }); - } - } - - private IHtmlContent GenerateBrand() - { - // Anchor - var brand = new TagBuilder(TagNames.Anchor); - brand.AddCssClass(CssClasses.NavBarBrand); - brand.Attributes.Add("href", GetBrandHref()); - - // Image - if (!IsNullOrEmpty(BrandImage)) - { - var img = new TagBuilder(TagNames.Img) { TagRenderMode = TagRenderMode.SelfClosing }; - img.Attributes.Add(AttributeNames.Src, BrandImage); - img.Attributes.Add("height", "30"); - img.Attributes.Add("alt", BrandText); - - if (!IsNullOrEmpty(BrandText)) - { - img.AddCssClass($"{CssClasses.DInlineBlock} {CssClasses.AlignTop}"); - } - - brand.InnerHtml.AppendHtml(img); - } - - // Text - brand.InnerHtml.Append($" {BrandText}"); - - return brand; - } + + BackgroundAttributeName; +private const string BrandTextAttributeName = "brand-text"; +private const string BrandImageAttributeName = "brand-image"; +private const string BrandHrefAttributeName = "brand-href"; +private const string BrandAreaAttributeName = "brand-area"; +private const string BrandControllerAttributeName = "brand-controller"; +private const string BrandActionAttributeName = "brand-action"; +private const string ThemeAttributeName = "theme"; +private const string BackgroundAttributeName = "background"; +#endregion + +#region --- Properties --- + +public IActionContextAccessor ActionContextAccessor => actionContextAccessor; + +[HtmlAttributeName(BrandHrefAttributeName)] +public string BrandHref { get; set; } = "#"; + +[HtmlAttributeName(BrandAreaAttributeName)] +public string BrandArea { get; set; } = string.Empty; + +[HtmlAttributeName(BrandControllerAttributeName)] +public string BrandController { get; set; } = string.Empty; + +[HtmlAttributeName(BrandActionAttributeName)] +public string BrandAction { get; set; } = string.Empty; + +[HtmlAttributeName(BrandTextAttributeName)] +public string BrandText { get; set; } + +[HtmlAttributeName(BrandImageAttributeName)] +[ConvertVirtualUrl] +public string BrandImage { get; set; } + +[HtmlAttributeName(ThemeAttributeName)] +public Theme Theme { get; set; } = Theme.Light; + +[HtmlAttributeName(BackgroundAttributeName)] +public Color Background { get; set; } = Color.Light; + +[ViewContext] +[HtmlAttributeNotBound] +public ViewContext ViewContext { get; set; } + +[CopyToOutput] +public string Id { get; set; } = guid.NewGuid().ToString()[..8]; + +#endregion + +// public override void Init(TagHelperContext context) +// { +// this.Init(context, ActionContextAccessor); +// base.Init(context); +// } + +public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + await output.GetChildContentAsync(); + + output.TagName = TagNames.Nav; + output.AddCssClass( + $"{CssClasses.Navbar} {CssClasses.NavbarExpandLg} {CssClasses.BgPrimary}" + ); + + // Theme + if (Theme != Theme.Default) + { + output.AddCssClass( + $"navbar-{Theme.GetEnumInfo().Name} data-bs-theme-{Theme.GetEnumInfo().Name}" + ); + + // Set background to valid color + Background = Theme == Theme.Dark && Background == Color.Light ? Color.Dark : Background; + } + else + { + output.AddCssClass(CssClasses.NavBarLight); + } + + // Background + output.AddCssClass(Background.GetColorInfo().BackgroundCssClass); + + // Brand + if (!IsNullOrEmpty(BrandText) || !IsNullOrEmpty(BrandImage)) + { + output.PreContent.AppendHtml(GenerateBrand()); + } + + // Toggler + output.PreContent.AppendHtml( + $"" + ); + + // Wrapper + output.WrapHtmlContentInside( + $"
    ", + "
    " + ); +} + +private string GetBrandHref() +{ + // Href + if (!IsNullOrEmpty(BrandHref)) + { + return BrandHref; + } + else + { + var urlHelper = new UrlHelper(ViewContext); + return urlHelper.Action(BrandAction, BrandController, new { area = BrandArea }); + } +} + +private IHtmlContent GenerateBrand() +{ + // Anchor + var brand = new TagBuilder(TagNames.Anchor); + brand.AddCssClass(CssClasses.NavBarBrand); + brand.Attributes.Add("href", GetBrandHref()); + + // Image + if (!IsNullOrEmpty(BrandImage)) + { + var img = new TagBuilder(TagNames.Img) { TagRenderMode = TagRenderMode.SelfClosing }; + img.Attributes.Add(AttributeNames.Src, BrandImage); + img.Attributes.Add("height", "30"); + img.Attributes.Add("alt", BrandText); + + if (!IsNullOrEmpty(BrandText)) + { + img.AddCssClass($"{CssClasses.DInlineBlock} {CssClasses.AlignTop}"); + } + + brand.InnerHtml.AppendHtml(img); + } + + // Text + brand.InnerHtml.Append($" {BrandText}"); + + return brand; +} } diff --git a/src/TagHelpers/Bootstrap/Navigation.No/NavbarTextTagHelper.cs b/src/TagHelpers/Bootstrap/Navigation.No/NavbarTextTagHelper.cs index 0f53e349..a074fc61 100644 --- a/src/TagHelpers/Bootstrap/Navigation.No/NavbarTextTagHelper.cs +++ b/src/TagHelpers/Bootstrap/Navigation.No/NavbarTextTagHelper.cs @@ -4,14 +4,14 @@ [HtmlTargetElement(TagNames.NavText, ParentTag = TagNames.NavbarNav)] public class NavbarTextTagHelper() : DgmjrTagHelperBase(TagNames.Li) { - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - await base.ProcessAsync(context, output); - output.TagName = TagNames.Li; - output.AddCssClass(CssClasses.NavItem); - output.AddCssClass(CssClasses.NavLink); - output.AddCssClass(CssClasses.NavText); - output.AddCssClass(CssClasses.Disabled); - output.AddCssClass(TagNames.NavText); - } + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + await base.ProcessAsync(context, output); + output.TagName = TagNames.Li; + output.AddCssClass(CssClasses.NavItem); + output.AddCssClass(CssClasses.NavLink); + output.AddCssClass(CssClasses.NavText); + output.AddCssClass(CssClasses.Disabled); + output.AddCssClass(TagNames.NavText); +} } diff --git a/src/TagHelpers/Bootstrap/PageElements/Footer.cs b/src/TagHelpers/Bootstrap/PageElements/Footer.cs index 151b9611..cb167c27 100644 --- a/src/TagHelpers/Bootstrap/PageElements/Footer.cs +++ b/src/TagHelpers/Bootstrap/PageElements/Footer.cs @@ -54,7 +54,7 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu ); output.PreContent.AppendHtml( $$$""" -
    + < div class="{{{CssClasses.Container}}}"> """ ); if (!IsNullOrEmpty(CopyrightHolder)) @@ -70,43 +70,45 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu output.PreContent.AppendHtml( $$$""" - {{{datetime.Now.Year}}} + {{{datetime.Now.Year +} +}} """ ); } - if (CopyrightEndYear.HasValue && CopyrightEndYear != CopyrightStartYear) - { - output.PreContent.AppendHtml( - $$$""" - - - {{{datetime.Now.Year}}} - """ - ); - } - if (!IsNullOrEmpty(CopyrightHolderEmail)) - { - output.PreContent.AppendHtml( - $$$""" - - - {{{CopyrightHolder}}} - + if (CopyrightEndYear.HasValue && CopyrightEndYear != CopyrightStartYear) +{ + output.PreContent.AppendHtml( + $$$""" + + - { { { datetime.Now.Year} } } + """ + ); +} +if (!IsNullOrEmpty(CopyrightHolderEmail)) +{ + output.PreContent.AppendHtml( + $$$""" + + < a href = "mailto:{{{CopyrightHolderEmail}}}" > + { { { CopyrightHolder} } } + | - """ - ); - } - else - { - output.PreContent.AppendHtml( - $$$""" - {{{CopyrightHolder}}} + """ + ); +} +else +{ + output.PreContent.AppendHtml( + $$$""" + { { { CopyrightHolder} } } | - """ - ); - } + """ + ); +} } } } diff --git a/src/TagHelpers/Bootstrap/PageElements/FooterNavLinkHelper.cs b/src/TagHelpers/Bootstrap/PageElements/FooterNavLinkHelper.cs index 95f43e18..f8c4b034 100644 --- a/src/TagHelpers/Bootstrap/PageElements/FooterNavLinkHelper.cs +++ b/src/TagHelpers/Bootstrap/PageElements/FooterNavLinkHelper.cs @@ -18,51 +18,51 @@ namespace Dgmjr.AspNetCore.TagHelpers.Bootstrap; // [HtmlTargetElement(TagNames.NavLink, ParentTag = TagNames.Container)] public class FooterNavLinkTagHelper(IHtmlGenerator generator) : AnchorTagHelper(generator) { - public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - base.ProcessAsync(context, output); - output.TagName = "a"; - - if (ShouldBeActive()) - { - MakeActive(output); - } - return Task.CompletedTask; - } - - private bool ShouldBeActive() - { - var currentController = ViewContext.RouteData.Values["Controller"]?.ToString(); - var currentAction = ViewContext.RouteData.Values["Action"]?.ToString(); - - if ( - !IsNullOrWhiteSpace(Controller) && Controller?.ToLower() != currentController?.ToLower() - ) - { - return false; - } - - if (!IsNullOrWhiteSpace(Action) && Action?.ToLower() != currentAction?.ToLower()) - { - return false; - } - - foreach (var routeValue in RouteValues) - { - if ( - !ViewContext.RouteData.Values.ContainsKey(routeValue.Key) - || ViewContext.RouteData.Values[routeValue.Key].ToString() != routeValue.Value - ) - { - return false; - } - } - - return true; - } - - private static void MakeActive(TagHelperOutput output) - { - output.AddCssClass("active"); - } + public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + base.ProcessAsync(context, output); + output.TagName = "a"; + + if (ShouldBeActive()) + { + MakeActive(output); + } + return Task.CompletedTask; +} + +private bool ShouldBeActive() +{ + var currentController = ViewContext.RouteData.Values["Controller"]?.ToString(); + var currentAction = ViewContext.RouteData.Values["Action"]?.ToString(); + + if ( + !IsNullOrWhiteSpace(Controller) && Controller?.ToLower() != currentController?.ToLower() + ) + { + return false; + } + + if (!IsNullOrWhiteSpace(Action) && Action?.ToLower() != currentAction?.ToLower()) + { + return false; + } + + foreach (var routeValue in RouteValues) + { + if ( + !ViewContext.RouteData.Values.ContainsKey(routeValue.Key) + || ViewContext.RouteData.Values[routeValue.Key].ToString() != routeValue.Value + ) + { + return false; + } + } + + return true; +} + +private static void MakeActive(TagHelperOutput output) +{ + output.AddCssClass("active"); +} } diff --git a/src/TagHelpers/Bootstrap/PageElements/PageHeader.cs b/src/TagHelpers/Bootstrap/PageElements/PageHeader.cs index 04fdc2ff..11122be4 100644 --- a/src/TagHelpers/Bootstrap/PageElements/PageHeader.cs +++ b/src/TagHelpers/Bootstrap/PageElements/PageHeader.cs @@ -17,26 +17,26 @@ namespace Dgmjr.AspNetCore.TagHelpers.Bootstrap; [HtmlTargetElement(TagNames.PageHeader)] public class PageHeader(IHtmlGenerator generator) : TagHelper(), IHaveAWritableId { - [HtmlAttributeName(AttributeNames.HeadingType)] - public HeadingType HeadingType { get; set; } = HeadingType.h1; - - [HtmlAttributeName(AttributeNames.Id)] - public string Id { get; set; } - - [HtmlAttributeName(AttributeNames.Title)] - public string Title { get; set; } = string.Empty; - - [ViewContext] - public ViewContext ViewContext { get; set; } - - protected IHtmlGenerator Generator => generator; - - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - output.TagName = "div"; - output.AddClass("page-header", HtmlEncoder.Default); - output.Content.AppendHtml( - $"<{HeadingType.ToString().ToLower()}>{Title}" - ); - } + [HtmlAttributeName(AttributeNames.HeadingType)] +public HeadingType HeadingType { get; set; } = HeadingType.h1; + +[HtmlAttributeName(AttributeNames.Id)] +public string Id { get; set; } + +[HtmlAttributeName(AttributeNames.Title)] +public string Title { get; set; } = string.Empty; + +[ViewContext] +public ViewContext ViewContext { get; set; } + +protected IHtmlGenerator Generator => generator; + +public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +{ + output.TagName = "div"; + output.AddClass("page-header", HtmlEncoder.Default); + output.Content.AppendHtml( + $"<{HeadingType.ToString().ToLower()}>{Title}" + ); +} } diff --git a/src/TagHelpers/Card/CardImageTagHelper.cs b/src/TagHelpers/Card/CardImageTagHelper.cs index 96f80170..2fe3f16f 100644 --- a/src/TagHelpers/Card/CardImageTagHelper.cs +++ b/src/TagHelpers/Card/CardImageTagHelper.cs @@ -9,32 +9,32 @@ public class CardImageTagHelper(IActionContextAccessor actionContextAccessor) : TagHelper, IHaveAnActionContextAccessor { - public IActionContextAccessor ActionContextAccessor => actionContextAccessor; - - #region --- Attribute Names --- - - private const string PositionAttributeName = "position"; - - #endregion - - #region --- Properties --- - - // [HtmlAttributeName(PositionAttributeName)] - public CardImagePosition Position { get; set; } = CardImagePosition.Top; - - [CopyToOutput] - [ConvertVirtualUrl] - public string Src { get; set; } - - #endregion - - public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - output.TagName = "img"; - output.TagMode = TagMode.SelfClosing; - - // Position - output.AddCssClass($"card-img-{this.Position.GetEnumInfo().Name}"); - } - } + public IActionContextAccessor ActionContextAccessor => actionContextAccessor; + + #region --- Attribute Names --- + + private const string PositionAttributeName = "position"; + + #endregion + + #region --- Properties --- + + // [HtmlAttributeName(PositionAttributeName)] + public CardImagePosition Position { get; set; } = CardImagePosition.Top; + + [CopyToOutput] + [ConvertVirtualUrl] + public string Src { get; set; } + + #endregion + + public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) + { + output.TagName = "img"; + output.TagMode = TagMode.SelfClosing; + + // Position + output.AddCssClass($"card-img-{this.Position.GetEnumInfo().Name}"); + } +} } diff --git a/src/TagHelpers/Carousel/CarouselItemTagHelper.cs b/src/TagHelpers/Carousel/CarouselItemTagHelper.cs index 9e045fc6..e27fff10 100644 --- a/src/TagHelpers/Carousel/CarouselItemTagHelper.cs +++ b/src/TagHelpers/Carousel/CarouselItemTagHelper.cs @@ -10,61 +10,61 @@ public class CarouselItemTagHelper(IActionContextAccessor actionContextAccessor) : TagHelper, IHaveAnActionContextAccessor { - public IActionContextAccessor ActionContextAccessor => actionContextAccessor; - - #region --- Attribute Names --- - - private const string ActiveAttributeName = "active"; - private const string SrcAttributeName = "src"; - private const string AltAttributeName = "alt"; - - #endregion - - #region --- Properties --- - - [HtmlAttributeName(SrcAttributeName)] - [ConvertVirtualUrl] - public string Src { get; set; } - - [HtmlAttributeName(AltAttributeName)] - public string Alt { get; set; } - - [HtmlAttributeName(ActiveAttributeName)] - public bool Active { get; set; } - - [Context] - protected CarouselTagHelper CarouselContext { get; set; } - - #endregion - - public override void Init(TagHelperContext context) - { - base.Init(context); - CarouselContext.Items.Add(this); - } - - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - output.TagName = "div"; - output.AddCssClass("carousel-item"); - - // Active - if (this.Active) - { - output.AddCssClass("active"); - } - - output.PreContent.PrependHtml( - $"\"{this.Alt}\"" - ); - output.Content.SetHtmlContent(await output.GetChildContentAsync()); - - // Caption - if (!output.Content.IsEmptyOrWhiteSpace) - { - output.PreContent.AppendHtml("
    "); - output.PostContent.PrependHtml("
    "); - } - } - } + public IActionContextAccessor ActionContextAccessor => actionContextAccessor; + + #region --- Attribute Names --- + + private const string ActiveAttributeName = "active"; + private const string SrcAttributeName = "src"; + private const string AltAttributeName = "alt"; + + #endregion + + #region --- Properties --- + + [HtmlAttributeName(SrcAttributeName)] + [ConvertVirtualUrl] + public string Src { get; set; } + + [HtmlAttributeName(AltAttributeName)] + public string Alt { get; set; } + + [HtmlAttributeName(ActiveAttributeName)] + public bool Active { get; set; } + + [Context] + protected CarouselTagHelper CarouselContext { get; set; } + + #endregion + + public override void Init(TagHelperContext context) + { + base.Init(context); + CarouselContext.Items.Add(this); + } + + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) + { + output.TagName = "div"; + output.AddCssClass("carousel-item"); + + // Active + if (this.Active) + { + output.AddCssClass("active"); + } + + output.PreContent.PrependHtml( + $"\"{this.Alt}\"" + ); + output.Content.SetHtmlContent(await output.GetChildContentAsync()); + + // Caption + if (!output.Content.IsEmptyOrWhiteSpace) + { + output.PreContent.AppendHtml("
    "); + output.PostContent.PrependHtml("
    "); + } + } +} } diff --git a/src/TagHelpers/Components/FigureTagHelper.cs b/src/TagHelpers/Components/FigureTagHelper.cs index de8aa76b..2ec498df 100644 --- a/src/TagHelpers/Components/FigureTagHelper.cs +++ b/src/TagHelpers/Components/FigureTagHelper.cs @@ -10,66 +10,66 @@ public class FigureTagHelper(IActionContextAccessor actionContextAccessor) : TagHelper, IHaveAnActionContextAccessor { - public IActionContextAccessor ActionContextAccessor => actionContextAccessor; - - #region --- Attribute Names --- - - private const string ImageAttributeName = "image"; - private const string WidthAttributeName = "width"; - private const string HeightAttributeName = "height"; - private const string CaptionAttributeName = "caption"; - private const string HorizontalAligmentAttributeName = "alignment"; - - #endregion - - #region --- Properties --- - - [HtmlAttributeName(ImageAttributeName)] - [ConvertVirtualUrl] - public string Image { get; set; } - - [HtmlAttributeName(CaptionAttributeName)] - public string Caption { get; set; } - - [HtmlAttributeName(HorizontalAligmentAttributeName)] - public HorizontalAlignment HorizontalAlignment { get; set; } - - [HtmlAttributeName(WidthAttributeName)] - public int Width { get; set; } - - [HtmlAttributeName(HeightAttributeName)] - public int Height { get; set; } - - #endregion - - public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - output.TagName = "figure"; - output.TagMode = TagMode.StartTagAndEndTag; - output.AddCssClass("figure"); - - // Image - TagBuilder img = new TagBuilder("img") { TagRenderMode = TagRenderMode.SelfClosing }; - img.AddCssClass("figure-img img-fluid rounded"); - img.Attributes.Add("src", this.Image); - if (this.Width > 0) - img.Attributes.Add("width", this.Width.ToString()); - if (this.Height > 0) - img.Attributes.Add("height", this.Height.ToString()); - output.PreContent.AppendHtml(img); - - // Caption - TagBuilder figcaption = new TagBuilder("figcaption"); - figcaption.AddCssClass("figure-caption"); - figcaption.InnerHtml.Append(this.Caption); - - // Alignment - if (this.HorizontalAlignment != HorizontalAlignment.Default) - { - figcaption.AddCssClass($"text-{this.HorizontalAlignment.GetEnumInfo().Name}"); - } - - output.PostContent.AppendHtml(figcaption); - } - } + public IActionContextAccessor ActionContextAccessor => actionContextAccessor; + + #region --- Attribute Names --- + + private const string ImageAttributeName = "image"; + private const string WidthAttributeName = "width"; + private const string HeightAttributeName = "height"; + private const string CaptionAttributeName = "caption"; + private const string HorizontalAligmentAttributeName = "alignment"; + + #endregion + + #region --- Properties --- + + [HtmlAttributeName(ImageAttributeName)] + [ConvertVirtualUrl] + public string Image { get; set; } + + [HtmlAttributeName(CaptionAttributeName)] + public string Caption { get; set; } + + [HtmlAttributeName(HorizontalAligmentAttributeName)] + public HorizontalAlignment HorizontalAlignment { get; set; } + + [HtmlAttributeName(WidthAttributeName)] + public int Width { get; set; } + + [HtmlAttributeName(HeightAttributeName)] + public int Height { get; set; } + + #endregion + + public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) + { + output.TagName = "figure"; + output.TagMode = TagMode.StartTagAndEndTag; + output.AddCssClass("figure"); + + // Image + TagBuilder img = new TagBuilder("img") { TagRenderMode = TagRenderMode.SelfClosing }; + img.AddCssClass("figure-img img-fluid rounded"); + img.Attributes.Add("src", this.Image); + if (this.Width > 0) + img.Attributes.Add("width", this.Width.ToString()); + if (this.Height > 0) + img.Attributes.Add("height", this.Height.ToString()); + output.PreContent.AppendHtml(img); + + // Caption + TagBuilder figcaption = new TagBuilder("figcaption"); + figcaption.AddCssClass("figure-caption"); + figcaption.InnerHtml.Append(this.Caption); + + // Alignment + if (this.HorizontalAlignment != HorizontalAlignment.Default) + { + figcaption.AddCssClass($"text-{this.HorizontalAlignment.GetEnumInfo().Name}"); + } + + output.PostContent.AppendHtml(figcaption); + } +} } diff --git a/src/TagHelpers/DgmjrTagHelperBase.cs b/src/TagHelpers/DgmjrTagHelperBase.cs index af5292f2..c1e936c0 100644 --- a/src/TagHelpers/DgmjrTagHelperBase.cs +++ b/src/TagHelpers/DgmjrTagHelperBase.cs @@ -19,99 +19,99 @@ public class DgmjrTagHelperBase( IActionContextAccessor actionContextAccessor = default ) : TagHelper, IHaveAnActionContextAccessor { - protected const string AttributePrefix = "dgmjr-"; - - [HtmlAttributeNotBound] - public string TagName { get; set; } = tagName; - - private const string DisableBootstrapAttributeName = "disable-bootstrap"; - - [HtmlAttributeName(DisableBootstrapAttributeName)] - [HtmlAttributeNotBound] - [HtmlAttributeMinimizable] - public bool DisableBootstrap { get; set; } - - [HtmlAttributeNotBound] - public string GeneratedId { get; set; } - - [CopyToOutput] - public string Id { get; set; } - - [CopyToOutput] - public string Name { get; set; } - - [HtmlAttributeNotBound] - public TagHelperOutput Output { get; set; } - - [HtmlAttributeNotBound] - public IActionContextAccessor ActionContextAccessor - { - get => _actionContextAccessor ??= Services.GetRequiredService(); - set => _actionContextAccessor = value; - } - private IActionContextAccessor _actionContextAccessor; - - protected IServiceProvider Services => ViewContext.HttpContext.RequestServices; - - [ViewContext] - [HtmlAttributeNotBound] - public ViewContext ViewContext { get; set; } - - private IUrlHelper _urlHelper; - - [HtmlAttributeNotBound] - public IUrlHelper UrlHelper - { - get => - _urlHelper ??= Services - .GetRequiredService() - .GetUrlHelper(ViewContext); - set => _urlHelper = value; - } - - // public override void Init(TagHelperContext context) - // { - // this.SetContexts(context); - // this.SetContext(context); - // this.FillMinimizableAttributes(context); - // this.ConvertUrls(ActionContextAccessor); - // } - - // public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - // { - // Output = output; - // if (!DisableBootstrap) - // { - // this.CopyPropertiesToOutput(output); - // this.CheckMandatoryProperties(); - // this.CopyIdentifier(); - // RenderProcess(context, output); - // this.RenderIdentifier(this, output); - // RemoveMinimizableAttributes(output); - // } - // } - - // public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - // { - // Output = output; - // if (!DisableBootstrap) - // { - // CopyToOutputAttribute.CopyPropertiesToOutput(this, output); - // MandatoryAttribute.CheckProperties(this); - // GenerateIdAttribute.CopyIdentifier(this); - // await RenderProcessAsync(context, output); - // GenerateIdAttribute.RenderIdentifier(this, output); - // RemoveMinimizableAttributes(output); - // } - // } - - protected virtual void RenderProcess(TagHelperContext context, TagHelperOutput output) { } - - protected virtual async Task RenderProcessAsync( - TagHelperContext context, - TagHelperOutput output - ) - { - RenderProcess(context, output); - } + protected const string AttributePrefix = "dgmjr-"; + +[HtmlAttributeNotBound] +public string TagName { get; set; } = tagName; + +private const string DisableBootstrapAttributeName = "disable-bootstrap"; + +[HtmlAttributeName(DisableBootstrapAttributeName)] +[HtmlAttributeNotBound] +[HtmlAttributeMinimizable] +public bool DisableBootstrap { get; set; } + +[HtmlAttributeNotBound] +public string GeneratedId { get; set; } + +[CopyToOutput] +public string Id { get; set; } + +[CopyToOutput] +public string Name { get; set; } + +[HtmlAttributeNotBound] +public TagHelperOutput Output { get; set; } + +[HtmlAttributeNotBound] +public IActionContextAccessor ActionContextAccessor +{ + get => _actionContextAccessor ??= Services.GetRequiredService(); + set => _actionContextAccessor = value; +} +private IActionContextAccessor _actionContextAccessor; + +protected IServiceProvider Services => ViewContext.HttpContext.RequestServices; + +[ViewContext] +[HtmlAttributeNotBound] +public ViewContext ViewContext { get; set; } + +private IUrlHelper _urlHelper; + +[HtmlAttributeNotBound] +public IUrlHelper UrlHelper +{ + get => + _urlHelper ??= Services + .GetRequiredService() + .GetUrlHelper(ViewContext); + set => _urlHelper = value; +} + +// public override void Init(TagHelperContext context) +// { +// this.SetContexts(context); +// this.SetContext(context); +// this.FillMinimizableAttributes(context); +// this.ConvertUrls(ActionContextAccessor); +// } + +// public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +// { +// Output = output; +// if (!DisableBootstrap) +// { +// this.CopyPropertiesToOutput(output); +// this.CheckMandatoryProperties(); +// this.CopyIdentifier(); +// RenderProcess(context, output); +// this.RenderIdentifier(this, output); +// RemoveMinimizableAttributes(output); +// } +// } + +// public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) +// { +// Output = output; +// if (!DisableBootstrap) +// { +// CopyToOutputAttribute.CopyPropertiesToOutput(this, output); +// MandatoryAttribute.CheckProperties(this); +// GenerateIdAttribute.CopyIdentifier(this); +// await RenderProcessAsync(context, output); +// GenerateIdAttribute.RenderIdentifier(this, output); +// RemoveMinimizableAttributes(output); +// } +// } + +protected virtual void RenderProcess(TagHelperContext context, TagHelperOutput output) { } + +protected virtual async Task RenderProcessAsync( + TagHelperContext context, + TagHelperOutput output +) +{ + RenderProcess(context, output); +} } diff --git a/src/TagHelpers/Extensions/ColorInfoExtensions.cs b/src/TagHelpers/Extensions/ColorInfoExtensions.cs index aa058466..13168854 100644 --- a/src/TagHelpers/Extensions/ColorInfoExtensions.cs +++ b/src/TagHelpers/Extensions/ColorInfoExtensions.cs @@ -42,11 +42,11 @@ public static ColorInfo GetColorInfo(this Color color) public readonly record struct ColorInfo(ColorInfoAttribute? ColorInfoAttribute) { - public string Name => ColorInfoAttribute?.Name ?? string.Empty; - - public string TextCssClass => ColorInfoAttribute?.TextCssClass ?? string.Empty; - - public string BackgroundCssClass => ColorInfoAttribute?.BackgroundCssClass ?? string.Empty; - - public string BorderCssClass => ColorInfoAttribute?.BorderCssClass ?? string.Empty; + public string Name => ColorInfoAttribute?.Name ?? string.Empty; + +public string TextCssClass => ColorInfoAttribute?.TextCssClass ?? string.Empty; + +public string BackgroundCssClass => ColorInfoAttribute?.BackgroundCssClass ?? string.Empty; + +public string BorderCssClass => ColorInfoAttribute?.BorderCssClass ?? string.Empty; } diff --git a/src/TagHelpers/Extensions/ContextAttributeExtensions.cs b/src/TagHelpers/Extensions/ContextAttributeExtensions.cs index 2b5d229a..66eb3ba5 100644 --- a/src/TagHelpers/Extensions/ContextAttributeExtensions.cs +++ b/src/TagHelpers/Extensions/ContextAttributeExtensions.cs @@ -33,9 +33,9 @@ var item in from pi in typeof(T) | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic - ) - where pi.HasCustomAttribute() - select pi + ) + where pi.HasCustomAttribute() + select pi ) { var customAttribute = item.GetCustomAttribute(); diff --git a/src/TagHelpers/Extensions/ConvertUrlAttributeExtensions.cs b/src/TagHelpers/Extensions/ConvertUrlAttributeExtensions.cs index cb70ae97..64c2a9ee 100644 --- a/src/TagHelpers/Extensions/ConvertUrlAttributeExtensions.cs +++ b/src/TagHelpers/Extensions/ConvertUrlAttributeExtensions.cs @@ -21,9 +21,9 @@ public static void ConvertUrls(this T target, IActionContextAccessor accessor { throw new ArgumentNullException(nameof(target)); } - var convertVirtualUrlAttributeProperties = (from pi in target.GetType().GetProperties() - where pi.HasCustomAttribute() - select pi).ToList(); + var convertVirtualUrlAttributeProperties = (from pi in target.GetType().GetProperties() + where pi.HasCustomAttribute() + select pi).ToList(); if (!convertVirtualUrlAttributeProperties.Any()) { return; diff --git a/src/TagHelpers/Extensions/CopyToOutputExtensions.cs b/src/TagHelpers/Extensions/CopyToOutputExtensions.cs index 98d48893..c9c8ed02 100644 --- a/src/TagHelpers/Extensions/CopyToOutputExtensions.cs +++ b/src/TagHelpers/Extensions/CopyToOutputExtensions.cs @@ -26,9 +26,9 @@ public static void CopyPropertiesToOutput(this T target, TagHelperOutput outp throw new ArgumentNullException(nameof(output)); } foreach ( - var item in from pI in target.GetType().GetProperties() - where pI.HasCustomAttribute() - select pI + var item in from pI in target.GetType().GetProperties() + where pI.HasCustomAttribute() + select pI ) { var obj = item.GetValue(target); diff --git a/src/TagHelpers/Extensions/InitExtensions.cs b/src/TagHelpers/Extensions/InitExtensions.cs index 2c32e4d4..131a3b9b 100644 --- a/src/TagHelpers/Extensions/InitExtensions.cs +++ b/src/TagHelpers/Extensions/InitExtensions.cs @@ -20,7 +20,7 @@ public static T Init(this T @this, TagHelperContext context) @this.SetContexts(context); @this.SetContext(context); @this.FillMinimizableAttributes(context); - if(@this is IHaveAnActionContextAccessor ihaaaca) + if (@this is IHaveAnActionContextAccessor ihaaaca) { @this.ConvertUrls(ihaaaca.ActionContextAccessor); } diff --git a/src/TagHelpers/Extensions/MandatoryPropertiesExtensions.cs b/src/TagHelpers/Extensions/MandatoryPropertiesExtensions.cs index 5168b86e..5ad854f3 100644 --- a/src/TagHelpers/Extensions/MandatoryPropertiesExtensions.cs +++ b/src/TagHelpers/Extensions/MandatoryPropertiesExtensions.cs @@ -17,9 +17,9 @@ public static class MandatoryPropertiesExtensions public static void CheckMandatoryProperties(this T tagHelper) where T : TagHelper { - foreach (var item in from pi in tagHelper.GetType().GetProperties() - where pi.HasCustomAttribute() - select pi) + foreach (var item in from pi in tagHelper.GetType().GetProperties() + where pi.HasCustomAttribute() + select pi) { var value = item.GetValue(tagHelper); var htmlAttributeName = item.GetHtmlAttributeName(); diff --git a/src/TagHelpers/Extensions/MinimizableAttributeExtensions.cs b/src/TagHelpers/Extensions/MinimizableAttributeExtensions.cs index d1156fc0..fd16add4 100644 --- a/src/TagHelpers/Extensions/MinimizableAttributeExtensions.cs +++ b/src/TagHelpers/Extensions/MinimizableAttributeExtensions.cs @@ -26,9 +26,9 @@ public static void FillMinimizableAttributes(this T target, TagHelperContext throw new ArgumentNullException(nameof(context)); } foreach ( - var item in from pI in target.GetType().GetProperties() - where pI.GetCustomAttribute() != null - select pI + var item in from pI in target.GetType().GetProperties() + where pI.GetCustomAttribute() != null + select pI ) { var htmlAttributeName = item.GetHtmlAttributeName(); diff --git a/src/TagHelpers/Extensions/ProcessTagHelperExtensions.cs b/src/TagHelpers/Extensions/ProcessTagHelperExtensions.cs index de3e3331..0914efe0 100644 --- a/src/TagHelpers/Extensions/ProcessTagHelperExtensions.cs +++ b/src/TagHelpers/Extensions/ProcessTagHelperExtensions.cs @@ -21,7 +21,7 @@ public static T Process(this T @this, Action iis) + if (@this is IIdentifiable iis) { iis.RenderIdentifier(output); } diff --git a/src/TagHelpers/Extensions/TagHelperOutputExtensions.cs b/src/TagHelpers/Extensions/TagHelperOutputExtensions.cs index 777433b2..421e4c82 100644 --- a/src/TagHelpers/Extensions/TagHelperOutputExtensions.cs +++ b/src/TagHelpers/Extensions/TagHelperOutputExtensions.cs @@ -16,14 +16,14 @@ public static class TagHelperOutputExtensions { public static void AddCssClass(this TagHelperOutput output, string cssClass) { - output.AddCssClass([ cssClass ]); + output.AddCssClass([cssClass]); } public static void AddCssClass(this TagHelperOutput output, IEnumerable cssClasses) { if (output.Attributes.ContainsName("class") && output.Attributes["class"] != null) { - var classes = output.Attributes["class"].Value.ToString().Split([ ' ' ]).ToList(); + var classes = output.Attributes["class"].Value.ToString().Split([' ']).ToList(); classes.AddRange(cssClasses.Where((string cssClass) => !classes.Contains(cssClass))); output.Attributes.SetAttribute("class", classes.Aggregate((string s, string s1) => s + " " + s1)); } @@ -43,7 +43,7 @@ public static void RemoveCssClass(this TagHelperOutput output, string cssClass) { return; } - var list = output.Attributes["class"].Value.ToString().Split([ ' ' ]).ToList(); + var list = output.Attributes["class"].Value.ToString().Split([' ']).ToList(); list.Remove(cssClass); if (list.Count == 0) { diff --git a/src/TagHelpers/Media/MediaImageTagHelper.cs b/src/TagHelpers/Media/MediaImageTagHelper.cs index 128bdfbc..2d8d1690 100644 --- a/src/TagHelpers/Media/MediaImageTagHelper.cs +++ b/src/TagHelpers/Media/MediaImageTagHelper.cs @@ -11,44 +11,44 @@ public class MediaImageTagHelper(IActionContextAccessor actionContextAccessor) { #region --- Attribute Names --- - private const string VerticalAlignmentAttributeName = "vertical-alignment"; - - #endregion - - #region --- Properties --- - - [CopyToOutput] - [ConvertVirtualUrl] - public string Src { get; set; } - - [HtmlAttributeName(VerticalAlignmentAttributeName)] - public VerticalAlignment VerticalAlignment { get; set; } = VerticalAlignment.Default; - - [ActionContext] - public IActionContextAccessor ActionContextAccessor => actionContextAccessor; - - #endregion - - public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) - { - output.TagName = "img"; - output.TagMode = TagMode.SelfClosing; - - output.AddCssClass("d-flex"); - - // Vertical Alignment - switch (this.VerticalAlignment) - { - case VerticalAlignment.Top: - output.AddCssClass("align-self-start"); - break; - case VerticalAlignment.Middle: - output.AddCssClass("align-self-center"); - break; - case VerticalAlignment.Bottom: - output.AddCssClass("align-self-end"); - break; - } - } - } + private const string VerticalAlignmentAttributeName = "vertical-alignment"; + + #endregion + + #region --- Properties --- + + [CopyToOutput] + [ConvertVirtualUrl] + public string Src { get; set; } + + [HtmlAttributeName(VerticalAlignmentAttributeName)] + public VerticalAlignment VerticalAlignment { get; set; } = VerticalAlignment.Default; + + [ActionContext] + public IActionContextAccessor ActionContextAccessor => actionContextAccessor; + + #endregion + + public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) + { + output.TagName = "img"; + output.TagMode = TagMode.SelfClosing; + + output.AddCssClass("d-flex"); + + // Vertical Alignment + switch (this.VerticalAlignment) + { + case VerticalAlignment.Top: + output.AddCssClass("align-self-start"); + break; + case VerticalAlignment.Middle: + output.AddCssClass("align-self-center"); + break; + case VerticalAlignment.Bottom: + output.AddCssClass("align-self-end"); + break; + } + } +} }