Skip to content

Commit

Permalink
Add additional code analyzers (#303)
Browse files Browse the repository at this point in the history
* Added Meziantou.Analyzer

* Added Roslynator.Analyzers

* Added the remaining analyzers
  • Loading branch information
nkz-soft authored Oct 16, 2024
1 parent 0e43af9 commit d29503e
Show file tree
Hide file tree
Showing 172 changed files with 1,496 additions and 1,249 deletions.
1,119 changes: 705 additions & 414 deletions .editorconfig

Large diffs are not rendered by default.

20 changes: 17 additions & 3 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@
<Nullable>enable</Nullable>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest</AnalysisLevel>
<Features>strict</Features>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<Features>strict</Features>
<RunAnalyzersDuringBuild>true</RunAnalyzersDuringBuild>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<AnalysisMode>Recommended</AnalysisMode>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<PropertyGroup>
Expand All @@ -24,11 +30,19 @@
</PropertyGroup>

<PropertyGroup>
<NoWarn>$(NoWarn);NETSDK1206;xUnit1028</NoWarn>
<NoWarn>$(NoWarn);NETSDK1206;xUnit1028;CS1591</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All"/>
<PackageReference Include="Meziantou.Analyzer" PrivateAssets="All"/>
<PackageReference Include="Roslynator.Analyzers" PrivateAssets="All"/>
<PackageReference Include="Roslynator.CodeAnalysis.Analyzers" PrivateAssets="All"/>
<PackageReference Include="Roslynator.Formatting.Analyzers" PrivateAssets="All"/>
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" PrivateAssets="All"/>
<PackageReference Include="AsyncAwaitBestPractices" PrivateAssets="All"/>
<PackageReference Include="SerilogAnalyzer" PrivateAssets="All"/>
<PackageReference Include="CSharpGuidelinesAnalyzer" PrivateAssets="All"/>
</ItemGroup>

</Project>
10 changes: 9 additions & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -109,5 +109,13 @@
<PackageVersion Include="NKZSoft.Service.Configuration.Swagger" Version="1.0.3" />
<PackageVersion Include="NKZSoft.Service.Configuration.Grpc" Version="1.2.1" />
<PackageVersion Include="EasyCaching.Serialization.Json" Version="1.9.2" />
<PackageVersion Include="Meziantou.Analyzer" Version="2.0.163" />
<PackageVersion Include="Roslynator.Analyzers" Version="4.12.5" />
<PackageVersion Include="Roslynator.CodeAnalysis.Analyzers" Version="4.12.5" />
<PackageVersion Include="Roslynator.Formatting.Analyzers" Version="4.12.5"/>
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.11.20" />
<PackageVersion Include="AsyncAwaitBestPractices" Version="8.0.0" />
<PackageVersion Include="SerilogAnalyzer" Version="0.15.0" />
<PackageVersion Include="CSharpGuidelinesAnalyzer" Version="3.8.5" />
</ItemGroup>
</Project>
</Project>
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
namespace NKZSoft.Template.Application.Common.Behaviours;

using Interfaces;
using NKZSoft.Template.Common.Extensions;

public sealed class LoggingBehaviour<TRequest> : IRequestPreProcessor<TRequest> where TRequest : notnull
{
private readonly ILogger _logger;

public LoggingBehaviour(ILogger<LoggingBehaviour<TRequest>> logger, ICurrentUserService currentUserService) => _logger = logger.ThrowIfNull();
public LoggingBehaviour(ILogger<LoggingBehaviour<TRequest>> logger) => _logger = logger.ThrowIfNull();

public async Task Process(TRequest request, CancellationToken cancellationToken)
{
_logger.LoggingRequest(request.ToString());
await Task.CompletedTask;
await Task.CompletedTask.ConfigureAwait(false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public async Task<TResponse> Handle(TRequest request,
{
_timer.Start();

var response = await next();
var response = await next().ConfigureAwait(false);

_timer.Stop();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TRe
{
try
{
return await next();
return await next().ConfigureAwait(false);
}
catch (Exception)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

using Exceptions;

public sealed class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
public sealed class ValidationBehaviour<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
: IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;

public ValidationBehaviour(IEnumerable<IValidator<TRequest>> validators) => _validators = validators.ThrowIfNull();
private readonly IEnumerable<IValidator<TRequest>> _validators = validators.ThrowIfNull();

public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
Expand All @@ -16,19 +15,20 @@ public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TRe
var context = new ValidationContext<TRequest>(request);

var validationResults = await Task.WhenAll(
_validators.Select(v =>
v.ValidateAsync(context, cancellationToken)));
_validators.Select(validator =>
validator.ValidateAsync(context, cancellationToken)))
.ConfigureAwait(false);

var failures = validationResults
.Where(r => r.Errors.Count != 0)
.SelectMany(r => r.Errors)
.Where(result => result.Errors.Count != 0)
.SelectMany(result => result.Errors)
.ToList();

if (failures.Count != 0)
{
throw new ValidationException(failures);
}
}
return await next();
return await next().ConfigureAwait(false);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
namespace NKZSoft.Template.Application.Common.Exceptions;

[Serializable]
public sealed class AuthorizationException(string message) : Exception(message);
public sealed class AuthorizationException : Exception
{
public AuthorizationException()
{
}

public AuthorizationException(string? message) : base(message)
{
}

public AuthorizationException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
namespace NKZSoft.Template.Application.Common.Exceptions;

[Serializable]
public sealed class BadRequestException(string message) : Exception(message);
public sealed class BadRequestException : Exception
{
public BadRequestException()
{
}

public BadRequestException(string? message) : base(message)
{
}

public BadRequestException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,12 @@ public ConflictException(string message)
: base(message)
{
}

public ConflictException()
{
}

public ConflictException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
namespace NKZSoft.Template.Application.Common.Exceptions;

[Serializable]
public sealed class DeleteFailureException(string name, object key, string message)
: Exception($"Deletion of entity \"{name}\" ({key}) failed. {message}");
public sealed class DeleteFailureException : Exception
{
public DeleteFailureException(string name, object key, string message)
: base($"Deletion of entity \"{name}\" ({key}) failed. {message}")
{
}

public DeleteFailureException()
{
}

public DeleteFailureException(string? message) : base(message)
{
}

public DeleteFailureException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,15 @@
[Serializable]
public sealed class ForbiddenAccessException : Exception
{
public ForbiddenAccessException()
{
}

public ForbiddenAccessException(string? message) : base(message)
{
}

public ForbiddenAccessException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
public sealed class NotFoundException : Exception
{
public NotFoundException()
: base()
{
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
namespace NKZSoft.Template.Application.Common.Exceptions;

[Serializable]
public sealed class PermissionDeniedException(string message) : Exception(message);
public sealed class PermissionDeniedException : Exception
{
public PermissionDeniedException()
{
}

public PermissionDeniedException(string? message) : base(message)
{
}

public PermissionDeniedException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
namespace NKZSoft.Template.Application.Common.Exceptions;

[Serializable]
public sealed class UnauthorizedException(string message) : Exception(message)
public sealed class UnauthorizedException : Exception
{
public static UnauthorizedException Response(string message)
=> new UnauthorizedException(message);
public UnauthorizedException()
{
}

public UnauthorizedException(string? message) : base(message)
{
}

public UnauthorizedException(string? message, Exception? innerException) : base(message, innerException)
{
}

public static UnauthorizedException Response(string message) => new(message);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,12 @@ public UnprocessableEntityException(string message)
: base(message)
{
}

public UnprocessableEntityException()
{
}

public UnprocessableEntityException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,13 @@ public ValidationException(IReadOnlyCollection<ValidationFailure> failures)
}
}

public IList<KeyValuePair<string, string>> Failures { get; } = new List<KeyValuePair<string, string>>();
public ValidationException(string? message) : base(message)
{
}

public ValidationException(string? message, Exception? innerException) : base(message, innerException)
{
}

public IList<KeyValuePair<string, string>> Failures { get; } = [];
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
namespace NKZSoft.Template.Application.Common.Filters;

public static class FilterDefinitionExtension
public static class FilterDefinitionExtensions
{
public static bool HasValue<T>([NotNullWhen(true)] this FilterFieldDefinition<T>? testValue)
{
return testValue switch
public static bool HasValue<T>([NotNullWhen(true)] this FilterFieldDefinition<T>? testValue) =>
testValue switch
{
null => false,
FilterFieldDefinition<string> stringValue => !string.IsNullOrEmpty(stringValue.Value),
var nullableValue => nullableValue.Value != null
var nullableValue => nullableValue.Value is not null,
};
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
using System.ComponentModel.DataAnnotations.Schema;

namespace NKZSoft.Template.Application.Common.Mappings;
namespace NKZSoft.Template.Application.Common.Mappings;
using System.ComponentModel.DataAnnotations.Schema;

public class AppCodeGenerationRegister : ICodeGenerationRegister
{
//TODO Add async support
//see https://github.com/MapsterMapper/Mapster/wiki/Async
public void Register(CodeGenerationConfig config)
{
config.AdaptTo("[name]Dto").ForType<ToDoItem>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

public sealed class CollectionViewModel<T>
{
public CollectionViewModel() => Data = new HashSet<T>();
public CollectionViewModel() => Data = [];

public CollectionViewModel(IEnumerable<T> list, int count)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

public enum EnumSortDirection : byte
{
None,
Asc,
Desc
None = 0,
Asc = 1,
Desc = 2,
}
Loading

0 comments on commit d29503e

Please sign in to comment.