diff --git a/src/Application/Common/Behaviours/AuthorizationBehaviour.cs b/src/Application/Common/Behaviours/AuthorizationBehaviour.cs index 640e43758..a42419ef0 100644 --- a/src/Application/Common/Behaviours/AuthorizationBehaviour.cs +++ b/src/Application/Common/Behaviours/AuthorizationBehaviour.cs @@ -1,9 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity; using CleanArchitecture.Blazor.Application.Common.Security; -using System.Reflection; namespace CleanArchitecture.Blazor.Application.Common.Behaviours; diff --git a/src/Application/Common/Behaviours/CacheInvalidationBehaviour.cs b/src/Application/Common/Behaviours/CacheInvalidationBehaviour.cs index 9e3e60a3f..b13838cba 100644 --- a/src/Application/Common/Behaviours/CacheInvalidationBehaviour.cs +++ b/src/Application/Common/Behaviours/CacheInvalidationBehaviour.cs @@ -20,7 +20,7 @@ ILogger> logger } public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { - _logger.LogTrace("{Name} cache expire with {@Request}.", nameof(request), request); + _logger.LogTrace("{Name} cache expire with {@Request}", nameof(request), request); var response = await next().ConfigureAwait(false); if (!string.IsNullOrEmpty(request.CacheKey)) { diff --git a/src/Application/Common/Behaviours/MemoryCacheBehaviour.cs b/src/Application/Common/Behaviours/MemoryCacheBehaviour.cs index 8bcc8d290..3e639af51 100644 --- a/src/Application/Common/Behaviours/MemoryCacheBehaviour.cs +++ b/src/Application/Common/Behaviours/MemoryCacheBehaviour.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using LazyCache; - namespace CleanArchitecture.Blazor.Application.Common.Behaviours; public class MemoryCacheBehaviour : IPipelineBehavior @@ -21,7 +19,7 @@ ILogger> logger } public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { - _logger.LogTrace("{Name} is caching with {@Request}.", nameof(request),request); + _logger.LogTrace("{Name} is caching with {@Request}", nameof(request),request); var response = await _cache.GetOrAddAsync( request.CacheKey, async () => diff --git a/src/Application/Common/Behaviours/UnhandledExceptionBehaviour.cs b/src/Application/Common/Behaviours/UnhandledExceptionBehaviour.cs index 3e478ff72..91edfa10d 100644 --- a/src/Application/Common/Behaviours/UnhandledExceptionBehaviour.cs +++ b/src/Application/Common/Behaviours/UnhandledExceptionBehaviour.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Threading; - namespace CleanArchitecture.Blazor.Application.Common.Behaviours; public class UnhandledExceptionBehaviour : IPipelineBehavior where TRequest : IRequest diff --git a/src/Application/Common/Behaviours/ValidationBehaviour.cs b/src/Application/Common/Behaviours/ValidationBehaviour.cs index cfbe6bb9d..565f49b9c 100644 --- a/src/Application/Common/Behaviours/ValidationBehaviour.cs +++ b/src/Application/Common/Behaviours/ValidationBehaviour.cs @@ -17,14 +17,14 @@ public ValidationBehaviour( public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { var context = new ValidationContext(request); - var failrules = _validators + var failRules = _validators .Select(validator => validator.Validate(context)) .SelectMany(result => result.Errors) - .Where(failrules => failrules != null) + .Where(failRules => failRules != null) .ToList(); - if (failrules.Any()) + if (failRules.Any()) { - throw new ValidationException(failrules); + throw new ValidationException(failRules); } return await next().ConfigureAwait(false); } diff --git a/src/Application/Common/Configurations/AppConfigurationSettings.cs b/src/Application/Common/Configurations/AppConfigurationSettings.cs index 6c361ae6c..ad14abe83 100644 --- a/src/Application/Common/Configurations/AppConfigurationSettings.cs +++ b/src/Application/Common/Configurations/AppConfigurationSettings.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Application.Configurations; +namespace CleanArchitecture.Blazor.Application.Common.Configurations; public class AppConfigurationSettings { diff --git a/src/Application/Common/Configurations/DashbordSettings.cs b/src/Application/Common/Configurations/DashbordSettings.cs index 15d3f50e5..8ffdcf7e7 100644 --- a/src/Application/Common/Configurations/DashbordSettings.cs +++ b/src/Application/Common/Configurations/DashbordSettings.cs @@ -1,18 +1,18 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Application.Configurations; +namespace CleanArchitecture.Blazor.Application.Common.Configurations; public class DashboardSettings { public const string SectionName = nameof(DashboardSettings); - public string Version { get; set; }="6.0.2"; + public string Version { get; set; } = "6.0.2"; public string App { get; set; } = "Dashboard"; public string AppName { get; set; } = "Admin Dashboard"; public string AppFlavor { get; set; } = String.Empty; public string AppFlavorSubscript { get; set; } = String.Empty; public string Company { get; set; } = "Company"; - public string Copyright { get; set; } = "@2022 Copyright"; + public string Copyright { get; set; } = "@2023 Copyright"; } diff --git a/src/Application/Common/ExceptionHandlers/ConflictException.cs b/src/Application/Common/ExceptionHandlers/ConflictException.cs index 022d7d33b..0716d42d3 100644 --- a/src/Application/Common/ExceptionHandlers/ConflictException.cs +++ b/src/Application/Common/ExceptionHandlers/ConflictException.cs @@ -1,4 +1,4 @@ -namespace CleanArchitecture.Blazor.Application.Common.Exceptions; +namespace CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; public class ConflictException : ServerException { public ConflictException(string message) diff --git a/src/Application/Common/ExceptionHandlers/DbExceptionHandler.cs b/src/Application/Common/ExceptionHandlers/DbExceptionHandler.cs index fc67c66d2..6a3b3ce2d 100644 --- a/src/Application/Common/ExceptionHandlers/DbExceptionHandler.cs +++ b/src/Application/Common/ExceptionHandlers/DbExceptionHandler.cs @@ -1,15 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.NetworkInformation; -using System.Text; -using System.Threading.Tasks; -using CleanArchitecture.Blazor.Application.Features.Products.Commands.AddEdit; -using Microsoft.Data.SqlClient; -using Microsoft.EntityFrameworkCore; +using Microsoft.Data.SqlClient; namespace CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; -public class DbExceptionHandler : IRequestExceptionHandler + +public class + DbExceptionHandler : IRequestExceptionHandler where TRequest : IRequest where TException : DbUpdateException { @@ -20,51 +14,53 @@ public DbExceptionHandler(ILogger state, CancellationToken cancellationToken) + public Task Handle(TRequest request, TException exception, RequestExceptionHandlerState state, + CancellationToken cancellationToken) { - var response = Activator.CreateInstance(); + TResponse response = Activator.CreateInstance(); if (response is Result result) { result.Succeeded = false; - result.Errors = getErrors(exception); + result.Errors = GetErrors(exception); state.SetHandled(response); } + return Task.CompletedTask; } - private string[] getErrors(DbUpdateException exception) + private static string[] GetErrors(DbUpdateException exception) { IList errors = new List(); if (exception.InnerException != null - && exception.InnerException != null - && exception.InnerException is SqlException sqlException - ) + && exception.InnerException != null + && exception.InnerException is SqlException sqlException + ) { switch (sqlException.Number) { - case 2627: // Unique constraint error - errors.Add("A Unique Constraint Error Has Occured While Updating the record! Duplicate Record cannot be inserted in the System."); + case 2627: // Unique constraint error + errors.Add( + "A Unique Constraint Error Has Occured While Updating the record! Duplicate Record cannot be inserted in the System."); break; - case 544: // Cannot insert explicit value for identity column in table 'Departments' when IDENTITY_INSERT is set to OFF - errors.Add("Cannot insert explicit value for identity column in the system when the id is set to OFF"); + case 544 + : // Cannot insert explicit value for identity column in table 'Departments' when IDENTITY_INSERT is set to OFF + errors.Add( + "Cannot insert explicit value for identity column in the system when the id is set to OFF"); break; - case 547: // Constraint check violation, Conflict in the database + case 547: // Constraint check violation, Conflict in the database errors.Add("A Constraint Check violation Error Has Occured While Updating the record(s)!"); break; - case 2601: // Duplicated key row error // Constraint violation exception // A custom exception of yours for concurrency issues + case 2601 + : // Duplicated key row error // Constraint violation exception // A custom exception of yours for concurrency issues errors.Add("A Duplicate Key Error Has Occured While Updating the record(s)!"); break; - case 201: // Proceudre missing parameters + case 201: // Procedure missing parameters errors.Add("A Missing Parameter has led to Error While Creating the record(s)!"); break; - default: - break; } } - return errors.ToArray(); - } -} +} \ No newline at end of file diff --git a/src/Application/Common/ExceptionHandlers/ForbiddenAccessException.cs b/src/Application/Common/ExceptionHandlers/ForbiddenAccessException.cs index ad0c5e50a..a57fed2c7 100644 --- a/src/Application/Common/ExceptionHandlers/ForbiddenAccessException.cs +++ b/src/Application/Common/ExceptionHandlers/ForbiddenAccessException.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Application.Common.Exceptions; +namespace CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; public class ForbiddenException : ServerException { diff --git a/src/Application/Common/ExceptionHandlers/InternalServerException.cs b/src/Application/Common/ExceptionHandlers/InternalServerException.cs index 942e40b0c..c81ea2496 100644 --- a/src/Application/Common/ExceptionHandlers/InternalServerException.cs +++ b/src/Application/Common/ExceptionHandlers/InternalServerException.cs @@ -1,4 +1,4 @@ -namespace CleanArchitecture.Blazor.Application.Common.Exceptions; +namespace CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; public class InternalServerException : ServerException { public InternalServerException(string message) diff --git a/src/Application/Common/ExceptionHandlers/NotFoundException.cs b/src/Application/Common/ExceptionHandlers/NotFoundException.cs index 095c17710..ffe1808ff 100644 --- a/src/Application/Common/ExceptionHandlers/NotFoundException.cs +++ b/src/Application/Common/ExceptionHandlers/NotFoundException.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Application.Common.Exceptions; +namespace CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; public class NotFoundException : ServerException { diff --git a/src/Application/Common/ExceptionHandlers/ServerException.cs b/src/Application/Common/ExceptionHandlers/ServerException.cs index 83e2d2250..5a6aa9771 100644 --- a/src/Application/Common/ExceptionHandlers/ServerException.cs +++ b/src/Application/Common/ExceptionHandlers/ServerException.cs @@ -1,6 +1,6 @@ using System.Net; -namespace CleanArchitecture.Blazor.Application.Common.Exceptions; +namespace CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; public class ServerException : Exception { public IEnumerable ErrorMessages { get; } diff --git a/src/Application/Common/ExceptionHandlers/UnauthorizedException.cs b/src/Application/Common/ExceptionHandlers/UnauthorizedException.cs index 28ac53e3b..c6505be82 100644 --- a/src/Application/Common/ExceptionHandlers/UnauthorizedException.cs +++ b/src/Application/Common/ExceptionHandlers/UnauthorizedException.cs @@ -1,4 +1,4 @@ -namespace CleanArchitecture.Blazor.Application.Common.Exceptions; +namespace CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; public class UnauthorizedException : ServerException { public UnauthorizedException(string message) diff --git a/src/Application/Common/ExceptionHandlers/ValidationExceptionHandler.cs b/src/Application/Common/ExceptionHandlers/ValidationExceptionHandler.cs index 4d34db154..219b62142 100644 --- a/src/Application/Common/ExceptionHandlers/ValidationExceptionHandler.cs +++ b/src/Application/Common/ExceptionHandlers/ValidationExceptionHandler.cs @@ -1,11 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; - -namespace CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; +namespace CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; public class ValidationExceptionHandler : IRequestExceptionHandler where TRequest : IRequest where TException : ValidationException diff --git a/src/Application/Common/Extensions/DataRowExtensions.cs b/src/Application/Common/Extensions/DataRowExtensions.cs index 83a9a8944..b7aac1624 100644 --- a/src/Application/Common/Extensions/DataRowExtensions.cs +++ b/src/Application/Common/Extensions/DataRowExtensions.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Text; - namespace CleanArchitecture.Blazor.Application.Common.Extensions; public static class DataRowExtensions diff --git a/src/Application/Common/Extensions/DescriptionAttributeExtensions.cs b/src/Application/Common/Extensions/DescriptionAttributeExtensions.cs index 71d643a0e..a630b5e73 100644 --- a/src/Application/Common/Extensions/DescriptionAttributeExtensions.cs +++ b/src/Application/Common/Extensions/DescriptionAttributeExtensions.cs @@ -1,7 +1,4 @@ -using System.ComponentModel; -using System.Reflection; - -namespace CleanArchitecture.Blazor.Application.Common.Extensions; +namespace CleanArchitecture.Blazor.Application.Common.Extensions; public static class DescriptionAttributeExtensions { public static string GetDescription(this Enum e) diff --git a/src/Application/Common/Extensions/ExpressionExtensions.cs b/src/Application/Common/Extensions/ExpressionExtensions.cs index bf7d7fa4d..7a5104cdf 100644 --- a/src/Application/Common/Extensions/ExpressionExtensions.cs +++ b/src/Application/Common/Extensions/ExpressionExtensions.cs @@ -1,12 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq.Expressions; using System.Text.Json.Serialization; -using System.Text.Json; -using System.ComponentModel; -using System.Globalization; -using System.Reflection; namespace CleanArchitecture.Blazor.Application.Common.Extensions; #nullable disable @@ -27,9 +22,9 @@ public static Expression> FromFilter(string filters) { foreach (var filter in filterRules) { - if (Enum.TryParse(filter.op, out OperationExpression op) && !string.IsNullOrEmpty(filter.value)) + if (Enum.TryParse(filter.Op, out OperationExpression op) && !string.IsNullOrEmpty(filter.Value)) { - var expression = GetCriteriaWhere(filter.field, op, filter.value); + var expression = GetCriteriaWhere(filter.Field, op, filter.Value); any = any.And(expression); } } @@ -75,48 +70,46 @@ private static Expression> GetCriteriaWhere(string fieldName, O } switch (selectedOperator) { - case OperationExpression.equal: + case OperationExpression.Equal: body = Expression.Equal(expressionParameter, Expression.Constant(Convert.ChangeType(fieldValue.ToString() == "null" ? null : fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); return Expression.Lambda>(body, parameter); - case OperationExpression.notequal: + case OperationExpression.NotEqual: body = Expression.NotEqual(expressionParameter, Expression.Constant(Convert.ChangeType(fieldValue.ToString() == "null" ? null : fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); return Expression.Lambda>(body, parameter); - case OperationExpression.less: + case OperationExpression.Less: body = Expression.LessThan(expressionParameter, Expression.Constant(Convert.ChangeType(fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); return Expression.Lambda>(body, parameter); - case OperationExpression.lessorequal: + case OperationExpression.LessOrEqual: body = Expression.LessThanOrEqual(expressionParameter, Expression.Constant(Convert.ChangeType(fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); return Expression.Lambda>(body, parameter); - case OperationExpression.greater: + case OperationExpression.Greater: body = Expression.GreaterThan(expressionParameter, Expression.Constant(Convert.ChangeType(fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); return Expression.Lambda>(body, parameter); - case OperationExpression.greaterorequal: + case OperationExpression.GreaterOrEqual: body = Expression.GreaterThanOrEqual(expressionParameter, Expression.Constant(Convert.ChangeType(fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); return Expression.Lambda>(body, parameter); - case OperationExpression.contains: + case OperationExpression.Contains: var contains = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var bodyLike = Expression.Call(expressionParameter, contains, Expression.Constant(Convert.ChangeType(fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); return Expression.Lambda>(bodyLike, parameter); - case OperationExpression.endwith: - var endswith = typeof(string).GetMethod("EndsWith", new[] { typeof(string) }); - var bodyendwith = Expression.Call(expressionParameter, endswith, Expression.Constant(Convert.ChangeType(fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); - return Expression.Lambda>(bodyendwith, parameter); - case OperationExpression.beginwith: - var startswith = typeof(string).GetMethod("StartsWith", new[] { typeof(string) }); - var bodystartswith = Expression.Call(expressionParameter, startswith, Expression.Constant(Convert.ChangeType(fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); - return Expression.Lambda>(bodystartswith, parameter); - case OperationExpression.includes: + case OperationExpression.EndsWith: + var endsWith = typeof(string).GetMethod("EndsWith", new[] { typeof(string) }); + var bodyEndsWith = Expression.Call(expressionParameter, endsWith, Expression.Constant(Convert.ChangeType(fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); + return Expression.Lambda>(bodyEndsWith, parameter); + case OperationExpression.BeginsWith: + var startsWith = typeof(string).GetMethod("StartsWith", new[] { typeof(string) }); + var bodyStartsWith = Expression.Call(expressionParameter, startsWith, Expression.Constant(Convert.ChangeType(fieldValue, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), prop.PropertyType)); + return Expression.Lambda>(bodyStartsWith, parameter); + case OperationExpression.Includes: return Includes(fieldValue, parameter, expressionParameter, prop.PropertyType); - case OperationExpression.between: + case OperationExpression.Between: return Between(fieldValue, parameter, expressionParameter, prop.PropertyType); default: throw new ArgumentException("OperationExpression"); } } - else - { - return x => false; - } + + return x => false; } private static Expression> GetCriteriaWhere(string fieldName, OperationExpression selectedOperator, object fieldValue) @@ -131,24 +124,17 @@ private static Expression> GetCriteriaWhere(string fieldNam if (prop != null && fieldValue != null) { - switch (selectedOperator) + return selectedOperator switch { - case OperationExpression.any: - return Any(fieldValue, parameter, expressionParameter); - - default: - throw new Exception("Not implement Operation"); - } - } - else - { - Expression> filter = x => true; - return filter; + OperationExpression.Any => Any(fieldValue, parameter, expressionParameter), + _ => throw new Exception("Not implement Operation") + }; } - } - - + Expression> filter = x => true; + return filter; + } + #endregion @@ -158,8 +144,8 @@ private static string GetOperand(Expression> exp) { if (!(exp.Body is MemberExpression body)) { - var ubody = (UnaryExpression)exp.Body; - body = ubody.Operand as MemberExpression; + var uBody = (UnaryExpression)exp.Body; + body = uBody.Operand as MemberExpression; } var operand = body.ToString(); @@ -186,38 +172,38 @@ private static MemberExpression GetMemberExpression(ParameterExpression param private static Expression> Includes(object fieldValue, ParameterExpression parameterExpression, MemberExpression memberExpression, Type type) { - var safetype = Nullable.GetUnderlyingType(type) ?? type; + var safeType = Nullable.GetUnderlyingType(type) ?? type; - switch (safetype.Name.ToLower()) + switch (safeType.Name.ToLower()) { case "string": - var strlist = fieldValue.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries).ToList(); - if (strlist == null || strlist.Count == 0) + var strList = fieldValue.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries).ToList(); + if (strList == null || strList.Count == 0) { return x => true; } - var strmethod = typeof(List).GetMethod("Contains", new Type[] { typeof(string) }); - var strcallexp = Expression.Call(Expression.Constant(strlist.ToList()), strmethod, memberExpression); - return Expression.Lambda>(strcallexp, parameterExpression); + var strMethod = typeof(List).GetMethod("Contains", new Type[] { typeof(string) }); + var strCallExp = Expression.Call(Expression.Constant(strList.ToList()), strMethod, memberExpression); + return Expression.Lambda>(strCallExp, parameterExpression); case "int32": - var intlist = fieldValue.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToList(); - if (intlist == null || intlist.Count == 0) + var intList = fieldValue.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToList(); + if (intList == null || intList.Count == 0) { return x => true; } - var intmethod = typeof(List).GetMethod("Contains", new Type[] { typeof(int) }); - var intcallexp = Expression.Call(Expression.Constant(intlist.ToList()), intmethod, memberExpression); - return Expression.Lambda>(intcallexp, parameterExpression); + var intMethod = typeof(List).GetMethod("Contains", new Type[] { typeof(int) }); + var intCallExp = Expression.Call(Expression.Constant(intList.ToList()), intMethod, memberExpression); + return Expression.Lambda>(intCallExp, parameterExpression); case "float": case "decimal": - var floatlist = fieldValue.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries).Select(Decimal.Parse).ToList(); - if (floatlist == null || floatlist.Count == 0) + var floatList = fieldValue.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries).Select(Decimal.Parse).ToList(); + if (floatList == null || floatList.Count == 0) { return x => true; } - var floatmethod = typeof(List).GetMethod("Contains", new Type[] { typeof(decimal) }); - var floatcallexp = Expression.Call(Expression.Constant(floatlist.ToList()), floatmethod, memberExpression); - return Expression.Lambda>(floatcallexp, parameterExpression); + var floatMethod = typeof(List).GetMethod("Contains", new Type[] { typeof(decimal) }); + var floatCallExp = Expression.Call(Expression.Constant(floatList.ToList()), floatMethod, memberExpression); + return Expression.Lambda>(floatCallExp, parameterExpression); default: return x => true; } @@ -226,53 +212,53 @@ private static Expression> Includes(object fieldValue, Paramete private static Expression> Between(object fieldValue, ParameterExpression parameterExpression, MemberExpression memberExpression, Type type) { - var safetype = Nullable.GetUnderlyingType(type) ?? type; - switch (safetype.Name.ToLower()) + var safeType = Nullable.GetUnderlyingType(type) ?? type; + switch (safeType.Name.ToLower()) { case "datetime": - var datearray = ((string)fieldValue).Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); - var start = Convert.ToDateTime(datearray[0] + " 00:00:00", CultureInfo.CurrentCulture); - var end = Convert.ToDateTime(datearray[1] + " 23:59:59", CultureInfo.CurrentCulture); + var dateArray = ((string)fieldValue).Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); + var start = Convert.ToDateTime(dateArray[0] + " 00:00:00", CultureInfo.CurrentCulture); + var end = Convert.ToDateTime(dateArray[1] + " 23:59:59", CultureInfo.CurrentCulture); var greater = Expression.GreaterThanOrEqual(memberExpression, Expression.Constant(start, type)); var less = Expression.LessThanOrEqual(memberExpression, Expression.Constant(end, type)); return Expression.Lambda>(greater, parameterExpression) .And(Expression.Lambda>(less, parameterExpression)); case "int": case "int32": - var intarray = ((string)fieldValue).Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); - var min = Convert.ToInt32(intarray[0], CultureInfo.CurrentCulture); - var max = Convert.ToInt32(intarray[1], CultureInfo.CurrentCulture); - var maxthen = Expression.GreaterThanOrEqual(memberExpression, Expression.Constant(min, type)); - var minthen = Expression.LessThanOrEqual(memberExpression, Expression.Constant(max, type)); - return Expression.Lambda>(maxthen, parameterExpression) - .And(Expression.Lambda>(minthen, parameterExpression)); + var intArray = ((string)fieldValue).Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); + var min = Convert.ToInt32(intArray[0], CultureInfo.CurrentCulture); + var max = Convert.ToInt32(intArray[1], CultureInfo.CurrentCulture); + var maxThan = Expression.GreaterThanOrEqual(memberExpression, Expression.Constant(min, type)); + var lessThan = Expression.LessThanOrEqual(memberExpression, Expression.Constant(max, type)); + return Expression.Lambda>(maxThan, parameterExpression) + .And(Expression.Lambda>(lessThan, parameterExpression)); case "decimal": - var decarray = ((string)fieldValue).Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); - var dmin = Convert.ToDecimal(decarray[0], CultureInfo.CurrentCulture); - var dmax = Convert.ToDecimal(decarray[1], CultureInfo.CurrentCulture); - var dmaxthen = Expression.GreaterThanOrEqual(memberExpression, Expression.Constant(dmin, type)); - var dminthen = Expression.LessThanOrEqual(memberExpression, Expression.Constant(dmax, type)); - return Expression.Lambda>(dmaxthen, parameterExpression) - .And(Expression.Lambda>(dminthen, parameterExpression)); + var decArray = ((string)fieldValue).Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); + var dMin = Convert.ToDecimal(decArray[0], CultureInfo.CurrentCulture); + var dMax = Convert.ToDecimal(decArray[1], CultureInfo.CurrentCulture); + var dMaxThan = Expression.GreaterThanOrEqual(memberExpression, Expression.Constant(dMin, type)); + var dLessThan = Expression.LessThanOrEqual(memberExpression, Expression.Constant(dMax, type)); + return Expression.Lambda>(dMaxThan, parameterExpression) + .And(Expression.Lambda>(dLessThan, parameterExpression)); case "float": - var farray = ((string)fieldValue).Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); - var fmin = Convert.ToDecimal(farray[0], CultureInfo.CurrentCulture); - var fmax = Convert.ToDecimal(farray[1], CultureInfo.CurrentCulture); - var fmaxthen = Expression.GreaterThanOrEqual(memberExpression, Expression.Constant(fmin, type)); - var fminthen = Expression.LessThanOrEqual(memberExpression, Expression.Constant(fmax, type)); - return Expression.Lambda>(fmaxthen, parameterExpression) - .And(Expression.Lambda>(fminthen, parameterExpression)); + var fArray = ((string)fieldValue).Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); + var fMin = Convert.ToDecimal(fArray[0], CultureInfo.CurrentCulture); + var fMax = Convert.ToDecimal(fArray[1], CultureInfo.CurrentCulture); + var fMaxThan = Expression.GreaterThanOrEqual(memberExpression, Expression.Constant(fMin, type)); + var fLessThan = Expression.LessThanOrEqual(memberExpression, Expression.Constant(fMax, type)); + return Expression.Lambda>(fMaxThan, parameterExpression) + .And(Expression.Lambda>(fLessThan, parameterExpression)); case "string": - var strarray = ((string)fieldValue).Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); - var strstart = strarray[0]; - var strend = strarray[1]; - var strmethod = typeof(string).GetMethod("CompareTo", new[] { typeof(string) }); - var callcomparetostart = Expression.Call(memberExpression, strmethod, Expression.Constant(strstart, type)); - var callcomparetoend = Expression.Call(memberExpression, strmethod, Expression.Constant(strend, type)); - var strgreater = Expression.GreaterThanOrEqual(callcomparetostart, Expression.Constant(0)); - var strless = Expression.LessThanOrEqual(callcomparetoend, Expression.Constant(0)); - return Expression.Lambda>(strgreater, parameterExpression) - .And(Expression.Lambda>(strless, parameterExpression)); + var strArray = ((string)fieldValue).Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); + var strStart = strArray[0]; + var strEnd = strArray[1]; + var strMethod = typeof(string).GetMethod("CompareTo", new[] { typeof(string) }); + var callCompareToStart = Expression.Call(memberExpression, strMethod, Expression.Constant(strStart, type)); + var callCompareToEnd = Expression.Call(memberExpression, strMethod, Expression.Constant(strEnd, type)); + var strGreater = Expression.GreaterThanOrEqual(callCompareToStart, Expression.Constant(0)); + var strLess = Expression.LessThanOrEqual(callCompareToEnd, Expression.Constant(0)); + return Expression.Lambda>(strGreater, parameterExpression) + .And(Expression.Lambda>(strLess, parameterExpression)); default: return x => true; } @@ -387,16 +373,16 @@ public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOp internal enum OperationExpression { - equal, - notequal, - less, - lessorequal, - greater, - greaterorequal, - contains, - beginwith, - endwith, - includes, - between, - any + Equal, + NotEqual, + Less, + LessOrEqual, + Greater, + GreaterOrEqual, + Contains, + BeginsWith, + EndsWith, + Includes, + Between, + Any } diff --git a/src/Application/Common/Helper/ConstantStringLocalizer.cs b/src/Application/Common/Helper/ConstantStringLocalizer.cs index 2e06f95d5..7d828924f 100644 --- a/src/Application/Common/Helper/ConstantStringLocalizer.cs +++ b/src/Application/Common/Helper/ConstantStringLocalizer.cs @@ -1,4 +1,3 @@ -using System.Globalization; using System.Resources; namespace CleanArchitecture.Blazor.Application.Common.Helper; diff --git a/src/Application/Common/Interfaces/IApplicationDbContext.cs b/src/Application/Common/Interfaces/IApplicationDbContext.cs index 618a53de6..4291015fb 100644 --- a/src/Application/Common/Interfaces/IApplicationDbContext.cs +++ b/src/Application/Common/Interfaces/IApplicationDbContext.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. - +using CleanArchitecture.Blazor.Domain.Entities.Logger; using Microsoft.EntityFrameworkCore.ChangeTracking; namespace CleanArchitecture.Blazor.Application.Common.Interfaces; diff --git a/src/Application/Common/Interfaces/IMailService.cs b/src/Application/Common/Interfaces/IMailService.cs index 228aa981d..ebc270985 100644 --- a/src/Application/Common/Interfaces/IMailService.cs +++ b/src/Application/Common/Interfaces/IMailService.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Settings; using FluentEmail.Core.Models; namespace CleanArchitecture.Blazor.Application.Common.Interfaces; diff --git a/src/Application/Common/Interfaces/ISpecification.cs b/src/Application/Common/Interfaces/ISpecification.cs index cb1de4d29..3d2c63dfb 100644 --- a/src/Application/Common/Interfaces/ISpecification.cs +++ b/src/Application/Common/Interfaces/ISpecification.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq.Expressions; using CleanArchitecture.Blazor.Domain.Common; using Microsoft.EntityFrameworkCore.Query; diff --git a/src/Application/Common/Interfaces/Identity/IUserDataProvider.cs b/src/Application/Common/Interfaces/Identity/IUserDataProvider.cs index 8385c8a37..0f880f7e9 100644 --- a/src/Application/Common/Interfaces/Identity/IUserDataProvider.cs +++ b/src/Application/Common/Interfaces/Identity/IUserDataProvider.cs @@ -1,6 +1,5 @@ -using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity.DTOs; using CleanArchitecture.Blazor.Application.Features.Identity.Dto; namespace CleanArchitecture.Blazor.Application.Common.Interfaces.Identity; diff --git a/src/Application/Common/Interfaces/Serialization/DefaultJsonSerializerOptions.cs b/src/Application/Common/Interfaces/Serialization/DefaultJsonSerializerOptions.cs index 7ef86e35c..07c2ac520 100644 --- a/src/Application/Common/Interfaces/Serialization/DefaultJsonSerializerOptions.cs +++ b/src/Application/Common/Interfaces/Serialization/DefaultJsonSerializerOptions.cs @@ -1,6 +1,5 @@ using System.Text.Encodings.Web; using System.Text.Json.Serialization; -using System.Text.Json; using System.Text.Unicode; namespace CleanArchitecture.Blazor.Application.Common.Interfaces.Serialization; @@ -8,7 +7,6 @@ public class DefaultJsonSerializerOptions { public static JsonSerializerOptions Options => new() { - Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs), PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, diff --git a/src/Application/Common/Mappings/MappingProfile.cs b/src/Application/Common/Mappings/MappingProfile.cs index b5fa52313..27eba7436 100644 --- a/src/Application/Common/Mappings/MappingProfile.cs +++ b/src/Application/Common/Mappings/MappingProfile.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Reflection; - namespace CleanArchitecture.Blazor.Application.Common.Mappings; public class MappingProfile : Profile diff --git a/src/Application/Common/Models/FilterRule.cs b/src/Application/Common/Models/FilterRule.cs index 5aaa3f858..13b3d8452 100644 --- a/src/Application/Common/Models/FilterRule.cs +++ b/src/Application/Common/Models/FilterRule.cs @@ -5,7 +5,7 @@ namespace CleanArchitecture.Blazor.Application.Common.Models; public class FilterRule { - public string? field { get; set; } - public string? op { get; set; } - public string? value { get; set; } + public string? Field { get; set; } + public string? Op { get; set; } + public string? Value { get; set; } } diff --git a/src/Application/Common/Models/MailRequest.cs b/src/Application/Common/Models/MailRequest.cs index 4310bd1d7..6d817a470 100644 --- a/src/Application/Common/Models/MailRequest.cs +++ b/src/Application/Common/Models/MailRequest.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Application.Settings; +namespace CleanArchitecture.Blazor.Application.Common.Models; public class MailRequest { diff --git a/src/Application/Common/Models/UploadRequest.cs b/src/Application/Common/Models/UploadRequest.cs index a14b48237..b749a4421 100644 --- a/src/Application/Common/Models/UploadRequest.cs +++ b/src/Application/Common/Models/UploadRequest.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using CleanArchitecture.Blazor.Domain.Enums; + namespace CleanArchitecture.Blazor.Application.Common.Models; public class UploadRequest diff --git a/src/Application/Common/PublishStrategies/ParallelNoWaitPublisher.cs b/src/Application/Common/PublishStrategies/ParallelNoWaitPublisher.cs index 2f53d030a..27d73ecf0 100644 --- a/src/Application/Common/PublishStrategies/ParallelNoWaitPublisher.cs +++ b/src/Application/Common/PublishStrategies/ParallelNoWaitPublisher.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace CleanArchitecture.Blazor.Application.Common.PublishStrategies; +namespace CleanArchitecture.Blazor.Application.Common.PublishStrategies; public class ParallelNoWaitPublisher : INotificationPublisher { public Task Publish(IEnumerable handlerExecutors, INotification notification, CancellationToken cancellationToken) diff --git a/src/Application/Common/Security/LoginFormModel.cs b/src/Application/Common/Security/LoginFormModel.cs index 6c0005a34..c1843ee35 100644 --- a/src/Application/Common/Security/LoginFormModel.cs +++ b/src/Application/Common/Security/LoginFormModel.cs @@ -9,13 +9,11 @@ public class LoginFormModel -public class LoginFormModellFluentValidator : AbstractValidator +public class LoginFormModelFluentValidator : AbstractValidator { - private readonly IStringLocalizer _localizer; + private readonly IStringLocalizer _localizer; - public LoginFormModellFluentValidator( - IStringLocalizer localizer - ) + public LoginFormModelFluentValidator(IStringLocalizer localizer) { _localizer = localizer; RuleFor(x => x.UserName) diff --git a/src/Application/Common/Security/RegisterFormModelFluentValidator.cs b/src/Application/Common/Security/RegisterFormModelFluentValidator.cs index def9527eb..871a2348f 100644 --- a/src/Application/Common/Security/RegisterFormModelFluentValidator.cs +++ b/src/Application/Common/Security/RegisterFormModelFluentValidator.cs @@ -1,5 +1,3 @@ -using CleanArchitecture.Blazor.Application.Features.Products.Queries.Export; - namespace CleanArchitecture.Blazor.Application.Common.Security; public class RegisterFormModelFluentValidator : AbstractValidator diff --git a/src/Application/Common/Specification/Specification.cs b/src/Application/Common/Specification/Specification.cs index a34338409..cc7d15b5f 100644 --- a/src/Application/Common/Specification/Specification.cs +++ b/src/Application/Common/Specification/Specification.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq.Expressions; using CleanArchitecture.Blazor.Domain.Common; using Microsoft.EntityFrameworkCore.Query; diff --git a/src/Application/Constants/ClaimTypes/ApplicationClaimTypes.cs b/src/Application/Constants/ClaimTypes/ApplicationClaimTypes.cs index 03d111ae4..0ac35e686 100644 --- a/src/Application/Constants/ClaimTypes/ApplicationClaimTypes.cs +++ b/src/Application/Constants/ClaimTypes/ApplicationClaimTypes.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Application.Constants; +namespace CleanArchitecture.Blazor.Application.Constants.ClaimTypes; public static class ApplicationClaimTypes { diff --git a/src/Application/Constants/ConstantString.cs b/src/Application/Constants/ConstantString.cs index 8dabbeae6..294c997f5 100644 --- a/src/Application/Constants/ConstantString.cs +++ b/src/Application/Constants/ConstantString.cs @@ -1,82 +1,76 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace CleanArchitecture.Blazor.Application.Constants; +namespace CleanArchitecture.Blazor.Application.Constants; public static class ConstantString { //==========================================================// //for button text - public static string REFRESH => Localize("Refresh"); - public static string EDIT => Localize("Edit"); - public static string SUBMIT => Localize("Submit"); - public static string DELETE => Localize("Delete"); - public static string ADD => Localize("Add"); - public static string NEW => Localize("New"); - public static string EXPORT => Localize("Export to Excel"); - public static string EXPORTPDF => Localize("Export to PDF"); - public static string IMPORT => Localize("Import from Excel"); - public static string ACTIONS => Localize("Actions"); - public static string SAVE => Localize("Save"); - public static string SAVECHANGES => Localize("Save Changes"); - public static string CANCEL => Localize("Cancel"); - public static string CLOSE => Localize("Close"); - public static string SEARCH => Localize("Search"); - public static string CLEAR => Localize("Clear"); - public static string RESET => Localize("Reset"); - public static string OK => Localize("OK"); - public static string CONFIRM => Localize("Confirm"); - public static string YES => Localize("Yes"); - public static string NO => Localize("No"); - public static string NEXT => Localize("Next"); - public static string PREVIOUS => Localize("Previous"); - public static string UPLOAD => Localize("Upload"); - public static string DOWNLOAD => Localize("Download"); - public static string UPLOADING => Localize("Uploading..."); - public static string DOWNLOADING => Localize("Downloading..."); - public static string NOALLOWED => Localize("No Allowed"); - public static string SIGNINWITH => Localize("Sign in with {0}"); - public static string LOGOUT => Localize("Logout"); - public static string SIGNIN => Localize("Sign In"); + public static string Refresh => Localize("Refresh"); + public static string Edit => Localize("Edit"); + public static string Submit => Localize("Submit"); + public static string Delete => Localize("Delete"); + public static string Add => Localize("Add"); + public static string New => Localize("New"); + public static string Export => Localize("Export to Excel"); + public static string ExportPDF => Localize("Export to PDF"); + public static string Import => Localize("Import from Excel"); + public static string Actions => Localize("Actions"); + public static string Save => Localize("Save"); + public static string SaveChanges => Localize("Save Changes"); + public static string Cancel => Localize("Cancel"); + public static string Close => Localize("Close"); + public static string Search => Localize("Search"); + public static string Clear => Localize("Clear"); + public static string Reset => Localize("Reset"); + public static string Ok => Localize("OK"); + public static string Confirm => Localize("Confirm"); + public static string Yes => Localize("Yes"); + public static string No => Localize("No"); + public static string Next => Localize("Next"); + public static string Previous => Localize("Previous"); + public static string Upload => Localize("Upload"); + public static string Download => Localize("Download"); + public static string Uploading => Localize("Uploading..."); + public static string Downloading => Localize("Downloading..."); + public static string NoAllowed => Localize("No Allowed"); + public static string SigninWith => Localize("Sign in with {0}"); + public static string Logout => Localize("Logout"); + public static string Signin => Localize("Sign In"); public static string Microsoft => Localize("Microsoft"); public static string Facebook => Localize("Facebook"); public static string Google => Localize("Google"); //============================================================================// // for toast message - public static string SAVESUCCESS => Localize("Save successfully"); - public static string DELETESUCCESS => Localize("Delete successfully"); - public static string DELETEFAIL => Localize("Delete fail"); - public static string UPDATESUCCESS => Localize("Update successfully"); - public static string CREATESUCCESS => Localize("Create successfully"); - public static string LOGINSUCCESS => Localize("Login successfully"); - public static string LOGOUTSUCCESS => Localize("Logout successfully"); - public static string LOGINFAIL => Localize("Login fail"); - public static string LOGOUTFAIL => Localize("Logout fail"); - public static string IMPORTSUCCESS => Localize("Import successfully"); - public static string IMPORTFAIL => Localize("Import fail"); - public static string EXPORTSUCESS => Localize("Export successfully"); - public static string EXPORTFAIL => Localize("Export fail"); - public static string UPLOADSUCCESS => Localize("Upload successfully"); + public static string SaveSuccess => Localize("Save successfully"); + public static string DeleteSuccess => Localize("Delete successfully"); + public static string DeleteFail => Localize("Delete fail"); + public static string UpdateSuccess => Localize("Update successfully"); + public static string CreateSuccess => Localize("Create successfully"); + public static string LoginSuccess => Localize("Login successfully"); + public static string LogoutSuccess => Localize("Logout successfully"); + public static string LoginFail => Localize("Login fail"); + public static string LogoutFail => Localize("Logout fail"); + public static string ImportSuccess => Localize("Import successfully"); + public static string ImportFail => Localize("Import fail"); + public static string ExportSuccess => Localize("Export successfully"); + public static string ExportFail => Localize("Export fail"); + public static string UploadSuccess => Localize("Upload successfully"); //======================================================== - public static string ADVANCEDSEARCH => Localize("Advanced Search"); - public static string ORDERBY => Localize("Order By"); - public static string CREATEAITEM => Localize("Create a new {0}"); - public static string EDITTHEITEM => Localize("Edit the {0}"); - public static string DELETETHEITEM => Localize("Delete the {0}"); - public static string DELETEITEMS => Localize("Delete selected items: {0}"); - public static string DELETECONFIRMATION => Localize("Are you sure you want to delete this item: {0}?"); - public static string DELETECONFIRMATIONWITHID => Localize("Are you sure you want to delete this item with Id: {0}?"); - public static string DELETECONFIRMWITHSELECTED => Localize("Are you sure you want to delete the selected items: {0}?"); - public static string NORECORDS => Localize("There are no records to view."); - public static string LOADING => Localize("Loading..."); - public static string WATING => Localize("Wating..."); - public static string PROCESSING => Localize("Processing..."); - public static string DELETECONFIRMATIONTITLE => Localize("Delete Confirmation"); - public static string LOGOUTCONFIRMATIONTITLE => Localize("Logout Confirmation"); - public static string LOGOUTCONFIRMATION => Localize("You are attempting to log out of application. Do you really want to log out?"); + public static string AdvancedSearch => Localize("Advanced Search"); + public static string OrderBy => Localize("Order By"); + public static string CreateAnItem => Localize("Create a new {0}"); + public static string EditTheItem => Localize("Edit the {0}"); + public static string DeleteTheItem => Localize("Delete the {0}"); + public static string DeleteItems => Localize("Delete selected items: {0}"); + public static string DeleteConfirmation => Localize("Are you sure you want to delete this item: {0}?"); + public static string DeleteConfirmationWithId => Localize("Are you sure you want to delete this item with Id: {0}?"); + public static string DeleteConfirmWithSelected => Localize("Are you sure you want to delete the selected items: {0}?"); + public static string NoRecords => Localize("There are no records to view."); + public static string Loading => Localize("Loading..."); + public static string Waiting => Localize("Wating..."); + public static string Processing => Localize("Processing..."); + public static string DeleteConfirmationTitle => Localize("Delete Confirmation"); + public static string LogoutConfirmationTitle => Localize("Logout Confirmation"); + public static string LogoutConfirmation => Localize("You are attempting to log out of application. Do you really want to log out?"); } diff --git a/src/Application/Constants/GlobalVariable.cs b/src/Application/Constants/GlobalVariable.cs index 33f3f7bc7..0335ab684 100644 --- a/src/Application/Constants/GlobalVariable.cs +++ b/src/Application/Constants/GlobalVariable.cs @@ -1,5 +1,5 @@ namespace CleanArchitecture.Blazor.Application.Constants; public static class GlobalVariable { - public static long maxAllowedSize => 512000 * 100; + public static long MaxAllowedSize => 512000 * 100; } diff --git a/src/Application/Constants/LocalStorage/LocalStorage.cs b/src/Application/Constants/LocalStorage/LocalStorage.cs index f95637c82..9ed44b30d 100644 --- a/src/Application/Constants/LocalStorage/LocalStorage.cs +++ b/src/Application/Constants/LocalStorage/LocalStorage.cs @@ -1,9 +1,9 @@ -namespace CleanArchitecture.Blazor.Application.Constants; +namespace CleanArchitecture.Blazor.Application.Constants.LocalStorage; public static class LocalStorage { - public const string USERID = "UserId"; - public const string USERNAME = "UserName"; - public const string TENANTID = "TenantId"; - public const string TENANTNAME = "TenantName"; - public const string CLAIMSIDENTITY = "ClaimsIdentity"; + public const string UserId = "UserId"; + public const string Username = "UserName"; + public const string TenantId = "TenantId"; + public const string TenantName = "TenantName"; + public const string ClaimsIdentity = "ClaimsIdentity"; } diff --git a/src/Application/Constants/Permission/PermissionModules.cs b/src/Application/Constants/Permission/PermissionModules.cs index ecdc48f34..b0eedfb2b 100644 --- a/src/Application/Constants/Permission/PermissionModules.cs +++ b/src/Application/Constants/Permission/PermissionModules.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Application.Constants; +namespace CleanArchitecture.Blazor.Application.Constants.Permission; public static class PermissionModules { diff --git a/src/Application/Constants/Permission/Permissions.cs b/src/Application/Constants/Permission/Permissions.cs index b50515daf..6ed8e9e7c 100644 --- a/src/Application/Constants/Permission/Permissions.cs +++ b/src/Application/Constants/Permission/Permissions.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.ComponentModel; -using System.Reflection; - -namespace CleanArchitecture.Blazor.Application.Constants; +namespace CleanArchitecture.Blazor.Application.Constants.Permission; public static class Permissions { diff --git a/src/Application/Constants/Role/RoleNameConstants.cs b/src/Application/Constants/Role/RoleNameConstants.cs index ef9a60a62..c7bc235d8 100644 --- a/src/Application/Constants/Role/RoleNameConstants.cs +++ b/src/Application/Constants/Role/RoleNameConstants.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Application.Constants; +namespace CleanArchitecture.Blazor.Application.Constants.Role; public static class RoleName { diff --git a/src/Application/Constants/User/UserNameConstants.cs b/src/Application/Constants/User/UserNameConstants.cs index 0997eb91f..9ee0ed177 100644 --- a/src/Application/Constants/User/UserNameConstants.cs +++ b/src/Application/Constants/User/UserNameConstants.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Application.Constants; +namespace CleanArchitecture.Blazor.Application.Constants.User; public static class UserName { diff --git a/src/Application/DependencyInjection.cs b/src/Application/DependencyInjection.cs index 14446b9ec..d6445e605 100644 --- a/src/Application/DependencyInjection.cs +++ b/src/Application/DependencyInjection.cs @@ -7,10 +7,7 @@ using CleanArchitecture.Blazor.Application.Common.Security; using CleanArchitecture.Blazor.Application.Services.MultiTenant; using CleanArchitecture.Blazor.Application.Services.Picklist; -using MediatR; -using MediatR.Pipeline; using Microsoft.Extensions.DependencyInjection; -using System.Reflection; namespace CleanArchitecture.Blazor.Application; diff --git a/src/Application/Features/AuditTrails/Caching/AuditTrailsCacheKey.cs b/src/Application/Features/AuditTrails/Caching/AuditTrailsCacheKey.cs index 820763dc0..467f9e09c 100644 --- a/src/Application/Features/AuditTrails/Caching/AuditTrailsCacheKey.cs +++ b/src/Application/Features/AuditTrails/Caching/AuditTrailsCacheKey.cs @@ -5,7 +5,7 @@ namespace CleanArchitecture.Blazor.Application.Features.AuditTrails.Caching; public static class AuditTrailsCacheKey { - private static readonly TimeSpan refreshInterval = TimeSpan.FromMilliseconds(30); + private static readonly TimeSpan RefreshInterval = TimeSpan.FromMilliseconds(30); public const string GetAllCacheKey = "all-audittrails"; public static string GetPaginationCacheKey(string parameters) { @@ -13,16 +13,16 @@ public static string GetPaginationCacheKey(string parameters) } static AuditTrailsCacheKey() { - _tokensource = new CancellationTokenSource(refreshInterval); + _tokenSource = new CancellationTokenSource(RefreshInterval); } - private static CancellationTokenSource _tokensource; + private static CancellationTokenSource _tokenSource; public static CancellationTokenSource SharedExpiryTokenSource() { - if (_tokensource.IsCancellationRequested) + if (_tokenSource.IsCancellationRequested) { - _tokensource = new CancellationTokenSource(refreshInterval); + _tokenSource = new CancellationTokenSource(RefreshInterval); } - return _tokensource; + return _tokenSource; } public static void Refresh() => SharedExpiryTokenSource().Cancel(); public static MemoryCacheEntryOptions MemoryCacheEntryOptions => new MemoryCacheEntryOptions().AddExpirationToken(new CancellationChangeToken(SharedExpiryTokenSource().Token)); diff --git a/src/Application/Features/AuditTrails/DTOs/AuditTrailDto.cs b/src/Application/Features/AuditTrails/DTOs/AuditTrailDto.cs index 954c71ff5..077b6e7e1 100644 --- a/src/Application/Features/AuditTrails/DTOs/AuditTrailDto.cs +++ b/src/Application/Features/AuditTrails/DTOs/AuditTrailDto.cs @@ -3,7 +3,7 @@ using CleanArchitecture.Blazor.Application.Common.Interfaces.Serialization; using CleanArchitecture.Blazor.Application.Features.Identity.Dto; - +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.AuditTrails.DTOs; [Description("Audit Trails")] diff --git a/src/Application/Features/AuditTrails/Queries/PaginationQuery/AuditTrailsWithPaginationQuery.cs b/src/Application/Features/AuditTrails/Queries/PaginationQuery/AuditTrailsWithPaginationQuery.cs index 512257f2c..49de8ad6d 100644 --- a/src/Application/Features/AuditTrails/Queries/PaginationQuery/AuditTrailsWithPaginationQuery.cs +++ b/src/Application/Features/AuditTrails/Queries/PaginationQuery/AuditTrailsWithPaginationQuery.cs @@ -1,12 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Globalization; -using System.Linq.Expressions; -using System.Reflection; using CleanArchitecture.Blazor.Application.Features.AuditTrails.Caching; using CleanArchitecture.Blazor.Application.Features.AuditTrails.DTOs; -using CleanArchitecture.Blazor.Application.Features.Products.Queries; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.AuditTrails.Queries.PaginationQuery; diff --git a/src/Application/Features/Customers/Commands/AddEdit/AddEditCustomerCommand.cs b/src/Application/Features/Customers/Commands/AddEdit/AddEditCustomerCommand.cs index 38d1d2ecf..2db6a3ab9 100644 --- a/src/Application/Features/Customers/Commands/AddEdit/AddEditCustomerCommand.cs +++ b/src/Application/Features/Customers/Commands/AddEdit/AddEditCustomerCommand.cs @@ -1,8 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using CleanArchitecture.Blazor.Application.Features.Customers.Caching; +using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; + namespace CleanArchitecture.Blazor.Application.Features.Customers.Commands.AddEdit; public class AddEditCustomerCommand: IMapFrom,ICacheInvalidatorRequest> diff --git a/src/Application/Features/Customers/Commands/Create/CreateCustomerCommand.cs b/src/Application/Features/Customers/Commands/Create/CreateCustomerCommand.cs index f307ff44a..62e99c20a 100644 --- a/src/Application/Features/Customers/Commands/Create/CreateCustomerCommand.cs +++ b/src/Application/Features/Customers/Commands/Create/CreateCustomerCommand.cs @@ -1,8 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.ComponentModel; -using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; + using CleanArchitecture.Blazor.Application.Features.Customers.Caching; +using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; namespace CleanArchitecture.Blazor.Application.Features.Customers.Commands.Create; diff --git a/src/Application/Features/Customers/Commands/Delete/DeleteCustomerCommand.cs b/src/Application/Features/Customers/Commands/Delete/DeleteCustomerCommand.cs index 8ce8d94d5..c9dbfdc74 100644 --- a/src/Application/Features/Customers/Commands/Delete/DeleteCustomerCommand.cs +++ b/src/Application/Features/Customers/Commands/Delete/DeleteCustomerCommand.cs @@ -1,10 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; using CleanArchitecture.Blazor.Application.Features.Customers.Caching; - namespace CleanArchitecture.Blazor.Application.Features.Customers.Commands.Delete; public class DeleteCustomerCommand: FilterBase, ICacheInvalidatorRequest> diff --git a/src/Application/Features/Customers/Commands/Import/ImportCustomersCommand.cs b/src/Application/Features/Customers/Commands/Import/ImportCustomersCommand.cs index 947cf963d..fae4146a7 100644 --- a/src/Application/Features/Customers/Commands/Import/ImportCustomersCommand.cs +++ b/src/Application/Features/Customers/Commands/Import/ImportCustomersCommand.cs @@ -1,8 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; using CleanArchitecture.Blazor.Application.Features.Customers.Caching; +using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; namespace CleanArchitecture.Blazor.Application.Features.Customers.Commands.Import; diff --git a/src/Application/Features/Customers/Commands/Update/UpdateCustomerCommand.cs b/src/Application/Features/Customers/Commands/Update/UpdateCustomerCommand.cs index 8051c012f..c0a83f305 100644 --- a/src/Application/Features/Customers/Commands/Update/UpdateCustomerCommand.cs +++ b/src/Application/Features/Customers/Commands/Update/UpdateCustomerCommand.cs @@ -1,8 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.ComponentModel; -using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; + +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using CleanArchitecture.Blazor.Application.Features.Customers.Caching; +using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; namespace CleanArchitecture.Blazor.Application.Features.Customers.Commands.Update; diff --git a/src/Application/Features/Customers/DTOs/CustomerDto.cs b/src/Application/Features/Customers/DTOs/CustomerDto.cs index dd3b2b2e6..e5b346647 100644 --- a/src/Application/Features/Customers/DTOs/CustomerDto.cs +++ b/src/Application/Features/Customers/DTOs/CustomerDto.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.ComponentModel; namespace CleanArchitecture.Blazor.Application.Features.Customers.DTOs; [Description("Customers")] diff --git a/src/Application/Features/Customers/Queries/GetAll/GetAllCustomersQuery.cs b/src/Application/Features/Customers/Queries/GetAll/GetAllCustomersQuery.cs index 2f251257a..68a66a287 100644 --- a/src/Application/Features/Customers/Queries/GetAll/GetAllCustomersQuery.cs +++ b/src/Application/Features/Customers/Queries/GetAll/GetAllCustomersQuery.cs @@ -1,8 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; using CleanArchitecture.Blazor.Application.Features.Customers.Caching; +using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; namespace CleanArchitecture.Blazor.Application.Features.Customers.Queries.GetAll; diff --git a/src/Application/Features/Customers/Queries/GetById/GetCustomerByIdQuery.cs b/src/Application/Features/Customers/Queries/GetById/GetCustomerByIdQuery.cs index 834e8b3c8..2b831912c 100644 --- a/src/Application/Features/Customers/Queries/GetById/GetCustomerByIdQuery.cs +++ b/src/Application/Features/Customers/Queries/GetById/GetCustomerByIdQuery.cs @@ -1,8 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using CleanArchitecture.Blazor.Application.Features.Customers.Caching; +using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; namespace CleanArchitecture.Blazor.Application.Features.Customers.Queries.GetById; diff --git a/src/Application/Features/Customers/Queries/Pagination/CustomersPaginationQuery.cs b/src/Application/Features/Customers/Queries/Pagination/CustomersPaginationQuery.cs index c2e432dc2..241da77eb 100644 --- a/src/Application/Features/Customers/Queries/Pagination/CustomersPaginationQuery.cs +++ b/src/Application/Features/Customers/Queries/Pagination/CustomersPaginationQuery.cs @@ -1,8 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; using CleanArchitecture.Blazor.Application.Features.Customers.Caching; +using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; namespace CleanArchitecture.Blazor.Application.Features.Customers.Queries.Pagination; diff --git a/src/Application/Features/Documents/Commands/AddEdit/AddEditDocumentCommand.cs b/src/Application/Features/Documents/Commands/AddEdit/AddEditDocumentCommand.cs index 59d147b5b..37869a5de 100644 --- a/src/Application/Features/Documents/Commands/AddEdit/AddEditDocumentCommand.cs +++ b/src/Application/Features/Documents/Commands/AddEdit/AddEditDocumentCommand.cs @@ -1,9 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Documents.DTOs; +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using CleanArchitecture.Blazor.Application.Features.Documents.Caching; -using CleanArchitecture.Blazor.Application.Features.Identity.Dto; +using CleanArchitecture.Blazor.Application.Features.Documents.DTOs; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.Documents.Commands.AddEdit; diff --git a/src/Application/Features/Documents/Commands/Upload/UploadDocumentCommand.cs b/src/Application/Features/Documents/Commands/Upload/UploadDocumentCommand.cs index 997802563..30d09a34f 100644 --- a/src/Application/Features/Documents/Commands/Upload/UploadDocumentCommand.cs +++ b/src/Application/Features/Documents/Commands/Upload/UploadDocumentCommand.cs @@ -1,8 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Documents.DTOs; using CleanArchitecture.Blazor.Application.Features.Documents.Caching; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.Documents.Commands.Upload; diff --git a/src/Application/Features/Documents/DTOs/DocumentDto.cs b/src/Application/Features/Documents/DTOs/DocumentDto.cs index a8df58ce6..6b6549993 100644 --- a/src/Application/Features/Documents/DTOs/DocumentDto.cs +++ b/src/Application/Features/Documents/DTOs/DocumentDto.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using CleanArchitecture.Blazor.Application.Features.Identity.Dto; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.Documents.DTOs; [Description("Documents")] diff --git a/src/Application/Features/Documents/EventHandlers/DocumentCreatedEventHandler.cs b/src/Application/Features/Documents/EventHandlers/DocumentCreatedEventHandler.cs index a72466381..35d4c0626 100644 --- a/src/Application/Features/Documents/EventHandlers/DocumentCreatedEventHandler.cs +++ b/src/Application/Features/Documents/EventHandlers/DocumentCreatedEventHandler.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. - using CleanArchitecture.Blazor.Application.Services.PaddleOCR; using Hangfire; using Microsoft.Extensions.DependencyInjection; diff --git a/src/Application/Features/Documents/EventHandlers/DocumentDeletedEventHandler.cs b/src/Application/Features/Documents/EventHandlers/DocumentDeletedEventHandler.cs index 9b7afb282..9b5bba617 100644 --- a/src/Application/Features/Documents/EventHandlers/DocumentDeletedEventHandler.cs +++ b/src/Application/Features/Documents/EventHandlers/DocumentDeletedEventHandler.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. - -using CleanArchitecture.Blazor.Application.Services.PaddleOCR; -using Hangfire; -using MediatR; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.Documents.EventHandlers; diff --git a/src/Application/Features/Documents/Queries/GetFileStream/GetFileStreamQuery.cs b/src/Application/Features/Documents/Queries/GetFileStream/GetFileStreamQuery.cs index d90800c05..e6da9b840 100644 --- a/src/Application/Features/Documents/Queries/GetFileStream/GetFileStreamQuery.cs +++ b/src/Application/Features/Documents/Queries/GetFileStream/GetFileStreamQuery.cs @@ -1,9 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Documents.DTOs; using CleanArchitecture.Blazor.Application.Features.Documents.Caching; -using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant; namespace CleanArchitecture.Blazor.Application.Features.Documents.Queries.PaginationQuery; diff --git a/src/Application/Features/Documents/Queries/PaginationQuery/DocumentsWithPaginationQuery.cs b/src/Application/Features/Documents/Queries/PaginationQuery/DocumentsWithPaginationQuery.cs index 11c1b73e7..6b63de53b 100644 --- a/src/Application/Features/Documents/Queries/PaginationQuery/DocumentsWithPaginationQuery.cs +++ b/src/Application/Features/Documents/Queries/PaginationQuery/DocumentsWithPaginationQuery.cs @@ -1,10 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Documents.DTOs; using CleanArchitecture.Blazor.Application.Features.Documents.Caching; -using DocumentFormat.OpenXml.Wordprocessing; -using Document = CleanArchitecture.Blazor.Domain.Entities.Document; +using CleanArchitecture.Blazor.Application.Features.Documents.DTOs; namespace CleanArchitecture.Blazor.Application.Features.Documents.Queries.PaginationQuery; diff --git a/src/Application/Features/Identity/Notification/UpdateUserProfileCommand.cs b/src/Application/Features/Identity/Notification/UpdateUserProfileCommand.cs index 6cb7fa00a..dcba0bc5a 100644 --- a/src/Application/Features/Identity/Notification/UpdateUserProfileCommand.cs +++ b/src/Application/Features/Identity/Notification/UpdateUserProfileCommand.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace CleanArchitecture.Blazor.Application.Features.Identity.Notification; +namespace CleanArchitecture.Blazor.Application.Features.Identity.Notification; public class UpdateUserProfileCommand:INotification { public UserProfile UserProfile { get; set; } = null!; diff --git a/src/Application/Features/KeyValues/Commands/AddEdit/AddEditKeyValueCommand.cs b/src/Application/Features/KeyValues/Commands/AddEdit/AddEditKeyValueCommand.cs index c91397906..047b1da83 100644 --- a/src/Application/Features/KeyValues/Commands/AddEdit/AddEditKeyValueCommand.cs +++ b/src/Application/Features/KeyValues/Commands/AddEdit/AddEditKeyValueCommand.cs @@ -1,8 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using CleanArchitecture.Blazor.Application.Features.KeyValues.Caching; using CleanArchitecture.Blazor.Application.Features.KeyValues.DTOs; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.AddEdit; diff --git a/src/Application/Features/KeyValues/Commands/AddEdit/AddEditKeyValueCommandValidator.cs b/src/Application/Features/KeyValues/Commands/AddEdit/AddEditKeyValueCommandValidator.cs index d9f1bc201..37b73c076 100644 --- a/src/Application/Features/KeyValues/Commands/AddEdit/AddEditKeyValueCommandValidator.cs +++ b/src/Application/Features/KeyValues/Commands/AddEdit/AddEditKeyValueCommandValidator.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Tenants.Commands.AddEdit; - namespace CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.AddEdit; public class AddEditKeyValueCommandValidator : AbstractValidator diff --git a/src/Application/Features/KeyValues/Commands/Import/ImportKeyValuesCommand.cs b/src/Application/Features/KeyValues/Commands/Import/ImportKeyValuesCommand.cs index 6d19dc1ee..2f7c8f40e 100644 --- a/src/Application/Features/KeyValues/Commands/Import/ImportKeyValuesCommand.cs +++ b/src/Application/Features/KeyValues/Commands/Import/ImportKeyValuesCommand.cs @@ -3,7 +3,7 @@ using CleanArchitecture.Blazor.Application.Features.KeyValues.Caching; using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.AddEdit; -using CleanArchitecture.Blazor.Application.Features.KeyValues.DTOs; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.Import; diff --git a/src/Application/Features/KeyValues/DTOs/KeyValueDto.cs b/src/Application/Features/KeyValues/DTOs/KeyValueDto.cs index 3c0baf2c3..b9155b740 100644 --- a/src/Application/Features/KeyValues/DTOs/KeyValueDto.cs +++ b/src/Application/Features/KeyValues/DTOs/KeyValueDto.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using CleanArchitecture.Blazor.Domain.Enums; + namespace CleanArchitecture.Blazor.Application.Features.KeyValues.DTOs; [Description("Picklist")] diff --git a/src/Application/Features/KeyValues/Queries/ByName/KeyValuesQueryByName.cs b/src/Application/Features/KeyValues/Queries/ByName/KeyValuesQueryByName.cs index 127d471b7..0fc09ec3c 100644 --- a/src/Application/Features/KeyValues/Queries/ByName/KeyValuesQueryByName.cs +++ b/src/Application/Features/KeyValues/Queries/ByName/KeyValuesQueryByName.cs @@ -3,6 +3,7 @@ using CleanArchitecture.Blazor.Application.Features.KeyValues.Caching; using CleanArchitecture.Blazor.Application.Features.KeyValues.DTOs; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.ByName; diff --git a/src/Application/Features/KeyValues/Queries/PaginationQuery/KeyValuesWithPaginationQuery.cs b/src/Application/Features/KeyValues/Queries/PaginationQuery/KeyValuesWithPaginationQuery.cs index 9a8e1eae7..f0906ed3a 100644 --- a/src/Application/Features/KeyValues/Queries/PaginationQuery/KeyValuesWithPaginationQuery.cs +++ b/src/Application/Features/KeyValues/Queries/PaginationQuery/KeyValuesWithPaginationQuery.cs @@ -1,9 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.KeyValues.DTOs; using CleanArchitecture.Blazor.Application.Features.KeyValues.Caching; -using CleanArchitecture.Blazor.Application.Features.AuditTrails.DTOs; +using CleanArchitecture.Blazor.Application.Features.KeyValues.DTOs; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.PaginationQuery; diff --git a/src/Application/Features/Loggers/Commands/Clear/ClearLogsCommand.cs b/src/Application/Features/Loggers/Commands/Clear/ClearLogsCommand.cs index 05af7d2f4..196ba78ee 100644 --- a/src/Application/Features/Loggers/Commands/Clear/ClearLogsCommand.cs +++ b/src/Application/Features/Loggers/Commands/Clear/ClearLogsCommand.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. - -using CleanArchitecture.Blazor.Application.Common.Interfaces; using CleanArchitecture.Blazor.Application.Features.Loggers.Caching; -using static CleanArchitecture.Blazor.Application.Constants.Permissions; namespace CleanArchitecture.Blazor.Application.Features.Loggers.Commands.Delete; diff --git a/src/Application/Features/Loggers/DTOs/LogDto.cs b/src/Application/Features/Loggers/DTOs/LogDto.cs index 6287f5c20..166f35cbf 100644 --- a/src/Application/Features/Loggers/DTOs/LogDto.cs +++ b/src/Application/Features/Loggers/DTOs/LogDto.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using CleanArchitecture.Blazor.Domain.Entities.Logger; + namespace CleanArchitecture.Blazor.Application.Features.Loggers.DTOs; public class LogDto : IMapFrom diff --git a/src/Application/Features/Loggers/Queries/PaginationQuery/LogsWithPaginationQuery.cs b/src/Application/Features/Loggers/Queries/PaginationQuery/LogsWithPaginationQuery.cs index 10fd782a4..aa193a213 100644 --- a/src/Application/Features/Loggers/Queries/PaginationQuery/LogsWithPaginationQuery.cs +++ b/src/Application/Features/Loggers/Queries/PaginationQuery/LogsWithPaginationQuery.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Globalization; -using System.Linq.Expressions; -using System.Reflection; using CleanArchitecture.Blazor.Application.Features.Loggers.Caching; using CleanArchitecture.Blazor.Application.Features.Loggers.DTOs; diff --git a/src/Application/Features/Products/Commands/AddEdit/AddEditProductCommand.cs b/src/Application/Features/Products/Commands/AddEdit/AddEditProductCommand.cs index b186a74e4..4a68224ef 100644 --- a/src/Application/Features/Products/Commands/AddEdit/AddEditProductCommand.cs +++ b/src/Application/Features/Products/Commands/AddEdit/AddEditProductCommand.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Documents.DTOs; +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using CleanArchitecture.Blazor.Application.Features.Products.Caching; using CleanArchitecture.Blazor.Application.Features.Products.DTOs; using Microsoft.AspNetCore.Components.Forms; diff --git a/src/Application/Features/Products/Commands/Delete/DeleteProductCommand.cs b/src/Application/Features/Products/Commands/Delete/DeleteProductCommand.cs index 353d4f7b0..fb624bbbb 100644 --- a/src/Application/Features/Products/Commands/Delete/DeleteProductCommand.cs +++ b/src/Application/Features/Products/Commands/Delete/DeleteProductCommand.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. - using CleanArchitecture.Blazor.Application.Features.Products.Caching; namespace CleanArchitecture.Blazor.Application.Features.Products.Commands.Delete; diff --git a/src/Application/Features/Products/DTOs/ProductDto.cs b/src/Application/Features/Products/DTOs/ProductDto.cs index 45987b69e..0bdc0c06e 100644 --- a/src/Application/Features/Products/DTOs/ProductDto.cs +++ b/src/Application/Features/Products/DTOs/ProductDto.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Documents.DTOs; -using Microsoft.AspNetCore.Components.Forms; - namespace CleanArchitecture.Blazor.Application.Features.Products.DTOs; [Description("Products")] diff --git a/src/Application/Features/Products/Queries/Export/ExportProductsQuery.cs b/src/Application/Features/Products/Queries/Export/ExportProductsQuery.cs index d2a44b88a..d42d0a7d6 100644 --- a/src/Application/Features/Products/Queries/Export/ExportProductsQuery.cs +++ b/src/Application/Features/Products/Queries/Export/ExportProductsQuery.cs @@ -4,6 +4,7 @@ using CleanArchitecture.Blazor.Application.Common.Interfaces.Serialization; using CleanArchitecture.Blazor.Application.Features.Products.DTOs; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Application.Features.Products.Queries.Export; diff --git a/src/Application/Features/Products/Queries/Pagination/ProductsPaginationQuery.cs b/src/Application/Features/Products/Queries/Pagination/ProductsPaginationQuery.cs index d48068682..73179fbda 100644 --- a/src/Application/Features/Products/Queries/Pagination/ProductsPaginationQuery.cs +++ b/src/Application/Features/Products/Queries/Pagination/ProductsPaginationQuery.cs @@ -4,9 +4,6 @@ using CleanArchitecture.Blazor.Application.Features.Products.Caching; using CleanArchitecture.Blazor.Application.Features.Products.DTOs; -using CleanArchitecture.Blazor.Application.Features.Products.Queries; -using DocumentFormat.OpenXml.Wordprocessing; -using Microsoft.AspNetCore.Mvc; namespace CleanArchitecture.Blazor.Application.Features.Products.Queries.Pagination; diff --git a/src/Application/Features/Products/Queries/Specification/SearchProductSpecification.cs b/src/Application/Features/Products/Queries/Specification/SearchProductSpecification.cs index d32114f62..406302e56 100644 --- a/src/Application/Features/Products/Queries/Specification/SearchProductSpecification.cs +++ b/src/Application/Features/Products/Queries/Specification/SearchProductSpecification.cs @@ -1,6 +1,3 @@ -using System.Globalization; -using System.Linq.Expressions; -using System.Reflection; using CleanArchitecture.Blazor.Application.Features.Products.Queries.Pagination; namespace CleanArchitecture.Blazor.Application.Features.Products.Queries; diff --git a/src/Application/Features/Tenants/Commands/AddEdit/AddEditTenantCommand.cs b/src/Application/Features/Tenants/Commands/AddEdit/AddEditTenantCommand.cs index 4fd733aea..0fd009215 100644 --- a/src/Application/Features/Tenants/Commands/AddEdit/AddEditTenantCommand.cs +++ b/src/Application/Features/Tenants/Commands/AddEdit/AddEditTenantCommand.cs @@ -2,8 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Tenants.DTOs; using CleanArchitecture.Blazor.Application.Features.Tenants.Caching; +using CleanArchitecture.Blazor.Application.Features.Tenants.DTOs; + namespace CleanArchitecture.Blazor.Application.Features.Tenants.Commands.AddEdit; public class AddEditTenantCommand : IMapFrom, ICacheInvalidatorRequest> diff --git a/src/Application/Features/Tenants/Commands/Delete/DeleteTenantCommand.cs b/src/Application/Features/Tenants/Commands/Delete/DeleteTenantCommand.cs index ddd9521cd..348d72886 100644 --- a/src/Application/Features/Tenants/Commands/Delete/DeleteTenantCommand.cs +++ b/src/Application/Features/Tenants/Commands/Delete/DeleteTenantCommand.cs @@ -1,10 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Tenants.DTOs; using CleanArchitecture.Blazor.Application.Features.Tenants.Caching; - namespace CleanArchitecture.Blazor.Application.Features.Tenants.Commands.Delete; public class DeleteTenantCommand : ICacheInvalidatorRequest> diff --git a/src/Application/Features/Tenants/Queries/GetAll/GetAllTenantsQuery.cs b/src/Application/Features/Tenants/Queries/GetAll/GetAllTenantsQuery.cs index 6e7601b8e..2351b6ac6 100644 --- a/src/Application/Features/Tenants/Queries/GetAll/GetAllTenantsQuery.cs +++ b/src/Application/Features/Tenants/Queries/GetAll/GetAllTenantsQuery.cs @@ -1,8 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Tenants.DTOs; using CleanArchitecture.Blazor.Application.Features.Tenants.Caching; +using CleanArchitecture.Blazor.Application.Features.Tenants.DTOs; namespace CleanArchitecture.Blazor.Application.Features.Tenants.Queries.GetAll; diff --git a/src/Application/Features/Tenants/Queries/Pagination/TenantsPaginationQuery.cs b/src/Application/Features/Tenants/Queries/Pagination/TenantsPaginationQuery.cs index 18b1674e0..9520de410 100644 --- a/src/Application/Features/Tenants/Queries/Pagination/TenantsPaginationQuery.cs +++ b/src/Application/Features/Tenants/Queries/Pagination/TenantsPaginationQuery.cs @@ -1,9 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Application.Features.Tenants.DTOs; using CleanArchitecture.Blazor.Application.Features.Tenants.Caching; - +using CleanArchitecture.Blazor.Application.Features.Tenants.DTOs; namespace CleanArchitecture.Blazor.Application.Features.Tenants.Queries.Pagination; diff --git a/src/Application/Services/MultiTenant/TenantService.cs b/src/Application/Services/MultiTenant/TenantService.cs index 36bf1e6a2..80b6b93f0 100644 --- a/src/Application/Services/MultiTenant/TenantService.cs +++ b/src/Application/Services/MultiTenant/TenantService.cs @@ -1,7 +1,6 @@ using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant; using CleanArchitecture.Blazor.Application.Features.Tenants.Caching; using CleanArchitecture.Blazor.Application.Features.Tenants.DTOs; -using LazyCache; namespace CleanArchitecture.Blazor.Application.Services.MultiTenant; @@ -10,40 +9,37 @@ public class TenantService : ITenantService private readonly IAppCache _cache; private readonly IApplicationDbContext _context; private readonly IMapper _mapper; - public event Action? OnChange; - public List DataSource { get; private set; } = new(); public TenantService( - IAppCache cache, - IApplicationDbContext context, IMapper mapper) + IAppCache cache, + IApplicationDbContext context, IMapper mapper) { _cache = cache; _context = context; _mapper = mapper; } + + public event Action? OnChange; + public List DataSource { get; private set; } = new(); + public async Task InitializeAsync() { - DataSource = await _cache.GetOrAddAsync(TenantCacheKey.TenantsCacheKey, () => _context.Tenants.OrderBy(x => x.Name) .ProjectTo(_mapper.ConfigurationProvider) .ToListAsync(), - TenantCacheKey.MemoryCacheEntryOptions); - - - + TenantCacheKey.MemoryCacheEntryOptions); } + public void Initialize() { - DataSource = _cache.GetOrAdd(TenantCacheKey.TenantsCacheKey, () => _context.Tenants.OrderBy(x => x.Name) .ProjectTo(_mapper.ConfigurationProvider) .ToList(), - TenantCacheKey.MemoryCacheEntryOptions); - - + TenantCacheKey.MemoryCacheEntryOptions); } + public async Task Refresh() { _cache.Remove(TenantCacheKey.TenantsCacheKey); @@ -51,7 +47,7 @@ public async Task Refresh() () => _context.Tenants.OrderBy(x => x.Name) .ProjectTo(_mapper.ConfigurationProvider) .ToListAsync(), - TenantCacheKey.MemoryCacheEntryOptions); + TenantCacheKey.MemoryCacheEntryOptions); OnChange?.Invoke(); } -} +} \ No newline at end of file diff --git a/src/Application/Services/PaddleOCR/IDocumentOcrJob.cs b/src/Application/Services/PaddleOCR/IDocumentOcrJob.cs index 274a15012..7165e80a9 100644 --- a/src/Application/Services/PaddleOCR/IDocumentOcrJob.cs +++ b/src/Application/Services/PaddleOCR/IDocumentOcrJob.cs @@ -1,13 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - namespace CleanArchitecture.Blazor.Application.Services.PaddleOCR; public interface IDocumentOcrJob diff --git a/src/Application/Services/Picklist/PicklistService.cs b/src/Application/Services/Picklist/PicklistService.cs index 929087253..c436a47f4 100644 --- a/src/Application/Services/Picklist/PicklistService.cs +++ b/src/Application/Services/Picklist/PicklistService.cs @@ -1,45 +1,44 @@ -using AutoMapper; -using AutoMapper.QueryableExtensions; using CleanArchitecture.Blazor.Application.Features.KeyValues.Caching; using CleanArchitecture.Blazor.Application.Features.KeyValues.DTOs; -using LazyCache; namespace CleanArchitecture.Blazor.Application.Services.Picklist; public class PicklistService : IPicklistService { - private readonly IAppCache _cache; private readonly IApplicationDbContext _context; private readonly IMapper _mapper; - public event Action? OnChange; - public List DataSource { get; private set; } = new(); - public PicklistService( - IAppCache cache, - IApplicationDbContext context, IMapper mapper) + IAppCache cache, + IApplicationDbContext context, IMapper mapper) { _cache = cache; _context = context; _mapper = mapper; } + + public event Action? OnChange; + public List DataSource { get; private set; } = new(); + public async Task InitializeAsync() { DataSource = await _cache.GetOrAddAsync(KeyValueCacheKey.PicklistCacheKey, () => _context.KeyValues.OrderBy(x => x.Name).ThenBy(x => x.Value) .ProjectTo(_mapper.ConfigurationProvider) .ToListAsync(), - KeyValueCacheKey.MemoryCacheEntryOptions); + KeyValueCacheKey.MemoryCacheEntryOptions); } + public void Initialize() { - DataSource = _cache.GetOrAdd(KeyValueCacheKey.PicklistCacheKey, + DataSource = _cache.GetOrAdd(KeyValueCacheKey.PicklistCacheKey, () => _context.KeyValues.OrderBy(x => x.Name).ThenBy(x => x.Value) .ProjectTo(_mapper.ConfigurationProvider) .ToList(), - KeyValueCacheKey.MemoryCacheEntryOptions); + KeyValueCacheKey.MemoryCacheEntryOptions); } + public async Task Refresh() { _cache.Remove(KeyValueCacheKey.PicklistCacheKey); @@ -48,7 +47,7 @@ public async Task Refresh() .ProjectTo(_mapper.ConfigurationProvider) .ToListAsync(), KeyValueCacheKey.MemoryCacheEntryOptions - ); + ); OnChange?.Invoke(); } -} +} \ No newline at end of file diff --git a/src/Application/_Imports.cs b/src/Application/_Imports.cs index 10ec49e66..d1c9e64f1 100644 --- a/src/Application/_Imports.cs +++ b/src/Application/_Imports.cs @@ -25,9 +25,7 @@ global using CleanArchitecture.Blazor.Application.Common.Interfaces; global using CleanArchitecture.Blazor.Application.Common.Interfaces.Caching; global using CleanArchitecture.Blazor.Domain.Entities.Audit; -global using CleanArchitecture.Blazor.Domain.Entities.Log; global using CleanArchitecture.Blazor.Application.Common.Specification; -global using CleanArchitecture.Blazor.Application.Common.Exceptions; global using AutoFilterer.Attributes; global using AutoFilterer.Enums; global using AutoFilterer.Extensions; diff --git a/src/Blazor.Server.UI/Components/Common/CustomError.razor b/src/Blazor.Server.UI/Components/Common/CustomError.razor index 4ed991d34..a68dab973 100644 --- a/src/Blazor.Server.UI/Components/Common/CustomError.razor +++ b/src/Blazor.Server.UI/Components/Common/CustomError.razor @@ -1,32 +1,32 @@ -@using CleanArchitecture.Blazor.Application.Common.Exceptions @using System.Net +@using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers - @statusCode + @StatusCode
@DateTime.Now - More + More
- @_message For more information, contact your system administrator - @if (_showstacktrace) + @Message For more information, contact your system administrator + @if (ShowStackTrace) { - @stacktrace + @StackTrace }
- @ConstantString.REFRESH + @ConstantString.Refresh
@code { - private string? _message { get; set; } - private bool _showstacktrace { get; set; } - private string? stacktrace { get; set; } - private string? statusCode { get; set; } = HttpStatusCode.InternalServerError.ToString(); + private string? Message { get; set; } + private bool ShowStackTrace { get; set; } + private string? StackTrace { get; set; } + private string? StatusCode { get; set; } = HttpStatusCode.InternalServerError.ToString(); [EditorRequired][Parameter] public Exception Exception { get; set; } = default!; - [Inject] private NavigationManager _navigation { get; set; } = default!; - [Inject] private ILogger _logger { get; set; } = default!; + [Inject] private NavigationManager Navigation { get; set; } = default!; + [Inject] private ILogger Logger { get; set; } = default!; [CascadingParameter] private Task _authState { get; set; } = default!; protected override async Task OnInitializedAsync() @@ -36,10 +36,10 @@ switch (Exception) { case ServerException e: - statusCode = e.StatusCode.ToString(); + StatusCode = e.StatusCode.ToString(); if (e.ErrorMessages is not null) { - _message = string.Join(", ", e.ErrorMessages.ToArray()); + Message = string.Join(", ", e.ErrorMessages.ToArray()); } break; default: @@ -50,14 +50,14 @@ Exception = Exception.InnerException; } } - _message = Exception.Message; + Message = Exception.Message; break; } - stacktrace = Exception.StackTrace; - _logger.LogError(Exception, "{message}. request url: {@url} {@UserName}", _message, _navigation.Uri, userName); + StackTrace = Exception.StackTrace; + Logger.LogError(Exception, "{Message}. request url: {@url} {@UserName}", Message, Navigation.Uri, userName); } private void OnRefresh() { - _navigation.NavigateTo(_navigation.Uri, true); + Navigation.NavigateTo(Navigation.Uri, true); } } diff --git a/src/Blazor.Server.UI/Components/Common/CustomValidation.cs b/src/Blazor.Server.UI/Components/Common/CustomValidation.cs index 0bd3a9cb3..c7f2d6440 100644 --- a/src/Blazor.Server.UI/Components/Common/CustomValidation.cs +++ b/src/Blazor.Server.UI/Components/Common/CustomValidation.cs @@ -1,4 +1,3 @@ -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Forms; namespace Blazor.Server.UI.Components.Common; diff --git a/src/Blazor.Server.UI/Components/Common/DataGridExtensions.cs b/src/Blazor.Server.UI/Components/Common/DataGridExtensions.cs index 0b851d6db..15624ee04 100644 --- a/src/Blazor.Server.UI/Components/Common/DataGridExtensions.cs +++ b/src/Blazor.Server.UI/Components/Common/DataGridExtensions.cs @@ -1,11 +1,12 @@ using System.Linq.Expressions; + namespace Blazor.Server.UI; public static class DataGridExtensions { - public static IQueryable EFOrderBySortDefinitions(this IQueryable source, GridState state) - => EFOrderBySortDefinitions(source, state.SortDefinitions); + public static IQueryable EfOrderBySortDefinitions(this IQueryable source, GridState state) + => EfOrderBySortDefinitions(source, state.SortDefinitions); - public static IQueryable EFOrderBySortDefinitions(this IQueryable source, ICollection> sortDefinitions) + public static IQueryable EfOrderBySortDefinitions(this IQueryable source, ICollection> sortDefinitions) { // avoid multiple enumeration var sourceQuery = source; @@ -19,24 +20,24 @@ public static IQueryable EFOrderBySortDefinitions(this IQueryable so { var parameter = Expression.Parameter(typeof(T), "x"); var orderByProperty = Expression.Property(parameter, sortDefinition.SortBy); - var sortlambda= Expression.Lambda(orderByProperty, parameter); + var sortLambda= Expression.Lambda(orderByProperty, parameter); if (orderedQuery is null) { - var sortmethod = typeof(Queryable).GetMethods() - .Where(m => m.Name == (sortDefinition.Descending? "OrderByDescending" : "OrderBy") && m.IsGenericMethodDefinition) - .Where(m => m.GetParameters().ToList().Count == 2) // ensure selecting the right overload - .Single(); - var genericMethod = sortmethod.MakeGenericMethod(typeof(T), orderByProperty.Type); - orderedQuery = (IOrderedQueryable?)genericMethod.Invoke(genericMethod, new object[] { source, sortlambda }); + var sortMethod = typeof(Queryable) + .GetMethods() + .Where(m => m.Name == (sortDefinition.Descending? "OrderByDescending" : "OrderBy") && m.IsGenericMethodDefinition) // ensure selecting the right overload + .Single(m => m.GetParameters().ToList().Count == 2); + var genericMethod = sortMethod.MakeGenericMethod(typeof(T), orderByProperty.Type); + orderedQuery = (IOrderedQueryable?)genericMethod.Invoke(genericMethod, new object[] { source, sortLambda }); } else { - var sortmethod = typeof(Queryable).GetMethods() - .Where(m => m.Name == (sortDefinition.Descending ? "ThenByDescending" : "ThenBy") && m.IsGenericMethodDefinition) - .Where(m => m.GetParameters().ToList().Count == 2) // ensure selecting the right overload - .Single(); - var genericMethod = sortmethod.MakeGenericMethod(typeof(T), orderByProperty.Type); - orderedQuery = (IOrderedQueryable?)genericMethod.Invoke(genericMethod, new object[] { source, sortlambda }); + var sortMethod = typeof(Queryable) + .GetMethods() + .Where(m => m.Name == (sortDefinition.Descending ? "ThenByDescending" : "ThenBy") && m.IsGenericMethodDefinition) // ensure selecting the right overload + .Single(m => m.GetParameters().ToList().Count == 2); + var genericMethod = sortMethod.MakeGenericMethod(typeof(T), orderByProperty.Type); + orderedQuery = (IOrderedQueryable?)genericMethod.Invoke(genericMethod, new object[] { source, sortLambda }); } } return orderedQuery ?? sourceQuery; diff --git a/src/Blazor.Server.UI/Components/Common/ErrorHandler.razor.cs b/src/Blazor.Server.UI/Components/Common/ErrorHandler.razor.cs index 09f7acdf7..f3ec2a4e3 100644 --- a/src/Blazor.Server.UI/Components/Common/ErrorHandler.razor.cs +++ b/src/Blazor.Server.UI/Components/Common/ErrorHandler.razor.cs @@ -1,15 +1,13 @@ -using MudBlazor; - namespace Blazor.Server.UI.Components.Common; public partial class ErrorHandler { - public List _receivedExceptions = new(); + public List ReceivedExceptions = new(); protected override Task OnErrorAsync(Exception exception) { - _receivedExceptions.Add(exception); + ReceivedExceptions.Add(exception); switch (exception) { case UnauthorizedAccessException: @@ -21,7 +19,7 @@ protected override Task OnErrorAsync(Exception exception) public new void Recover() { - _receivedExceptions.Clear(); + ReceivedExceptions.Clear(); base.Recover(); } } \ No newline at end of file diff --git a/src/Blazor.Server.UI/Components/Common/MudEnumSelect.razor b/src/Blazor.Server.UI/Components/Common/MudEnumSelect.razor index d2aff131f..abba2a17b 100644 --- a/src/Blazor.Server.UI/Components/Common/MudEnumSelect.razor +++ b/src/Blazor.Server.UI/Components/Common/MudEnumSelect.razor @@ -1,9 +1,7 @@ -@using MudBlazor -@using System.ComponentModel -@using System.Reflection; -@using MudBlazor.Extensions; -@typeparam TEnum +@typeparam TEnum +@using System.Reflection +@using System.ComponentModel @inherits MudSelect @{ base.BuildRenderTree(__builder); diff --git a/src/Blazor.Server.UI/Components/Common/MultiTenantAutocomplete.cs b/src/Blazor.Server.UI/Components/Common/MultiTenantAutocomplete.cs index 6f593fd58..10a6bcf5a 100644 --- a/src/Blazor.Server.UI/Components/Common/MultiTenantAutocomplete.cs +++ b/src/Blazor.Server.UI/Components/Common/MultiTenantAutocomplete.cs @@ -5,50 +5,50 @@ namespace Blazor.Server.UI.Components.Common; public class MultiTenantAutocomplete : MudAutocomplete { [Inject] - private ITenantService _tenantsService { get; set; } = default!; + private ITenantService TenantsService { get; set; } = default!; protected override void OnInitialized() { - _tenantsService.OnChange += tenantsService_OnChange; + TenantsService.OnChange += tenantsService_OnChange; } private void tenantsService_OnChange() { - InvokeAsync(() =>StateHasChanged()); + InvokeAsync(() => StateHasChanged()); } protected override void Dispose(bool disposing) { - _tenantsService.OnChange -= tenantsService_OnChange; + TenantsService.OnChange -= tenantsService_OnChange; base.Dispose(disposing); } public override Task SetParametersAsync(ParameterView parameters) { - SearchFuncWithCancel = searchKeyValues; - ToStringFunc = toStringFunc; + SearchFuncWithCancel = SearchKeyValues; + base.ToStringFunc = ToStringFunc; Clearable = true; Dense = true; ResetValueOnEmptyText = true; ShowProgressIndicator = true; return base.SetParametersAsync(parameters); } - private Task> searchKeyValues(string value, CancellationToken token) + private Task> SearchKeyValues(string value, CancellationToken token) { // if text is null or empty, show complete list if (string.IsNullOrEmpty(value)) { - var result = _tenantsService.DataSource.OrderBy(x => x.Name).Select(x=>x.Id).ToList(); + var result = TenantsService.DataSource.OrderBy(x => x.Name).Select(x=>x.Id).ToList(); return Task.FromResult>(result); } - return Task.FromResult>(_tenantsService.DataSource.Where(x => x.Name!.Contains(value, StringComparison.InvariantCultureIgnoreCase) || + return Task.FromResult>(TenantsService.DataSource.Where(x => x.Name!.Contains(value, StringComparison.InvariantCultureIgnoreCase) || x.Description != null && x.Description.Contains(value, StringComparison.InvariantCultureIgnoreCase) ).OrderBy(x => x.Name).Select(x=>x.Id).ToList()); } - private string toStringFunc(string val) + private string ToStringFunc(string val) { - return _tenantsService.DataSource.Where(x => x.Id == val).Select(x => x.Name).FirstOrDefault()??""; + return TenantsService.DataSource.Where(x => x.Id == val).Select(x => x.Name).FirstOrDefault()??""; } diff --git a/src/Blazor.Server.UI/Components/Common/PickSuperiorIdAutocomplete.cs b/src/Blazor.Server.UI/Components/Common/PickSuperiorIdAutocomplete.cs index 7314a32c4..411cfeb8e 100644 --- a/src/Blazor.Server.UI/Components/Common/PickSuperiorIdAutocomplete.cs +++ b/src/Blazor.Server.UI/Components/Common/PickSuperiorIdAutocomplete.cs @@ -1,69 +1,71 @@ using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity; -using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity.DTOs; using CleanArchitecture.Blazor.Application.Features.Identity.Dto; -using IdentityModel.Client; namespace Blazor.Server.UI.Components.Common; public class PickSuperiorIdAutocomplete : MudAutocomplete { - [Parameter] - public string TenantId { get; set; }=string.Empty; - [Parameter] - public string OwnerName { get; set; }=string.Empty; + private List? _userList; - [Inject] - private IIdentityService _identityService { get; set; } = default!; + [Parameter] + public string TenantId { get; set; } = string.Empty; + + [Parameter] + public string OwnerName { get; set; } = string.Empty; + + [Inject] + private IIdentityService IdentityService { get; set; } = default!; - private List? _userList; - - public override Task SetParametersAsync(ParameterView parameters) + public override Task SetParametersAsync(ParameterView parameters) { - SearchFuncWithCancel = searchKeyValues; - ToStringFunc = toString; + SearchFuncWithCancel = SearchKeyValues; + ToStringFunc = ToString; Clearable = true; Dense = true; ResetValueOnEmptyText = true; ShowProgressIndicator = true; MaxItems = 50; return base.SetParametersAsync(parameters); - } - private async Task> searchKeyValues(string value, CancellationToken cancellation) + private async Task> SearchKeyValues(string value, CancellationToken cancellation) { // if text is null or empty, show complete list - _userList = await _identityService.GetUsers(TenantId, cancellation); - var result= new List(); + _userList = await IdentityService.GetUsers(TenantId, cancellation); + List result = new List(); if (string.IsNullOrEmpty(value) && _userList is not null) { - result= _userList.Select(x => x.Id).Take(MaxItems??50).ToList(); + result = _userList.Select(x => x.Id).Take(MaxItems ?? 50).ToList(); } - else if(_userList is not null) + else if (_userList is not null) { - result = _userList.Where(x => !x.UserName.Equals(OwnerName, StringComparison.OrdinalIgnoreCase) && (x.UserName.Contains(value, StringComparison.OrdinalIgnoreCase) || x.Email.Contains(value, StringComparison.OrdinalIgnoreCase))).Select(x => x.Id).Take(MaxItems ?? 50).ToList(); ; + result = _userList + .Where(x => !x.UserName.Equals(OwnerName, StringComparison.OrdinalIgnoreCase) && + (x.UserName.Contains(value, StringComparison.OrdinalIgnoreCase) || + x.Email.Contains(value, StringComparison.OrdinalIgnoreCase))).Select(x => x.Id) + .Take(MaxItems ?? 50).ToList(); + ; } + return result; } - private string toString(string str) + + private string ToString(string str) { - if(_userList is not null && !string.IsNullOrEmpty(str) && _userList.Any(x => x.Id.Equals(str, StringComparison.OrdinalIgnoreCase))) + if (_userList is not null && !string.IsNullOrEmpty(str) && + _userList.Any(x => x.Id.Equals(str, StringComparison.OrdinalIgnoreCase))) { - var userDto = _userList.First(x => x.Id==str); + ApplicationUserDto userDto = _userList.First(x => x.Id == str); return userDto.UserName; } - if(_userList is null && !string.IsNullOrEmpty(str)) + + if (_userList is null && !string.IsNullOrEmpty(str)) { - var userName = _identityService.GetUserName(str); + string userName = IdentityService.GetUserName(str); return userName; } - + return string.Empty; } - - -} - - - +} \ No newline at end of file diff --git a/src/Blazor.Server.UI/Components/Common/PickUserAutocomplete.cs b/src/Blazor.Server.UI/Components/Common/PickUserAutocomplete.cs index 979319f02..ea359084b 100644 --- a/src/Blazor.Server.UI/Components/Common/PickUserAutocomplete.cs +++ b/src/Blazor.Server.UI/Components/Common/PickUserAutocomplete.cs @@ -1,7 +1,5 @@ using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity; -using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity.DTOs; using CleanArchitecture.Blazor.Application.Features.Identity.Dto; -using IdentityModel.Client; namespace Blazor.Server.UI.Components.Common; @@ -10,14 +8,14 @@ public class PickUserAutocomplete : MudAutocomplete [Parameter] public string TenantId { get; set; }=string.Empty; [Inject] - private IUserDataProvider _dataProvider { get; set; } = default!; + private IUserDataProvider DataProvider { get; set; } = default!; private List? _userList; public override Task SetParametersAsync(ParameterView parameters) { - SearchFuncWithCancel = searchKeyValues; + SearchFuncWithCancel = SearchKeyValues; Clearable = true; Dense = true; ResetValueOnEmptyText = true; @@ -26,10 +24,10 @@ public override Task SetParametersAsync(ParameterView parameters) return base.SetParametersAsync(parameters); } - private Task> searchKeyValues(string value, CancellationToken cancellation) + private Task> SearchKeyValues(string value, CancellationToken cancellation) { // if text is null or empty, show complete list - _userList = _dataProvider.DataSource.Where(x => x.TenantId == TenantId).ToList(); + _userList = DataProvider.DataSource.Where(x => x.TenantId == TenantId).ToList(); var result= new List(); if (_userList is not null && string.IsNullOrEmpty(value)) { @@ -42,7 +40,7 @@ private Task> searchKeyValues(string value, CancellationToke return Task.FromResult(result.AsEnumerable()); } - private string toString(string str) + private string ToString(string str) { if (!string.IsNullOrEmpty(str) && _userList != null && _userList.Any(x => (x.DisplayName != null && x.DisplayName.Contains(str, StringComparison.OrdinalIgnoreCase)) || x.UserName.Contains(str, StringComparison.OrdinalIgnoreCase))) { diff --git a/src/Blazor.Server.UI/Components/Common/PicklistAutocomplete.cs b/src/Blazor.Server.UI/Components/Common/PicklistAutocomplete.cs index f85bb5484..e0299cb76 100644 --- a/src/Blazor.Server.UI/Components/Common/PicklistAutocomplete.cs +++ b/src/Blazor.Server.UI/Components/Common/PicklistAutocomplete.cs @@ -1,6 +1,4 @@ -using CleanArchitecture.Blazor.Application.Common.Interfaces; -using Microsoft.AspNetCore.Components; -using MudBlazor; +using CleanArchitecture.Blazor.Domain.Enums; namespace Blazor.Server.UI.Components.Common; @@ -10,21 +8,21 @@ public class PicklistAutocomplete : MudAutocomplete public Picklist Picklist { get; set; } [Inject] - private IPicklistService _picklistService { get; set; } = default!; + private IPicklistService PicklistService { get; set; } = default!; protected override async Task OnInitializedAsync() { - _picklistService.OnChange += _picklistService_OnChange; + PicklistService.OnChange += _picklistService_OnChange; await base.OnInitializedAsync(); } private void _picklistService_OnChange() { - InvokeAsync(() =>StateHasChanged()); + InvokeAsync(() => StateHasChanged()); } protected override void Dispose(bool disposing) { - _picklistService.OnChange -= _picklistService_OnChange; + PicklistService.OnChange -= _picklistService_OnChange; base.Dispose(disposing); } public override Task SetParametersAsync(ParameterView parameters) @@ -40,9 +38,9 @@ private Task> SearchKeyValues(string value) // if text is null or empty, show complete list if (string.IsNullOrEmpty(value)) { - return Task.FromResult(_picklistService.DataSource.Where(x => x.Name == Picklist).Select(x => x.Value ?? String.Empty)); + return Task.FromResult(PicklistService.DataSource.Where(x => x.Name == Picklist).Select(x => x.Value ?? String.Empty)); } - return Task.FromResult(_picklistService.DataSource.Where(x => x.Name == Picklist && + return Task.FromResult(PicklistService.DataSource.Where(x => x.Name == Picklist && ( x.Value!=null && x.Value.Contains(value, StringComparison.InvariantCultureIgnoreCase) || x.Text!=null && x.Text.Contains(value, StringComparison.InvariantCultureIgnoreCase) )).Select(x=>x.Value??String.Empty)); diff --git a/src/Blazor.Server.UI/Components/Common/RedirectToLogin.razor b/src/Blazor.Server.UI/Components/Common/RedirectToLogin.razor index 7cb0dea74..59808aa82 100644 --- a/src/Blazor.Server.UI/Components/Common/RedirectToLogin.razor +++ b/src/Blazor.Server.UI/Components/Common/RedirectToLogin.razor @@ -2,13 +2,13 @@ @code { [CascadingParameter] - private Task _authStateTask { get; set; } = null!; + private Task AuthStateTask { get; set; } = null!; [Inject] protected NavigationManager NavigationManager { get; set; } = null!; protected override async Task OnInitializedAsync() { - var authState = await _authStateTask; + var authState = await AuthStateTask; if (authState?.User?.Identity is null || !authState.User.Identity.IsAuthenticated) { var returnUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); diff --git a/src/Blazor.Server.UI/Components/Dialogs/ConfirmationDialog.razor b/src/Blazor.Server.UI/Components/Dialogs/ConfirmationDialog.razor index f5384c60f..535f9b7b8 100644 --- a/src/Blazor.Server.UI/Components/Dialogs/ConfirmationDialog.razor +++ b/src/Blazor.Server.UI/Components/Dialogs/ConfirmationDialog.razor @@ -4,8 +4,8 @@ @ContentText - @ConstantString.CANCEL - @ConstantString.CONFIRM + @ConstantString.Cancel + @ConstantString.Confirm diff --git a/src/Blazor.Server.UI/Components/Dialogs/DeleteConfirmation.razor b/src/Blazor.Server.UI/Components/Dialogs/DeleteConfirmation.razor index 8d2b8483a..8cb488fdc 100644 --- a/src/Blazor.Server.UI/Components/Dialogs/DeleteConfirmation.razor +++ b/src/Blazor.Server.UI/Components/Dialogs/DeleteConfirmation.razor @@ -3,15 +3,15 @@ - @ConstantString.DELETECONFIRMATIONTITLE + @ConstantString.DeleteConfirmationTitle @ContentText - @ConstantString.CANCEL - @ConstantString.CONFIRM + @ConstantString.Cancel + @ConstantString.Confirm @@ -26,12 +26,12 @@ [Parameter] public IRequest> Command { get; set; } = default!; [Inject] - private IMediator _mediator { get; set; } = default!; + private IMediator Mediator { get; set; } = default!; async Task Submit() { - var result = await _mediator.Send(Command); + var result = await Mediator.Send(Command); if (result.Succeeded) { - Snackbar.Add($"{ConstantString.DELETESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.DeleteSuccess}", MudBlazor.Severity.Info); MudDialog.Close(DialogResult.Ok(true)); } else { diff --git a/src/Blazor.Server.UI/Components/Dialogs/LogoutConfirmation.razor b/src/Blazor.Server.UI/Components/Dialogs/LogoutConfirmation.razor index 52c6827f4..6fa053a48 100644 --- a/src/Blazor.Server.UI/Components/Dialogs/LogoutConfirmation.razor +++ b/src/Blazor.Server.UI/Components/Dialogs/LogoutConfirmation.razor @@ -2,15 +2,15 @@ - @ConstantString.LOGOUTCONFIRMATIONTITLE + @ConstantString.LogoutConfirmationTitle @ContentText - @ConstantString.CANCEL - @ConstantString.LOGOUT + @ConstantString.Cancel + @ConstantString.Logout @@ -20,12 +20,12 @@ [Parameter] public Color Color { get; set; } [CascadingParameter] MudDialogInstance MudDialog { get; set; } = default!; - [Inject] private NavigationManager _navigation { get; set; }= default!; + [Inject] private NavigationManager Navigation { get; set; }= default!; Task Submit() { MudDialog.Close(DialogResult.Ok(true)); - Snackbar.Add(@ConstantString.LOGOUTSUCCESS, MudBlazor.Severity.Info); + Snackbar.Add(@ConstantString.LogoutSuccess, MudBlazor.Severity.Info); return Task.CompletedTask; } diff --git a/src/Blazor.Server.UI/Components/Localization/LanguageSelector.razor b/src/Blazor.Server.UI/Components/Localization/LanguageSelector.razor index 197ddd9f3..fcbc25e3e 100644 --- a/src/Blazor.Server.UI/Components/Localization/LanguageSelector.razor +++ b/src/Blazor.Server.UI/Components/Localization/LanguageSelector.razor @@ -1,8 +1,6 @@ -@using Microsoft.Extensions.Options -@using Blazor.Server.UI.Models.Localization @using System.Globalization +@using Microsoft.Extensions.Options @using Blazor.Server.UI.Services - @if (SupportedLanguages is not null) @@ -25,13 +23,13 @@ @code { public string? CurrentLanguage { get; set; } = "en-US"; public List? SupportedLanguages { get; set; } = new(); - [Inject] private NavigationManager _navigation { get; set; } = null!; - [Inject] private IOptions localizationOptions { get; set; } = null!; + [Inject] private NavigationManager Navigation { get; set; } = null!; + [Inject] private IOptions LocalizationOptions { get; set; } = null!; [Inject] private LayoutService LayoutService { get; set; } = null!; protected override Task OnInitializedAsync() { - SupportedLanguages = localizationOptions.Value.SupportedCultures?.ToList(); + SupportedLanguages = LocalizationOptions.Value.SupportedCultures?.ToList(); CurrentLanguage = CultureInfo.CurrentCulture.Name; return Task.CompletedTask; } @@ -40,7 +38,7 @@ private async Task ChangeLanguageAsync(string languageCode) { CurrentLanguage = languageCode; - _navigation.NavigateTo(_navigation.BaseUri + "?culture=" + languageCode, forceLoad: true); + Navigation.NavigateTo(Navigation.BaseUri + "?culture=" + languageCode, forceLoad: true); if (new CultureInfo(languageCode).TextInfo.IsRightToLeft) await LayoutService.SetRightToLeft(); diff --git a/src/Blazor.Server.UI/Components/Shared/LandingSection.razor b/src/Blazor.Server.UI/Components/Shared/LandingSection.razor index f0b0e5e74..9f82363b2 100644 --- a/src/Blazor.Server.UI/Components/Shared/LandingSection.razor +++ b/src/Blazor.Server.UI/Components/Shared/LandingSection.razor @@ -1,6 +1,4 @@ @using MudBlazor.Utilities - -
diff --git a/src/Blazor.Server.UI/Components/Shared/NavMenu.razor.cs b/src/Blazor.Server.UI/Components/Shared/NavMenu.razor.cs index 39745743e..107aaec20 100644 --- a/src/Blazor.Server.UI/Components/Shared/NavMenu.razor.cs +++ b/src/Blazor.Server.UI/Components/Shared/NavMenu.razor.cs @@ -1,5 +1,3 @@ -using Microsoft.AspNetCore.Components; -using CleanArchitecture.Blazor.Application.Common.Models; using Microsoft.AspNetCore.Components.Web; namespace Blazor.Server.UI.Components.Shared; diff --git a/src/Blazor.Server.UI/Components/Shared/NotificationMenu.razor b/src/Blazor.Server.UI/Components/Shared/NotificationMenu.razor index 129f33b30..3964ac287 100644 --- a/src/Blazor.Server.UI/Components/Shared/NotificationMenu.razor +++ b/src/Blazor.Server.UI/Components/Shared/NotificationMenu.razor @@ -13,7 +13,7 @@ { @message.Title - @($"{message.Authors.FirstOrDefault()?.DisplayName} • {message.PublishDate.ToString("MM/dd/yyyy")}") + @($"{message.Authors.FirstOrDefault()?.DisplayName} • {message.PublishDate:MM/dd/yyyy}") } diff --git a/src/Blazor.Server.UI/Components/Shared/NotificationMenu.razor.cs b/src/Blazor.Server.UI/Components/Shared/NotificationMenu.razor.cs index 1957315f9..796c45414 100644 --- a/src/Blazor.Server.UI/Components/Shared/NotificationMenu.razor.cs +++ b/src/Blazor.Server.UI/Components/Shared/NotificationMenu.razor.cs @@ -1,5 +1,3 @@ -using Microsoft.AspNetCore.Components; -using MudBlazor; using Blazor.Server.UI.Services.Notifications; namespace Blazor.Server.UI.Components.Shared; diff --git a/src/Blazor.Server.UI/Components/Shared/SideMenu.razor b/src/Blazor.Server.UI/Components/Shared/SideMenu.razor index 52b30d7c2..533fe41cc 100644 --- a/src/Blazor.Server.UI/Components/Shared/SideMenu.razor +++ b/src/Blazor.Server.UI/Components/Shared/SideMenu.razor @@ -1,5 +1,5 @@ -@using Blazor.Server.UI.Models.SideMenu @inject IStringLocalizer L +@using Blazor.Server.UI.Models.SideMenu @inherits UserProfileStateComponent - @foreach (var section in _menuSections.Where(x => x.Roles == null || x.Roles.Any(x => _roles.Contains(x)))) + @foreach (var section in MenuSections.Where(x => x.Roles == null || x.Roles.Any(x => Roles.Contains(x)))) { @if(section is not null) { @@ -70,12 +70,12 @@ @if (section.SectionItems is not null) { - @foreach (var sectionItem in section.SectionItems.Where(x => x.Roles == null || x.Roles.Any(x => _roles.Contains(x)))) + @foreach (var sectionItem in section.SectionItems.Where(x => x.Roles == null || x.Roles.Any(x => Roles.Contains(x)))) { @if (sectionItem.IsParent && sectionItem.MenuItems is not null) { - @foreach (var menuItem in sectionItem.MenuItems.Where(x => x.Roles == null || x.Roles.Any(x => _roles.Contains(x)))) + @foreach (var menuItem in sectionItem.MenuItems.Where(x => x.Roles == null || x.Roles.Any(x => Roles.Contains(x)))) { @if (SideMenuDrawerOpen) { diff --git a/src/Blazor.Server.UI/Components/Shared/SideMenu.razor.cs b/src/Blazor.Server.UI/Components/Shared/SideMenu.razor.cs index 259f9d843..e0706f30c 100644 --- a/src/Blazor.Server.UI/Components/Shared/SideMenu.razor.cs +++ b/src/Blazor.Server.UI/Components/Shared/SideMenu.razor.cs @@ -4,22 +4,17 @@ namespace Blazor.Server.UI.Components.Shared; -public partial class SideMenu: UserProfileStateComponent +public partial class SideMenu : UserProfileStateComponent { + [EditorRequired] [Parameter] public bool SideMenuDrawerOpen { get; set; } + [EditorRequired] [Parameter] public EventCallback SideMenuDrawerOpenChanged { get; set; } - [EditorRequired] [Parameter] - public bool SideMenuDrawerOpen { get; set; } - - [EditorRequired] [Parameter] - public EventCallback SideMenuDrawerOpenChanged { get; set; } + [Inject] private IMenuService MenuService { get; set; } = default!; - [Inject] - private IMenuService _menuService { get; set; } = default!; - private IEnumerable _menuSections => _menuService.Features; - - [Inject] - private LayoutService LayoutService { get; set; } = default!; + private IEnumerable MenuSections => MenuService.Features; - private string[] _roles => UserProfile?.AssignedRoles??new string[] { }; + [Inject] private LayoutService LayoutService { get; set; } = default!; + + private string[] Roles => UserProfile?.AssignedRoles ?? new string[] { }; } \ No newline at end of file diff --git a/src/Blazor.Server.UI/Components/Shared/Themes/ThemesButton.razor.cs b/src/Blazor.Server.UI/Components/Shared/Themes/ThemesButton.razor.cs index 096bcde09..339c3a3a2 100644 --- a/src/Blazor.Server.UI/Components/Shared/Themes/ThemesButton.razor.cs +++ b/src/Blazor.Server.UI/Components/Shared/Themes/ThemesButton.razor.cs @@ -1,5 +1,4 @@ using Blazor.Server.UI.Services; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; namespace Blazor.Server.UI.Components.Shared.Themes; diff --git a/src/Blazor.Server.UI/Components/Shared/Themes/ThemesMenu.razor b/src/Blazor.Server.UI/Components/Shared/Themes/ThemesMenu.razor index 8e89eb45f..285826f57 100644 --- a/src/Blazor.Server.UI/Components/Shared/Themes/ThemesMenu.razor +++ b/src/Blazor.Server.UI/Components/Shared/Themes/ThemesMenu.razor @@ -1,5 +1,6 @@ -@inject IStringLocalizer L @using Blazor.Server.UI.Services +@using Blazor.Server.UI.Services.UserPreferences +@inject IStringLocalizer L - @foreach (var color in getColorDefinition()) + @foreach (var color in GetColorDefinition()) { getColorDefinition() + private List GetColorDefinition() { return UserPreferences.DarkLightTheme switch { diff --git a/src/Blazor.Server.UI/Components/Shared/UserMenu.razor b/src/Blazor.Server.UI/Components/Shared/UserMenu.razor index 6f268bce1..5d7621549 100644 --- a/src/Blazor.Server.UI/Components/Shared/UserMenu.razor +++ b/src/Blazor.Server.UI/Components/Shared/UserMenu.razor @@ -1,6 +1,6 @@ -@using CleanArchitecture.Blazor.Infrastructure.Services.JWT; @inject IStringLocalizer L @inject AccessTokenProvider TokenProvider +@using CleanArchitecture.Blazor.Infrastructure.Services.JWT @inherits UserProfileStateComponent (ConstantString.LOGOUTCONFIRMATIONTITLE, parameters, options); + var dialog = DialogService.Show(ConstantString.LogoutConfirmationTitle, parameters, options); var result = await dialog.Result; if (!result.Canceled) { diff --git a/src/Blazor.Server.UI/Components/Shared/UserProfileStateComponent.cs b/src/Blazor.Server.UI/Components/Shared/UserProfileStateComponent.cs index 864747d14..c5eb24bce 100644 --- a/src/Blazor.Server.UI/Components/Shared/UserProfileStateComponent.cs +++ b/src/Blazor.Server.UI/Components/Shared/UserProfileStateComponent.cs @@ -7,24 +7,24 @@ namespace Blazor.Server.UI.Components.Shared; public class UserProfileStateComponent : ComponentBase, INotificationHandler { - private static event EventHandler _userProfileChanged = null!; + private static event EventHandler UserProfileChanged = null!; public UserProfile? UserProfile { get; private set; } = null!; [CascadingParameter] - protected Task _authState { get; set; } = default!; + protected Task AuthState { get; set; } = default!; [Inject] - private AuthenticationStateProvider _authenticationStateProvider { get; set; } = default!; + private AuthenticationStateProvider AuthenticationStateProvider { get; set; } = default!; [Inject] - private IIdentityService _identityService { get; set; } = default!; + private IIdentityService IdentityService { get; set; } = default!; protected override async Task OnInitializedAsync() { - _userProfileChanged += userProfileChangedHandler; - _authenticationStateProvider.AuthenticationStateChanged += _authenticationStateProvider_AuthenticationStateChanged; - var state = await _authState; + UserProfileChanged += UserProfileChangedHandler; + AuthenticationStateProvider.AuthenticationStateChanged += _authenticationStateProvider_AuthenticationStateChanged; + var state = await AuthState; if (state?.User?.Identity?.IsAuthenticated ?? false) { - var userDto = await _identityService.GetApplicationUserDto(state.User.GetUserId()); - await setProfile(userDto); + var userDto = await IdentityService.GetApplicationUserDto(state.User.GetUserId()); + await SetProfile(userDto); } } @@ -35,29 +35,29 @@ private void _authenticationStateProvider_AuthenticationStateChanged(Task StateHasChanged()); } public Task Handle(UpdateUserProfileCommand notification, CancellationToken cancellationToken) { - _userProfileChanged?.Invoke(this, new UpdateUserProfileEventArgs() { UserProfile = notification.UserProfile }); + UserProfileChanged?.Invoke(this, new UpdateUserProfileEventArgs() { UserProfile = notification.UserProfile }); return Task.CompletedTask; } } diff --git a/src/Blazor.Server.UI/ConfigureServices.cs b/src/Blazor.Server.UI/ConfigureServices.cs index a785f313b..2a0649f3d 100644 --- a/src/Blazor.Server.UI/ConfigureServices.cs +++ b/src/Blazor.Server.UI/ConfigureServices.cs @@ -1,21 +1,20 @@ -using System.Text.Json.Serialization; -using System.Text.Json; using Blazor.Analytics; +using Blazor.Server.UI.Components.Shared; using Blazor.Server.UI.Services; using Blazor.Server.UI.Services.Navigation; using Blazor.Server.UI.Services.Notifications; +using Blazor.Server.UI.Services.UserPreferences; using BlazorDownloadFile; +using CleanArchitecture.Blazor.Application.Features.Identity.Notification; using MudBlazor.Services; -using Toolbelt.Blazor.Extensions.DependencyInjection; using MudExtensions.Services; -using CleanArchitecture.Blazor.Application.Features.Identity.Notification; -using Blazor.Server.UI.Components.Shared; +using Toolbelt.Blazor.Extensions.DependencyInjection; namespace Blazor.Server.UI; public static class ConfigureServices { - public static IServiceCollection AddBlazorUIServices(this IServiceCollection services) + public static IServiceCollection AddBlazorUiServices(this IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor( diff --git a/src/Blazor.Server.UI/EndPoints/AuthController.cs b/src/Blazor.Server.UI/EndPoints/AuthController.cs index f64e3916a..2cae3821b 100644 --- a/src/Blazor.Server.UI/EndPoints/AuthController.cs +++ b/src/Blazor.Server.UI/EndPoints/AuthController.cs @@ -1,9 +1,10 @@ +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; +using CleanArchitecture.Blazor.Application.Constants.Role; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; - namespace Blazor.Server.UI.EndPoints; public class AuthController : Controller { @@ -44,7 +45,7 @@ public async Task Login(string token,string returnUrl) await _signInManager.SignInAsync(identityUser, isPersistent); identityUser.IsLive= true; await _userManager.UpdateAsync(identityUser); - _logger.LogInformation("{@UserName} login successful.", identityUser.UserName); + _logger.LogInformation("{@UserName} login successful", identityUser.UserName); return Redirect($"/{returnUrl}"); } @@ -100,7 +101,7 @@ public async Task Logout() var identityUser = await _userManager.FindByIdAsync(userId) ?? throw new NotFoundException($"Application user not found."); identityUser.IsLive = false; await _userManager.UpdateAsync(identityUser); - _logger.LogInformation("{@UserName} logout successful.", identityUser.UserName); + _logger.LogInformation("{@UserName} logout successful", identityUser.UserName); await _signInManager.SignOutAsync(); return Redirect("/"); } diff --git a/src/Blazor.Server.UI/Models/Notification/NotificationModel.cs b/src/Blazor.Server.UI/Models/Notification/NotificationModel.cs index 838775d4a..cae0d2d96 100644 --- a/src/Blazor.Server.UI/Models/Notification/NotificationModel.cs +++ b/src/Blazor.Server.UI/Models/Notification/NotificationModel.cs @@ -1,5 +1,3 @@ -using MudBlazor; - namespace Blazor.Server.UI.Models.Notification; public class NotificationModel diff --git a/src/Blazor.Server.UI/Models/NumericExtensions.cs b/src/Blazor.Server.UI/Models/NumericExtensions.cs index b71a5144b..2b7b27734 100644 --- a/src/Blazor.Server.UI/Models/NumericExtensions.cs +++ b/src/Blazor.Server.UI/Models/NumericExtensions.cs @@ -6,29 +6,14 @@ public static class NumericExtensions { public static string RoundedToString(this decimal? num) { - if (num is null) + return num switch { - return "0"; - } - if (num > 999999999 || num < -999999999) - { - return num.Value.ToString("0,,,.#B", CultureInfo.InvariantCulture); - } - else if (num > 999999 || num < -999999) - { - return num.Value.ToString("0,,.#M", CultureInfo.InvariantCulture); - } - else if (num > 9999 || num < -9999) - { - return num.Value.ToString("0,k", CultureInfo.InvariantCulture); - } - else if (num > 999 || num < -999) - { - return num.Value.ToString("0,.#k", CultureInfo.InvariantCulture); - } - else - { - return num.Value.ToString(CultureInfo.InvariantCulture); - } + null => "0", + > 999999999 or < -999999999 => num.Value.ToString("0,,,.#B", CultureInfo.InvariantCulture), + > 999999 or < -999999 => num.Value.ToString("0,,.#M", CultureInfo.InvariantCulture), + > 9999 or < -9999 => num.Value.ToString("0,k", CultureInfo.InvariantCulture), + > 999 or < -999 => num.Value.ToString("0,.#k", CultureInfo.InvariantCulture), + _ => num.Value.ToString(CultureInfo.InvariantCulture) + }; } } diff --git a/src/Blazor.Server.UI/Pages/Authentication/Forgot.razor b/src/Blazor.Server.UI/Pages/Authentication/Forgot.razor index 8065701e1..45f886ad1 100644 --- a/src/Blazor.Server.UI/Pages/Authentication/Forgot.razor +++ b/src/Blazor.Server.UI/Pages/Authentication/Forgot.razor @@ -1,10 +1,9 @@ @page "/pages/authentication/forgot-password" -@using Blazor.Server.UI.Pages.Identity.Users -@using CleanArchitecture.Blazor.Application.Common.Exceptions; -@using FluentEmail.Core -@using FluentEmail.Core.Models @inject IStringLocalizer L @attribute [AllowAnonymous] +@using FluentEmail.Core.Models +@using Blazor.Server.UI.Pages.Identity.Users +@using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers @inherits OwningComponentBase @Title @@ -13,8 +12,8 @@ @if (_step == 1) { @L["Enter the email address linked to your account and you will recieve an email containing a token string to reset your password."] - - + + @if (_sending) { @@ -26,7 +25,7 @@ } } - else if (_step == 2 && _resetpasswordToken!=string.Empty) + else if (_step == 2 && _resetPasswordToken!=string.Empty) { @L["Enter the token string from the recovery email to set your new password."] - + @if (_sending) { @@ -58,43 +57,43 @@ @code { public string Title = "Forgot Password"; private int _step = 1; - private string _emailaddress = string.Empty; + private string _emailAddress = string.Empty; private bool _sending = false; - private string _resetpasswordToken=string.Empty; + private string _resetPasswordToken = string.Empty; private string _inputToken = string.Empty; private ApplicationUser? _user = null; - private UserManager _userManager { get; set; } = null!; + private UserManager UserManager { get; set; } = null!; [Inject] - private IMailService _mailService { get; set; } = null!; - [Inject] private ILogger _logger { get; set; } = default!; - [Inject] private NavigationManager _navigation { get; set; } = default!; + private IMailService MailService { get; set; } = null!; + [Inject] private ILogger Logger { get; set; } = default!; + [Inject] private NavigationManager Navigation { get; set; } = default!; protected override Task OnInitializedAsync() { Title = L["Forgot Password"]; - _userManager = ScopedServices.GetRequiredService>(); + UserManager = ScopedServices.GetRequiredService>(); return base.OnInitializedAsync(); } - private async Task resetPassword() + private async Task ResetPassword() { try { _sending = true; - _user = await _userManager.FindByEmailAsync(_emailaddress) ?? throw new NotFoundException($"Application user {_emailaddress} Not Found."); ; + _user = await UserManager.FindByEmailAsync(_emailAddress) ?? throw new NotFoundException($"Application user {_emailAddress} Not Found."); ; if (_user is null) { Snackbar.Add(L["No user found by email, please contact the administrator"], MudBlazor.Severity.Error); return; } - _resetpasswordToken = await _userManager.GeneratePasswordResetTokenAsync(_user); - var response = await sendResetPasswordToken(_emailaddress, _user.UserName!, _resetpasswordToken); + _resetPasswordToken = await UserManager.GeneratePasswordResetTokenAsync(_user); + var response = await SendResetPasswordToken(_emailAddress, _user.UserName!, _resetPasswordToken); if (response.Successful) { _step = 2; Snackbar.Clear(); Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopCenter; - Snackbar.Add(string.Format(L["The email has been sent, please check the email:{0} "],_emailaddress), MudBlazor.Severity.Success,config=> { config.ShowCloseIcon = false; config.HideTransitionDuration = 5000; }); - _logger.LogInformation("{@UserName}'s token: {@token} for resetting the password has been sent.", _user.UserName,_resetpasswordToken); + Snackbar.Add(string.Format(L["The email has been sent, please check the email:{0} "],_emailAddress), MudBlazor.Severity.Success,config=> { config.ShowCloseIcon = false; config.HideTransitionDuration = 5000; }); + Logger.LogInformation("{@UserName}'s token: {@Token} for resetting the password has been sent", _user.UserName,_resetPasswordToken); } else { @@ -117,16 +116,16 @@ } } - private Task sendResetPasswordToken(string toemail, string userName, string token) + private Task SendResetPasswordToken(string toEmail, string userName, string token) { var subject = L["Verify your recovery email"]; //var template = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "EmailTemplates" ,"_recoverypassword.txt"); - return _mailService.SendAsync(toemail, subject, "_recoverypassword", new { AppName = Settings.AppName, Email = toemail, Token = token }); + return MailService.SendAsync(toEmail, subject, "_recoverypassword", new { AppName = Settings.AppName, Email = toEmail, Token = token }); } - private async Task setNewPassword() + private async Task SetNewPassword() { try { @@ -143,14 +142,14 @@ var result = await dialog.Result; if (!result.Canceled) { - var state = await _userManager.ResetPasswordAsync(_user, _inputToken, model.Password!); + var state = await UserManager.ResetPasswordAsync(_user, _inputToken, model.Password!); if (state.Succeeded) { _user.IsActive = true; - await _userManager.UpdateAsync(_user); + await UserManager.UpdateAsync(_user); Snackbar.Add($"{L["The new password has been set successfully, please login again"]}", MudBlazor.Severity.Info); - _logger.LogInformation("{@UserName} has set a new password", model.UserName); - _navigation.NavigateTo("/"); + Logger.LogInformation("{@UserName} has set a new password", model.UserName); + Navigation.NavigateTo("/"); } else { diff --git a/src/Blazor.Server.UI/Pages/Authentication/Login.razor b/src/Blazor.Server.UI/Pages/Authentication/Login.razor index e38b9d154..ac02b195b 100644 --- a/src/Blazor.Server.UI/Pages/Authentication/Login.razor +++ b/src/Blazor.Server.UI/Pages/Authentication/Login.razor @@ -1,22 +1,21 @@ @page "/pages/authentication/login" -@using System.Text.RegularExpressions -@using Blazor.Server.UI.Pages.Identity.Users -@using CleanArchitecture.Blazor.Application.Common.Security -@using CleanArchitecture.Blazor.Infrastructure.Services.JWT; -@using Microsoft.AspNetCore.Authentication -@using Microsoft.AspNetCore.DataProtection -@using Microsoft.AspNetCore.Identity -@using System.Security.Claims @inject AccessTokenProvider TokenProvider @inject IJSRuntime JS @inherits OwningComponentBase +@using CleanArchitecture.Blazor.Infrastructure.Services.JWT +@using Microsoft.AspNetCore.DataProtection +@using CleanArchitecture.Blazor.Application.Common.Security +@using Blazor.Server.UI.Pages.Identity.Users +@using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers +@using CleanArchitecture.Blazor.Application.Constants.Role +@using CleanArchitecture.Blazor.Application.Constants.User @implements IDisposable @inject IStringLocalizer L @Title - + @L["Sign In"] @L["Don't have an account?"] @L["Sign Up"] - @ConstantString.LOADING + @ConstantString.Loading } else { @@ -80,10 +79,10 @@ @code { public string Title = "Sign In"; - private UserManager _userManager { get; set; } = default!; - private AccessTokenProvider _tokenProvider { get; set; } = default!; - [Inject] private ILogger _logger { get; set; } = default!; - [Inject] private IDataProtectionProvider _dataProtectionProvider { get; set; } = default!; + private UserManager UserManager { get; set; } = default!; + private AccessTokenProvider AccessTokenProvider { get; set; } = default!; + [Inject] private ILogger Logger { get; set; } = default!; + [Inject] private IDataProtectionProvider DataProtectionProvider { get; set; } = default!; [Inject] protected NavigationManager NavigationManager { get; set; } = null!; private LoginFormModel _model = new() @@ -96,15 +95,15 @@ MudForm? _form; bool _success; bool _loading; - [Inject] private LoginFormModellFluentValidator _loginValidator { get; set; } = default!; + [Inject] private LoginFormModelFluentValidator LoginValidator { get; set; } = default!; protected override async Task OnInitializedAsync() { await base.OnInitializedAsync(); Title = L["Sign In"]; - _userManager = ScopedServices.GetRequiredService>(); - _tokenProvider = ScopedServices.GetRequiredService(); + UserManager = ScopedServices.GetRequiredService>(); + AccessTokenProvider = ScopedServices.GetRequiredService(); } private async Task OnSubmit() @@ -115,10 +114,10 @@ await _form!.Validate(); if (_form!.IsValid) { - var user = await _userManager.FindByNameAsync(_model.UserName!); + var user = await UserManager.FindByNameAsync(_model.UserName!); if (user is null) { - _logger.LogWarning("{@UserName} user does not exist.", _model.UserName); + Logger.LogWarning("{@UserName} user does not exist", _model.UserName); Snackbar.Add(L["No user found, or no authorization, please contact the administrator."], MudBlazor.Severity.Error); } else @@ -129,17 +128,17 @@ } else { - var result = await _userManager.CheckPasswordAsync(user, _model.Password!); + var result = await UserManager.CheckPasswordAsync(user, _model.Password!); if (!result) { - _logger.LogWarning("{@UserName} login fail.", _model.UserName); + Logger.LogWarning("{@UserName} login fail", _model.UserName); Snackbar.Add(L["Please check your username and password. If you are still unable to log in, contact your administrator."], MudBlazor.Severity.Error); } else { await TokenProvider.GenerateJwt(user); NavigationManager.NavigateTo(NavigationManager.Uri, true); - _logger.LogInformation("{@UserName} login successfully.", _model.UserName); + Logger.LogInformation("{@UserName} login successfully", _model.UserName); } } } @@ -162,14 +161,14 @@ var result = await dialog.Result; if (!result.Canceled) { - var token = await _userManager.GeneratePasswordResetTokenAsync(item); - var state = await _userManager.ResetPasswordAsync(item, token, model.Password!); + var token = await UserManager.GeneratePasswordResetTokenAsync(item); + var state = await UserManager.ResetPasswordAsync(item, token, model.Password!); if (state.Succeeded) { item.IsActive = true; - await _userManager.UpdateAsync(item); + await UserManager.UpdateAsync(item); Snackbar.Add($"{L["Password update successfuly"]}", MudBlazor.Severity.Info); - _logger.LogInformation("{@UserName} has set a new password", model.UserName); + Logger.LogInformation("{@UserName} has set a new password", model.UserName); _model.Password = ""; } else @@ -183,20 +182,20 @@ await JS.InvokeVoidAsync("externalLogin", provider, DotNetObjectReference.Create(this)); } [JSInvokable] - public async Task ConfirmExternal(string provider, string userName, string name, string accesstoken) + public async Task ConfirmExternal(string provider, string userName, string name, string accessToken) { - var user =await createUserWithExternalProvider(provider, userName, name, accesstoken); + var user =await CreateUserWithExternalProvider(provider, userName, name, accessToken); await TokenProvider.GenerateJwt(user); NavigationManager.NavigateTo(NavigationManager.Uri, true); - _logger.LogInformation("{@UserName} login successfully.", userName); + Logger.LogInformation("{@UserName} login successfully", userName); } - private async Task createUserWithExternalProvider(string provider, string userName, string name, string accesstoken) + private async Task CreateUserWithExternalProvider(string provider, string userName, string name, string accessToken) { - var user = await _userManager.FindByNameAsync(userName); + var user = await UserManager.FindByNameAsync(userName); if (user is null) { - var admin = await _userManager.FindByNameAsync(UserName.Administrator) ?? throw new NotFoundException($"Administrator's account Not Found."); + var admin = await UserManager.FindByNameAsync(UserName.Administrator) ?? throw new NotFoundException($"Administrator's account Not Found."); user = new ApplicationUser { EmailConfirmed = true, @@ -210,12 +209,12 @@ TenantId = admin.TenantId, TenantName = admin.TenantName }; - var createResult = await _userManager.CreateAsync(user); + var createResult = await UserManager.CreateAsync(user); if (createResult.Succeeded) { - var assignResult = await _userManager.AddToRoleAsync(user, RoleName.Basic); + var assignResult = await UserManager.AddToRoleAsync(user, RoleName.Basic); } - await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, userName, accesstoken)); + await UserManager.AddLoginAsync(user, new UserLoginInfo(provider, userName, accessToken)); } return user; diff --git a/src/Blazor.Server.UI/Pages/Authentication/Register.razor b/src/Blazor.Server.UI/Pages/Authentication/Register.razor index cfd97f38a..9d985ae30 100644 --- a/src/Blazor.Server.UI/Pages/Authentication/Register.razor +++ b/src/Blazor.Server.UI/Pages/Authentication/Register.razor @@ -1,19 +1,14 @@ @page "/pages/authentication/register" -@using System.Text.RegularExpressions -@using CleanArchitecture.Blazor.Application.Common.Security -@using FluentEmail.Core -@using FluentEmail.Core.Models -@using Microsoft.AspNetCore.Identity -@using System.ComponentModel.DataAnnotations -@using System.Security.Claims -@using FluentValidation; @inject IStringLocalizer L @attribute [AllowAnonymous] +@using CleanArchitecture.Blazor.Application.Common.Security +@using CleanArchitecture.Blazor.Application.Constants.Role +@using FluentEmail.Core.Models @inherits OwningComponentBase @Title - + @L["Sign Up"] @L["have an account?"] @L["Sign In"] @@ -66,7 +61,7 @@ @if (_loading) { - @ConstantString.LOADING + @ConstantString.Loading } else { @@ -84,18 +79,18 @@ @code { public string Title = "Sign Up"; - [Inject] private NavigationManager _navigation { get; set; } = default!; - private UserManager _userManager { get; set; } = default!; + [Inject] private NavigationManager Navigation { get; set; } = default!; + private UserManager UserManager { get; set; } = default!; MudForm? _form; bool _loading; - RegisterFormModel _model = new(); - [Inject] private RegisterFormModelFluentValidator _registerValidator { get; set; } = default!; + readonly RegisterFormModel _model = new(); + [Inject] private RegisterFormModelFluentValidator RegisterValidator { get; set; } = default!; [Inject] - private IMailService _mailService { get; set; } = null!; + private IMailService MailService { get; set; } = null!; protected override Task OnInitializedAsync() { - _userManager = ScopedServices.GetRequiredService>(); + UserManager = ScopedServices.GetRequiredService>(); return base.OnInitializedAsync(); } private async Task Submit() @@ -106,24 +101,24 @@ await _form!.Validate(); if (_form!.IsValid) { - var user = new ApplicationUser() + var user = new ApplicationUser { UserName = _model.UserName, Email = _model.Email }; - var result = await _userManager.CreateAsync(user, _model.Password!); + var result = await UserManager.CreateAsync(user, _model.Password!); if (result.Succeeded) { - var assignResult= await _userManager.AddToRoleAsync(user, RoleName.Basic); + var assignResult= await UserManager.AddToRoleAsync(user, RoleName.Basic); if (assignResult.Succeeded && !string.IsNullOrEmpty(user.Email) && !string.IsNullOrEmpty(user.UserName)) { - var response= await sendWelcome(user.Email!, user.UserName!); + var response= await SendWelcome(user.Email!, user.UserName!); if (response.Successful == false) { Snackbar.Add(string.Format(L["{0}"],response.ErrorMessages.FirstOrDefault()), MudBlazor.Severity.Warning); } Snackbar.Add(L["Register successfully!"], MudBlazor.Severity.Info); - _navigation.NavigateTo("/"); + Navigation.NavigateTo("/"); } else { @@ -143,11 +138,11 @@ } } - private Task sendWelcome(string toemail, string userName) + private Task SendWelcome(string toEmail, string userName) { var subject =string.Format(L["Welcome to {0}"],Settings.AppName); var template = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "EmailTemplates" ,"_welcome.txt"); - return _mailService.SendAsync(toemail, subject, "_welcome", new { AppName = Settings.AppName, Email = toemail, UserName = userName }); + return MailService.SendAsync(toEmail, subject, "_welcome", new { AppName = Settings.AppName, Email = toEmail, UserName = userName }); } } diff --git a/src/Blazor.Server.UI/Pages/Authentication/Reset.razor b/src/Blazor.Server.UI/Pages/Authentication/Reset.razor index bd4bf3bb4..402aeebb6 100644 --- a/src/Blazor.Server.UI/Pages/Authentication/Reset.razor +++ b/src/Blazor.Server.UI/Pages/Authentication/Reset.razor @@ -6,7 +6,7 @@ @L["Set new password"] - + @L["Set new password"] @@ -20,23 +20,23 @@ @code { string Password { get; set; } = string.Empty; - bool PasswordVisibility; - InputType PasswordInput = InputType.Password; - string PasswordInputIcon = Icons.Material.Filled.VisibilityOff; + bool _passwordVisibility; + InputType _passwordInput = InputType.Password; + string _passwordInputIcon = Icons.Material.Filled.VisibilityOff; void TogglePasswordVisibility() { - @if (PasswordVisibility) + @if (_passwordVisibility) { - PasswordVisibility = false; - PasswordInputIcon = Icons.Material.Filled.VisibilityOff; - PasswordInput = InputType.Password; + _passwordVisibility = false; + _passwordInputIcon = Icons.Material.Filled.VisibilityOff; + _passwordInput = InputType.Password; } else { - PasswordVisibility = true; - PasswordInputIcon = Icons.Material.Filled.Visibility; - PasswordInput = InputType.Text; + _passwordVisibility = true; + _passwordInputIcon = Icons.Material.Filled.Visibility; + _passwordInput = InputType.Text; } } } diff --git a/src/Blazor.Server.UI/Pages/Customers/Components/CustomersAdvancedSearchComponent.razor b/src/Blazor.Server.UI/Pages/Customers/Components/CustomersAdvancedSearchComponent.razor index 1f5fc7279..798b88ae9 100644 --- a/src/Blazor.Server.UI/Pages/Customers/Components/CustomersAdvancedSearchComponent.razor +++ b/src/Blazor.Server.UI/Pages/Customers/Components/CustomersAdvancedSearchComponent.razor @@ -3,7 +3,7 @@ + Class="mud-elevation-25 pa-2 mb-3" Text="@ConstantString.AdvancedSearch"> @*TODO: define advanced search query fields, for example:*@ diff --git a/src/Blazor.Server.UI/Pages/Customers/Customers.razor b/src/Blazor.Server.UI/Pages/Customers/Customers.razor index a58bba181..05587f733 100644 --- a/src/Blazor.Server.UI/Pages/Customers/Customers.razor +++ b/src/Blazor.Server.UI/Pages/Customers/Customers.razor @@ -1,13 +1,13 @@ @page "/pages/Customers" - -@using BlazorDownloadFile -@using CleanArchitecture.Blazor.Application.Features.Customers.Caching @using CleanArchitecture.Blazor.Application.Features.Customers.DTOs -@using CleanArchitecture.Blazor.Application.Features.Customers.Commands.Delete -@using CleanArchitecture.Blazor.Application.Features.Customers.Commands.Import @using CleanArchitecture.Blazor.Application.Features.Customers.Queries.Export @using CleanArchitecture.Blazor.Application.Features.Customers.Queries.Pagination +@using BlazorDownloadFile +@using CleanArchitecture.Blazor.Application.Constants.Permission +@using CleanArchitecture.Blazor.Application.Features.Customers.Caching @using CleanArchitecture.Blazor.Application.Features.Customers.Commands.AddEdit +@using CleanArchitecture.Blazor.Application.Features.Customers.Commands.Delete +@using CleanArchitecture.Blazor.Application.Features.Customers.Commands.Import @inject IJSRuntime JS @inject IStringLocalizer L @@ -38,7 +38,7 @@
@Title - +
@@ -52,7 +52,7 @@ Disabled="@_loading" OnClick="@(()=>OnRefresh())" StartIcon="@Icons.Material.Filled.Refresh" IconColor="Color.Surface" Color="Color.Primary" - Style="margin-right: 4px; margin-bottom:4px">@ConstantString.REFRESH + Style="margin-right: 4px; margin-bottom:4px">@ConstantString.Refresh @if (_canCreate) { @ConstantString.NEW + IconColor="Color.Surface">@ConstantString.New } @if (_canDelete) { @@ -71,19 +71,19 @@ Size="Size.Small" Style="margin-right: 4px; margin-bottom:4px" OnClick="OnDeleteChecked" - IconColor="Color.Surface">@ConstantString.DELETE + IconColor="Color.Surface">@ConstantString.Delete } @if (_canExport) { - @ConstantString.EXPORT + @ConstantString.Export } @if (_canImport) @@ -100,11 +100,11 @@ @if (_uploading) { - @ConstantString.UPLOADING + @ConstantString.Uploading } else { - @ConstantString.IMPORT + @ConstantString.Import } @@ -120,7 +120,7 @@ Disabled="@_loading" OnClick="OnCreate" Style="margin-right: 4px; margin-bottom:4px" - IconColor="Color.Surface">@ConstantString.NEW + IconColor="Color.Surface">@ConstantString.New } @if (_canDelete) { @@ -130,13 +130,13 @@ Size="Size.Small" Style="margin-right: 4px; margin-bottom:4px" OnClick="OnDeleteChecked" - IconColor="Color.Surface">@ConstantString.DELETE + IconColor="Color.Surface">@ConstantString.Delete }
@if (_canSearch) { - } @@ -145,7 +145,7 @@ - + @if (_canEdit || _canDelete) { @@ -154,11 +154,11 @@ EndIcon="@Icons.Material.Filled.KeyboardArrowDown" IconColor="Color.Info" AnchorOrigin="Origin.CenterLeft"> @if (_canEdit) { - @ConstantString.EDIT + @ConstantString.Edit } @if (_canDelete) { - @ConstantString.DELETE + @ConstantString.Delete } } @@ -167,7 +167,7 @@ - @ConstantString.NOALLOWED + @ConstantString.NoAllowed } @@ -184,10 +184,10 @@ - @ConstantString.NORECORDS + @ConstantString.NoRecords - @ConstantString.LOADING + @ConstantString.Loading @@ -211,15 +211,15 @@ private bool _downloading; private bool _exporting; [Inject] - private IMediator _mediator { get; set; } = default!; + private IMediator Mediator { get; set; } = default!; [Inject] - private IMapper _mapper { get; set; } = default!; + private IMapper Mapper { get; set; } = default!; [CascadingParameter] - private Task _authState { get; set; } = default!; + private Task AuthState { get; set; } = default!; - private CustomersWithPaginationQuery _query { get; set; } = new(); + private CustomersWithPaginationQuery Query { get; set; } = new(); [Inject] - private IBlazorDownloadFileService _blazorDownloadFileService { get; set; } = null!; + private IBlazorDownloadFileService BlazorDownloadFileService { get; set; } = null!; private bool _canSearch; private bool _canCreate; private bool _canEdit; @@ -230,7 +230,7 @@ protected override async Task OnInitializedAsync() { Title = L[_currentDto.GetClassDescription()]; - var state = await _authState; + var state = await AuthState; _canCreate = (await AuthService.AuthorizeAsync(state.User, Permissions.Customers.Create)).Succeeded; _canSearch = (await AuthService.AuthorizeAsync(state.User, Permissions.Customers.Search)).Succeeded; _canEdit = (await AuthService.AuthorizeAsync(state.User, Permissions.Customers.Edit)).Succeeded; @@ -243,11 +243,11 @@ try { _loading = true; - _query.Sort = state.SortDefinitions.FirstOrDefault()?.SortBy ?? "Id"; - _query.SortBy = (state.SortDefinitions.FirstOrDefault()?.Descending ?? true ? AutoFilterer.Enums.Sorting.Descending : AutoFilterer.Enums.Sorting.Ascending); - _query.Page = state.Page + 1; - _query.PerPage = state.PageSize; - var result = await _mediator.Send(_query).ConfigureAwait(false); + Query.Sort = state.SortDefinitions.FirstOrDefault()?.SortBy ?? "Id"; + Query.SortBy = (state.SortDefinitions.FirstOrDefault()?.Descending ?? true ? AutoFilterer.Enums.Sorting.Descending : AutoFilterer.Enums.Sorting.Ascending); + Query.Page = state.Page + 1; + Query.PerPage = state.PageSize; + var result = await Mediator.Send(Query).ConfigureAwait(false); return new GridData() { TotalItems = result.TotalItems, Items = result.Items }; } finally @@ -259,19 +259,19 @@ private async Task OnSearch(string text) { _selectedItems = new(); - _query.Keyword = text; + Query.Keyword = text; await _table.ReloadServerData(); } private async Task OnChangedListView(CustomerListView listview) { - _query.ListView = listview; + Query.ListView = listview; await _table.ReloadServerData(); } private async Task OnRefresh() { CustomerCacheKey.Refresh(); _selectedItems = new(); - _query.Keyword = string.Empty; + Query.Keyword = string.Empty; await _table.ReloadServerData(); } @@ -280,7 +280,7 @@ var command = new AddEditCustomerCommand(); var parameters = new DialogParameters { - { nameof(_CustomerFormDialog.model),command }, + { nameof(_CustomerFormDialog.Model),command }, }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Medium, FullWidth = true }; var dialog = DialogService.Show<_CustomerFormDialog> @@ -294,10 +294,10 @@ private async Task OnEdit(CustomerDto dto) { - var command = _mapper.Map(dto); + var command = Mapper.Map(dto); var parameters = new DialogParameters { - { nameof(_CustomerFormDialog.model),command }, + { nameof(_CustomerFormDialog.Model),command }, }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Medium, FullWidth = true }; var dialog = DialogService.Show<_CustomerFormDialog> @@ -315,10 +315,10 @@ var parameters = new DialogParameters { { nameof(DeleteConfirmation.Command), command }, - { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DELETECONFIRMATION, dto.Name) } + { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DeleteConfirmation, dto.Name) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Small, FullWidth = true, DisableBackdropClick = true }; - var dialog = DialogService.Show(ConstantString.DELETECONFIRMATIONTITLE, parameters, options); + var dialog = DialogService.Show(ConstantString.DeleteConfirmationTitle, parameters, options); var state = await dialog.Result; if (!state.Canceled) { @@ -332,10 +332,10 @@ var parameters = new DialogParameters { { nameof(DeleteConfirmation.Command), command }, - { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DELETECONFIRMWITHSELECTED,_selectedItems.Count) } + { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DeleteConfirmWithSelected,_selectedItems.Count) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall, FullWidth = true, DisableBackdropClick = true }; - var dialog = DialogService.Show(ConstantString.DELETECONFIRMATIONTITLE, parameters, options); + var dialog = DialogService.Show(ConstantString.DeleteConfirmationTitle, parameters, options); var state = await dialog.Result; if (!state.Canceled) { @@ -348,16 +348,16 @@ _exporting = true; var request = new ExportCustomersQuery() { - Keyword = _query.Keyword, - ListView = _query.ListView, + Keyword = Query.Keyword, + ListView = Query.ListView, Sort = _table.SortDefinitions.Values.FirstOrDefault()?.SortBy ?? "Id", SortBy = (_table.SortDefinitions.Values.FirstOrDefault()?.Descending ?? false) ? AutoFilterer.Enums.Sorting.Ascending : AutoFilterer.Enums.Sorting.Descending }; - var result = await _mediator.Send(request); + var result = await Mediator.Send(request); if (result.Succeeded) { - var downloadresult = await _blazorDownloadFileService.DownloadFile($"{L["Customers"]}.xlsx", result.Data, contentType: "application/octet-stream"); - Snackbar.Add($"{ConstantString.EXPORTSUCESS}", MudBlazor.Severity.Info); + var downloadResult = await BlazorDownloadFileService.DownloadFile($"{L["Customers"]}.xlsx", result.Data, contentType: "application/octet-stream"); + Snackbar.Add($"{ConstantString.ExportSuccess}", MudBlazor.Severity.Info); } else { @@ -371,11 +371,11 @@ var stream = new MemoryStream(); await file.OpenReadStream().CopyToAsync(stream); var command = new ImportCustomersCommand(file.Name, stream.ToArray()); - var result = await _mediator.Send(command); + var result = await Mediator.Send(command); if (result.Succeeded) { await _table.ReloadServerData(); - Snackbar.Add($"{ConstantString.IMPORTSUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.ImportSuccess}", MudBlazor.Severity.Info); } else { diff --git a/src/Blazor.Server.UI/Pages/Customers/_CustomerFormDialog.razor b/src/Blazor.Server.UI/Pages/Customers/_CustomerFormDialog.razor index 6db478b62..02ea6c50f 100644 --- a/src/Blazor.Server.UI/Pages/Customers/_CustomerFormDialog.razor +++ b/src/Blazor.Server.UI/Pages/Customers/_CustomerFormDialog.razor @@ -1,37 +1,41 @@ @using CleanArchitecture.Blazor.Application.Features.Customers.Commands.AddEdit - +@using Severity = MudBlazor.Severity @inherits MudComponentBase @inject IStringLocalizer L - + @*TODO: define mudform that should be edit fields, for example:*@ - - - - - - + + + + + + - @ConstantString.CANCEL - @ConstantString.SAVE + @ConstantString.Cancel + @ConstantString.Save @code { MudForm? _form; - private bool _saving = false; - [CascadingParameter] - MudDialogInstance MudDialog { get; set; } = default!; - AddEditCustomerCommandValidator _modelValidator = new (); - [EditorRequired] [Parameter] public AddEditCustomerCommand model { get; set; } = null!; - [Inject] private IMediator _mediator { get; set; } = default!; + private bool _saving; + + [CascadingParameter] MudDialogInstance MudDialog { get; set; } = default!; + + readonly AddEditCustomerCommandValidator _modelValidator = new(); + + [EditorRequired] [Parameter] public AddEditCustomerCommand Model { get; set; } = null!; + + [Inject] private IMediator Mediator { get; set; } = default!; + async Task Submit() { try @@ -42,16 +46,16 @@ if (!_form!.IsValid) return; - var result = await _mediator.Send(model); + var result = await Mediator.Send(Model); if (result.Succeeded) { MudDialog.Close(DialogResult.Ok(true)); - Snackbar.Add(ConstantString.SAVESUCCESS, MudBlazor.Severity.Info); + Snackbar.Add(ConstantString.SaveSuccess, Severity.Info); } else { - Snackbar.Add(result.ErrorMessage, MudBlazor.Severity.Error); + Snackbar.Add(result.ErrorMessage, Severity.Error); } } finally @@ -59,5 +63,10 @@ _saving = false; } } - void Cancel() => MudDialog.Cancel(); + + void Cancel() + { + MudDialog.Cancel(); + } + } \ No newline at end of file diff --git a/src/Blazor.Server.UI/Pages/Documents/Documents.razor b/src/Blazor.Server.UI/Pages/Documents/Documents.razor index 0fbadeb49..86f7e0b92 100644 --- a/src/Blazor.Server.UI/Pages/Documents/Documents.razor +++ b/src/Blazor.Server.UI/Pages/Documents/Documents.razor @@ -1,19 +1,18 @@ @page "/pages/documents" -@using AutoMapper; -@using Blazor.Server.UI.Services.JsInterop; -@using BlazorDownloadFile -@using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant -@using CleanArchitecture.Blazor.Application.Features.Documents.Caching; -@using CleanArchitecture.Blazor.Application.Features.Documents.Commands.Delete -@using CleanArchitecture.Blazor.Application.Features.Documents.DTOs -@using CleanArchitecture.Blazor.Application.Features.Documents.Commands.AddEdit -@using CleanArchitecture.Blazor.Application.Features.Documents.Queries.PaginationQuery -@using CleanArchitecture.Blazor.Infrastructure.Hubs - @inject IJSRuntime JS @inject IStringLocalizer L @inherits UserProfileStateComponent +@using CleanArchitecture.Blazor.Application.Features.Documents.DTOs +@using CleanArchitecture.Blazor.Application.Features.Documents.Queries.PaginationQuery +@using CleanArchitecture.Blazor.Infrastructure.Hubs +@using BlazorDownloadFile +@using CleanArchitecture.Blazor.Application.Features.Documents.Caching +@using CleanArchitecture.Blazor.Application.Features.Documents.Commands.AddEdit +@using CleanArchitecture.Blazor.Application.Features.Documents.Commands.Delete +@using Blazor.Server.UI.Services.JsInterop +@using CleanArchitecture.Blazor.Application.Constants.Permission +@using CleanArchitecture.Blazor.Domain.Enums @implements IDisposable @attribute [Authorize(Policy = Permissions.Documents.View)] @Title @@ -41,7 +40,7 @@
@L["Documents"] - +
@@ -55,7 +54,7 @@ Disabled="@_loading" OnClick="@(()=>OnRefresh())" StartIcon="@Icons.Material.Filled.Refresh" IconColor="Color.Surface" Color="Color.Primary" - Style="margin-right: 4px; margin-bottom:4px">@ConstantString.REFRESH + Style="margin-right: 4px; margin-bottom:4px">@ConstantString.Refresh @if (_canCreate) { @ConstantString.DELETE + IconColor="Color.Surface">@ConstantString.Delete } - @ConstantString.REFRESH + @ConstantString.Refresh @if (_canCreate) { @L["Upload Pictures"] } @if (_canDelete) { - @ConstantString.DELETE + @ConstantString.Delete } @@ -96,7 +95,7 @@ @if (_canSearch) { - } @@ -105,7 +104,7 @@ - + @if (_canEdit || _canDelete) { @@ -114,15 +113,15 @@ EndIcon="@Icons.Material.Filled.KeyboardArrowDown" IconColor="Color.Info" AnchorOrigin="Origin.CenterLeft"> @if (_canEdit) { - @ConstantString.EDIT + @ConstantString.Edit } @if (_canDelete) { - @ConstantString.DELETE + @ConstantString.Delete } @if (_canDownload) { - @ConstantString.DOWNLOAD + @ConstantString.Download } } @@ -131,7 +130,7 @@ - @ConstantString.NOALLOWED + @ConstantString.NoAllowed } @@ -203,10 +202,10 @@ - @ConstantString.NORECORDS + @ConstantString.NoRecords - @ConstantString.LOADING + @ConstantString.Loading @@ -221,7 +220,7 @@ public string? Title { get; private set; } private HashSet _selectedItems = new HashSet(); - private DocumentDto _currentDto = new(); + private readonly DocumentDto _currentDto = new(); private MudDataGrid _table = null!; private int _defaultPageSize = 15; private string _searchString = string.Empty; @@ -230,15 +229,15 @@ [Inject] IBlazorDownloadFileService BlazorDownloadFileService { get; set; } = null!; [Inject] - private IMediator _mediator { get; set; } = default!; + private IMediator Mediator { get; set; } = default!; [Inject] - private HubClient _client { get; set; } = default!; + private HubClient Client { get; set; } = default!; [Inject] - private IMapper _mapper { get; set; } = default!; + private IMapper Mapper { get; set; } = default!; private string _tenantId = string.Empty; - private DocumentsWithPaginationQuery _query { get; set; } = new DocumentsWithPaginationQuery() ; + private DocumentsWithPaginationQuery Query { get; set; } = new DocumentsWithPaginationQuery() ; private bool _canSearch; private bool _canCreate; @@ -251,7 +250,7 @@ { await base.OnInitializedAsync(); Title = L[_currentDto.GetClassDescription()]; - var state = await _authState; + var state = await AuthState; _canCreate = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Create)).Succeeded; _canSearch = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Search)).Succeeded; _canEdit = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Edit)).Succeeded; @@ -259,10 +258,10 @@ _canImport = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Import)).Succeeded; _canExport = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Export)).Succeeded; _canDownload = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Download)).Succeeded; - _client.JobCompleted += _client_JobCompleted; - _client.JobStarted += _client_JobStarted; + Client.JobCompleted += _client_JobCompleted; + Client.JobStarted += _client_JobStarted; - await _client.StartAsync(); + await Client.StartAsync(); } private void _client_JobCompleted(object? sender, string e) @@ -285,21 +284,21 @@ protected void Dispose() { base.Dispose(); - _client.JobCompleted -= _client_JobCompleted; - _client.JobStarted -= _client_JobStarted; + Client.JobCompleted -= _client_JobCompleted; + Client.JobStarted -= _client_JobStarted; } private async Task> ServerReload(GridState state) { try { _loading = true; - _query.Keyword = _searchString; - _query.CurrentUser = UserProfile; - _query.OrderBy = state.SortDefinitions.FirstOrDefault()?.SortBy??"Id"; - _query.SortDirection = state.SortDefinitions.FirstOrDefault() == null ? SortDirection.Descending.ToString() : (state.SortDefinitions.First().Descending ? SortDirection.Descending.ToString():SortDirection.Ascending.ToString()); - _query.PageNumber = state.Page + 1; - _query.PageSize = state.PageSize; - var result = await _mediator.Send(_query); + Query.Keyword = _searchString; + Query.CurrentUser = UserProfile; + Query.OrderBy = state.SortDefinitions.FirstOrDefault()?.SortBy??"Id"; + Query.SortDirection = state.SortDefinitions.FirstOrDefault() == null ? SortDirection.Descending.ToString() : (state.SortDefinitions.First().Descending ? SortDirection.Descending.ToString():SortDirection.Ascending.ToString()); + Query.PageNumber = state.Page + 1; + Query.PageSize = state.PageSize; + var result = await Mediator.Send(Query); return new GridData() { TotalItems = result.TotalItems, Items = result.Items }; } finally @@ -318,7 +317,7 @@ } private async Task OnChangedListView(DocumentListView listview) { - _query.ListView = listview; + Query.ListView = listview; await _table.ReloadServerData(); } private async Task OnSearch(string text) @@ -339,7 +338,7 @@ var command = new AddEditDocumentCommand() { DocumentType = DocumentType.Document }; var parameters = new DialogParameters { - { nameof(_DocumentFormDialog.model),command }, + { nameof(_DocumentFormDialog.Model),command }, }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Small, FullWidth = true }; var dialog = DialogService.Show<_UploadFilesFormDialog> @@ -348,19 +347,19 @@ if (!state.Canceled) { await _table.ReloadServerData(); - Snackbar.Add(ConstantString.UPLOADSUCCESS, MudBlazor.Severity.Info); + Snackbar.Add(ConstantString.UploadSuccess, MudBlazor.Severity.Info); } } private async Task OnEdit(DocumentDto dto) { - var command = _mapper.Map(dto); + var command = Mapper.Map(dto); var parameters = new DialogParameters { { nameof(DeleteConfirmation.Command), command }, - { nameof(_DocumentFormDialog.model),command }, + { nameof(_DocumentFormDialog.Model),command }, }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Medium, FullWidth = true }; - var dialog = DialogService.Show<_DocumentFormDialog>(string.Format(ConstantString.EDITTHEITEM, L["Document"]), parameters, options); + var dialog = DialogService.Show<_DocumentFormDialog>(string.Format(ConstantString.EditTheItem, L["Document"]), parameters, options); await Task.Delay(300); if (!string.IsNullOrEmpty(dto.URL)) await (new OpenSeadragon(JS)).Open(dto.URL); @@ -377,10 +376,10 @@ var parameters = new DialogParameters { { nameof(DeleteConfirmation.Command), command }, - { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DELETECONFIRMATION, dto.Title) } + { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DeleteConfirmation, dto.Title) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Small, FullWidth = true, DisableBackdropClick = true }; - var dialog = DialogService.Show(string.Format(ConstantString.EDITTHEITEM, L["Document"]), parameters, options); + var dialog = DialogService.Show(string.Format(ConstantString.EditTheItem, L["Document"]), parameters, options); var state = await dialog.Result; if (!state.Canceled) { @@ -394,11 +393,11 @@ var parameters = new DialogParameters { { nameof(DeleteConfirmation.Command), command }, - { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DELETECONFIRMWITHSELECTED,_selectedItems.Count) } + { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DeleteConfirmWithSelected,_selectedItems.Count) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall, FullWidth = true, DisableBackdropClick = true }; var dialog = DialogService.Show - (string.Format(ConstantString.DELETETHEITEM, L["Document"]), parameters, options); + (string.Format(ConstantString.DeleteTheItem, L["Document"]), parameters, options); var state = await dialog.Result; if (!state.Canceled) { @@ -411,7 +410,7 @@ try { _downloading = true; - var file = await _mediator.Send(new GetFileStreamQuery(dto.Id)); + var file = await Mediator.Send(new GetFileStreamQuery(dto.Id)); if (file.Item2 != null) { var result = await BlazorDownloadFileService.DownloadFile(file.Item1, file.Item2, "application/octet-stream"); diff --git a/src/Blazor.Server.UI/Pages/Documents/_DocumentFormDialog.razor b/src/Blazor.Server.UI/Pages/Documents/_DocumentFormDialog.razor index 389625bc7..209fce91c 100644 --- a/src/Blazor.Server.UI/Pages/Documents/_DocumentFormDialog.razor +++ b/src/Blazor.Server.UI/Pages/Documents/_DocumentFormDialog.razor @@ -1,26 +1,24 @@ @using CleanArchitecture.Blazor.Application.Features.Documents.Commands.AddEdit -@using SixLabors.ImageSharp -@using SixLabors.ImageSharp.Formats -@using SixLabors.ImageSharp.Processing +@using CleanArchitecture.Blazor.Domain.Enums @inherits MudComponentBase @inject IStringLocalizer L - + - + @bind-Value="Model.DocumentType"> @foreach (var doctype in Enum.GetValues()) { @doctype @@ -29,25 +27,24 @@ + For="@(() => Model.Description)" + @bind-Value="Model.Description"> + For="@(() => Model.Content)" + @bind-Value="Model.Content"> + For="@(() => Model.Status)" + @bind-Value="Model.Status"> + For="@(() => Model.IsPublic)" + @bind-Checked="Model.IsPublic"> @@ -61,8 +58,8 @@ - @ConstantString.CANCEL - @ConstantString.OK + @ConstantString.Cancel + @ConstantString.Ok @@ -70,9 +67,10 @@ MudForm? _form = default!; [CascadingParameter] MudDialogInstance MudDialog { get; set; } = default!; - AddEditDocumentCommandValidator modelValidator = new AddEditDocumentCommandValidator(); - [EditorRequired][Parameter] public AddEditDocumentCommand model { get; set; } = default!; - const long MAXALLOWEDSIZE = 3145728; + + readonly AddEditDocumentCommandValidator _modelValidator = new AddEditDocumentCommandValidator(); + [EditorRequired][Parameter] public AddEditDocumentCommand Model { get; set; } = default!; + const long MaxAllowedSize = 3145728; async Task Submit() { diff --git a/src/Blazor.Server.UI/Pages/Documents/_UploadFilesFormDialog.razor b/src/Blazor.Server.UI/Pages/Documents/_UploadFilesFormDialog.razor index 948faa3d5..06db5ad84 100644 --- a/src/Blazor.Server.UI/Pages/Documents/_UploadFilesFormDialog.razor +++ b/src/Blazor.Server.UI/Pages/Documents/_UploadFilesFormDialog.razor @@ -1,18 +1,15 @@ -@using Blazor.Server.UI.Services.JsInterop; @using CleanArchitecture.Blazor.Application.Features.Documents.Commands.AddEdit @using CleanArchitecture.Blazor.Application.Features.Documents.Commands.Upload -@using SixLabors.ImageSharp -@using SixLabors.ImageSharp.Formats -@using SixLabors.ImageSharp.Processing - +@using Blazor.Server.UI.Services.JsInterop +@using CleanArchitecture.Blazor.Domain.Enums @inherits MudComponentBase @inject IStringLocalizer L - @if (uploadedFiles.Any()) + @if (_uploadedFiles.Any()) {
- @foreach (var item in uploadedFiles) + @foreach (var item in _uploadedFiles) { @@ -36,9 +33,9 @@ @@ -54,29 +51,28 @@ @code { - [CascadingParameter] - MudDialogInstance MudDialog { get; set; } = default!; - [EditorRequired][Parameter] public AddEditDocumentCommand model { get; set; } = default!; + [CascadingParameter] MudDialogInstance MudDialog { get; set; } = default!; + [EditorRequired][Parameter] public AddEditDocumentCommand Model { get; set; } = default!; bool _processing; bool _uploading; [Inject] - private IJSRuntime _js { get; set; } = default!; + private IJSRuntime Js { get; set; } = default!; [Inject] - private ISender _mediator { get; set; } = default!; - [Inject] private IUploadService _uploadService { get; set; } = default!; - List uploadedFiles = new(); + private ISender Mediator { get; set; } = default!; + [Inject] private IUploadService UploadService { get; set; } = default!; + List _uploadedFiles = new(); private async ValueTask LoadFiles(InputFileChangeEventArgs e) { try { _uploading = true; var files = e.GetMultipleFiles(maximumFileCount: 100); - var startIndex = uploadedFiles.Count; + var startIndex = _uploadedFiles.Count; // Add all files to the UI foreach (var file in files) { var progress = new FileUploadProgress(file.Name, file.Size, file); - uploadedFiles.Add(progress); + _uploadedFiles.Add(progress); } // We don't want to refresh the UI too frequently, @@ -90,10 +86,10 @@ { foreach (var file in files) { - using var stream = file.OpenReadStream(GlobalVariable.maxAllowedSize); + using var stream = file.OpenReadStream(GlobalVariable.MaxAllowedSize); while (await stream.ReadAsync(buffer) is int read && read > 0) { - uploadedFiles[startIndex].UploadedBytes += read; + _uploadedFiles[startIndex].UploadedBytes += read; // TODO Do something with the file chunk, such as save it // to a database or a local file system @@ -134,20 +130,20 @@ try { _processing = true; - if (uploadedFiles.Any()) + if (_uploadedFiles.Any()) { var list = new List(); - foreach (var uploaded in uploadedFiles) + foreach (var uploaded in _uploadedFiles) { try { - var filestream = uploaded.File.OpenReadStream(GlobalVariable.maxAllowedSize); - var imgstream = new MemoryStream(); - await filestream.CopyToAsync(imgstream); - imgstream.Position = 0; + var filestream = uploaded.File.OpenReadStream(GlobalVariable.MaxAllowedSize); + var imgStream = new MemoryStream(); + await filestream.CopyToAsync(imgStream); + imgStream.Position = 0; using (var outStream = new MemoryStream()) { - using (var image = Image.Load(imgstream)) + using (var image = Image.Load(imgStream)) { var scale = 0m; if (image.Width > 1600) @@ -174,11 +170,9 @@ { Snackbar.Add($"{e.Message}", MudBlazor.Severity.Error); } - - } - var uploadcommand = new UploadDocumentCommand(list); - await _mediator.Send(uploadcommand); + var uploadCommand = new UploadDocumentCommand(list); + await Mediator.Send(uploadCommand); await Clear(); MudDialog.Close(DialogResult.Ok(true)); } @@ -191,8 +185,8 @@ void Cancel() => MudDialog.Cancel(); async Task Clear() { - await (new InputClear(_js)).Clear("fileInput"); - uploadedFiles = new(); + await (new InputClear(Js)).Clear("fileInput"); + _uploadedFiles = new(); } record FileUploadProgress(string FileName, long Size, IBrowserFile File) { diff --git a/src/Blazor.Server.UI/Pages/Identity/Roles/RoleDtoValidator.cs b/src/Blazor.Server.UI/Pages/Identity/Roles/RoleDtoValidator.cs index b676e8013..14a2f4702 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Roles/RoleDtoValidator.cs +++ b/src/Blazor.Server.UI/Pages/Identity/Roles/RoleDtoValidator.cs @@ -1,5 +1,4 @@ using CleanArchitecture.Blazor.Application.Features.Identity.Dto; -using FluentValidation; namespace Blazor.Server.UI.Pages.Identity.Roles; diff --git a/src/Blazor.Server.UI/Pages/Identity/Roles/Roles.razor b/src/Blazor.Server.UI/Pages/Identity/Roles/Roles.razor index 1f1f2d214..209262863 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Roles/Roles.razor +++ b/src/Blazor.Server.UI/Pages/Identity/Roles/Roles.razor @@ -1,15 +1,13 @@ -@inherits OwningComponentBase -@page "/identity/roles" -@using Blazor.Server.UI.Components.Dialogs -@using CleanArchitecture.Blazor.Application.Common.Exceptions +@using LazyCache @using CleanArchitecture.Blazor.Application.Features.Identity.Dto -@using CleanArchitecture.Blazor.Infrastructure.Constants -@using CleanArchitecture.Blazor.Application.Common.Security -@using LazyCache; -@using Microsoft.AspNetCore.Identity +@using System.Security.Claims @using System.ComponentModel @using System.Reflection -@using System.Security.Claims +@using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers +@using CleanArchitecture.Blazor.Application.Constants.ClaimTypes +@using CleanArchitecture.Blazor.Application.Constants.Permission +@inherits OwningComponentBase +@page "/identity/roles" @attribute [Authorize(Policy = Permissions.Roles.View)] @inject IStringLocalizer L @@ -49,7 +47,7 @@ OnClick="OnRefresh" Disabled="@_loading" StartIcon="@Icons.Material.Filled.Refresh" IconColor="Color.Surface" Color="Color.Primary" - Style="margin-right: 4px; margin-bottom:4px">@ConstantString.REFRESH + Style="margin-right: 4px; margin-bottom:4px">@ConstantString.Refresh @if (_canCreate) { @ConstantString.NEW + IconColor="Color.Surface">@ConstantString.New } @if (_canDelete) { @@ -67,7 +65,7 @@ OnClick="OnDeleteChecked" Size="Size.Small" Style="margin-right: 4px; margin-bottom:4px" - IconColor="Color.Surface">@ConstantString.DELETE + IconColor="Color.Surface">@ConstantString.Delete } @if (_canExport) @@ -76,7 +74,7 @@ StartIcon="@Icons.Material.Filled.Download" Size="Size.Small" Style="margin-right: 4px; margin-bottom:4px" - IconColor="Color.Surface">@ConstantString.EXPORT + IconColor="Color.Surface">@ConstantString.Export } @if (_canImport) { @@ -92,11 +90,11 @@ @if (_uploading) { - @ConstantString.UPLOADING + @ConstantString.Uploading } else { - @ConstantString.IMPORT + @ConstantString.Import } @@ -105,14 +103,14 @@ - @ConstantString.REFRESH + @ConstantString.Refresh @if (_canCreate) { - @ConstantString.NEW + @ConstantString.New } @if (_canDelete) { - @ConstantString.DELETE + @ConstantString.Delete } @@ -130,7 +128,7 @@ - + @if (_canEdit || _canDelete) { @@ -139,11 +137,11 @@ EndIcon="@Icons.Material.Filled.KeyboardArrowDown" IconColor="Color.Info" AnchorOrigin="Origin.CenterLeft"> @if (_canEdit) { - @ConstantString.EDIT + @ConstantString.Edit } @if (_canDelete) { - @ConstantString.DELETE + @ConstantString.Delete } } @@ -152,7 +150,7 @@ - @ConstantString.NOALLOWED + @ConstantString.NoAllowed } @@ -174,7 +172,7 @@ - <_PermissionsDrawer OnAssignAllChanged="OnAssignAllChangedHandler" Waiting="@processing" OnOpenChanged="OnOpenChangedHandler" Open="_showPermissionsDrawer" Permissions="_permissions" OnAssignChanged="OnAssignChangedHandler"> + <_PermissionsDrawer OnAssignAllChanged="OnAssignAllChangedHandler" Waiting="@_processing" OnOpenChanged="OnOpenChangedHandler" Open="_showPermissionsDrawer" Permissions="_permissions" OnAssignChanged="OnAssignChangedHandler"> @@ -182,22 +180,22 @@ @code { - private bool processing = false; + private bool _processing = false; private string _currentRoleName = string.Empty; private int _defaultPageSize = 15; private HashSet _selectedItems = new(); - private ApplicationRoleDto _currentDto = new(); + private readonly ApplicationRoleDto _currentDto = new(); private string _searchString = string.Empty; - public string? Title { get; private set; } + private string? Title { get; set; } [CascadingParameter] - private Task _authState { get; set; } = default!; + private Task AuthState { get; set; } = default!; - private RoleManager _roleManager { get; set; } = default!; + private RoleManager RoleManager { get; set; } = default!; - private TimeSpan refreshInterval => TimeSpan.FromSeconds(60); - private LazyCacheEntryOptions _options => new LazyCacheEntryOptions().SetAbsoluteExpiration(refreshInterval, ExpirationMode.LazyExpiration); + private TimeSpan RefreshInterval => TimeSpan.FromSeconds(60); + private LazyCacheEntryOptions Options => new LazyCacheEntryOptions().SetAbsoluteExpiration(RefreshInterval, ExpirationMode.LazyExpiration); [Inject] - private IAppCache _cache { get; set; } = null!; + private IAppCache Cache { get; set; } = null!; private List _permissions = new(); private IList _assignedClaims = default!; private MudDataGrid _table = null!; @@ -213,9 +211,9 @@ private bool _uploading; protected override async Task OnInitializedAsync() { - _roleManager = ScopedServices.GetRequiredService>(); + RoleManager = ScopedServices.GetRequiredService>(); Title = L[_currentDto.GetClassDescription()]; - var state = await _authState; + var state = await AuthState; _canCreate = (await AuthService.AuthorizeAsync(state.User, Permissions.Roles.Create)).Succeeded; _canSearch = (await AuthService.AuthorizeAsync(state.User, Permissions.Roles.Search)).Succeeded; _canEdit = (await AuthService.AuthorizeAsync(state.User, Permissions.Roles.Edit)).Succeeded; @@ -229,12 +227,12 @@ try { _loading = true; - var items =await _roleManager.Roles.Where(x => x.Name.Contains(_searchString) || x.Description.Contains(_searchString)) - .EFOrderBySortDefinitions(state) + var items =await RoleManager.Roles.Where(x => x.Name.Contains(_searchString) || x.Description.Contains(_searchString)) + .EfOrderBySortDefinitions(state) .Skip(state.Page * state.PageSize).Take(state.PageSize) .Select(x => new ApplicationRoleDto() { Id = x.Id, Name = x.Name!, Description = x.Description, NormalizedName = x.NormalizedName }) .ToListAsync(); - var total = await _roleManager.Roles.CountAsync(x => x.Name.Contains(_searchString) || x.Description.Contains(_searchString)); + var total = await RoleManager.Roles.CountAsync(x => x.Name.Contains(_searchString) || x.Description.Contains(_searchString)); return new GridData() { TotalItems = total, Items = items }; } finally @@ -268,10 +266,10 @@ Description = model.Description }; - var state = await _roleManager.CreateAsync(applicationRole); + var state = await RoleManager.CreateAsync(applicationRole); if (state.Succeeded) { - Snackbar.Add($"{ConstantString.CREATESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.CreateSuccess}", MudBlazor.Severity.Info); await OnRefresh(); } else @@ -288,15 +286,15 @@ var result = await dialog.Result; if (!result.Canceled) { - var role = await _roleManager.FindByIdAsync(item.Id); + var role = await RoleManager.FindByIdAsync(item.Id); if (role is not null) { role.Description = item.Description; role.Name = item.Name; - var state = await _roleManager.UpdateAsync(role); + var state = await RoleManager.UpdateAsync(role); if (state.Succeeded) { - Snackbar.Add($"{ConstantString.UPDATESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.UpdateSuccess}", MudBlazor.Severity.Info); await OnRefresh(); } else @@ -322,12 +320,12 @@ { Func>> getcalims = async (roleId) => { - var role = await _roleManager.FindByIdAsync(dto.Id) ?? throw new NotFoundException($"not found application role: {roleId}"); - var claims = await _roleManager.GetClaimsAsync(role); + var role = await RoleManager.FindByIdAsync(dto.Id) ?? throw new NotFoundException($"not found application role: {roleId}"); + var claims = await RoleManager.GetClaimsAsync(role); return claims; }; var key = $"get-claims-by-{dto.Id}"; - _assignedClaims = await _cache.GetOrAddAsync(key, async () => await getcalims(dto.Id), _options); + _assignedClaims = await Cache.GetOrAddAsync(key, async () => await getcalims(dto.Id), Options); var allPermissions = new List(); var modules = typeof(Permissions).GetNestedTypes(); foreach (var module in modules) @@ -374,13 +372,13 @@ { try { - processing = true; + _processing = true; var roleId = model.RoleId!; - var role = await _roleManager.FindByIdAsync(roleId) ?? throw new NotFoundException($"Application role {roleId} Not Found."); ; + var role = await RoleManager.FindByIdAsync(roleId) ?? throw new NotFoundException($"Application role {roleId} Not Found."); ; model.Assigned = !model.Assigned; if (model.Assigned && model.ClaimType is not null && model.ClaimValue is not null) { - await _roleManager.AddClaimAsync(role, new Claim(model.ClaimType, model.ClaimValue)); + await RoleManager.AddClaimAsync(role, new Claim(model.ClaimType, model.ClaimValue)); Snackbar.Add($"{L["Authorization successful"]}", MudBlazor.Severity.Info); } else @@ -388,16 +386,16 @@ var removed = _assignedClaims.FirstOrDefault(x => x.Value == model.ClaimValue); if (removed is not null) { - await _roleManager.RemoveClaimAsync(role, removed); + await RoleManager.RemoveClaimAsync(role, removed); } Snackbar.Add($"{L["Authorization canceled successfully"]}", MudBlazor.Severity.Info); } var key = $"get-claims-by-{role.Id}"; - _cache.Remove(key); + Cache.Remove(key); } finally { - processing = false; + _processing = false; } } @@ -405,16 +403,16 @@ { try { - processing = true; + _processing = true; var roleId = models.First().RoleId; - var role = await _roleManager.FindByIdAsync(roleId!) ?? throw new NotFoundException($"not found application role: {roleId}"); + var role = await RoleManager.FindByIdAsync(roleId!) ?? throw new NotFoundException($"not found application role: {roleId}"); foreach (var model in models) { if (model.Assigned) { if (model.ClaimType is not null && model.ClaimValue is not null) { - await _roleManager.AddClaimAsync(role, new Claim(model.ClaimType, model.ClaimValue)); + await RoleManager.AddClaimAsync(role, new Claim(model.ClaimType, model.ClaimValue)); } } else @@ -422,36 +420,36 @@ var removed = _assignedClaims.FirstOrDefault(x => x.Value == model.ClaimValue); if (removed is not null) { - await _roleManager.RemoveClaimAsync(role, removed); + await RoleManager.RemoveClaimAsync(role, removed); } } } Snackbar.Add($"{L["Authorization has been changed"]}", MudBlazor.Severity.Info); await Task.Delay(300); var key = $"get-claims-by-{role.Id}"; - _cache.Remove(key); + Cache.Remove(key); } finally { - processing = false; + _processing = false; } } private async Task OnDelete(ApplicationRoleDto dto) { - string deleteContent = ConstantString.DELETECONFIRMATION; + string deleteContent = ConstantString.DeleteConfirmation; var parameters = new DialogParameters { { nameof(ConfirmationDialog.ContentText), string.Format(deleteContent, dto.Name) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall, FullWidth = true, DisableBackdropClick = true }; - var dialog = DialogService.Show(ConstantString.DELETECONFIRMATIONTITLE, parameters, options); + var dialog = DialogService.Show(ConstantString.DeleteConfirmationTitle, parameters, options); var result = await dialog.Result; if (!result.Canceled) { - var deleteRoles = await _roleManager.Roles.Where(x => x.Id==dto.Id).ToListAsync(); + var deleteRoles = await RoleManager.Roles.Where(x => x.Id==dto.Id).ToListAsync(); foreach (var role in deleteRoles) { - var deleteresult = await _roleManager.DeleteAsync(role); + var deleteresult = await RoleManager.DeleteAsync(role); if (!deleteresult.Succeeded) { Snackbar.Add($"{string.Join(",", (deleteresult.Errors.Select(x => x.Description).ToArray()))}", MudBlazor.Severity.Error); @@ -459,27 +457,27 @@ } } - Snackbar.Add($"{ConstantString.DELETESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.DeleteSuccess}", MudBlazor.Severity.Info); await OnRefresh(); } } private async Task OnDeleteChecked() { - string deleteContent = ConstantString.DELETECONFIRMATION; + string deleteContent = ConstantString.DeleteConfirmation; var parameters = new DialogParameters { { nameof(ConfirmationDialog.ContentText), string.Format(deleteContent, _selectedItems.Count) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall, FullWidth = true, DisableBackdropClick = true }; - var dialog = DialogService.Show(ConstantString.DELETECONFIRMATIONTITLE, parameters, options); + var dialog = DialogService.Show(ConstantString.DeleteConfirmationTitle, parameters, options); var result = await dialog.Result; if (!result.Canceled) { var deleteId = _selectedItems.Select(x => x.Id).ToArray(); - var deleteRoles = await _roleManager.Roles.Where(x => deleteId.Contains(x.Id)).ToListAsync(); + var deleteRoles = await RoleManager.Roles.Where(x => deleteId.Contains(x.Id)).ToListAsync(); foreach (var role in deleteRoles) { - var deleteresult = await _roleManager.DeleteAsync(role); + var deleteresult = await RoleManager.DeleteAsync(role); if (!deleteresult.Succeeded) { Snackbar.Add($"{string.Join(",", (deleteresult.Errors.Select(x => x.Description).ToArray()))}", MudBlazor.Severity.Error); @@ -487,7 +485,7 @@ } } - Snackbar.Add($"{ConstantString.DELETESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.DeleteSuccess}", MudBlazor.Severity.Info); await OnRefresh(); } } diff --git a/src/Blazor.Server.UI/Pages/Identity/Roles/_PermissionsDrawer.razor b/src/Blazor.Server.UI/Pages/Identity/Roles/_PermissionsDrawer.razor index a0f267530..f35711f67 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Roles/_PermissionsDrawer.razor +++ b/src/Blazor.Server.UI/Pages/Identity/Roles/_PermissionsDrawer.razor @@ -10,7 +10,7 @@ Set Permissions - @if(Permissions.Any()){ - @foreach (var group in Permissions.Where(x => x.Group.Contains(keyword, StringComparison.InvariantCultureIgnoreCase) || x.Description.Contains(keyword, StringComparison.InvariantCultureIgnoreCase)).Select(x => x.Group).Distinct().ToList()) + @foreach (var group in Permissions.Where(x => x.Group.Contains(Keyword, StringComparison.InvariantCultureIgnoreCase) || x.Description.Contains(Keyword, StringComparison.InvariantCultureIgnoreCase)).Select(x => x.Group).Distinct().ToList()) { @@ -72,7 +72,7 @@ [EditorRequired][Parameter] public EventCallback> OnAssignAllChanged { get; set; } [EditorRequired][Parameter] public EventCallback OnOpenChanged { get; set; } [Parameter] public bool Waiting { get; set; } - private string keyword { get; set; } = string.Empty; + private string Keyword { get; set; } = string.Empty; private async Task OnAssignAll(string? groupName) { var list = new List(); diff --git a/src/Blazor.Server.UI/Pages/Identity/Roles/_RoleFormDialog.razor b/src/Blazor.Server.UI/Pages/Identity/Roles/_RoleFormDialog.razor index 5da8a3fbc..d68bcd2cb 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Roles/_RoleFormDialog.razor +++ b/src/Blazor.Server.UI/Pages/Identity/Roles/_RoleFormDialog.razor @@ -1,38 +1,38 @@ -@using CleanArchitecture.Blazor.Application.Features.Identity.Dto; +@using CleanArchitecture.Blazor.Application.Features.Identity.Dto @inherits MudComponentBase @inject IStringLocalizer L - + - + Validation="@(_modelValidator.ValidateValue)"> - + - @ConstantString.CANCEL - @ConstantString.OK + @ConstantString.Cancel + @ConstantString.Ok @code { MudForm? _form = default!; - RoleDtoValidator modelValidator = new RoleDtoValidator(); + readonly RoleDtoValidator _modelValidator = new RoleDtoValidator(); [EditorRequired] [Parameter] - public ApplicationRoleDto model { get; set; } = default!; + public ApplicationRoleDto Model { get; set; } = default!; [CascadingParameter] MudDialogInstance MudDialog { get; set; } = default!; diff --git a/src/Blazor.Server.UI/Pages/Identity/Users/ChangePasswordModel.cs b/src/Blazor.Server.UI/Pages/Identity/Users/ChangePasswordModel.cs index 7a1b1a280..26e923360 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Users/ChangePasswordModel.cs +++ b/src/Blazor.Server.UI/Pages/Identity/Users/ChangePasswordModel.cs @@ -1,6 +1,4 @@ -using FluentValidation; - -namespace Blazor.Server.UI.Pages.Identity.Users; +namespace Blazor.Server.UI.Pages.Identity.Users; public class ChangePasswordModel { diff --git a/src/Blazor.Server.UI/Pages/Identity/Users/OrgItem.cs b/src/Blazor.Server.UI/Pages/Identity/Users/OrgItem.cs index 847374bf3..f597263d2 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Users/OrgItem.cs +++ b/src/Blazor.Server.UI/Pages/Identity/Users/OrgItem.cs @@ -1,22 +1,19 @@ -using System.ComponentModel.DataAnnotations.Schema; -using FluentValidation; - namespace Blazor.Server.UI.Pages.Identity.Users; public class OrgItem { - public string? id { get; set; } - public string? area { get; set; } - public string? imageUrl { get; set; } - public bool isLoggedUser { get; set; } - public string? name { get; set; } - public string? office { get; set; } - public string? parentId { get; set; } - public string? positionName { get; set; } - public string? profileUrl { get; set; } - public string? size { get; set; } - public string? tags { get; set; } - public int _directSubordinates { get; set; } - public int _totalSubordinates { get; set; } + public string? Id { get; set; } + public string? Area { get; set; } + public string? ImageUrl { get; set; } + public bool IsLoggedUser { get; set; } + public string? Name { get; set; } + public string? Office { get; set; } + public string? ParentId { get; set; } + public string? PositionName { get; set; } + public string? ProfileUrl { get; set; } + public string? Size { get; set; } + public string? Tags { get; set; } + public int DirectSubordinates { get; set; } + public int TotalSubordinates { get; set; } } \ No newline at end of file diff --git a/src/Blazor.Server.UI/Pages/Identity/Users/Profile.razor b/src/Blazor.Server.UI/Pages/Identity/Users/Profile.razor index b80f99653..b3bc11116 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Users/Profile.razor +++ b/src/Blazor.Server.UI/Pages/Identity/Users/Profile.razor @@ -1,8 +1,4 @@ @page "/user/profile" -@using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity -@using SixLabors.ImageSharp -@using SixLabors.ImageSharp.Formats -@using SixLabors.ImageSharp.Processing @inherits OwningComponentBase @inject IStringLocalizer L @@ -10,26 +6,26 @@ @Title - @if(model is null) + @if(Model is null) { }else{ - +
- @if (string.IsNullOrEmpty(model.ProfilePictureDataUrl)) + @if (string.IsNullOrEmpty(Model.ProfilePictureDataUrl)) { - @model.UserName.ToUpper().First() + @Model.UserName.ToUpper().First()
- @if (model.AssignedRoles is not null) + @if (Model.AssignedRoles is not null) { - @foreach (var role in model.AssignedRoles) + @foreach (var role in Model.AssignedRoles) { @role } @@ -41,11 +37,11 @@ else { - +
- @if (model.AssignedRoles is not null) + @if (Model.AssignedRoles is not null) { - @foreach (var role in model.AssignedRoles) + @foreach (var role in Model.AssignedRoles) { @role } @@ -63,33 +59,33 @@
- + - + - + - + - + - + - - @if (submitting) + + @if (_submitting) { - @ConstantString.WATING + @ConstantString.Waiting } else { - @ConstantString.SAVE + @ConstantString.Save } @@ -97,13 +93,13 @@ - + - @if (submitting) + @if (_submitting) { - @ConstantString.WATING + @ConstantString.Waiting } else { diff --git a/src/Blazor.Server.UI/Pages/Identity/Users/Profile.razor.cs b/src/Blazor.Server.UI/Pages/Identity/Users/Profile.razor.cs index 3d2061572..df816ae0d 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Users/Profile.razor.cs +++ b/src/Blazor.Server.UI/Pages/Identity/Users/Profile.razor.cs @@ -1,10 +1,10 @@ -using Microsoft.AspNetCore.Components.Forms; -using Microsoft.AspNetCore.Components.Authorization; -using Microsoft.AspNetCore.Identity; -using Microsoft.JSInterop; +using Blazor.Server.UI.Services.JsInterop; using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity; using CleanArchitecture.Blazor.Application.Features.Identity.Notification; -using Blazor.Server.UI.Services.JsInterop; +using CleanArchitecture.Blazor.Domain.Enums; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.AspNetCore.Identity; namespace Blazor.Server.UI.Pages.Identity.Users { @@ -12,24 +12,24 @@ public partial class Profile { [Inject] - private IMediator _mediator { get; set; } = default!; + private IMediator Mediator { get; set; } = default!; private MudForm? _form = null !; - private MudForm? _passwordform = null !; + private MudForm? _Passwordform = null !; public string Title { get; set; } = "Profile"; - private bool submitting; + private bool _submitting; [CascadingParameter] - private Task _authState { get; set; } = default !; + private Task AuthState { get; set; } = default !; [Inject] - private IUploadService _uploadService { get; set; } = default !; - private UserProfile? model { get; set; } = null!; - private UserProfileEditValidator _userValidator = new(); - private UserManager _userManager { get; set; } = default !; + private IUploadService UploadService { get; set; } = default !; + private UserProfile? Model { get; set; } = null!; + private readonly UserProfileEditValidator _userValidator = new(); + private UserManager UserManager { get; set; } = default !; [Inject] - private IIdentityService _identityService { get; set; } = default !; + private IIdentityService IdentityService { get; set; } = default !; public string Id => Guid.NewGuid().ToString(); - private ChangePasswordModel _changepassword { get; set; } = new(); - private ChangePasswordModelValidator _passwordValidator = new(); - private List _orgData = new(); + private ChangePasswordModel Changepassword { get; set; } = new(); + private readonly ChangePasswordModelValidator _passwordValidator = new(); + private readonly List _orgData = new(); private async void ActivePanelIndexChanged(int index) @@ -43,101 +43,101 @@ private async void ActivePanelIndexChanged(int index) private async Task LoadOrgData() { - var currerntuserName = (await _authState).User.GetUserName(); - var list = await _userManager.Users.Include(x => x.UserRoles).ThenInclude(x => x.Role).Include(x => x.Superior).ToListAsync(); + var currentUsername = (await AuthState).User.GetUserName(); + var list = await UserManager.Users.Include(x => x.UserRoles).ThenInclude(x => x.Role).Include(x => x.Superior).ToListAsync(); foreach (var item in list) { - var roles = await _userManager.GetRolesAsync(item); - var count = await _userManager.Users.Where(x => x.SuperiorId == item.Id).CountAsync(); - var orgitem = new OrgItem(); - orgitem.id = item.Id; - orgitem.name = item.DisplayName ?? item.UserName; - orgitem.area = item.TenantName; - orgitem.profileUrl = item.ProfilePictureDataUrl; - orgitem.imageUrl = item.ProfilePictureDataUrl; - if (currerntuserName == item.UserName) - orgitem.isLoggedUser = true; - orgitem.size = ""; - orgitem.tags = item.PhoneNumber ?? item.Email; + var roles = await UserManager.GetRolesAsync(item); + var count = await UserManager.Users.Where(x => x.SuperiorId == item.Id).CountAsync(); + var orgItem = new OrgItem(); + orgItem.Id = item.Id; + orgItem.Name = item.DisplayName ?? item.UserName; + orgItem.Area = item.TenantName; + orgItem.ProfileUrl = item.ProfilePictureDataUrl; + orgItem.ImageUrl = item.ProfilePictureDataUrl; + if (currentUsername == item.UserName) + orgItem.IsLoggedUser = true; + orgItem.Size = ""; + orgItem.Tags = item.PhoneNumber ?? item.Email; if (roles != null && roles.Count > 0) - orgitem.positionName = string.Join(',', roles); - orgitem.parentId = item.SuperiorId; - orgitem._directSubordinates = count; - this._orgData.Add(orgitem); + orgItem.PositionName = string.Join(',', roles); + orgItem.ParentId = item.SuperiorId; + orgItem.DirectSubordinates = count; + this._orgData.Add(orgItem); } } protected override async Task OnInitializedAsync() { - _userManager = ScopedServices.GetRequiredService>(); - var userId = (await _authState).User.GetUserId(); + UserManager = ScopedServices.GetRequiredService>(); + var userId = (await AuthState).User.GetUserId(); if (!string.IsNullOrEmpty(userId)) { - var userDto = await _identityService.GetApplicationUserDto(userId); - this.model = userDto.ToUserProfile(); + var userDto = await IdentityService.GetApplicationUserDto(userId); + this.Model = userDto.ToUserProfile(); } } private async Task UploadPhoto(InputFileChangeEventArgs e) { - var filestream = e.File.OpenReadStream(GlobalVariable.maxAllowedSize); - var imgstream = new MemoryStream(); - await filestream.CopyToAsync(imgstream); - imgstream.Position = 0; + var filestream = e.File.OpenReadStream(GlobalVariable.MaxAllowedSize); + var imgStream = new MemoryStream(); + await filestream.CopyToAsync(imgStream); + imgStream.Position = 0; using (var outStream = new MemoryStream()) { - using (var image = Image.Load(imgstream)) + using (var image = Image.Load(imgStream)) { image.Mutate(i => i.Resize(new ResizeOptions() { Mode = SixLabors.ImageSharp.Processing.ResizeMode.Crop, Size = new SixLabors.ImageSharp.Size(128, 128) })); image.Save(outStream, SixLabors.ImageSharp.Formats.Png.PngFormat.Instance); var filename = e.File.Name; var fi = new FileInfo(filename); var ext = fi.Extension; - var result = await _uploadService.UploadAsync(new UploadRequest(Guid.NewGuid().ToString() + ext, UploadType.ProfilePicture, outStream.ToArray())); - model.ProfilePictureDataUrl = result; - var user = await _userManager.FindByIdAsync(model.UserId!); - user!.ProfilePictureDataUrl = model.ProfilePictureDataUrl; - await _userManager.UpdateAsync(user); + var result = await UploadService.UploadAsync(new UploadRequest(Guid.NewGuid().ToString() + ext, UploadType.ProfilePicture, outStream.ToArray())); + Model.ProfilePictureDataUrl = result; + var user = await UserManager.FindByIdAsync(Model.UserId!); + user!.ProfilePictureDataUrl = Model.ProfilePictureDataUrl; + await UserManager.UpdateAsync(user); Snackbar.Add(L["The avatar has been updated."], MudBlazor.Severity.Info); - await _mediator.Publish(new UpdateUserProfileCommand() { UserProfile = model }); + await Mediator.Publish(new UpdateUserProfileCommand() { UserProfile = Model }); } } } private async Task Submit() { - submitting = true; + _submitting = true; try { await _form!.Validate(); if (_form.IsValid) { - var state = await _authState; - var user = await _userManager.FindByIdAsync(model.UserId!); - user!.PhoneNumber = model.PhoneNumber; - user.DisplayName = model.DisplayName; - user.ProfilePictureDataUrl = model.ProfilePictureDataUrl; - await _userManager.UpdateAsync(user); - Snackbar.Add($"{ConstantString.UPDATESUCCESS}", MudBlazor.Severity.Info); - await _mediator.Publish(new UpdateUserProfileCommand() { UserProfile = model }); + var state = await AuthState; + var user = await UserManager.FindByIdAsync(Model.UserId!); + user!.PhoneNumber = Model.PhoneNumber; + user.DisplayName = Model.DisplayName; + user.ProfilePictureDataUrl = Model.ProfilePictureDataUrl; + await UserManager.UpdateAsync(user); + Snackbar.Add($"{ConstantString.UpdateSuccess}", MudBlazor.Severity.Info); + await Mediator.Publish(new UpdateUserProfileCommand() { UserProfile = Model }); } } finally { - submitting = false; + _submitting = false; } } private async Task ChangePassword() { - submitting = true; + _submitting = true; try { - await _passwordform!.Validate(); - if (_passwordform!.IsValid) + await _Passwordform!.Validate(); + if (_Passwordform!.IsValid) { - var user = await _userManager.FindByIdAsync(model.UserId!); - var result = await _userManager.ChangePasswordAsync(user!, _changepassword.CurrentPassword, _changepassword.NewPassword); + var user = await UserManager.FindByIdAsync(Model.UserId!); + var result = await UserManager.ChangePasswordAsync(user!, Changepassword.CurrentPassword, Changepassword.NewPassword); if (result.Succeeded) { Snackbar.Add($"{L["Changed password successfully."]}", MudBlazor.Severity.Info); @@ -150,7 +150,7 @@ private async Task ChangePassword() } finally { - submitting = false; + _submitting = false; } } diff --git a/src/Blazor.Server.UI/Pages/Identity/Users/ResetPasswordFormModel.cs b/src/Blazor.Server.UI/Pages/Identity/Users/ResetPasswordFormModel.cs index 0d4d5fbeb..bff07d009 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Users/ResetPasswordFormModel.cs +++ b/src/Blazor.Server.UI/Pages/Identity/Users/ResetPasswordFormModel.cs @@ -1,5 +1,3 @@ -using FluentValidation; - namespace Blazor.Server.UI.Pages.Identity.Users; public class ResetPasswordFormModel diff --git a/src/Blazor.Server.UI/Pages/Identity/Users/UserDtoValidator.cs b/src/Blazor.Server.UI/Pages/Identity/Users/UserDtoValidator.cs index 6cfc64524..f059d5909 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Users/UserDtoValidator.cs +++ b/src/Blazor.Server.UI/Pages/Identity/Users/UserDtoValidator.cs @@ -1,6 +1,3 @@ -using System.ComponentModel.DataAnnotations.Schema; -using CleanArchitecture.Blazor.Application.Common.Security; -using FluentValidation; using CleanArchitecture.Blazor.Application.Features.Identity.Dto; namespace Blazor.Server.UI.Pages.Identity.Users; diff --git a/src/Blazor.Server.UI/Pages/Identity/Users/Users.razor b/src/Blazor.Server.UI/Pages/Identity/Users/Users.razor index e5dc6c9f8..a1d0b51a7 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Users/Users.razor +++ b/src/Blazor.Server.UI/Pages/Identity/Users/Users.razor @@ -1,24 +1,20 @@ @inherits OwningComponentBase -@implements IDisposable -@page "/identity/users" -@using Blazor.Server.UI.Components.Dialogs -@using BlazorDownloadFile; -@using CleanArchitecture.Blazor.Application.Common.Exceptions -@using Blazor.Server.UI.Pages.Identity.Roles; +@using LazyCache @using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity @using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant -@using CleanArchitecture.Blazor.Application.Common.Security -@using CleanArchitecture.Blazor.Infrastructure.Constants -@using CleanArchitecture.Blazor.Infrastructure.Services -@using Duende.IdentityServer.Events -@using LazyCache; -@using Microsoft.AspNetCore.Components.Server.Circuits -@using Microsoft.AspNetCore.Identity; -@using CleanArchitecture.Blazor.Application.Features.Identity.Dto; -@using System.ComponentModel; -@using System.Reflection; -@using System.Security.Claims; -@using System.Linq.Expressions; +@using CleanArchitecture.Blazor.Application.Features.Identity.Dto +@using Blazor.Server.UI.Pages.Identity.Roles +@using BlazorDownloadFile +@using System.Security.Claims +@using System.ComponentModel +@using System.Linq.Expressions +@using System.Reflection +@using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers +@using CleanArchitecture.Blazor.Application.Constants.ClaimTypes +@using CleanArchitecture.Blazor.Application.Constants.Permission +@using CleanArchitecture.Blazor.Application.Constants.Role +@implements IDisposable +@page "/identity/users" @inject IStringLocalizer L @attribute [Authorize(Policy = Permissions.Users.View)] @Title @@ -56,7 +52,7 @@ Disabled="@_loading" OnClick="@(()=>OnRefresh())" StartIcon="@Icons.Material.Filled.Refresh" IconColor="Color.Surface" Color="Color.Primary" - Style="margin-right: 4px; margin-bottom:4px">@ConstantString.REFRESH + Style="margin-right: 4px; margin-bottom:4px">@ConstantString.Refresh @if (_canCreate) { @ConstantString.NEW + IconColor="Color.Surface">@ConstantString.New } @if (_canDelete) { @@ -74,7 +70,7 @@ Size="Size.Small" Style="margin-right: 4px; margin-bottom:4px" OnClick="OnDeleteChecked" - IconColor="Color.Surface">@ConstantString.DELETE + IconColor="Color.Surface">@ConstantString.Delete } @if (_canExport) { @@ -83,7 +79,7 @@ Size="Size.Small" @bind-Loading="_exporting" LoadingAdornment="Adornment.Start" OnClick="OnExport" Style="margin-right: 4px; margin-bottom:4px" - IconColor="Color.Surface">@ConstantString.EXPORT + IconColor="Color.Surface">@ConstantString.Export } @if (_canImport) { @@ -99,11 +95,11 @@ @if (_uploading) { - @ConstantString.UPLOADING + @ConstantString.Uploading } else { - @ConstantString.IMPORT + @ConstantString.Import } @@ -118,7 +114,7 @@ Size="Size.Small" Style="margin-right: 4px; margin-bottom:4px" OnClick="OnCreate" - IconColor="Color.Surface">@ConstantString.NEW + IconColor="Color.Surface">@ConstantString.New } @if (_canDelete) { @@ -128,20 +124,20 @@ Size="Size.Small" Style="margin-right: 4px; margin-bottom:4px" OnClick="OnDeleteChecked" - IconColor="Color.Surface">@ConstantString.DELETE + IconColor="Color.Surface">@ConstantString.Delete }
@if (_canSearch) { - + @foreach (var str in _roles) { @str } - @@ -153,7 +149,7 @@ - + @if (_canEdit || _canDelete || _canManageRoles || _canRestPassword || _canActive || _canManagePermissions) { @@ -162,11 +158,11 @@ EndIcon="@Icons.Material.Filled.KeyboardArrowDown" IconColor="Color.Info" AnchorOrigin="Origin.CenterLeft"> @if (_canEdit) { - @ConstantString.EDIT + @ConstantString.Edit } @if (_canDelete) { - @ConstantString.DELETE + @ConstantString.Delete } @if (_canManagePermissions) { @@ -195,7 +191,7 @@ - @ConstantString.NOALLOWED + @ConstantString.NoAllowed } @@ -274,32 +270,32 @@ @code { [Inject] - private IUsersStateContainer _usersStateContainer { get; set; } = default!; + private IUsersStateContainer UsersStateContainer { get; set; } = default!; private int _defaultPageSize = 15; private HashSet _selectedItems = new(); - private ApplicationUserDto _currentDto = new(); + private readonly ApplicationUserDto _currentDto = new(); private string _searchString = string.Empty; private string Title { get; set; } = "Users"; private List _permissions = new(); private IList _assignedClaims = default!; [CascadingParameter] - private Task _authState { get; set; } = default!; - private UserManager _userManager { get; set; } = default!; - private RoleManager _roleManager { get; set; } = default!; - private TimeSpan refreshInterval => TimeSpan.FromSeconds(60); - private LazyCacheEntryOptions _options => new LazyCacheEntryOptions().SetAbsoluteExpiration(refreshInterval, ExpirationMode.LazyExpiration); + private Task AuthState { get; set; } = default!; + private UserManager UserManager { get; set; } = default!; + private RoleManager RoleManager { get; set; } = default!; + private TimeSpan RefreshInterval => TimeSpan.FromSeconds(60); + private LazyCacheEntryOptions Options => new LazyCacheEntryOptions().SetAbsoluteExpiration(RefreshInterval, ExpirationMode.LazyExpiration); [Inject] - private IAppCache _cache { get; set; } = null!; + private IAppCache Cache { get; set; } = null!; [Inject] - private ITenantProvider _tenantProvider { get; set; } = default!; + private ITenantProvider TenantProvider { get; set; } = default!; [Inject] - private ITenantService _tenantsService { get; set; } = null!; + private ITenantService TenantsService { get; set; } = null!; [Inject] - private IBlazorDownloadFileService _blazorDownloadFileService { get; set; } = null!; + private IBlazorDownloadFileService BlazorDownloadFileService { get; set; } = null!; [Inject] - private IExcelService _excelService { get; set; } = null!; + private IExcelService ExcelService { get; set; } = null!; [Inject] - private IMapper _mapper { get; set; } = null!; + private IMapper Mapper { get; set; } = null!; private MudDataGrid _table = null!; private bool _processing; private bool _showPermissionsDrawer; @@ -317,15 +313,15 @@ private bool _exporting; private bool _uploading; private List _roles = new(); - private string? _searchrole; + private string? _searchRole; protected override async Task OnInitializedAsync() { - _userManager = ScopedServices.GetRequiredService>(); - _roleManager = ScopedServices.GetRequiredService>(); + UserManager = ScopedServices.GetRequiredService>(); + RoleManager = ScopedServices.GetRequiredService>(); Title = L[_currentDto.GetClassDescription()]; - var state = await _authState; + var state = await AuthState; _canCreate = (await AuthService.AuthorizeAsync(state.User, Permissions.Users.Create)).Succeeded; _canSearch = (await AuthService.AuthorizeAsync(state.User, Permissions.Users.Search)).Succeeded; _canEdit = (await AuthService.AuthorizeAsync(state.User, Permissions.Users.Edit)).Succeeded; @@ -336,11 +332,11 @@ _canManagePermissions = (await AuthService.AuthorizeAsync(state.User, Permissions.Users.ManagePermissions)).Succeeded; _canImport = (await AuthService.AuthorizeAsync(state.User, Permissions.Users.Import)).Succeeded; _canExport = (await AuthService.AuthorizeAsync(state.User, Permissions.Users.Export)).Succeeded; - _roles = await _roleManager.Roles.Select(x => x.Name).ToListAsync(); + _roles = await RoleManager.Roles.Select(x => x.Name).ToListAsync(); } private bool isOnline(string username) { - return _usersStateContainer.UsersByConnectionId.Any(x => x.Value.Equals(username, StringComparison.OrdinalIgnoreCase)); + return UsersStateContainer.UsersByConnectionId.Any(x => x.Value.Equals(username, StringComparison.OrdinalIgnoreCase)); } private async Task> ServerReload(GridState state) @@ -355,12 +351,12 @@ x.PhoneNumber.Contains(_searchString) || x.TenantName.Contains(_searchString) || x.Provider.Contains(_searchString)) && - (_searchrole == null || (_searchrole != null && x.UserRoles.Any(x => x.Role.Name == _searchrole))); - var items = await _userManager.Users.Where(searchPredicate) + (_searchRole == null || (_searchRole != null && x.UserRoles.Any(x => x.Role.Name == _searchRole))); + var items = await UserManager.Users.Where(searchPredicate) .Include(x => x.UserRoles).ThenInclude(x => x.Role) - .EFOrderBySortDefinitions(state) - .Skip(state.Page * state.PageSize).Take(state.PageSize).ProjectTo(_mapper.ConfigurationProvider).ToListAsync(); - var total = await _userManager.Users.CountAsync(searchPredicate); + .EfOrderBySortDefinitions(state) + .Skip(state.Page * state.PageSize).Take(state.PageSize).ProjectTo(Mapper.ConfigurationProvider).ToListAsync(); + var total = await UserManager.Users.CountAsync(searchPredicate); return new GridData() { TotalItems = total, Items = items }; } finally @@ -377,7 +373,7 @@ private async Task OnSearchRole(string role) { if (_loading) return; - _searchrole = role; + _searchRole = role; await _table.ReloadServerData(); } private async Task OnRefresh() @@ -388,7 +384,7 @@ { var model = new ApplicationUserDto() { Provider = "Local", Email = "", UserName = "", AssignedRoles = new string[] { RoleName.Basic } }; var parameters = new DialogParameters { - { nameof(_UserFormDialog.model),model } + { nameof(_UserFormDialog.Model),model } }; var options = new DialogOptions { CloseButton = true, CloseOnEscapeKey = true, MaxWidth = MaxWidth.Small, FullWidth = true }; var dialog = DialogService.Show<_UserFormDialog>(L["Create a new user"], parameters, options); @@ -409,19 +405,19 @@ IsActive = model.IsActive, }; var password = model.Password; - var state = await _userManager.CreateAsync(applicationUser, password!); + var state = await UserManager.CreateAsync(applicationUser, password!); if (state.Succeeded) { if (model.AssignedRoles is not null && model.AssignedRoles.Length > 0) { - await _userManager.AddToRolesAsync(applicationUser, model.AssignedRoles); + await UserManager.AddToRolesAsync(applicationUser, model.AssignedRoles); } else { - await _userManager.AddToRoleAsync(applicationUser, RoleName.Basic); + await UserManager.AddToRoleAsync(applicationUser, RoleName.Basic); } - Snackbar.Add($"{ConstantString.CREATESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.CreateSuccess}", MudBlazor.Severity.Info); await OnRefresh(); } else @@ -435,15 +431,15 @@ { var parameters = new DialogParameters { - { nameof(_UserFormDialog.model),item } + { nameof(_UserFormDialog.Model),item } }; var options = new DialogOptions { CloseButton = true, CloseOnEscapeKey = true, MaxWidth = MaxWidth.Small, FullWidth = true }; var dialog = DialogService.Show<_UserFormDialog>(L["Edit the user"], parameters, options); var result = await dialog.Result; if (!result.Canceled) { - var user = await _userManager.FindByIdAsync(item.Id!) ?? throw new NotFoundException($"The application user [{item.Id}] was not found."); - var state = await _authState; + var user = await UserManager.FindByIdAsync(item.Id!) ?? throw new NotFoundException($"The application user [{item.Id}] was not found."); + var state = await AuthState; user.Email = item.Email; user.PhoneNumber = item.PhoneNumber; user.ProfilePictureDataUrl = item.ProfilePictureDataUrl; @@ -454,22 +450,22 @@ user.TenantId = item.TenantId; user.TenantName = item.TenantName; user.SuperiorId = item.SuperiorId; - var identityResult = await _userManager.UpdateAsync(user); + var identityResult = await UserManager.UpdateAsync(user); if (identityResult.Succeeded) { - var roles = await _userManager.GetRolesAsync(user!); + var roles = await UserManager.GetRolesAsync(user!); if (roles.Count > 0) { - var removeRoleResult = await _userManager.RemoveFromRolesAsync(user, roles); + var removeRoleResult = await UserManager.RemoveFromRolesAsync(user, roles); if (removeRoleResult.Succeeded) { if (item.AssignedRoles is not null && item.AssignedRoles.Length > 0) { - await _userManager.AddToRolesAsync(user, item.AssignedRoles); + await UserManager.AddToRolesAsync(user, item.AssignedRoles); } } } - Snackbar.Add($"{ConstantString.UPDATESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.UpdateSuccess}", MudBlazor.Severity.Info); await OnRefresh(); } else @@ -480,34 +476,34 @@ } private async Task OnDelete(ApplicationUserDto dto) { - string deleteContent = ConstantString.DELETECONFIRMATION; + string deleteContent = ConstantString.DeleteConfirmation; var parameters = new DialogParameters { { nameof(ConfirmationDialog.ContentText), string.Format(deleteContent, dto.UserName) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall, FullWidth = true, DisableBackdropClick = true }; - var dialog = DialogService.Show(ConstantString.DELETECONFIRMATIONTITLE, parameters, options); + var dialog = DialogService.Show(ConstantString.DeleteConfirmationTitle, parameters, options); var result = await dialog.Result; if (!result.Canceled) { - var deleteUser = await _userManager.Users.Where(x => x.Id == dto.Id).ToListAsync(); + var deleteUser = await UserManager.Users.Where(x => x.Id == dto.Id).ToListAsync(); foreach (var user in deleteUser) { - var deleteresult = await _userManager.DeleteAsync(user); - if (!deleteresult.Succeeded) + var deleteResult = await UserManager.DeleteAsync(user); + if (!deleteResult.Succeeded) { - Snackbar.Add($"{string.Join(",", (deleteresult.Errors.Select(x => x.Description).ToArray()))}", MudBlazor.Severity.Error); + Snackbar.Add($"{string.Join(",", (deleteResult.Errors.Select(x => x.Description).ToArray()))}", MudBlazor.Severity.Error); return; } } - Snackbar.Add($"{ConstantString.DELETESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.DeleteSuccess}", MudBlazor.Severity.Info); await OnRefresh(); } } private async Task OnDeleteChecked() { - var state = await _authState; + var state = await AuthState; var currentUserId = state.User.GetUserId(); var isSelectedItemContainCurrentUser = _selectedItems.Any(x => x.Id == currentUserId); @@ -515,14 +511,14 @@ { if (_selectedItems.Count == 1) { - Snackbar.Add($"{ConstantString.DELETEFAIL}", MudBlazor.Severity.Error); + Snackbar.Add($"{ConstantString.DeleteFail}", MudBlazor.Severity.Error); return; } _selectedItems.Remove(_selectedItems.First(x => x.Id == currentUserId)); } - string deleteContent = ConstantString.DELETECONFIRMATION; + string deleteContent = ConstantString.DeleteConfirmation; var parameters = new DialogParameters { { nameof(ConfirmationDialog.ContentText), string.Format(deleteContent, _selectedItems.Count) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall, FullWidth = true, DisableBackdropClick = true }; var dialog = DialogService.Show(L["Delete"], parameters, options); @@ -531,18 +527,18 @@ if (!result.Canceled) { var deleteId = _selectedItems.Select(x => x.Id).ToArray(); - var deleteUsers = await _userManager.Users.Where(x => deleteId.Contains(x.Id)).ToListAsync(); + var deleteUsers = await UserManager.Users.Where(x => deleteId.Contains(x.Id)).ToListAsync(); foreach (var deleteUser in deleteUsers) { - var deleteresult = await _userManager.DeleteAsync(deleteUser); - if (!deleteresult.Succeeded) + var deleteResult = await UserManager.DeleteAsync(deleteUser); + if (!deleteResult.Succeeded) { - Snackbar.Add($"{string.Join(",", (deleteresult.Errors.Select(x => x.Description).ToArray()))}", MudBlazor.Severity.Error); + Snackbar.Add($"{string.Join(",", (deleteResult.Errors.Select(x => x.Description).ToArray()))}", MudBlazor.Severity.Error); return; } } - Snackbar.Add($"{ConstantString.DELETESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.DeleteSuccess}", MudBlazor.Severity.Info); await OnRefresh(); } @@ -550,13 +546,13 @@ private async Task OnSetActive(ApplicationUserDto item) { - var user = await _userManager.FindByIdAsync(item.Id!) ?? throw new NotFoundException($"Application user not found {item.Id}."); + var user = await UserManager.FindByIdAsync(item.Id!) ?? throw new NotFoundException($"Application user not found {item.Id}."); user.IsActive = !item.IsActive; - var state = await _userManager.UpdateAsync(user); + var state = await UserManager.UpdateAsync(user); item.IsActive = !item.IsActive; if (state.Succeeded) { - Snackbar.Add($"{ConstantString.UPDATESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.UpdateSuccess}", MudBlazor.Severity.Info); } else { @@ -576,9 +572,9 @@ if (!result.Canceled) { - var user = await _userManager.FindByIdAsync(item.Id!); - var token = await _userManager.GeneratePasswordResetTokenAsync(user!); - var state = await _userManager.ResetPasswordAsync(user!, token, model!.Password!); + var user = await UserManager.FindByIdAsync(item.Id!); + var token = await UserManager.GeneratePasswordResetTokenAsync(user!); + var state = await UserManager.ResetPasswordAsync(user!, token, model!.Password!); if (state.Succeeded) { Snackbar.Add($"{L["Reset password successfully"]}", MudBlazor.Severity.Info); @@ -604,14 +600,14 @@ } private async Task> GetAllPermissions(ApplicationUserDto dto) { - Func>> getcalims = async (userId) => + Func>> getClaims = async (userId) => { - var user = await _userManager.FindByIdAsync(dto.Id) ?? throw new NotFoundException($"not found application user: {userId}"); - var claims = await _userManager.GetClaimsAsync(user); + var user = await UserManager.FindByIdAsync(dto.Id) ?? throw new NotFoundException($"not found application user: {userId}"); + var claims = await UserManager.GetClaimsAsync(user); return claims; }; var key = $"get-claims-by-{dto.Id}"; - _assignedClaims = await _cache.GetOrAddAsync(key, async () => await getcalims(dto.Id), _options); + _assignedClaims = await Cache.GetOrAddAsync(key, async () => await getClaims(dto.Id), Options); var allPermissions = new List(); var modules = typeof(Permissions).GetNestedTypes(); foreach (var module in modules) @@ -655,14 +651,14 @@ { _processing = true; var userId = models.First().UserId; - var user = await _userManager.FindByIdAsync(userId!) ?? throw new NotFoundException($"not found application user: {userId}"); + var user = await UserManager.FindByIdAsync(userId!) ?? throw new NotFoundException($"not found application user: {userId}"); foreach (var model in models) { if (model.Assigned) { if (model.ClaimType is not null && model.ClaimValue is not null) { - await _userManager.AddClaimAsync(user, new Claim(model.ClaimType, model.ClaimValue)); + await UserManager.AddClaimAsync(user, new Claim(model.ClaimType, model.ClaimValue)); } } else @@ -670,7 +666,7 @@ var removed = _assignedClaims.FirstOrDefault(x => x.Value == model.ClaimValue); if (removed is not null) { - await _userManager.RemoveClaimAsync(user, removed); + await UserManager.RemoveClaimAsync(user, removed); } } } @@ -678,7 +674,7 @@ Snackbar.Add($"{L["Authorization has been changed"]}", MudBlazor.Severity.Info); await Task.Delay(300); var key = $"get-claims-by-{user.Id}"; - _cache.Remove(key); + Cache.Remove(key); } finally { @@ -692,11 +688,11 @@ { _processing = true; var userId = model.UserId!; - var user = await _userManager.FindByIdAsync(userId) ?? throw new NotFoundException($"Application user Not Found {userId}."); ; + var user = await UserManager.FindByIdAsync(userId) ?? throw new NotFoundException($"Application user Not Found {userId}."); ; model.Assigned = !model.Assigned; if (model.Assigned && model.ClaimType is not null && model.ClaimValue is not null) { - await _userManager.AddClaimAsync(user, new Claim(model.ClaimType, model.ClaimValue)); + await UserManager.AddClaimAsync(user, new Claim(model.ClaimType, model.ClaimValue)); Snackbar.Add($"{L["Authorization successful"]}", MudBlazor.Severity.Info); } else @@ -704,12 +700,12 @@ var removed = _assignedClaims.FirstOrDefault(x => x.Value == model.ClaimValue); if (removed is not null) { - await _userManager.RemoveClaimAsync(user, removed); + await UserManager.RemoveClaimAsync(user, removed); } Snackbar.Add($"{L["Authorization canceled successfully"]}", MudBlazor.Severity.Info); } var key = $"get-claims-by-{user.Id}"; - _cache.Remove(key); + Cache.Remove(key); } finally @@ -730,8 +726,8 @@ x.PhoneNumber.Contains(_searchString) || x.TenantName.Contains(_searchString) || x.Provider.Contains(_searchString)) && - (_searchrole == null || (_searchrole != null && x.UserRoles.Any(x => x.Role.Name == _searchrole))); - var items = await _userManager.Users.Where(searchPredicate) + (_searchRole == null || (_searchRole != null && x.UserRoles.Any(x => x.Role.Name == _searchRole))); + var items = await UserManager.Users.Where(searchPredicate) .Select(x => new ApplicationUserDto() { Id = x.Id, @@ -742,7 +738,7 @@ TenantId = x.TenantId, TenantName = x.TenantName, }).ToListAsync(); - var result = await _excelService.ExportAsync(items, + var result = await ExcelService.ExportAsync(items, new Dictionary>() { {L["Id"],item => item.Id}, @@ -754,8 +750,8 @@ {L["Tenant Name"],item => item.TenantName}, } , L["Users"]); - var downloadresult = await _blazorDownloadFileService.DownloadFile($"{L["Users"]}.xlsx", result, contentType: "application/octet-stream"); - Snackbar.Add($"{ConstantString.EXPORTSUCESS}", MudBlazor.Severity.Info); + var downloadResult = await BlazorDownloadFileService.DownloadFile($"{L["Users"]}.xlsx", result, contentType: "application/octet-stream"); + Snackbar.Add($"{ConstantString.ExportSuccess}", MudBlazor.Severity.Info); } finally { @@ -768,8 +764,8 @@ { _uploading = true; var stream = new MemoryStream(); - await file.OpenReadStream(GlobalVariable.maxAllowedSize).CopyToAsync(stream); - var result = await _excelService.ImportAsync(stream.ToArray(), mappers: new Dictionary> + await file.OpenReadStream(GlobalVariable.MaxAllowedSize).CopyToAsync(stream); + var result = await ExcelService.ImportAsync(stream.ToArray(), mappers: new Dictionary> { { L["User Name"], (row, item) => item.UserName = row[L["User Name"]]?.ToString() }, { L["Display Name"], (row, item) => item.DisplayName = row[L["Display Name"]]?.ToString() }, @@ -781,24 +777,24 @@ { foreach (var user in result.Data) { - if (!_userManager.Users.Any(x => x.UserName == user.UserName || x.Email == user.Email)) + if (!UserManager.Users.Any(x => x.UserName == user.UserName || x.Email == user.Email)) { - var tenantId = _tenantsService.DataSource.Any(x => x.Name == user.TenantName) ? _tenantsService.DataSource.First(x => x.Name == user.TenantName).Id : _tenantsService.DataSource.First().Id; + var tenantId = TenantsService.DataSource.Any(x => x.Name == user.TenantName) ? TenantsService.DataSource.First(x => x.Name == user.TenantName).Id : TenantsService.DataSource.First().Id; user.TenantId = tenantId; - var iresult = await _userManager.CreateAsync(user); - if (iresult.Succeeded) + var iResult = await UserManager.CreateAsync(user); + if (iResult.Succeeded) { - await _userManager.AddToRolesAsync(user, new string[] { RoleName.Basic }); + await UserManager.AddToRolesAsync(user, new string[] { RoleName.Basic }); } else { - Snackbar.Add($"{string.Join(',', iresult.Errors.Select(x => x.Description))}", MudBlazor.Severity.Error); + Snackbar.Add($"{string.Join(',', iResult.Errors.Select(x => x.Description))}", MudBlazor.Severity.Error); } } } await _table.ReloadServerData(); - Snackbar.Add($"{ConstantString.IMPORTSUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.ImportSuccess}", MudBlazor.Severity.Info); } else { diff --git a/src/Blazor.Server.UI/Pages/Identity/Users/_ResetPasswordDialog.razor b/src/Blazor.Server.UI/Pages/Identity/Users/_ResetPasswordDialog.razor index 12a426090..1dc358ae3 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Users/_ResetPasswordDialog.razor +++ b/src/Blazor.Server.UI/Pages/Identity/Users/_ResetPasswordDialog.razor @@ -2,16 +2,16 @@ @inject IStringLocalizer L - + - + - @ConstantString.CANCEL - @ConstantString.OK + @ConstantString.Cancel + @ConstantString.Ok @code { - MudForm? form = default!; - ResetPasswordFormModelValidator modelValidator = new ResetPasswordFormModelValidator(); - [EditorRequired][Parameter] public ResetPasswordFormModel model { get; set; } = default!; + MudForm? _form = default!; + readonly ResetPasswordFormModelValidator _modelValidator = new ResetPasswordFormModelValidator(); + [EditorRequired][Parameter] public ResetPasswordFormModel Model { get; set; } = default!; [CascadingParameter] MudDialogInstance MudDialog { get; set; } = default!; async Task Submit() { - await form!.Validate(); - if (form.IsValid) + await _form!.Validate(); + if (_form.IsValid) { MudDialog.Close(DialogResult.Ok(true)); } diff --git a/src/Blazor.Server.UI/Pages/Identity/Users/_UserForm.razor b/src/Blazor.Server.UI/Pages/Identity/Users/_UserForm.razor index 572b3fb61..e3e36ce14 100644 --- a/src/Blazor.Server.UI/Pages/Identity/Users/_UserForm.razor +++ b/src/Blazor.Server.UI/Pages/Identity/Users/_UserForm.razor @@ -1,30 +1,25 @@ -@using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity; @using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant -@using CleanArchitecture.Blazor.Application.Features.Identity.Dto; -@using Microsoft.AspNetCore.Identity -@using SixLabors.ImageSharp -@using SixLabors.ImageSharp.Formats -@using SixLabors.ImageSharp.Processing - +@using CleanArchitecture.Blazor.Application.Features.Identity.Dto +@using CleanArchitecture.Blazor.Domain.Enums @inherits MudComponentBase @inject IStringLocalizer L - - - + + +
@if (_canSearch) { - } @@ -158,7 +158,7 @@ - + @if (_canEdit || _canDelete) { @@ -167,11 +167,11 @@ EndIcon="@Icons.Material.Filled.KeyboardArrowDown" IconColor="Color.Info" AnchorOrigin="Origin.CenterLeft"> @if (_canEdit) { - @ConstantString.EDIT + @ConstantString.Edit } @if (_canDelete) { - @ConstantString.DELETE + @ConstantString.Delete } } @@ -180,7 +180,7 @@ - @ConstantString.NOALLOWED + @ConstantString.NoAllowed } @@ -207,10 +207,10 @@ - @ConstantString.NORECORDS + @ConstantString.NoRecords - @ConstantString.LOADING + @ConstantString.Loading @@ -229,18 +229,18 @@ private bool _loading; private bool _uploading; private bool _exporting; - private bool _pdfexporting; + private bool _pdfExporting; private int _defaultPageSize = 15; [Inject] - private IMediator _mediator { get; set; } = default!; + private IMediator Mediator { get; set; } = default!; [Inject] private IMapper _mapper { get; set; } = default!; [CascadingParameter] - private Task _authState { get; set; } = default!; + private Task AuthState { get; set; } = default!; - private ProductsWithPaginationQuery _query { get; set; } = new(); + private ProductsWithPaginationQuery Query { get; set; } = new(); [Inject] - private IBlazorDownloadFileService _blazorDownloadFileService { get; set; } = null!; + private IBlazorDownloadFileService BlazorDownloadFileService { get; set; } = null!; private bool _canSearch; private bool _canCreate; private bool _canEdit; @@ -250,7 +250,7 @@ protected override async Task OnInitializedAsync() { Title = L[_currentDto.GetClassDescription()]; - var state = await _authState; + var state = await AuthState; _canCreate = (await AuthService.AuthorizeAsync(state.User, Permissions.Products.Create)).Succeeded; _canSearch = (await AuthService.AuthorizeAsync(state.User, Permissions.Products.Search)).Succeeded; _canEdit = (await AuthService.AuthorizeAsync(state.User, Permissions.Products.Edit)).Succeeded; @@ -263,11 +263,11 @@ try { _loading = true; - _query.Sort = state.SortDefinitions.FirstOrDefault()?.SortBy??"Id"; - _query.SortBy = (state.SortDefinitions.FirstOrDefault()?.Descending??true ? AutoFilterer.Enums.Sorting.Descending : AutoFilterer.Enums.Sorting.Ascending); - _query.Page = state.Page + 1; - _query.PerPage = state.PageSize; - var result = await _mediator.Send(_query).ConfigureAwait(false); + Query.Sort = state.SortDefinitions.FirstOrDefault()?.SortBy??"Id"; + Query.SortBy = (state.SortDefinitions.FirstOrDefault()?.Descending??true ? AutoFilterer.Enums.Sorting.Descending : AutoFilterer.Enums.Sorting.Ascending); + Query.Page = state.Page + 1; + Query.PerPage = state.PageSize; + var result = await Mediator.Send(Query).ConfigureAwait(false); return new GridData() { TotalItems = result.TotalItems, Items = result.Items }; } finally @@ -291,19 +291,19 @@ private async Task OnSearch(string text) { _selectedItems = new(); - _query.Keyword = text; + Query.Keyword = text; await _table.ReloadServerData(); } private async Task OnChangedListView(ProductListView listview) { - _query.ListView = listview; + Query.ListView = listview; await _table.ReloadServerData(); } private async Task OnRefresh() { ProductCacheKey.Refresh(); _selectedItems = new(); - _query.Keyword = string.Empty; + Query.Keyword = string.Empty; await _table.ReloadServerData(); } private async Task OnCreate() @@ -311,11 +311,11 @@ var command = new AddEditProductCommand() { Pictures=new List() }; var parameters = new DialogParameters { - { nameof(_ProductFormDialog.model),command }, + { nameof(_ProductFormDialog.Model),command }, }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Medium, FullWidth = true }; var dialog = DialogService.Show<_ProductFormDialog> - (string.Format(ConstantString.CREATEAITEM, L["Product"]), parameters, options); + (string.Format(ConstantString.CreateAnItem, L["Product"]), parameters, options); var state = await dialog.Result; if (!state.Canceled) { @@ -327,11 +327,11 @@ var command = _mapper.Map(dto); var parameters = new DialogParameters { - { nameof(_ProductFormDialog.model),command }, + { nameof(_ProductFormDialog.Model),command }, }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Medium, FullWidth = true }; var dialog = DialogService.Show<_ProductFormDialog> - (string.Format(ConstantString.EDITTHEITEM, L["Product"]), parameters, options); + (string.Format(ConstantString.EditTheItem, L["Product"]), parameters, options); var state = await dialog.Result; if (!state.Canceled) { @@ -346,10 +346,10 @@ var parameters = new DialogParameters { { nameof(DeleteConfirmation.Command), command }, - { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DELETECONFIRMATION, dto.Name) } + { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DeleteConfirmation, dto.Name) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Small, FullWidth = true, DisableBackdropClick = true }; - var dialog = DialogService.Show(string.Format(ConstantString.EDITTHEITEM, L["Product"]), parameters, options); + var dialog = DialogService.Show(string.Format(ConstantString.EditTheItem, L["Product"]), parameters, options); var state = await dialog.Result; if (!state.Canceled) { @@ -363,11 +363,11 @@ var parameters = new DialogParameters { { nameof(DeleteConfirmation.Command), command }, - { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DELETECONFIRMWITHSELECTED,_selectedItems.Count) } + { nameof(DeleteConfirmation.ContentText), string.Format(ConstantString.DeleteConfirmWithSelected,_selectedItems.Count) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall, FullWidth = true, DisableBackdropClick = true }; var dialog = DialogService.Show - (string.Format(ConstantString.DELETETHEITEM, L["Product"]), parameters, options); + (string.Format(ConstantString.DeleteTheItem, L["Product"]), parameters, options); var state = await dialog.Result; if (!state.Canceled) { @@ -380,20 +380,20 @@ _exporting = true; var request = new ExportProductsQuery() { - Brand = _query.Brand, - Name = _query.Name, - Price = _query.Price, - Unit = _query.Unit, - Keyword = _query.Keyword, - ListView = _query.ListView, + Brand = Query.Brand, + Name = Query.Name, + Price = Query.Price, + Unit = Query.Unit, + Keyword = Query.Keyword, + ListView = Query.ListView, Sort = _table.SortDefinitions.Values.FirstOrDefault()?.SortBy ?? "Id", SortBy = (_table.SortDefinitions.Values.FirstOrDefault()?.Descending??false) ? AutoFilterer.Enums.Sorting.Ascending : AutoFilterer.Enums.Sorting.Descending }; - var result = await _mediator.Send(request); + var result = await Mediator.Send(request); if (result.Succeeded) { - var downloadresult = await _blazorDownloadFileService.DownloadFile($"{L["Products"]}.xlsx", result.Data, contentType: "application/octet-stream"); - Snackbar.Add($"{ConstantString.EXPORTSUCESS}", MudBlazor.Severity.Info); + var downloadResult = await BlazorDownloadFileService.DownloadFile($"{L["Products"]}.xlsx", result.Data, contentType: "application/octet-stream"); + Snackbar.Add($"{ConstantString.ExportSuccess}", MudBlazor.Severity.Info); } else { @@ -403,43 +403,43 @@ } private async Task OnExportPDF() { - _pdfexporting = true; + _pdfExporting = true; var request = new ExportProductsQuery() { - Brand = _query.Brand, - Name = _query.Name, - Price = _query.Price, - Unit = _query.Unit, - Keyword = _query.Keyword, - ListView = _query.ListView, + Brand = Query.Brand, + Name = Query.Name, + Price = Query.Price, + Unit = Query.Unit, + Keyword = Query.Keyword, + ListView = Query.ListView, Sort = _table.SortDefinitions.Values.FirstOrDefault()?.SortBy ?? "Id", SortBy = (_table.SortDefinitions.Values.FirstOrDefault()?.Descending ?? false) ? AutoFilterer.Enums.Sorting.Ascending : AutoFilterer.Enums.Sorting.Descending, ExportType = ExportType.PDF }; - var result = await _mediator.Send(request); + var result = await Mediator.Send(request); if (result.Succeeded) { - var downloadresult = await _blazorDownloadFileService.DownloadFile($"{L["Products"]}.pdf", result.Data, contentType: "application/octet-stream"); - Snackbar.Add($"{ConstantString.EXPORTSUCESS}", MudBlazor.Severity.Info); + var downloadResult = await BlazorDownloadFileService.DownloadFile($"{L["Products"]}.pdf", result.Data, contentType: "application/octet-stream"); + Snackbar.Add($"{ConstantString.ExportSuccess}", MudBlazor.Severity.Info); } else { Snackbar.Add($"{result.ErrorMessage}", MudBlazor.Severity.Error); } - _pdfexporting = false; + _pdfExporting = false; } private async Task OnImportData(IBrowserFile file) { _uploading = true; var stream = new MemoryStream(); - await file.OpenReadStream(GlobalVariable.maxAllowedSize).CopyToAsync(stream); + await file.OpenReadStream(GlobalVariable.MaxAllowedSize).CopyToAsync(stream); var command = new ImportProductsCommand(file.Name, stream.ToArray()); - var result = await _mediator.Send(command); + var result = await Mediator.Send(command); if (result.Succeeded) { await _table.ReloadServerData(); - Snackbar.Add($"{ConstantString.IMPORTSUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.ImportSuccess}", MudBlazor.Severity.Info); } else { diff --git a/src/Blazor.Server.UI/Pages/Products/_ProductFormDialog.razor b/src/Blazor.Server.UI/Pages/Products/_ProductFormDialog.razor index 6c5cc0db9..6e6688d1a 100644 --- a/src/Blazor.Server.UI/Pages/Products/_ProductFormDialog.razor +++ b/src/Blazor.Server.UI/Pages/Products/_ProductFormDialog.razor @@ -1,17 +1,15 @@ @using CleanArchitecture.Blazor.Application.Features.Products.Commands.AddEdit -@using SixLabors.ImageSharp -@using SixLabors.ImageSharp.Formats -@using SixLabors.ImageSharp.Processing +@using CleanArchitecture.Blazor.Domain.Enums @inherits MudComponentBase @inject IJSRuntime JS @inject IStringLocalizer L - + - @@ -19,16 +17,16 @@ + For="@(() => Model.Description)" + @bind-Value="Model.Description"> + @bind-Value="Model.Brand"> @@ -38,17 +36,17 @@ + @bind-Value="Model.Price"> + @bind-Value="Model.Unit"> @@ -58,7 +56,7 @@
+ @bind-Files="Model.UploadPictures" OnFilesChanged="UploadFiles" For="@(() => Model.UploadPictures)"> @L["The recommended size for uploading images is 640X320"]
- @if (model.Pictures is not null) + @if (Model.Pictures is not null) { - foreach (var img in model.Pictures) + foreach (var img in Model.Pictures) {
- +
@@ -94,8 +92,8 @@ - @ConstantString.CANCEL - @ConstantString.SAVE + @ConstantString.Cancel + @ConstantString.Save @@ -104,17 +102,18 @@ private bool _saving = false; [CascadingParameter] MudDialogInstance MudDialog { get; set; } = default!; - [Inject] private IUploadService _uploadService { get; set; } = default!; + [Inject] private IUploadService UploadService { get; set; } = default!; [Inject] - private IMediator _mediator { get; set; } = default!; - AddEditProductCommandValidator _modelValidator = new(); - [EditorRequired][Parameter] public AddEditProductCommand model { get; set; } = default!; - const long MAXALLOWEDSIZE = 3145728; + private IMediator Mediator { get; set; } = default!; + + readonly AddEditProductCommandValidator _modelValidator = new(); + [EditorRequired][Parameter] public AddEditProductCommand Model { get; set; } = default!; + const long MaxAllowedSize = 3145728; bool _uploading; private async Task DeleteImage(ProductImage picture) { - if (model.Pictures != null) + if (Model.Pictures != null) { var parameters = new DialogParameters { @@ -126,11 +125,11 @@ if (!state.Canceled) { - model.Pictures.Remove(picture); + Model.Pictures.Remove(picture); } } } - private async Task previewImage(string url, List imgs) + private async Task PreviewImage(string url, List imgs) { await JS.InvokeVoidAsync("previewImage", url, imgs.Select(x=>x.Url).ToArray()); } @@ -144,13 +143,13 @@ { try { - var filestream = file.OpenReadStream(GlobalVariable.maxAllowedSize); - var imgstream = new MemoryStream(); - await filestream.CopyToAsync(imgstream); - imgstream.Position = 0; + var filestream = file.OpenReadStream(GlobalVariable.MaxAllowedSize); + var imgStream = new MemoryStream(); + await filestream.CopyToAsync(imgStream); + imgStream.Position = 0; using (var outStream = new MemoryStream()) { - using (var image = Image.Load(imgstream)) + using (var image = Image.Load(imgStream)) { image.Mutate( i => i.Resize(new ResizeOptions() { Mode = SixLabors.ImageSharp.Processing.ResizeMode.Crop, Size = new SixLabors.ImageSharp.Size(640, 320) })); @@ -158,7 +157,7 @@ var filename = file.Name; var fi = new FileInfo(filename); var ext = fi.Extension; - var result = await _uploadService.UploadAsync(new UploadRequest(Guid.NewGuid().ToString() + ext, UploadType.Product, outStream.ToArray())); + var result = await UploadService.UploadAsync(new UploadRequest(Guid.NewGuid().ToString() + ext, UploadType.Product, outStream.ToArray())); list.Add(new ProductImage() { Name = filename, Size = outStream.Length, Url = result }); } } @@ -170,10 +169,10 @@ } Snackbar.Add(L["Upload pictures successfully"], MudBlazor.Severity.Info); - if (model.Pictures is null) - model.Pictures = list; + if (Model.Pictures is null) + Model.Pictures = list; else - model.Pictures.AddRange(list); + Model.Pictures.AddRange(list); } finally @@ -190,12 +189,12 @@ if (!_form!.IsValid) return; - var result = await _mediator.Send(model); + var result = await Mediator.Send(Model); if (result.Succeeded) { MudDialog.Close(DialogResult.Ok(true)); - Snackbar.Add(ConstantString.SAVESUCCESS, MudBlazor.Severity.Info); + Snackbar.Add(ConstantString.SaveSuccess, MudBlazor.Severity.Info); } else { diff --git a/src/Blazor.Server.UI/Pages/SystemManagement/AuditTrails.razor b/src/Blazor.Server.UI/Pages/SystemManagement/AuditTrails.razor index c39ffdd2a..f62ccb230 100644 --- a/src/Blazor.Server.UI/Pages/SystemManagement/AuditTrails.razor +++ b/src/Blazor.Server.UI/Pages/SystemManagement/AuditTrails.razor @@ -1,7 +1,9 @@ @page "/system/audittrails" -@using CleanArchitecture.Blazor.Application.Features.AuditTrails.Caching; @using CleanArchitecture.Blazor.Application.Features.AuditTrails.DTOs @using CleanArchitecture.Blazor.Application.Features.AuditTrails.Queries.PaginationQuery +@using CleanArchitecture.Blazor.Application.Features.AuditTrails.Caching +@using CleanArchitecture.Blazor.Application.Constants.Permission +@using CleanArchitecture.Blazor.Domain.Enums @attribute [Authorize(Policy = Permissions.AuditTrails.View)] @@ -41,7 +43,7 @@ Size="Size.Small" OnClick="@(()=>OnRefresh())" StartIcon="@Icons.Material.Filled.Refresh" IconColor="Color.Surface" Color="Color.Primary" - Style="margin-right: 5px;">@ConstantString.REFRESH + Style="margin-right: 5px;">@ConstantString.Refresh
@@ -92,10 +94,10 @@ - @ConstantString.NORECORDS + @ConstantString.NoRecords - @ConstantString.LOADING + @ConstantString.Loading @@ -112,16 +114,16 @@ private bool _loading; private int _defaultPageSize = 15; [Inject] - private IMediator _mediator { get; set; } = default!; - private AuditTrailDto _currentDto = new(); - private AuditTrailsWithPaginationQuery _query = new(); + private IMediator Mediator { get; set; } = default!; + private readonly AuditTrailDto _currentDto = new(); + private readonly AuditTrailsWithPaginationQuery _query = new(); [CascadingParameter] - private Task _authState { get; set; } = default!; + private Task AuthState { get; set; } = default!; protected override async Task OnInitializedAsync() { Title = L[_currentDto.GetClassDescription()]; - var state = await _authState; + var state = await AuthState; } private async Task> ServerReload(GridState state) @@ -134,7 +136,7 @@ _query.Page = state.Page + 1; _query.PerPage = state.PageSize; - var result = await _mediator.Send(_query).ConfigureAwait(false); + var result = await Mediator.Send(_query).ConfigureAwait(false); return new GridData() { TotalItems = result.TotalItems, Items = result.Items }; } finally diff --git a/src/Blazor.Server.UI/Pages/SystemManagement/Components/LogsLineCharts.razor b/src/Blazor.Server.UI/Pages/SystemManagement/Components/LogsLineCharts.razor index 2ce90a451..9cee715a6 100644 --- a/src/Blazor.Server.UI/Pages/SystemManagement/Components/LogsLineCharts.razor +++ b/src/Blazor.Server.UI/Pages/SystemManagement/Components/LogsLineCharts.razor @@ -1,13 +1,12 @@ -@using ApexCharts +@using CleanArchitecture.Blazor.Application.Features.Loggers.DTOs +@using ApexCharts @using Blazor.Server.UI.Services -@using CleanArchitecture.Blazor.Application.Features.Loggers.DTOs -@using CleanArchitecture.Blazor.Application.Features.Loggers.Queries.ChatData @implements IDisposable @inject IStringLocalizer L
- - + @@ -23,24 +22,24 @@
@code { - private ApexChart? chart { get; set; } - private ApexChartOptions options { get; set; } = new(); + private ApexChart? Chart { get; set; } + private ApexChartOptions Options { get; set; } = new(); [EditorRequired][Parameter] public List Data { get; set; } = new(); [Inject] - private LayoutService _layoutService { get; set; } = null!; - public string backgroundColor = "background:#fff"; + private LayoutService LayoutService { get; set; } = null!; + public string BackgroundColor = "background:#fff"; protected override void OnInitialized() { - var isdarkmode = _layoutService.IsDarkMode; - var colors = isdarkmode ? new List() { "#0277BD", "#039BE5" } : new List() { "#1976D2", "#90CAF9" }; - backgroundColor = isdarkmode ? "background:rgb(66, 66, 66)" : "background:#fff"; + var isDarkMode = LayoutService.IsDarkMode; + var colors = isDarkMode ? new List() { "#0277BD", "#039BE5" } : new List() { "#1976D2", "#90CAF9" }; + BackgroundColor = isDarkMode ? "background:rgb(66, 66, 66)" : "background:#fff"; - options.Theme = new ApexCharts.Theme() + Options.Theme = new ApexCharts.Theme() { - Mode = (isdarkmode ? Mode.Dark : Mode.Light), + Mode = (isDarkMode ? Mode.Dark : Mode.Light), }; - options.Fill = new Fill + Options.Fill = new Fill { Type = new List { FillType.Gradient }, Gradient = new FillGradient @@ -54,8 +53,8 @@ }, }; - options.Yaxis = new List(); - options.Yaxis.Add(new YAxis + Options.Yaxis = new List(); + Options.Yaxis.Add(new YAxis { Labels = new YAxisLabels { @@ -63,7 +62,7 @@ } } ); - options.Xaxis = new XAxis + Options.Xaxis = new XAxis { Labels = new XAxisLabels { @@ -73,13 +72,13 @@ } }; - options.DataLabels = new DataLabels + Options.DataLabels = new DataLabels { Formatter = @"function(value, opts) { return Number(value).toLocaleString();}" }; - options.Tooltip = new ApexCharts.Tooltip + Options.Tooltip = new ApexCharts.Tooltip { X = new TooltipX { @@ -89,27 +88,27 @@ } }; - _layoutService.MajorUpdateOccured += LayoutServiceOnMajorUpdateOccured; + LayoutService.MajorUpdateOccured += LayoutServiceOnMajorUpdateOccured; } private async void LayoutServiceOnMajorUpdateOccured(object? sender, EventArgs e) { - var isdarkmode = _layoutService.IsDarkMode; - var colors = isdarkmode ? new List() { "#0277BD", "#039BE5" } : new List() { "#1976D2", "#90CAF9" }; - backgroundColor = isdarkmode ? "background:rgb(66, 66, 66)" : "background:#fff"; - options.Theme.Mode = (isdarkmode ? Mode.Dark : Mode.Light); - options.Fill.Gradient.GradientToColors = colors; - await chart!.UpdateOptionsAsync(true, true, false); - await chart!.RenderAsync(); + var isDarkMode = LayoutService.IsDarkMode; + var colors = isDarkMode ? new List() { "#0277BD", "#039BE5" } : new List() { "#1976D2", "#90CAF9" }; + BackgroundColor = isDarkMode ? "background:rgb(66, 66, 66)" : "background:#fff"; + Options.Theme.Mode = (isDarkMode ? Mode.Dark : Mode.Light); + Options.Fill.Gradient.GradientToColors = colors; + await Chart!.UpdateOptionsAsync(true, true, false); + await Chart!.RenderAsync(); StateHasChanged(); } public async Task RenderChart() { - await chart!.UpdateSeriesAsync(true); - await chart!.RenderAsync(); + await Chart!.UpdateSeriesAsync(true); + await Chart!.RenderAsync(); } public void Dispose() { - _layoutService.MajorUpdateOccured -= LayoutServiceOnMajorUpdateOccured; + LayoutService.MajorUpdateOccured -= LayoutServiceOnMajorUpdateOccured; GC.SuppressFinalize(this); } diff --git a/src/Blazor.Server.UI/Pages/SystemManagement/Dictionaries.razor b/src/Blazor.Server.UI/Pages/SystemManagement/Dictionaries.razor index 54e0e7f9a..3f8449310 100644 --- a/src/Blazor.Server.UI/Pages/SystemManagement/Dictionaries.razor +++ b/src/Blazor.Server.UI/Pages/SystemManagement/Dictionaries.razor @@ -1,15 +1,14 @@ @page "/system/picklist" -@using Blazor.Server.UI.Components.Dialogs +@using CleanArchitecture.Blazor.Application.Features.KeyValues.DTOs +@using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.Export +@using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.PaginationQuery @using BlazorDownloadFile -@using CleanArchitecture.Blazor.Application.Features.KeyValues.Caching; +@using CleanArchitecture.Blazor.Application.Constants.Permission +@using CleanArchitecture.Blazor.Application.Features.KeyValues.Caching @using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.AddEdit @using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.Delete @using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.Import -@using CleanArchitecture.Blazor.Application.Features.KeyValues.DTOs -@using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.ByName -@using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.Export -@using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.GetAll -@using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.PaginationQuery; +@using CleanArchitecture.Blazor.Domain.Enums @attribute [Authorize(Policy = Permissions.Dictionaries.View)] @inject IStringLocalizer L @@ -30,7 +29,7 @@ Hover="true" MultiSelection="true" @bind-SelectedItems="_selectedItems" - @bind-SelectedItem="_selectedItem" + @bind-SelectedItem="SelectedItem" ReadOnly="false" EditMode="DataGridEditMode.Cell" T="KeyValueDto" @@ -55,7 +54,7 @@ OnClick="OnRefresh" Disabled="@_loading" StartIcon="@Icons.Material.Filled.Refresh" IconColor="Color.Surface" Color="Color.Primary" - Style="margin-right: 4px; margin-bottom:4px">@ConstantString.REFRESH + Style="margin-right: 4px; margin-bottom:4px">@ConstantString.Refresh @if (_canCreate) { @ConstantString.NEW + IconColor="Color.Surface">@ConstantString.New } @if (_canDelete) { @@ -74,7 +73,7 @@ OnClick="OnDeleteChecked" Size="Size.Small" Style="margin-right: 4px; margin-bottom:4px" - IconColor="Color.Surface">@ConstantString.DELETE + IconColor="Color.Surface">@ConstantString.Delete } @if (_canImport) { @@ -88,11 +87,11 @@ @if (_uploading) { - @ConstantString.UPLOADING + @ConstantString.Uploading } else { - @ConstantString.IMPORT + @ConstantString.Import } @@ -109,11 +108,11 @@ @if (_downloading) { - @ConstantString.DOWNLOADING + @ConstantString.Downloading } else { - @ConstantString.EXPORT + @ConstantString.Export } } @@ -127,7 +126,7 @@ Size="Size.Small" OnClick="OnCreate" Style="margin-right: 4px; margin-bottom:4px" - IconColor="Color.Surface">@ConstantString.NEW + IconColor="Color.Surface">@ConstantString.New } @if (_canDelete) { @@ -137,7 +136,7 @@ OnClick="OnDeleteChecked" Size="Size.Small" Style="margin-right: 4px; margin-bottom:4px" - IconColor="Color.Surface">@ConstantString.DELETE + IconColor="Color.Surface">@ConstantString.Delete }
@@ -154,16 +153,16 @@
- + - - - - + + + + @@ -187,36 +186,36 @@ public string Title { get; set; } = "Picklist"; private IList _keyValueList = new List(); private HashSet _selectedItems = new HashSet(); - private KeyValueDto _selectedItem { get; set; } = new(); - private KeyValueDto _elementBeforeEdit { get; set; } = new(); + private KeyValueDto SelectedItem { get; set; } = new(); + private KeyValueDto ElementBeforeEdit { get; set; } = new(); private bool _canCancelEdit = true; private string _searchString = string.Empty; private Picklist? _searchPicklist = null; private int _defaultPageSize = 15; private bool _editing; [CascadingParameter] - private Task _authState { get; set; } = default!; + private Task AuthState { get; set; } = default!; [Inject] - private IMapper _mapper { get; set; } = default!; + private IMapper Mapper { get; set; } = default!; [Inject] - private IBlazorDownloadFileService _blazorDownloadFileService { get; set; } = null!; + private IBlazorDownloadFileService BlazorDownloadFileService { get; set; } = null!; [Inject] - private IMediator _mediator { get; set; } = default!; - private KeyValuesWithPaginationQuery request = new(); + private IMediator Mediator { get; set; } = default!; + private KeyValuesWithPaginationQuery _request = new(); private bool _canCreate; private bool _canSearch; private bool _canEdit; private bool _canDelete; private bool _canImport; private bool _canExport; - private bool _readonly => !_canCreate || !_canEdit; + private bool Readonly => !_canCreate || !_canEdit; private bool _loading; private bool _uploading; private bool _downloading; protected override async Task OnInitializedAsync() { - Title = L[_selectedItem.GetClassDescription()]; - var state = await _authState; + Title = L[SelectedItem.GetClassDescription()]; + var state = await AuthState; _canCreate = (await AuthService.AuthorizeAsync(state.User, Permissions.Dictionaries.Create)).Succeeded; _canSearch = (await AuthService.AuthorizeAsync(state.User, Permissions.Dictionaries.Search)).Succeeded; _canEdit = (await AuthService.AuthorizeAsync(state.User, Permissions.Dictionaries.Edit)).Succeeded; @@ -239,7 +238,7 @@ Page = state.Page + 1, PerPage = state.PageSize }; - var result = await _mediator.Send(request).ConfigureAwait(false); + var result = await Mediator.Send(request).ConfigureAwait(false); return new GridData() { TotalItems = result.TotalItems, Items = result.Items }; } finally @@ -268,8 +267,8 @@ { InvokeAsync(async () => { - var command = _mapper.Map(item); - var result = await _mediator.Send(command); + var command = Mapper.Map(item); + var result = await Mediator.Send(command); if (!result.Succeeded) { Snackbar.Add($"{result.ErrorMessage}", MudBlazor.Severity.Error); @@ -278,7 +277,7 @@ }); } private async Task DeleteItem(KeyValueDto item){ - var deleteContent = ConstantString.DELETECONFIRMATION; + var deleteContent = ConstantString.DeleteConfirmation; var command = new DeleteKeyValueCommand(new int[] { item.Id }); var parameters = new DialogParameters { @@ -286,7 +285,7 @@ { nameof(DeleteConfirmation.ContentText), string.Format(deleteContent,item.Name) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall, FullWidth = true, DisableBackdropClick = true }; - var dialog = DialogService.Show(ConstantString.DELETECONFIRMATIONTITLE, parameters, options); + var dialog = DialogService.Show(ConstantString.DeleteConfirmationTitle, parameters, options); var state = await dialog.Result; if (!state.Canceled) { @@ -295,28 +294,28 @@ } private async Task OnDeleteChecked() { - var deleteContent = ConstantString.DELETECONFIRMATION; + var deleteContent = ConstantString.DeleteConfirmation; var parameters = new DialogParameters { { nameof(DeleteConfirmation.ContentText), string.Format(deleteContent,_selectedItems.Count) } }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.ExtraSmall, FullWidth = true, DisableBackdropClick = true }; - var dialog = DialogService.Show(ConstantString.DELETECONFIRMATIONTITLE, parameters, options); + var dialog = DialogService.Show(ConstantString.DeleteConfirmationTitle, parameters, options); var state = await dialog.Result; if (!state.Canceled) { var command = new DeleteKeyValueCommand(_selectedItems.Select(x => x.Id).ToArray()); - var result = await _mediator.Send(command); + var result = await Mediator.Send(command); await _table.ReloadServerData(); - Snackbar.Add($"{ConstantString.DELETESUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.DeleteSuccess}", MudBlazor.Severity.Info); } } private async Task OnCreate() { var command = new AddEditKeyValueCommand() { - Name = _selectedItem.Name, - Description = _selectedItem?.Description, + Name = SelectedItem.Name, + Description = SelectedItem?.Description, }; var parameters = new DialogParameters { @@ -340,9 +339,9 @@ { Keyword = _searchString, }; - var result = await _mediator.Send(request); - var downloadresult = await _blazorDownloadFileService.DownloadFile($"{L["Picklist"]}.xlsx", result, contentType: "application/octet-stream"); - Snackbar.Add($"{ConstantString.EXPORTSUCESS}", MudBlazor.Severity.Info); + var result = await Mediator.Send(request); + var downloadResult = await BlazorDownloadFileService.DownloadFile($"{L["Picklist"]}.xlsx", result, contentType: "application/octet-stream"); + Snackbar.Add($"{ConstantString.ExportSuccess}", MudBlazor.Severity.Info); _downloading = false; } @@ -350,13 +349,13 @@ { _uploading = true; var stream = new MemoryStream(); - await e.File.OpenReadStream(GlobalVariable.maxAllowedSize).CopyToAsync(stream); + await e.File.OpenReadStream(GlobalVariable.MaxAllowedSize).CopyToAsync(stream); var command = new ImportKeyValuesCommand(e.File.Name, stream.ToArray()); - var result = await _mediator.Send(command); + var result = await Mediator.Send(command); if (result.Succeeded) { await OnRefresh(); - Snackbar.Add($"{ConstantString.IMPORTSUCCESS}", MudBlazor.Severity.Info); + Snackbar.Add($"{ConstantString.ImportSuccess}", MudBlazor.Severity.Info); } else { diff --git a/src/Blazor.Server.UI/Pages/SystemManagement/Logs.razor b/src/Blazor.Server.UI/Pages/SystemManagement/Logs.razor index 7b401c481..f80361c2b 100644 --- a/src/Blazor.Server.UI/Pages/SystemManagement/Logs.razor +++ b/src/Blazor.Server.UI/Pages/SystemManagement/Logs.razor @@ -1,6 +1,7 @@ @page "/system/logs" @using Blazor.Server.UI.Pages.SystemManagement.Components -@using CleanArchitecture.Blazor.Application.Features.Loggers.Commands.Delete; +@using CleanArchitecture.Blazor.Application.Constants.Permission +@using CleanArchitecture.Blazor.Application.Features.Loggers.Commands.Delete @using CleanArchitecture.Blazor.Application.Features.Loggers.DTOs @using CleanArchitecture.Blazor.Application.Features.Loggers.Queries.ChatData @using CleanArchitecture.Blazor.Application.Logs.Queries.PaginationQuery @@ -15,7 +16,7 @@ - + @ConstantString.REFRESH + Style="margin-right: 5px;">@ConstantString.Refresh @if (_canPurge) { @ConstantString.CLEAR + @ConstantString.Clear } @@ -127,10 +128,10 @@ - @ConstantString.NORECORDS + @ConstantString.NoRecords - @ConstantString.LOADING + @ConstantString.Loading @@ -142,34 +143,34 @@ @code { - private LogsLineCharts? chartcomponent; + private LogsLineCharts? _chartComponent; public string Title { get; private set; } = "Logs"; private string _searchString = string.Empty; private MudDataGrid _table = default!; - private LogDto _currentDto = new(); + private readonly LogDto _currentDto = new(); private int _defaultPageSize = 15; - public List _data { get; set; } = new(); + public List Data { get; set; } = new(); [CascadingParameter] - private Task _authState { get; set; } = default!; + private Task AuthState { get; set; } = default!; private bool _loading; private bool _clearing; [Inject] - private IMediator _mediator { get; set; } = default!; + private IMediator Mediator { get; set; } = default!; private bool _canPurge; - private LogsWithPaginationQuery _query = new(); + private readonly LogsWithPaginationQuery _query = new(); protected override async void OnInitialized() { Title = L["Logs"]; - var state = await _authState; + var state = await AuthState; _canPurge = (await AuthService.AuthorizeAsync(state.User, Permissions.Logs.Purge)).Succeeded; } protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { - _data = await _mediator.Send(new LogsTimeLineChatDataQuery()); + Data = await Mediator.Send(new LogsTimeLineChatDataQuery()); StateHasChanged(); - await chartcomponent!.RenderChart(); + await _chartComponent!.RenderChart(); } } @@ -183,7 +184,7 @@ _query.SortBy = (state.SortDefinitions.FirstOrDefault()?.Descending == false ? AutoFilterer.Enums.Sorting.Ascending : AutoFilterer.Enums.Sorting.Descending); _query.Page = state.Page + 1; _query.PerPage = state.PageSize; - var result = await _mediator.Send(_query).ConfigureAwait(false); + var result = await Mediator.Send(_query).ConfigureAwait(false); return new GridData() { TotalItems = result.TotalItems, Items = result.Items }; } finally @@ -232,7 +233,7 @@ try { var command = new ClearLogsCommand(); - var result = await _mediator.Send(command); + var result = await Mediator.Send(command); await _table.ReloadServerData(); Snackbar.Add(L["Logs are erased"], MudBlazor.Severity.Info); } diff --git a/src/Blazor.Server.UI/Pages/SystemManagement/_CreatePicklistDialog.razor b/src/Blazor.Server.UI/Pages/SystemManagement/_CreatePicklistDialog.razor index 0be732319..6745138ed 100644 --- a/src/Blazor.Server.UI/Pages/SystemManagement/_CreatePicklistDialog.razor +++ b/src/Blazor.Server.UI/Pages/SystemManagement/_CreatePicklistDialog.razor @@ -1,7 +1,4 @@ -@using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.AddEdit; -@using SixLabors.ImageSharp -@using SixLabors.ImageSharp.Formats -@using SixLabors.ImageSharp.Processing +@using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.AddEdit @inherits MudComponentBase @inject IStringLocalizer L @@ -39,8 +36,8 @@ - @ConstantString.CANCEL - @ConstantString.SAVE + @ConstantString.Cancel + @ConstantString.Save @@ -66,7 +63,7 @@ if (result.Succeeded) { MudDialog.Close(DialogResult.Ok(true)); - Snackbar.Add(ConstantString.SAVESUCCESS, MudBlazor.Severity.Info); + Snackbar.Add(ConstantString.SaveSuccess, MudBlazor.Severity.Info); } else { diff --git a/src/Blazor.Server.UI/Pages/Tenants/Tenants.razor b/src/Blazor.Server.UI/Pages/Tenants/Tenants.razor index b153b3de2..68033fb32 100644 --- a/src/Blazor.Server.UI/Pages/Tenants/Tenants.razor +++ b/src/Blazor.Server.UI/Pages/Tenants/Tenants.razor @@ -1,12 +1,11 @@ @page "/system/tenants" - - - -@using CleanArchitecture.Blazor.Application.Features.Tenants.Caching; -@using CleanArchitecture.Blazor.Application.Features.Tenants.Commands.Delete @using CleanArchitecture.Blazor.Application.Features.Tenants.DTOs @using CleanArchitecture.Blazor.Application.Features.Tenants.Queries.Pagination +@using CleanArchitecture.Blazor.Application.Features.Tenants.Caching @using CleanArchitecture.Blazor.Application.Features.Tenants.Commands.AddEdit +@using CleanArchitecture.Blazor.Application.Features.Tenants.Commands.Delete +@using CleanArchitecture.Blazor.Application.Constants.Permission + @inject IJSRuntime JS @inject IStringLocalizer L @@ -46,7 +45,7 @@ Disabled="@_loading" OnClick="@(()=>OnRefresh())" StartIcon="@Icons.Material.Filled.Refresh" IconColor="Color.Surface" Color="Color.Primary" - Style="margin-right: 4px; margin-bottom:4px">@ConstantString.REFRESH + Style="margin-right: 4px; margin-bottom:4px">@ConstantString.Refresh @if (_canCreate) { @ConstantString.NEW + IconColor="Color.Surface">@ConstantString.New } @if (_canDelete) { @@ -65,20 +64,20 @@ Size="Size.Small" Style="margin-right: 4px; margin-bottom:4px" OnClick="OnDeleteChecked" - IconColor="Color.Surface">@ConstantString.DELETE + IconColor="Color.Surface">@ConstantString.Delete } - @ConstantString.REFRESH + @ConstantString.Refresh @if (_canCreate) { - @ConstantString.NEW + @ConstantString.New } @if (_canDelete) { - @ConstantString.DELETE + @ConstantString.Delete } @@ -86,7 +85,7 @@
@if (_canSearch) { - } @@ -95,7 +94,7 @@ - + @if (_canEdit || _canDelete) { @@ -104,11 +103,11 @@ EndIcon="@Icons.Material.Filled.KeyboardArrowDown" IconColor="Color.Info" AnchorOrigin="Origin.CenterLeft"> @if (_canEdit) { - @ConstantString.EDIT + @ConstantString.Edit } @if (_canDelete) { - @ConstantString.DELETE + @ConstantString.Delete } } @@ -117,7 +116,7 @@ - @ConstantString.NOALLOWED + @ConstantString.NoAllowed } @@ -157,13 +156,13 @@ private bool _loading; [Inject] - private IMediator _mediator { get; set; } = default!; + private IMediator Mediator { get; set; } = default!; [Inject] - private IMapper _mapper { get; set; } = default!; + private IMapper Mapper { get; set; } = default!; [CascadingParameter] - private Task _authState { get; set; } = default!; + private Task AuthState { get; set; } = default!; - private TenantsWithPaginationQuery _query { get; set; } = new(); + private TenantsWithPaginationQuery Query { get; set; } = new(); private bool _canSearch; private bool _canCreate; @@ -173,7 +172,7 @@ protected override async Task OnInitializedAsync() { Title = L[_currentDto.GetClassDescription()]; - var state = await _authState; + var state = await AuthState; _canCreate = (await AuthService.AuthorizeAsync(state.User, Permissions.Tenants.Create)).Succeeded; _canSearch = (await AuthService.AuthorizeAsync(state.User, Permissions.Tenants.Search)).Succeeded; _canEdit = (await AuthService.AuthorizeAsync(state.User, Permissions.Tenants.Edit)).Succeeded; @@ -184,12 +183,12 @@ try { _loading = true; - _query.Keyword = _searchString; - _query.Sort = state.SortDefinitions.FirstOrDefault()?.SortBy; - _query.SortBy = (state.SortDefinitions.FirstOrDefault()?.Descending==false ? AutoFilterer.Enums.Sorting.Ascending : AutoFilterer.Enums.Sorting.Descending); - _query.Page = state.Page + 1; - _query.PerPage = state.PageSize; - var result = await _mediator.Send(_query); + Query.Keyword = _searchString; + Query.Sort = state.SortDefinitions.FirstOrDefault()?.SortBy; + Query.SortBy = (state.SortDefinitions.FirstOrDefault()?.Descending==false ? AutoFilterer.Enums.Sorting.Ascending : AutoFilterer.Enums.Sorting.Descending); + Query.Page = state.Page + 1; + Query.PerPage = state.PageSize; + var result = await Mediator.Send(Query); return new GridData() { TotalItems = result.TotalItems, Items = result.Items }; } finally @@ -217,7 +216,7 @@ var command = new AddEditTenantCommand(); var parameters = new DialogParameters { - { nameof(_TenantFormDialog.model),command }, + { nameof(_TenantFormDialog.Model),command }, }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Small, FullWidth = true }; var dialog = DialogService.Show<_TenantFormDialog> @@ -230,10 +229,10 @@ } private async Task OnEdit(TenantDto dto) { - var command = _mapper.Map(dto); + var command = Mapper.Map(dto); var parameters = new DialogParameters { - { nameof(_TenantFormDialog.model),command }, + { nameof(_TenantFormDialog.Model),command }, }; var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Small, FullWidth = true }; var dialog = DialogService.Show<_TenantFormDialog> @@ -247,7 +246,7 @@ private async Task OnDelete(TenantDto dto) { - var deleteContent = ConstantString.DELETECONFIRMATIONWITHID; + var deleteContent = ConstantString.DeleteConfirmationWithId; var command = new DeleteTenantCommand(new string[] { dto.Id }); var parameters = new DialogParameters { @@ -266,7 +265,7 @@ private async Task OnDeleteChecked() { var command = new DeleteTenantCommand(_selectedItems.Select(x => x.Id).ToArray()); - var deleteContent = ConstantString.DELETECONFIRMATION; + var deleteContent = ConstantString.DeleteConfirmation; var parameters = new DialogParameters { { nameof(DeleteConfirmation.Command), command }, diff --git a/src/Blazor.Server.UI/Pages/Tenants/_TenantFormDialog.razor b/src/Blazor.Server.UI/Pages/Tenants/_TenantFormDialog.razor index def1b3289..bdad92ba7 100644 --- a/src/Blazor.Server.UI/Pages/Tenants/_TenantFormDialog.razor +++ b/src/Blazor.Server.UI/Pages/Tenants/_TenantFormDialog.razor @@ -1,31 +1,28 @@ @using CleanArchitecture.Blazor.Application.Features.Tenants.Commands.AddEdit -@using SixLabors.ImageSharp -@using SixLabors.ImageSharp.Formats -@using SixLabors.ImageSharp.Processing @inherits MudComponentBase @inject IStringLocalizer L - + - - - + @@ -33,8 +30,8 @@ - @ConstantString.CANCEL - @ConstantString.SAVE + @ConstantString.Cancel + @ConstantString.Save @@ -43,8 +40,9 @@ bool _saving = false; [CascadingParameter] MudDialogInstance MudDialog { get; set; } = default!; - AddEditTenantCommandValidator modelValidator = new AddEditTenantCommandValidator(); - [EditorRequired][Parameter] public AddEditTenantCommand model { get; set; } = default!; + + readonly AddEditTenantCommandValidator _modelValidator = new AddEditTenantCommandValidator(); + [EditorRequired][Parameter] public AddEditTenantCommand Model { get; set; } = default!; [Inject] private IMediator _mediator { get; set; } = default!; async Task Submit() @@ -56,12 +54,12 @@ if (!_form!.IsValid) return; - var result = await _mediator.Send(model); + var result = await _mediator.Send(Model); if (result.Succeeded) { MudDialog.Close(DialogResult.Ok(true)); - Snackbar.Add(ConstantString.SAVESUCCESS, MudBlazor.Severity.Info); + Snackbar.Add(ConstantString.SaveSuccess, MudBlazor.Severity.Info); } else { diff --git a/src/Blazor.Server.UI/Pages/_Layout.cshtml b/src/Blazor.Server.UI/Pages/_Layout.cshtml index 4c11d86bb..b34dbd0f4 100644 --- a/src/Blazor.Server.UI/Pages/_Layout.cshtml +++ b/src/Blazor.Server.UI/Pages/_Layout.cshtml @@ -1,5 +1,4 @@ @using Microsoft.AspNetCore.Components.Web -@using Blazor.Server.UI @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/src/Blazor.Server.UI/Program.cs b/src/Blazor.Server.UI/Program.cs index 21802ddc7..9a9211cf6 100644 --- a/src/Blazor.Server.UI/Program.cs +++ b/src/Blazor.Server.UI/Program.cs @@ -1,13 +1,10 @@ -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using CleanArchitecture.Blazor.Infrastructure.Persistence; -using CleanArchitecture.Blazor.Infrastructure; +using Blazor.Server.UI; +using Blazor.Server.UI.Services.Notifications; using CleanArchitecture.Blazor.Application; -using CleanArchitecture.Blazor.Infrastructure.Extensions; +using CleanArchitecture.Blazor.Infrastructure; +using CleanArchitecture.Blazor.Infrastructure.Persistence; using Serilog; using Serilog.Events; -using Blazor.Server.UI; -using Blazor.Server.UI.Services.Notifications; var builder = WebApplication.CreateBuilder(args); @@ -28,7 +25,7 @@ .WriteTo.Console() ); -builder.Services.AddBlazorUIServices(); +builder.Services.AddBlazorUiServices(); builder.Services.AddInfrastructureServices(builder.Configuration) .AddApplicationServices(); @@ -47,13 +44,13 @@ using (var scope = app.Services.CreateScope()) { - var initialiser = scope.ServiceProvider.GetRequiredService(); - await initialiser.InitialiseAsync(); - await initialiser.SeedAsync(); + var initializer = scope.ServiceProvider.GetRequiredService(); + await initializer.InitialiseAsync(); + await initializer.SeedAsync(); var notificationService = scope.ServiceProvider.GetService(); - if (notificationService is InMemoryNotificationService inmemoryService) + if (notificationService is InMemoryNotificationService inMemoryNotificationService) { - inmemoryService.Preload(); + inMemoryNotificationService.Preload(); } } } diff --git a/src/Blazor.Server.UI/Services/JsInterop/InputClear.cs b/src/Blazor.Server.UI/Services/JsInterop/InputClear.cs index 776a0f9a6..622573677 100644 --- a/src/Blazor.Server.UI/Services/JsInterop/InputClear.cs +++ b/src/Blazor.Server.UI/Services/JsInterop/InputClear.cs @@ -1,6 +1,4 @@ -using System.Runtime.InteropServices.JavaScript; -using System.Runtime.Versioning; -using Microsoft.JSInterop; +using Microsoft.JSInterop; namespace Blazor.Server.UI.Services.JsInterop; diff --git a/src/Blazor.Server.UI/Services/JsInterop/OrgChart.cs b/src/Blazor.Server.UI/Services/JsInterop/OrgChart.cs index dbdd04b85..80a0ef39e 100644 --- a/src/Blazor.Server.UI/Services/JsInterop/OrgChart.cs +++ b/src/Blazor.Server.UI/Services/JsInterop/OrgChart.cs @@ -1,6 +1,4 @@ -using System.Runtime.InteropServices.JavaScript; -using System.Runtime.Versioning; -using Blazor.Server.UI.Pages.Identity.Users; +using Blazor.Server.UI.Pages.Identity.Users; using Microsoft.JSInterop; namespace Blazor.Server.UI.Services.JsInterop; diff --git a/src/Blazor.Server.UI/Services/Layout/LayoutService.cs b/src/Blazor.Server.UI/Services/Layout/LayoutService.cs index 11cf403bf..a00b8b399 100644 --- a/src/Blazor.Server.UI/Services/Layout/LayoutService.cs +++ b/src/Blazor.Server.UI/Services/Layout/LayoutService.cs @@ -1,4 +1,4 @@ -using MudBlazor; +using Blazor.Server.UI.Services.UserPreferences; namespace Blazor.Server.UI.Services; @@ -6,7 +6,7 @@ public class LayoutService { private bool _systemPreferences; private readonly IUserPreferencesService _userPreferencesService; - private UserPreferences _userPreferences=new(); + private UserPreferences.UserPreferences _userPreferences=new(); public DarkLightMode DarkModeToggle = DarkLightMode.System; public bool IsRTL { get; private set; } = false; public bool IsDarkMode { get; private set; } = false; @@ -27,7 +27,7 @@ public void SetDarkMode(bool value) IsDarkMode = value; } - public async Task ApplyUserPreferences(bool isDarkModeDefaultTheme) + public async Task ApplyUserPreferences(bool isDarkModeDefaultTheme) { _userPreferences = await _userPreferencesService.LoadUserPreferences(); if (_userPreferences != null) @@ -54,7 +54,7 @@ public async Task ApplyUserPreferences(bool isDarkModeDefaultTh else { IsDarkMode = isDarkModeDefaultTheme; - _userPreferences = new UserPreferences { IsDarkMode = IsDarkMode }; + _userPreferences = new UserPreferences.UserPreferences { IsDarkMode = IsDarkMode }; await _userPreferencesService.SaveUserPreferences(_userPreferences); } return _userPreferences; @@ -149,7 +149,7 @@ public async Task SetBorderRadius(double size) await _userPreferencesService.SaveUserPreferences(_userPreferences); OnMajorUpdateOccured(); } - public async Task UpdateUserPreferences(UserPreferences preferences) + public async Task UpdateUserPreferences(UserPreferences.UserPreferences preferences) { _userPreferences = preferences; IsDarkMode = _userPreferences.DarkLightTheme switch diff --git a/src/Blazor.Server.UI/Services/Navigation/MenuService.cs b/src/Blazor.Server.UI/Services/Navigation/MenuService.cs index 3b561bc92..7b2c242b7 100644 --- a/src/Blazor.Server.UI/Services/Navigation/MenuService.cs +++ b/src/Blazor.Server.UI/Services/Navigation/MenuService.cs @@ -1,6 +1,5 @@ using Blazor.Server.UI.Models.SideMenu; -using CleanArchitecture.Blazor.Infrastructure.Constants; -using MudBlazor; +using CleanArchitecture.Blazor.Application.Constants.Role; namespace Blazor.Server.UI.Services.Navigation; diff --git a/src/Blazor.Server.UI/Services/Notifications/InMemoryNotificationService.cs b/src/Blazor.Server.UI/Services/Notifications/InMemoryNotificationService.cs index 3e657e800..8e77e1312 100644 --- a/src/Blazor.Server.UI/Services/Notifications/InMemoryNotificationService.cs +++ b/src/Blazor.Server.UI/Services/Notifications/InMemoryNotificationService.cs @@ -1,7 +1,5 @@ -using CleanArchitecture.Blazor.Application.Constants; using System.Security.Cryptography; using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage; -using DocumentFormat.OpenXml.InkML; namespace Blazor.Server.UI.Services.Notifications; diff --git a/src/Blazor.Server.UI/Services/UserPreferences/UserPreferences.cs b/src/Blazor.Server.UI/Services/UserPreferences/UserPreferences.cs index eece981dd..f73fa8f8c 100644 --- a/src/Blazor.Server.UI/Services/UserPreferences/UserPreferences.cs +++ b/src/Blazor.Server.UI/Services/UserPreferences/UserPreferences.cs @@ -2,7 +2,7 @@ // MudBlazor licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace Blazor.Server.UI.Services; +namespace Blazor.Server.UI.Services.UserPreferences; public class UserPreferences { diff --git a/src/Blazor.Server.UI/Services/UserPreferences/UserPreferencesService.cs b/src/Blazor.Server.UI/Services/UserPreferences/UserPreferencesService.cs index 04b63a26f..ce0b8af8b 100644 --- a/src/Blazor.Server.UI/Services/UserPreferences/UserPreferencesService.cs +++ b/src/Blazor.Server.UI/Services/UserPreferences/UserPreferencesService.cs @@ -5,7 +5,7 @@ using System.Security.Cryptography; using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage; -namespace Blazor.Server.UI.Services; +namespace Blazor.Server.UI.Services.UserPreferences; public interface IUserPreferencesService { @@ -13,13 +13,13 @@ public interface IUserPreferencesService /// Saves UserPreferences in local storage /// /// The userPreferences to save in the local storage - public Task SaveUserPreferences(UserPreferences userPreferences); + public Task SaveUserPreferences(Services.UserPreferences.UserPreferences userPreferences); /// /// Loads UserPreferences in local storage /// /// UserPreferences object. Null when no settings were found. - public Task LoadUserPreferences(); + public Task LoadUserPreferences(); } public class UserPreferencesService : IUserPreferencesService @@ -32,26 +32,26 @@ public UserPreferencesService(ProtectedLocalStorage localStorage) _localStorage = localStorage; } - public async Task SaveUserPreferences(UserPreferences userPreferences) + public async Task SaveUserPreferences(Services.UserPreferences.UserPreferences userPreferences) { await _localStorage.SetAsync(Key, userPreferences); } - public async Task LoadUserPreferences() + public async Task LoadUserPreferences() { try { - var result = await _localStorage.GetAsync(Key); + var result = await _localStorage.GetAsync(Key); if (result.Success && result.Value is not null) { return result.Value; } - return new UserPreferences(); + return new Services.UserPreferences.UserPreferences(); } catch (CryptographicException) { await _localStorage.DeleteAsync(Key); - return new UserPreferences(); + return new Services.UserPreferences.UserPreferences(); } } diff --git a/src/Blazor.Server.UI/Shared/MainLayout.razor b/src/Blazor.Server.UI/Shared/MainLayout.razor index a3f5443a7..9287a54d6 100644 --- a/src/Blazor.Server.UI/Shared/MainLayout.razor +++ b/src/Blazor.Server.UI/Shared/MainLayout.razor @@ -1,10 +1,10 @@ @inherits LayoutComponentBase @inject IStringLocalizer L - + - + @@ -23,10 +23,10 @@ + UserPreferences="_userPreferences" + UserPreferencesChanged="LayoutService.UpdateUserPreferences" /> diff --git a/src/Blazor.Server.UI/Shared/MainLayout.razor.cs b/src/Blazor.Server.UI/Shared/MainLayout.razor.cs index c1b40114d..898d0e835 100644 --- a/src/Blazor.Server.UI/Shared/MainLayout.razor.cs +++ b/src/Blazor.Server.UI/Shared/MainLayout.razor.cs @@ -1,9 +1,6 @@ using Blazor.Server.UI.Components.Shared; using Blazor.Server.UI.Services; -using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity; -using CleanArchitecture.Blazor.Application.Features.Identity.Dto; -using CleanArchitecture.Blazor.Application.Features.Identity.Notification; -using Microsoft.AspNetCore.Components.Authorization; +using Blazor.Server.UI.Services.UserPreferences; using Toolbelt.Blazor.HotKeys2; namespace Blazor.Server.UI.Shared; @@ -13,21 +10,21 @@ public partial class MainLayout : LayoutComponentBase, IDisposable private bool _commandPaletteOpen; private HotKeysContext? _hotKeysContext; private bool _sideMenuDrawerOpen = true; - private UserPreferences UserPreferences = new(); + private UserPreferences _userPreferences = new(); [Inject] - private LayoutService _layoutService { get; set; } = null!; + private LayoutService LayoutService { get; set; } = null!; private MudThemeProvider _mudThemeProvider=null!; private bool _themingDrawerOpen; private bool _defaultDarkMode; [Inject] private IDialogService _dialogService { get; set; } = default!; - [Inject] private HotKeys _hotKeys { get; set; } = default!; + [Inject] private HotKeys HotKeys { get; set; } = default!; public void Dispose() { - _layoutService.MajorUpdateOccured -= LayoutServiceOnMajorUpdateOccured; + LayoutService.MajorUpdateOccured -= LayoutServiceOnMajorUpdateOccured; _hotKeysContext?.Dispose(); GC.SuppressFinalize(this); } @@ -45,19 +42,19 @@ protected override async Task OnAfterRenderAsync(bool firstRender) private async Task ApplyUserPreferences() { _defaultDarkMode =await _mudThemeProvider.GetSystemPreference(); - UserPreferences = await _layoutService.ApplyUserPreferences(_defaultDarkMode); + _userPreferences = await LayoutService.ApplyUserPreferences(_defaultDarkMode); } protected override void OnInitialized() { - _layoutService.MajorUpdateOccured += LayoutServiceOnMajorUpdateOccured; - _layoutService.SetBaseTheme(Theme.ApplicationTheme()); - _hotKeysContext = _hotKeys.CreateContext().Add(ModKey.Ctrl, Key.K, async () => await OpenCommandPalette(), "Open command palette."); + LayoutService.MajorUpdateOccured += LayoutServiceOnMajorUpdateOccured; + LayoutService.SetBaseTheme(Theme.Theme.ApplicationTheme()); + _hotKeysContext = HotKeys.CreateContext().Add(ModKey.Ctrl, Key.K, async () => await OpenCommandPalette(), "Open command palette."); } private async Task OnSystemPreferenceChanged(bool newValue) { - await _layoutService.OnSystemPreferenceChanged(newValue); + await LayoutService.OnSystemPreferenceChanged(newValue); } private void LayoutServiceOnMajorUpdateOccured(object? sender, EventArgs e) => StateHasChanged(); diff --git a/src/Blazor.Server.UI/Shared/UserLoginState.razor b/src/Blazor.Server.UI/Shared/UserLoginState.razor index 82a40e592..1b1ea9f2a 100644 --- a/src/Blazor.Server.UI/Shared/UserLoginState.razor +++ b/src/Blazor.Server.UI/Shared/UserLoginState.razor @@ -1,25 +1,20 @@ -@using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity -@using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant; -@using CleanArchitecture.Blazor.Application.Features.Identity.Dto -@using CleanArchitecture.Blazor.Application.Features.Identity.Notification; @using CleanArchitecture.Blazor.Infrastructure.Hubs - @implements IDisposable @code{ public void Dispose() { - _client.Login -= _client_Login; - _client.Logout -= _client_Logout; + Client.Login -= _client_Login; + Client.Logout -= _client_Logout; } [Inject] - private HubClient _client { get; set; } = default!; + private HubClient Client { get; set; } = default!; protected override async Task OnInitializedAsync() { - _client.Login += _client_Login; - _client.Logout += _client_Logout; - await _client.StartAsync().ConfigureAwait(false); + Client.Login += _client_Login; + Client.Logout += _client_Logout; + await Client.StartAsync().ConfigureAwait(false); } private void _client_Login(object? sender, string username) diff --git a/src/Blazor.Server.UI/Theme/DefaultTheme.cs b/src/Blazor.Server.UI/Theme/DefaultTheme.cs index ee50b22cf..8945d8c25 100644 --- a/src/Blazor.Server.UI/Theme/DefaultTheme.cs +++ b/src/Blazor.Server.UI/Theme/DefaultTheme.cs @@ -1,6 +1,4 @@ -using MudBlazor; - -namespace Blazor.Server.UI; +namespace Blazor.Server.UI.Theme; public class Theme { diff --git a/src/Blazor.Server.UI/_Imports.cs b/src/Blazor.Server.UI/_Imports.cs index 1a463d085..a65738ab0 100644 --- a/src/Blazor.Server.UI/_Imports.cs +++ b/src/Blazor.Server.UI/_Imports.cs @@ -1,34 +1,16 @@ global using MediatR; -global using Microsoft.Extensions.Localization; -global using AutoMapper; global using AutoMapper.QueryableExtensions; global using FluentValidation; global using Microsoft.EntityFrameworkCore; global using System.Data; -global using System.Text.Json; -global using System.Linq.Dynamic.Core; global using Microsoft.Extensions.Logging; -global using Microsoft.Extensions.Primitives; -global using Microsoft.Extensions.Caching.Memory; -global using CleanArchitecture.Blazor.Domain; global using CleanArchitecture.Blazor.Domain.Entities; -global using CleanArchitecture.Blazor.Domain.Events; global using CleanArchitecture.Blazor.Domain.Identity; -global using CleanArchitecture.Blazor.Application.Common.Mappings; global using CleanArchitecture.Blazor.Application.Common.Models; -global using CleanArchitecture.Blazor.Application.Common.Extensions; global using CleanArchitecture.Blazor.Application.Common.Interfaces; -global using CleanArchitecture.Blazor.Application.Common.Interfaces.Caching; -global using CleanArchitecture.Blazor.Domain.Entities.Audit; -global using CleanArchitecture.Blazor.Domain.Entities.Log; -global using CleanArchitecture.Blazor.Application.Common.Specification; -global using CleanArchitecture.Blazor.Application.Common.Exceptions; global using CleanArchitecture.Blazor.Infrastructure.Extensions; global using CleanArchitecture.Blazor.Application.Constants; global using Microsoft.AspNetCore.Components; - global using MudBlazor; -global using static CleanArchitecture.Blazor.Application.Common.Helper.ConstantStringLocalizer; -global using FluentValidationSeverity = FluentValidation.Severity; global using Severity = MudBlazor.Severity; global using Color = MudBlazor.Color; \ No newline at end of file diff --git a/src/Blazor.Server.UI/_Imports.razor b/src/Blazor.Server.UI/_Imports.razor index d684dc25b..b1afb3fde 100644 --- a/src/Blazor.Server.UI/_Imports.razor +++ b/src/Blazor.Server.UI/_Imports.razor @@ -21,7 +21,6 @@ @using FluentValidation; @using CleanArchitecture.Blazor.Domain @using CleanArchitecture.Blazor.Domain.Identity -@using CleanArchitecture.Blazor.Application.Configurations @using CleanArchitecture.Blazor.Application.Common.Extensions @using CleanArchitecture.Blazor.Application.Constants @using CleanArchitecture.Blazor.Application.Common.Interfaces @@ -31,6 +30,7 @@ @using Blazor.Server.UI.Components.Common @using Blazor.Server.UI.Components.Dialogs @using Blazor.Server.UI.Pages.Authentication +@using CleanArchitecture.Blazor.Application.Common.Configurations @using MudExtensions @using MudExtensions.Enums @inject DashboardSettings Settings diff --git a/src/Blazor.Server.UI/appsettings.json b/src/Blazor.Server.UI/appsettings.json index 25009b930..f9e8eb05a 100644 --- a/src/Blazor.Server.UI/appsettings.json +++ b/src/Blazor.Server.UI/appsettings.json @@ -26,7 +26,7 @@ "AppFlavor": "Blazor .NET 7.0", "AppFlavorSubscript": ".NET 7.0", "Company": "Company", - "Copyright": "@2022 Copyright" + "Copyright": "@2023 Copyright" }, "AllowedHosts": "*", "SmtpClientOptions": { diff --git a/src/Domain/Common/IMustHaveTenant.cs b/src/Domain/Common/IMustHaveTenant.cs index f13521031..2a7bef33f 100644 --- a/src/Domain/Common/IMustHaveTenant.cs +++ b/src/Domain/Common/IMustHaveTenant.cs @@ -1,9 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace CleanArchitecture.Blazor.Domain.Common; public interface IMustHaveTenant { diff --git a/src/Domain/Entities/Audit/AuditTrail.cs b/src/Domain/Entities/Audit/AuditTrail.cs index 46021b0dd..d0b934f0b 100644 --- a/src/Domain/Entities/Audit/AuditTrail.cs +++ b/src/Domain/Entities/Audit/AuditTrail.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.ComponentModel.DataAnnotations.Schema; +using CleanArchitecture.Blazor.Domain.Enums; using CleanArchitecture.Blazor.Domain.Identity; using Microsoft.EntityFrameworkCore.ChangeTracking; diff --git a/src/Domain/Entities/Document.cs b/src/Domain/Entities/Document.cs index 13971aa8d..bcae97678 100644 --- a/src/Domain/Entities/Document.cs +++ b/src/Domain/Entities/Document.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using CleanArchitecture.Blazor.Domain.Enums; + namespace CleanArchitecture.Blazor.Domain.Entities; public class Document : OwnerPropertyEntity, IMayHaveTenant, IAuditTrial diff --git a/src/Domain/Entities/KeyValue.cs b/src/Domain/Entities/KeyValue.cs index a30dc97b6..3ee19c403 100644 --- a/src/Domain/Entities/KeyValue.cs +++ b/src/Domain/Entities/KeyValue.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using CleanArchitecture.Blazor.Domain.Enums; + namespace CleanArchitecture.Blazor.Domain.Entities; public class KeyValue : BaseAuditableEntity, IAuditTrial diff --git a/src/Domain/Entities/Logger/Logger.cs b/src/Domain/Entities/Logger/Logger.cs index 57bf6b60e..fd45fabec 100644 --- a/src/Domain/Entities/Logger/Logger.cs +++ b/src/Domain/Entities/Logger/Logger.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Domain.Entities.Log; +namespace CleanArchitecture.Blazor.Domain.Entities.Logger; public class Logger : IEntity { diff --git a/src/Domain/Entities/Tenant.cs b/src/Domain/Entities/Tenant.cs index 4cb7896b5..da59f83e0 100644 --- a/src/Domain/Entities/Tenant.cs +++ b/src/Domain/Entities/Tenant.cs @@ -1,9 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace CleanArchitecture.Blazor.Domain.Entities; public class Tenant : BaseAuditableEntity { diff --git a/src/Domain/Enums/AuditType.cs b/src/Domain/Enums/AuditType.cs index a2c61083d..c97fe64d0 100644 --- a/src/Domain/Enums/AuditType.cs +++ b/src/Domain/Enums/AuditType.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Domain; +namespace CleanArchitecture.Blazor.Domain.Enums; public enum AuditType { diff --git a/src/Domain/Enums/DocumentType.cs b/src/Domain/Enums/DocumentType.cs index 8ffddc524..51573c3b8 100644 --- a/src/Domain/Enums/DocumentType.cs +++ b/src/Domain/Enums/DocumentType.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace CleanArchitecture.Blazor.Domain; +namespace CleanArchitecture.Blazor.Domain.Enums; public enum DocumentType { Document, diff --git a/src/Domain/Enums/ExportType.cs b/src/Domain/Enums/ExportType.cs index 68e885c13..ba415e2de 100644 --- a/src/Domain/Enums/ExportType.cs +++ b/src/Domain/Enums/ExportType.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace CleanArchitecture.Blazor.Domain; +namespace CleanArchitecture.Blazor.Domain.Enums; public enum ExportType { Excel, diff --git a/src/Domain/Enums/JobStatus.cs b/src/Domain/Enums/JobStatus.cs index 921914cad..a6c2dc6d0 100644 --- a/src/Domain/Enums/JobStatus.cs +++ b/src/Domain/Enums/JobStatus.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace CleanArchitecture.Blazor.Domain; +namespace CleanArchitecture.Blazor.Domain.Enums; public enum JobStatus { NotStart, diff --git a/src/Domain/Enums/PartnerType.cs b/src/Domain/Enums/PartnerType.cs index c0e9aecf6..e6a833cea 100644 --- a/src/Domain/Enums/PartnerType.cs +++ b/src/Domain/Enums/PartnerType.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Domain; +namespace CleanArchitecture.Blazor.Domain.Enums; public enum PartnerType { diff --git a/src/Domain/Enums/Picklist.cs b/src/Domain/Enums/Picklist.cs index b24ce64f0..a31db138d 100644 --- a/src/Domain/Enums/Picklist.cs +++ b/src/Domain/Enums/Picklist.cs @@ -3,7 +3,7 @@ using System.ComponentModel; -namespace CleanArchitecture.Blazor.Domain; +namespace CleanArchitecture.Blazor.Domain.Enums; public enum Picklist { diff --git a/src/Domain/Enums/TrackingState.cs b/src/Domain/Enums/TrackingState.cs index 4d8eeb7fa..00776bf5f 100644 --- a/src/Domain/Enums/TrackingState.cs +++ b/src/Domain/Enums/TrackingState.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Domain; +namespace CleanArchitecture.Blazor.Domain.Enums; public enum TrackingState { diff --git a/src/Domain/Enums/UploadType.cs b/src/Domain/Enums/UploadType.cs index 659e60660..3c5f81713 100644 --- a/src/Domain/Enums/UploadType.cs +++ b/src/Domain/Enums/UploadType.cs @@ -3,7 +3,7 @@ using System.ComponentModel; -namespace CleanArchitecture.Blazor.Domain; +namespace CleanArchitecture.Blazor.Domain.Enums; public enum UploadType : byte { diff --git a/src/Domain/Identity/ApplicationUser.cs b/src/Domain/Identity/ApplicationUser.cs index c7d7e7f13..8e3900a0b 100644 --- a/src/Domain/Identity/ApplicationUser.cs +++ b/src/Domain/Identity/ApplicationUser.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Metadata.Internal; using System.ComponentModel.DataAnnotations.Schema; namespace CleanArchitecture.Blazor.Domain.Identity; diff --git a/src/Infrastructure/Constants/Localization/LocalizationConstants.cs b/src/Infrastructure/Constants/Localization/LocalizationConstants.cs index 779aa3530..4add2dc5c 100644 --- a/src/Infrastructure/Constants/Localization/LocalizationConstants.cs +++ b/src/Infrastructure/Constants/Localization/LocalizationConstants.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Infrastructure.Constants; +namespace CleanArchitecture.Blazor.Infrastructure.Constants.Localization; public static class LocalizationConstants { diff --git a/src/Infrastructure/Constants/Role/RoleNameConstants.cs b/src/Infrastructure/Constants/Role/RoleNameConstants.cs index 48f77dfaa..3616d55bb 100644 --- a/src/Infrastructure/Constants/Role/RoleNameConstants.cs +++ b/src/Infrastructure/Constants/Role/RoleNameConstants.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Infrastructure.Constants; +namespace CleanArchitecture.Blazor.Infrastructure.Constants.Role; public static class RoleNameConstants { diff --git a/src/Infrastructure/Constants/User/UserNameConstants.cs b/src/Infrastructure/Constants/User/UserNameConstants.cs index 3b32560c3..c63a74ddd 100644 --- a/src/Infrastructure/Constants/User/UserNameConstants.cs +++ b/src/Infrastructure/Constants/User/UserNameConstants.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -namespace CleanArchitecture.Blazor.Infrastructure.Constants; +namespace CleanArchitecture.Blazor.Infrastructure.Constants.User; public static class UserNameConstants { diff --git a/src/Infrastructure/DependencyInjection.cs b/src/Infrastructure/DependencyInjection.cs index 4c334eae8..0a0292be1 100644 --- a/src/Infrastructure/DependencyInjection.cs +++ b/src/Infrastructure/DependencyInjection.cs @@ -1,12 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.Extensions.Configuration; +using CleanArchitecture.Blazor.Application.Common.Configurations; +using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant; using CleanArchitecture.Blazor.Infrastructure.Extensions; using CleanArchitecture.Blazor.Infrastructure.Persistence.Interceptors; using CleanArchitecture.Blazor.Infrastructure.Services.JWT; -using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant; using CleanArchitecture.Blazor.Infrastructure.Services.MultiTenant; +using Microsoft.Extensions.Configuration; namespace CleanArchitecture.Blazor.Infrastructure; @@ -52,7 +53,7 @@ public static IServiceCollection AddInfrastructureServices(this IServiceCollecti services.AddSingleton(s => s.GetRequiredService>().Value); services.AddScoped, BlazorContextFactory>(); services.AddTransient(provider => provider.GetRequiredService>().CreateDbContext()); - services.AddScoped(); + services.AddScoped(); services.AddLocalizationServices(); diff --git a/src/Infrastructure/Extensions/ApplicationBuilderExtensions.cs b/src/Infrastructure/Extensions/ApplicationBuilderExtensions.cs index 30df5f3ed..cd9a45fa5 100644 --- a/src/Infrastructure/Extensions/ApplicationBuilderExtensions.cs +++ b/src/Infrastructure/Extensions/ApplicationBuilderExtensions.cs @@ -1,4 +1,4 @@ -using CleanArchitecture.Blazor.Infrastructure.Constants; +using CleanArchitecture.Blazor.Infrastructure.Constants.Localization; using CleanArchitecture.Blazor.Infrastructure.Hubs; using Hangfire; using Microsoft.AspNetCore.Builder; @@ -6,7 +6,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.FileProviders; - namespace CleanArchitecture.Blazor.Infrastructure.Extensions; public static class ApplicationBuilderExtensions diff --git a/src/Infrastructure/Extensions/AuthenticationServiceCollectionExtensions.cs b/src/Infrastructure/Extensions/AuthenticationServiceCollectionExtensions.cs index 2066e05a4..dcb840cd1 100644 --- a/src/Infrastructure/Extensions/AuthenticationServiceCollectionExtensions.cs +++ b/src/Infrastructure/Extensions/AuthenticationServiceCollectionExtensions.cs @@ -1,11 +1,11 @@ using System.Reflection; using System.Text; -using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant; +using CleanArchitecture.Blazor.Application.Constants.ClaimTypes; +using CleanArchitecture.Blazor.Application.Constants.Permission; +using CleanArchitecture.Blazor.Application.Constants.User; using CleanArchitecture.Blazor.Infrastructure.Services.JWT; -using CleanArchitecture.Blazor.Infrastructure.Services.MultiTenant; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Configuration; -using Microsoft.Identity.Client; using Microsoft.IdentityModel.Tokens; namespace CleanArchitecture.Blazor.Infrastructure.Extensions; diff --git a/src/Infrastructure/Extensions/ClaimsPrincipalExtensions.cs b/src/Infrastructure/Extensions/ClaimsPrincipalExtensions.cs index 944d93b34..d822a99a5 100644 --- a/src/Infrastructure/Extensions/ClaimsPrincipalExtensions.cs +++ b/src/Infrastructure/Extensions/ClaimsPrincipalExtensions.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using CleanArchitecture.Blazor.Application.Constants.ClaimTypes; + namespace CleanArchitecture.Blazor.Infrastructure.Extensions; public static class ClaimsPrincipalExtensions diff --git a/src/Infrastructure/Extensions/HangfireServiceCollectionExtensions.cs b/src/Infrastructure/Extensions/HangfireServiceCollectionExtensions.cs index f66ff851e..529eda74b 100644 --- a/src/Infrastructure/Extensions/HangfireServiceCollectionExtensions.cs +++ b/src/Infrastructure/Extensions/HangfireServiceCollectionExtensions.cs @@ -1,8 +1,4 @@ -using CleanArchitecture.Blazor.Application.Common.Interfaces.Serialization; -using CleanArchitecture.Blazor.Infrastructure.Services.Serialization; using Hangfire; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; namespace CleanArchitecture.Blazor.Infrastructure.Extensions; public static class HangfireServiceCollectionExtensions diff --git a/src/Infrastructure/Extensions/HttpClientServiceCollectionExtensions.cs b/src/Infrastructure/Extensions/HttpClientServiceCollectionExtensions.cs index 5268c68db..756d096bd 100644 --- a/src/Infrastructure/Extensions/HttpClientServiceCollectionExtensions.cs +++ b/src/Infrastructure/Extensions/HttpClientServiceCollectionExtensions.cs @@ -1,7 +1,6 @@ using System.Net.Http.Headers; -using CleanArchitecture.Blazor.Application.Common.Interfaces.Serialization; -using CleanArchitecture.Blazor.Infrastructure.Services.Serialization; using Polly; + namespace CleanArchitecture.Blazor.Infrastructure.Extensions; public static class HttpClientServiceCollectionExtensions { diff --git a/src/Infrastructure/Extensions/LocalizationServiceCollectionExtensions.cs b/src/Infrastructure/Extensions/LocalizationServiceCollectionExtensions.cs index fc4f99c0d..1c3dfeaf9 100644 --- a/src/Infrastructure/Extensions/LocalizationServiceCollectionExtensions.cs +++ b/src/Infrastructure/Extensions/LocalizationServiceCollectionExtensions.cs @@ -1,16 +1,19 @@ +using CleanArchitecture.Blazor.Infrastructure.Constants.Localization; using Microsoft.AspNetCore.Builder; namespace CleanArchitecture.Blazor.Infrastructure.Extensions; + public static class LocalizationServiceCollectionExtensions { public static IServiceCollection AddLocalizationServices(this IServiceCollection services) - => services.AddScoped() - .Configure(options => - { - options.AddSupportedUICultures(LocalizationConstants.SupportedLanguages.Select(x => x.Code).ToArray()); - options.AddSupportedCultures(LocalizationConstants.SupportedLanguages.Select(x => x.Code).ToArray()); - options.FallBackToParentUICultures = true; - - }) - .AddLocalization(options => options.ResourcesPath = LocalizationConstants.ResourcesPath); -} + { + return services.AddScoped() + .Configure(options => + { + options.AddSupportedUICultures(LocalizationConstants.SupportedLanguages.Select(x => x.Code).ToArray()); + options.AddSupportedCultures(LocalizationConstants.SupportedLanguages.Select(x => x.Code).ToArray()); + options.FallBackToParentUICultures = true; + }) + .AddLocalization(options => options.ResourcesPath = LocalizationConstants.ResourcesPath); + } +} \ No newline at end of file diff --git a/src/Infrastructure/Extensions/MediatorExtensions.cs b/src/Infrastructure/Extensions/MediatorExtensions.cs index 640ffb0e4..d7b02a69c 100644 --- a/src/Infrastructure/Extensions/MediatorExtensions.cs +++ b/src/Infrastructure/Extensions/MediatorExtensions.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using MediatR; namespace CleanArchitecture.Blazor.Infrastructure.Extensions; diff --git a/src/Infrastructure/Extensions/MessageServiceCollectionExtensions.cs b/src/Infrastructure/Extensions/MessageServiceCollectionExtensions.cs index 3c13604f6..e82b255b4 100644 --- a/src/Infrastructure/Extensions/MessageServiceCollectionExtensions.cs +++ b/src/Infrastructure/Extensions/MessageServiceCollectionExtensions.cs @@ -1,6 +1,5 @@ using FluentEmail.MailKitSmtp; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; namespace CleanArchitecture.Blazor.Infrastructure.Extensions; public static class MessageServiceCollectionExtensions diff --git a/src/Infrastructure/Extensions/ServicesCollectionExtensions.cs b/src/Infrastructure/Extensions/ServicesCollectionExtensions.cs index 39c74ef00..728a1d748 100644 --- a/src/Infrastructure/Extensions/ServicesCollectionExtensions.cs +++ b/src/Infrastructure/Extensions/ServicesCollectionExtensions.cs @@ -2,15 +2,17 @@ using CleanArchitecture.Blazor.Infrastructure.Services.PaddleOCR; namespace CleanArchitecture.Blazor.Infrastructure.Extensions; + public static class ServicesCollectionExtensions { public static IServiceCollection AddServices(this IServiceCollection services) - => services - .AddScoped() - .AddScoped() - .AddScoped() - .AddScoped() - .AddTransient() - .AddScoped(); - -} + { + return services + .AddScoped() + .AddScoped() + .AddScoped() + .AddScoped() + .AddTransient() + .AddScoped(); + } +} \ No newline at end of file diff --git a/src/Infrastructure/Extensions/SignalRServiceCollectionExtensions.cs b/src/Infrastructure/Extensions/SignalRServiceCollectionExtensions.cs index 85f732612..fa229da2f 100644 --- a/src/Infrastructure/Extensions/SignalRServiceCollectionExtensions.cs +++ b/src/Infrastructure/Extensions/SignalRServiceCollectionExtensions.cs @@ -2,11 +2,14 @@ using Microsoft.AspNetCore.Components.Server.Circuits; namespace CleanArchitecture.Blazor.Infrastructure.Extensions; + public static class SignalRServiceCollectionExtensions { public static void AddSignalRServices(this IServiceCollection services) - => services.AddSingleton() - .AddScoped() - .AddTransient() - .AddSignalR(); -} + { + services.AddSingleton() + .AddScoped() + .AddTransient() + .AddSignalR(); + } +} \ No newline at end of file diff --git a/src/Infrastructure/Hubs/HubClient.cs b/src/Infrastructure/Hubs/HubClient.cs index c58c72ebf..ecc35f2a9 100644 --- a/src/Infrastructure/Hubs/HubClient.cs +++ b/src/Infrastructure/Hubs/HubClient.cs @@ -1,29 +1,21 @@ -using CleanArchitecture.Blazor.Infrastructure.Constants; -using CleanArchitecture.Blazor.Infrastructure.Extensions; using CleanArchitecture.Blazor.Infrastructure.Services.JWT; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Http.Connections; -using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR.Client; namespace CleanArchitecture.Blazor.Infrastructure.Hubs; public class HubClient : IAsyncDisposable { - private HubConnection _hubConnection; - private string _hubUrl = String.Empty; - private readonly NavigationManager _navigationManager; - private readonly AccessTokenProvider _authProvider; + private readonly HubConnection _hubConnection; private bool _started = false; public HubClient(NavigationManager navigationManager, AccessTokenProvider authProvider ) { - _navigationManager = navigationManager; - _authProvider = authProvider; - var token = _authProvider.AccessToken; - _hubUrl = _navigationManager.BaseUri.TrimEnd('/') + SignalR.HubUrl; + var token = authProvider.AccessToken; + string hubUrl = navigationManager.BaseUri.TrimEnd('/') + SignalR.HubUrl; _hubConnection = new HubConnectionBuilder() - .WithUrl(_hubUrl, options => { + .WithUrl(hubUrl, options => { options.AccessTokenProvider =()=> Task.FromResult(token); options.Transports = HttpTransportType.WebSockets; }) diff --git a/src/Infrastructure/Hubs/SignalRHub.cs b/src/Infrastructure/Hubs/SignalRHub.cs index 7d3b6cc6e..5bc8aa836 100644 --- a/src/Infrastructure/Hubs/SignalRHub.cs +++ b/src/Infrastructure/Hubs/SignalRHub.cs @@ -2,13 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Concurrent; -using CleanArchitecture.Blazor.Infrastructure.Constants; -using DocumentFormat.OpenXml.Office2010.Excel; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; - namespace CleanArchitecture.Blazor.Infrastructure.Hubs; public interface ISignalRHub @@ -23,14 +20,14 @@ public interface ISignalRHub [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class SignalRHub : Hub { - private static readonly ConcurrentDictionary _onlineUsers = new(); + private static readonly ConcurrentDictionary OnlineUsers = new(); public override async Task OnConnectedAsync() { var id = Context.ConnectionId; var userName = Context.User?.Identity?.Name ?? string.Empty; - if (!_onlineUsers.ContainsKey(id)) + if (!OnlineUsers.ContainsKey(id)) { - _onlineUsers.TryAdd(id, userName); + OnlineUsers.TryAdd(id, userName); } await Clients.All.Connect(userName); await base.OnConnectedAsync(); @@ -40,7 +37,7 @@ public override async Task OnDisconnectedAsync(Exception? exception) { var id = Context.ConnectionId; //try to remove key from dictionary - if (_onlineUsers.TryRemove(id, out string? userName)) + if (OnlineUsers.TryRemove(id, out string? userName)) { await Clients.All.Disconnect(userName); } diff --git a/src/Infrastructure/Middlewares/ExceptionHandlingMiddleware.cs b/src/Infrastructure/Middlewares/ExceptionHandlingMiddleware.cs index 0364ad03f..9ef6d08e8 100644 --- a/src/Infrastructure/Middlewares/ExceptionHandlingMiddleware.cs +++ b/src/Infrastructure/Middlewares/ExceptionHandlingMiddleware.cs @@ -1,8 +1,8 @@ using System.Net; +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Localization; - namespace CleanArchitecture.Blazor.Infrastructure.Middlewares; internal class ExceptionHandlingMiddleware : IMiddleware diff --git a/src/Infrastructure/Middlewares/HangfireDashboardAuthorizationFilter.cs b/src/Infrastructure/Middlewares/HangfireDashboardAuthorizationFilter.cs index fe96e0c06..51b921cb9 100644 --- a/src/Infrastructure/Middlewares/HangfireDashboardAuthorizationFilter.cs +++ b/src/Infrastructure/Middlewares/HangfireDashboardAuthorizationFilter.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Hangfire.Dashboard; +using Hangfire.Dashboard; namespace CleanArchitecture.Blazor.Infrastructure.Middlewares; public class HangfireDashboardAsyncAuthorizationFilter : IDashboardAsyncAuthorizationFilter diff --git a/src/Infrastructure/Persistence/ApplicationDbContext.cs b/src/Infrastructure/Persistence/ApplicationDbContext.cs index 309084054..98bc2a505 100644 --- a/src/Infrastructure/Persistence/ApplicationDbContext.cs +++ b/src/Infrastructure/Persistence/ApplicationDbContext.cs @@ -2,9 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; -using CleanArchitecture.Blazor.Infrastructure.Extensions; +using CleanArchitecture.Blazor.Domain.Entities.Logger; using CleanArchitecture.Blazor.Infrastructure.Persistence.Interceptors; -using MediatR; namespace CleanArchitecture.Blazor.Infrastructure.Persistence; diff --git a/src/Infrastructure/Persistence/ApplicationDbContextInitialiser.cs b/src/Infrastructure/Persistence/ApplicationDbContextInitializer.cs similarity index 91% rename from src/Infrastructure/Persistence/ApplicationDbContextInitialiser.cs rename to src/Infrastructure/Persistence/ApplicationDbContextInitializer.cs index 649627270..035c05cfa 100644 --- a/src/Infrastructure/Persistence/ApplicationDbContextInitialiser.cs +++ b/src/Infrastructure/Persistence/ApplicationDbContextInitializer.cs @@ -1,14 +1,19 @@ using System.Reflection; +using CleanArchitecture.Blazor.Application.Constants.ClaimTypes; +using CleanArchitecture.Blazor.Application.Constants.Permission; +using CleanArchitecture.Blazor.Application.Constants.Role; +using CleanArchitecture.Blazor.Application.Constants.User; +using CleanArchitecture.Blazor.Domain.Enums; namespace CleanArchitecture.Blazor.Infrastructure.Persistence; -public class ApplicationDbContextInitialiser +public class ApplicationDbContextInitializer { - private readonly ILogger _logger; + private readonly ILogger _logger; private readonly ApplicationDbContext _context; private readonly UserManager _userManager; private readonly RoleManager _roleManager; - public ApplicationDbContextInitialiser(ILogger logger, ApplicationDbContext context, UserManager userManager, RoleManager roleManager) + public ApplicationDbContextInitializer(ILogger logger, ApplicationDbContext context, UserManager userManager, RoleManager roleManager) { _logger = logger; _context = context; @@ -26,7 +31,7 @@ public async Task InitialiseAsync() } catch (Exception ex) { - _logger.LogError(ex, "An error occurred while initialising the database."); + _logger.LogError(ex, "An error occurred while initialising the database"); throw; } } @@ -39,7 +44,7 @@ public async Task SeedAsync() } catch (Exception ex) { - _logger.LogError(ex, "An error occurred while seeding the database."); + _logger.LogError(ex, "An error occurred while seeding the database"); throw; } } @@ -80,12 +85,12 @@ public async Task TrySeedAsync() // Default roles var administratorRole = new ApplicationRole(RoleName.Administrator) { Description = "Admin Group" }; var userRole = new ApplicationRole(RoleName.Basic) { Description = "Basic Group" }; - var Permissions = GetAllPermissions(); + var permissions = GetAllPermissions(); if (_roleManager.Roles.All(r => r.Name != administratorRole.Name)) { await _roleManager.CreateAsync(administratorRole); - foreach (var permission in Permissions) + foreach (var permission in permissions) { await _roleManager.AddClaimAsync(administratorRole, new System.Security.Claims.Claim(ApplicationClaimTypes.Permission, permission)); } @@ -93,7 +98,7 @@ public async Task TrySeedAsync() if (_roleManager.Roles.All(r => r.Name != userRole.Name)) { await _roleManager.CreateAsync(userRole); - foreach (var permission in Permissions) + foreach (var permission in permissions) { if (permission.StartsWith("Permissions.Products")) await _roleManager.AddClaimAsync(userRole, new System.Security.Claims.Claim(ApplicationClaimTypes.Permission, permission)); diff --git a/src/Infrastructure/Persistence/BlazorContextFactory.cs b/src/Infrastructure/Persistence/BlazorContextFactory.cs index 5c1776761..43aa76ca0 100644 --- a/src/Infrastructure/Persistence/BlazorContextFactory.cs +++ b/src/Infrastructure/Persistence/BlazorContextFactory.cs @@ -1,21 +1,21 @@ namespace CleanArchitecture.Blazor.Infrastructure.Persistence; public class BlazorContextFactory : IDbContextFactory where TContext : DbContext { - private readonly IServiceProvider provider; + private readonly IServiceProvider _provider; public BlazorContextFactory(IServiceProvider provider) { - this.provider = provider; + this._provider = provider; } public TContext CreateDbContext() { - if (provider == null) + if (_provider == null) { throw new InvalidOperationException( $"You must configure an instance of IServiceProvider"); } - return ActivatorUtilities.CreateInstance(provider); + return ActivatorUtilities.CreateInstance(_provider); } } diff --git a/src/Infrastructure/Persistence/Configurations/AuditTrailConfiguration.cs b/src/Infrastructure/Persistence/Configurations/AuditTrailConfiguration.cs index 947ff33e5..e342b1be7 100644 --- a/src/Infrastructure/Persistence/Configurations/AuditTrailConfiguration.cs +++ b/src/Infrastructure/Persistence/Configurations/AuditTrailConfiguration.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Text.Json; -using CleanArchitecture.Blazor.Application.Common.Interfaces.Serialization; using CleanArchitecture.Blazor.Infrastructure.Persistence.Conversions; using Microsoft.EntityFrameworkCore.Metadata.Builders; diff --git a/src/Infrastructure/Persistence/Configurations/CustomerConfiguration.cs b/src/Infrastructure/Persistence/Configurations/CustomerConfiguration.cs index 406bb43aa..09709f915 100644 --- a/src/Infrastructure/Persistence/Configurations/CustomerConfiguration.cs +++ b/src/Infrastructure/Persistence/Configurations/CustomerConfiguration.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Text.Json; -using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace CleanArchitecture.Blazor.Infrastructure.Persistence.Configurations; diff --git a/src/Infrastructure/Persistence/Configurations/ProductConfiguration.cs b/src/Infrastructure/Persistence/Configurations/ProductConfiguration.cs index 03965b50f..d25a7717b 100644 --- a/src/Infrastructure/Persistence/Configurations/ProductConfiguration.cs +++ b/src/Infrastructure/Persistence/Configurations/ProductConfiguration.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Text.Json; -using CleanArchitecture.Blazor.Application.Common.Interfaces.Serialization; -using CleanArchitecture.Blazor.Infrastructure.Persistence.Conversions; -using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace CleanArchitecture.Blazor.Infrastructure.Persistence.Configurations; diff --git a/src/Infrastructure/Persistence/Conversions/StringListConverter.cs b/src/Infrastructure/Persistence/Conversions/StringListConverter.cs index 53a5fb427..2bb45a6c1 100644 --- a/src/Infrastructure/Persistence/Conversions/StringListConverter.cs +++ b/src/Infrastructure/Persistence/Conversions/StringListConverter.cs @@ -9,11 +9,10 @@ namespace CleanArchitecture.Blazor.Infrastructure.Persistence.Conversions; public class StringListConverter : ValueConverter, string> { - public StringListConverter() : base(v => JsonSerializer.Serialize(v, DefaultJsonSerializerOptions.Options), - v => JsonSerializer.Deserialize>(string.IsNullOrEmpty(v) ? "[]" : v, DefaultJsonSerializerOptions.Options)??new() - ) + v => JsonSerializer.Deserialize>(string.IsNullOrEmpty(v) ? "[]" : v, + DefaultJsonSerializerOptions.Options) ?? new List() + ) { - } -} +} \ No newline at end of file diff --git a/src/Infrastructure/Persistence/Conversions/ValueConversionExtensions.cs b/src/Infrastructure/Persistence/Conversions/ValueConversionExtensions.cs index 7672400bc..90641a802 100644 --- a/src/Infrastructure/Persistence/Conversions/ValueConversionExtensions.cs +++ b/src/Infrastructure/Persistence/Conversions/ValueConversionExtensions.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json; -using System.Threading.Tasks; +using System.Text.Json; using CleanArchitecture.Blazor.Application.Common.Interfaces.Serialization; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Builders; diff --git a/src/Infrastructure/Persistence/Extensions/ModelBuilderExtensions.cs b/src/Infrastructure/Persistence/Extensions/ModelBuilderExtensions.cs index 71c6c177e..93beab9cc 100644 --- a/src/Infrastructure/Persistence/Extensions/ModelBuilderExtensions.cs +++ b/src/Infrastructure/Persistence/Extensions/ModelBuilderExtensions.cs @@ -17,8 +17,8 @@ public static void ApplyGlobalFilters(this ModelBuilder modelBuilder foreach (var entity in entities) { var newParam = Expression.Parameter(entity); - var newbody = ReplacingExpressionVisitor.Replace(expression.Parameters.Single(), newParam, expression.Body); - modelBuilder.Entity(entity).HasQueryFilter(Expression.Lambda(newbody, newParam)); + var newBody = ReplacingExpressionVisitor.Replace(expression.Parameters.Single(), newParam, expression.Body); + modelBuilder.Entity(entity).HasQueryFilter(Expression.Lambda(newBody, newParam)); } } } diff --git a/src/Infrastructure/Persistence/Interceptors/AuditableEntitySaveChangesInterceptor.cs b/src/Infrastructure/Persistence/Interceptors/AuditableEntitySaveChangesInterceptor.cs index 82d6973b7..818eb9251 100644 --- a/src/Infrastructure/Persistence/Interceptors/AuditableEntitySaveChangesInterceptor.cs +++ b/src/Infrastructure/Persistence/Interceptors/AuditableEntitySaveChangesInterceptor.cs @@ -1,9 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant; +using CleanArchitecture.Blazor.Domain.Enums; using CleanArchitecture.Blazor.Infrastructure.Extensions; using MediatR; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -33,19 +29,19 @@ public AuditableEntitySaveChangesInterceptor( public override async ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) { - updateEntities(eventData.Context!); + UpdateEntities(eventData.Context!); _temporaryAuditTrailList = TryInsertTemporaryAuditTrail(eventData.Context!, cancellationToken); _deletingDomainEvents = TryGetDeletingDomainEvents(eventData.Context!, cancellationToken); return await base.SavingChangesAsync(eventData, result, cancellationToken); } public override async ValueTask SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, CancellationToken cancellationToken = default) { - var resultvalueTask = await base.SavedChangesAsync(eventData, result, cancellationToken); + var resultValueTask = await base.SavedChangesAsync(eventData, result, cancellationToken); await TryUpdateTemporaryPropertiesForAuditTrail(eventData.Context!, cancellationToken).ConfigureAwait(false); await _mediator.DispatchDomainEvents(eventData.Context!, _deletingDomainEvents).ConfigureAwait(false); - return resultvalueTask; + return resultValueTask; } - private void updateEntities(DbContext context) + private void UpdateEntities(DbContext context) { var userId = _currentUserService.UserId; var tenantId = _tenantProvider.TenantId; @@ -56,13 +52,13 @@ private void updateEntities(DbContext context) case EntityState.Added: entry.Entity.CreatedBy = userId; entry.Entity.Created = _dateTime.Now; - if (entry.Entity is IMustHaveTenant mustenant) + if (entry.Entity is IMustHaveTenant mustTenant) { - mustenant.TenantId = tenantId; + mustTenant.TenantId = tenantId; } - if (entry.Entity is IMayHaveTenant maytenant) + if (entry.Entity is IMayHaveTenant mayTenant) { - maytenant.TenantId = tenantId; + mayTenant.TenantId = tenantId; } break; diff --git a/src/Infrastructure/Services/ApplicationClaimsIdentityFactory.cs b/src/Infrastructure/Services/ApplicationClaimsIdentityFactory.cs index a7c8a9ea4..9dc05b548 100644 --- a/src/Infrastructure/Services/ApplicationClaimsIdentityFactory.cs +++ b/src/Infrastructure/Services/ApplicationClaimsIdentityFactory.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.AspNetCore.Identity; +using CleanArchitecture.Blazor.Application.Constants.ClaimTypes; namespace CleanArchitecture.Blazor.Infrastructure.Services; #nullable disable diff --git a/src/Infrastructure/Services/CurrentUserService.cs b/src/Infrastructure/Services/CurrentUserService.cs index ad1338a78..70e8fafe3 100644 --- a/src/Infrastructure/Services/CurrentUserService.cs +++ b/src/Infrastructure/Services/CurrentUserService.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using CleanArchitecture.Blazor.Infrastructure.Extensions; -using Microsoft.AspNetCore.Components.Authorization; -using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage; -using Microsoft.AspNetCore.Http; - namespace CleanArchitecture.Blazor.Infrastructure.Services; public class CurrentUserService : ICurrentUserService diff --git a/src/Infrastructure/Services/ExcelService.cs b/src/Infrastructure/Services/ExcelService.cs index 8045c85b3..9b0f78822 100644 --- a/src/Infrastructure/Services/ExcelService.cs +++ b/src/Infrastructure/Services/ExcelService.cs @@ -1,9 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.Extensions.Localization; using System.Data; using ClosedXML.Excel; +using Microsoft.Extensions.Localization; namespace CleanArchitecture.Blazor.Infrastructure.Services; @@ -131,26 +131,26 @@ public async Task>> ImportAsync(byte[] dat { return await Result>.FailureAsync(errors); } - var lastrow = ws.LastRowUsed(); + var lastRow = ws.LastRowUsed(); var list = new List(); - foreach (IXLRow row in ws.Rows(startRow, lastrow.RowNumber())) + foreach (IXLRow row in ws.Rows(startRow, lastRow.RowNumber())) { try { - DataRow datarow = dt.Rows.Add(); + DataRow dataRow = dt.Rows.Add(); var item = (TEntity?)Activator.CreateInstance(typeof(TEntity))??throw new NullReferenceException($"{nameof(TEntity)}"); foreach (IXLCell cell in row.Cells()) { if (cell.DataType == XLDataType.DateTime) { - datarow[cell.Address.ColumnNumber - 1] = cell.GetDateTime().ToString("yyyy-MM-dd HH:mm:ss"); + dataRow[cell.Address.ColumnNumber - 1] = cell.GetDateTime().ToString("yyyy-MM-dd HH:mm:ss"); } else { - datarow[cell.Address.ColumnNumber - 1] = cell.Value.ToString(); + dataRow[cell.Address.ColumnNumber - 1] = cell.Value.ToString(); } } - headers.ForEach(x => mappers[x](datarow, item)); + headers.ForEach(x => mappers[x](dataRow, item)); list.Add(item); } catch (Exception e) diff --git a/src/Infrastructure/Services/Identity/IdentityService.cs b/src/Infrastructure/Services/Identity/IdentityService.cs index dc0d568bc..a54433a82 100644 --- a/src/Infrastructure/Services/Identity/IdentityService.cs +++ b/src/Infrastructure/Services/Identity/IdentityService.cs @@ -1,26 +1,25 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.IdentityModel.Tokens.Jwt; +using System.Security.Cryptography; +using System.Text; using AutoMapper; using AutoMapper.QueryableExtensions; +using CleanArchitecture.Blazor.Application.Common.Configurations; +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity.DTOs; using CleanArchitecture.Blazor.Application.Features.Identity.Dto; using CleanArchitecture.Blazor.Infrastructure.Extensions; using LazyCache; using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Caching.Memory; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.IdentityModel.Tokens; -using System.IdentityModel.Tokens.Jwt; -using System.Security.Cryptography; -using System.Text; namespace CleanArchitecture.Blazor.Infrastructure.Services.Identity; public class IdentityService : IIdentityService { - private readonly IServiceScopeFactory _scopeFactory; private readonly UserManager _userManager; private readonly RoleManager _roleManager; private readonly AppConfigurationSettings _appConfig; @@ -29,8 +28,8 @@ public class IdentityService : IIdentityService private readonly IAppCache _cache; private readonly IMapper _mapper; private readonly IStringLocalizer _localizer; - private TimeSpan refreshInterval => TimeSpan.FromSeconds(60); - private LazyCacheEntryOptions _options => new LazyCacheEntryOptions().SetAbsoluteExpiration(refreshInterval, ExpirationMode.LazyExpiration); + private TimeSpan RefreshInterval => TimeSpan.FromSeconds(60); + private LazyCacheEntryOptions Options => new LazyCacheEntryOptions().SetAbsoluteExpiration(RefreshInterval, ExpirationMode.LazyExpiration); public IdentityService( IServiceScopeFactory scopeFactory, AppConfigurationSettings appConfig, @@ -38,8 +37,7 @@ public IdentityService( IMapper mapper, IStringLocalizer localizer) { - _scopeFactory = scopeFactory; - var scope = _scopeFactory.CreateScope(); + var scope = scopeFactory.CreateScope(); _userManager = scope.ServiceProvider.GetRequiredService>(); _roleManager = scope.ServiceProvider.GetRequiredService>(); _userClaimsPrincipalFactory = scope.ServiceProvider.GetRequiredService>(); @@ -53,13 +51,13 @@ public IdentityService( public async Task GetUserNameAsync(string userId, CancellationToken cancellation = default) { var key = $"GetUserNameAsync:{userId}"; - var user = await _cache.GetOrAddAsync(key, async () => await _userManager.Users.SingleOrDefaultAsync(u => u.Id == userId), _options); + var user = await _cache.GetOrAddAsync(key, async () => await _userManager.Users.SingleOrDefaultAsync(u => u.Id == userId), Options); return user?.UserName; } public string GetUserName(string userId) { var key = $"GetUserName-byId:{userId}"; - var user = _cache.GetOrAdd(key, () => _userManager.Users.SingleOrDefault(u => u.Id == userId), _options); + var user = _cache.GetOrAdd(key, () => _userManager.Users.SingleOrDefault(u => u.Id == userId), Options); return user?.UserName??string.Empty; } public async Task IsInRoleAsync(string userId, string role, CancellationToken cancellation = default) @@ -86,7 +84,7 @@ public async Task DeleteUserAsync(string userId, CancellationToken cance public async Task> FetchUsers(string roleName, CancellationToken cancellation = default) { var result = await _userManager.Users - .Where(x => x.UserRoles.Where(y => y.Role.Name == roleName).Any()) + .Where(x => x.UserRoles.Any(y => y.Role.Name == roleName)) .Include(x => x.UserRoles) .ToDictionaryAsync(x => x.UserName!, y => y.DisplayName, cancellation); return result; @@ -113,17 +111,17 @@ public async Task> LoginAsync(TokenRequest request, Cancel return await Result.FailureAsync(new string[] { _localizer["Invalid Credentials."] }); } user.RefreshToken = GenerateRefreshToken(); - var TokenExpiryTime = DateTime.Now.AddDays(7); + var tokenExpiryTime = DateTime.Now.AddDays(7); if (request.RememberMe) { - TokenExpiryTime = DateTime.Now.AddYears(1); + tokenExpiryTime = DateTime.Now.AddYears(1); } - user.RefreshTokenExpiryTime = TokenExpiryTime; + user.RefreshTokenExpiryTime = tokenExpiryTime; await _userManager.UpdateAsync(user); var token = await GenerateJwtAsync(user); - var response = new TokenResponse { Token = token, RefreshTokenExpiryTime = TokenExpiryTime, RefreshToken = user.RefreshToken, ProfilePictureDataUrl = user.ProfilePictureDataUrl }; + var response = new TokenResponse { Token = token, RefreshTokenExpiryTime = tokenExpiryTime, RefreshToken = user.RefreshToken, ProfilePictureDataUrl = user.ProfilePictureDataUrl }; return await Result.SuccessAsync(response); } @@ -231,14 +229,14 @@ public async Task UpdateLiveStatus(string userId, bool isLive, CancellationToken public async Task GetApplicationUserDto(string userId, CancellationToken cancellation = default) { var key = $"GetApplicationUserDto:{userId}"; - var result = await _cache.GetOrAddAsync(key, async () => await _userManager.Users.Where(x => x.Id == userId).Include(x => x.UserRoles).ThenInclude(x => x.Role).ProjectTo(_mapper.ConfigurationProvider).FirstAsync(cancellation), _options); + var result = await _cache.GetOrAddAsync(key, async () => await _userManager.Users.Where(x => x.Id == userId).Include(x => x.UserRoles).ThenInclude(x => x.Role).ProjectTo(_mapper.ConfigurationProvider).FirstAsync(cancellation), Options); return result; } public async Task?> GetUsers(string tenantId, CancellationToken cancellation = default) { var key = $"GetApplicationUserDtoListWithTenantId:{tenantId}"; var result = await _cache.GetOrAddAsync(key, async () => await _userManager.Users.Where(x => x.TenantId == tenantId).Include(x => x.UserRoles).ThenInclude(x => x.Role) - .ProjectTo(_mapper.ConfigurationProvider).ToListAsync(), _options); + .ProjectTo(_mapper.ConfigurationProvider).ToListAsync(), Options); return result; } } diff --git a/src/Infrastructure/Services/Identity/UserDataProvider.cs b/src/Infrastructure/Services/Identity/UserDataProvider.cs index a12726917..56618c2e7 100644 --- a/src/Infrastructure/Services/Identity/UserDataProvider.cs +++ b/src/Infrastructure/Services/Identity/UserDataProvider.cs @@ -1,13 +1,11 @@ using AutoMapper; using AutoMapper.QueryableExtensions; -using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity.DTOs; using CleanArchitecture.Blazor.Application.Features.Identity.Dto; namespace CleanArchitecture.Blazor.Infrastructure.Services.Identity; public class UserDataProvider : IUserDataProvider { private readonly IMapper _mapper; - private readonly IServiceScopeFactory _scopeFactory; private readonly UserManager _userManager; public List DataSource { get; private set; } @@ -18,8 +16,7 @@ public UserDataProvider( IServiceScopeFactory scopeFactory) { _mapper = mapper; - _scopeFactory = scopeFactory; - var scope = _scopeFactory.CreateScope(); + var scope = scopeFactory.CreateScope(); _userManager = scope.ServiceProvider.GetRequiredService>(); DataSource = new List(); } diff --git a/src/Infrastructure/Services/InMemoryTicketStore.cs b/src/Infrastructure/Services/InMemoryTicketStore.cs index f5ac7e063..749a6627c 100644 --- a/src/Infrastructure/Services/InMemoryTicketStore.cs +++ b/src/Infrastructure/Services/InMemoryTicketStore.cs @@ -1,5 +1,5 @@ -using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.Extensions.Caching.Memory; namespace CleanArchitecture.Blazor.Infrastructure.Services; @@ -15,7 +15,7 @@ public class InMemoryTicketStore : ITicketStore public InMemoryTicketStore(IMemoryCache cache) { - _cache = cache ?? throw new ArgumentNullException(nameof(_cache)); ; + _cache = cache ?? throw new ArgumentNullException(nameof(cache)); ; } public Task RemoveAsync(string key) diff --git a/src/Infrastructure/Services/JWT/AccessTokenProvider.cs b/src/Infrastructure/Services/JWT/AccessTokenProvider.cs index 6305b0fd0..58f2d8b81 100644 --- a/src/Infrastructure/Services/JWT/AccessTokenProvider.cs +++ b/src/Infrastructure/Services/JWT/AccessTokenProvider.cs @@ -1,13 +1,13 @@ using System.Security.Cryptography; using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant; +using CleanArchitecture.Blazor.Infrastructure.Extensions; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage; -using CleanArchitecture.Blazor.Infrastructure.Extensions; namespace CleanArchitecture.Blazor.Infrastructure.Services.JWT; public class AccessTokenProvider { - private readonly string TokenKey = nameof(TokenKey); + private readonly string _tokenKey = nameof(_tokenKey); private readonly ProtectedLocalStorage _localStorage; private readonly NavigationManager _navigation; private readonly IIdentityService _identityService; @@ -28,7 +28,7 @@ public AccessTokenProvider(ProtectedLocalStorage localStorage, NavigationManager public async Task GenerateJwt(ApplicationUser applicationUser) { AccessToken = await _identityService.GenerateJwtAsync(applicationUser); - await _localStorage.SetAsync(TokenKey, AccessToken); + await _localStorage.SetAsync(_tokenKey, AccessToken); _tenantProvider.TenantId = applicationUser.TenantId; _tenantProvider.TenantName = applicationUser.TenantName; _currentUser.UserId = applicationUser.Id; @@ -41,7 +41,7 @@ public async Task GetClaimsPrincipal() { try { - var token = await _localStorage.GetAsync(TokenKey); + var token = await _localStorage.GetAsync(_tokenKey); if (token.Success && !string.IsNullOrEmpty(token.Value)) { AccessToken = token.Value; @@ -72,7 +72,7 @@ public async Task GetClaimsPrincipal() public async Task RemoveAuthDataFromStorage() { - await _localStorage.DeleteAsync(TokenKey); + await _localStorage.DeleteAsync(_tokenKey); _navigation.NavigateTo("/", true); } } diff --git a/src/Infrastructure/Services/JWT/BlazorAuthStateProvider.cs b/src/Infrastructure/Services/JWT/BlazorAuthStateProvider.cs index 98a70247a..065f5d0ae 100644 --- a/src/Infrastructure/Services/JWT/BlazorAuthStateProvider.cs +++ b/src/Infrastructure/Services/JWT/BlazorAuthStateProvider.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace CleanArchitecture.Blazor.Infrastructure.Services.JWT; +namespace CleanArchitecture.Blazor.Infrastructure.Services.JWT; public class BlazorAuthStateProvider : AuthenticationStateProvider { private readonly AccessTokenProvider _tokenProvider; diff --git a/src/Infrastructure/Services/MailService.cs b/src/Infrastructure/Services/MailService.cs index 73b608eaf..4dcf18b46 100644 --- a/src/Infrastructure/Services/MailService.cs +++ b/src/Infrastructure/Services/MailService.cs @@ -2,12 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; -using System.Threading; -using DocumentFormat.OpenXml.Wordprocessing; +using CleanArchitecture.Blazor.Application.Common.Configurations; using FluentEmail.Core; using FluentEmail.Core.Models; -using MailKit.Net.Smtp; -using MimeKit; using Polly; using Polly.Retry; @@ -55,7 +52,7 @@ public Task SendAsync(string to, string subject, string body) } catch (Exception e) { - _logger.LogError(e, $"Error sending an email to {to} with subject {subject}", to, subject); + _logger.LogError(e, "Error sending an email to {Unknown} with subject {Subject}", to, subject); throw; } } @@ -82,7 +79,7 @@ public Task SendAsync(string to, string subject, string template, } catch (Exception e) { - _logger.LogError(e, $"Error sending an email to {to} with subject {subject} and template {template}", to, subject,template); + _logger.LogError(e, "Error sending an email to {Unknown} with subject {Subject} and template {Template}", to, subject,template); throw; } } diff --git a/src/Infrastructure/Services/PDFService.cs b/src/Infrastructure/Services/PDFService.cs index d69393886..97bdb325d 100644 --- a/src/Infrastructure/Services/PDFService.cs +++ b/src/Infrastructure/Services/PDFService.cs @@ -1,18 +1,17 @@ using QuestPDF.Fluent; using QuestPDF.Helpers; using QuestPDF.Infrastructure; -using System.Data; using Document = QuestPDF.Fluent.Document; namespace CleanArchitecture.Blazor.Infrastructure.Services; public class PDFService : IPDFService { - private const int marginPTs = 56; - private const string fontFamilyName = Fonts.Consolas; - private const float fontSize = 10F; - private const int maxCharsPerCell = 80; - private const int minCharsPerCell = 10; + private const int MarginPTs = 56; + private const string FontFamilyName = Fonts.Consolas; + private const float FontSize = 10F; + private const int MaxCharsPerCell = 80; + private const int MinCharsPerCell = 10; public async Task ExportAsync(IEnumerable data , Dictionary> mappers @@ -25,9 +24,9 @@ public async Task ExportAsync(IEnumerable data container.Page(page => { page.Size(landscape? PageSizes.A4.Landscape() : PageSizes.A4); - page.Margin(marginPTs, Unit.Point); + page.Margin(MarginPTs, Unit.Point); page.PageColor(QuestPDF.Helpers.Colors.White); - page.DefaultTextStyle(x => x.FontSize(fontSize).FontFamily(fontFamilyName).Fallback(TextStyle.Default.FontFamily("simhei"))); + page.DefaultTextStyle(x => x.FontSize(FontSize).FontFamily(FontFamilyName).Fallback(TextStyle.Default.FontFamily("simhei"))); page.Header() .Text(title) @@ -41,12 +40,12 @@ public async Task ExportAsync(IEnumerable data var dataList = data.ToList(); // Rough fit columns calculation - int tableWidth = landscape ? (int)(PageSizes.A4.Landscape().Width - (marginPTs * 2)) : (int)(PageSizes.A4.Width - (marginPTs * 2)); + int tableWidth = landscape ? (int)(PageSizes.A4.Landscape().Width - (MarginPTs * 2)) : (int)(PageSizes.A4.Width - (MarginPTs * 2)); int[] columnsWidth = new int[headers.Count]; for (uint c = 0; c < headers.Count; c++) { - var cellWidth = Math.Max(minCharsPerCell, Math.Min($"{headers[(int)c]}".Length,maxCharsPerCell)); + var cellWidth = Math.Max(MinCharsPerCell, Math.Min($"{headers[(int)c]}".Length,MaxCharsPerCell)); if (columnsWidth[c] < cellWidth) columnsWidth[c] = cellWidth; @@ -59,7 +58,7 @@ public async Task ExportAsync(IEnumerable data uint c = 0; foreach (var value in result) { - var cellWidth = Math.Max(minCharsPerCell, Math.Min($"{value}".Length, maxCharsPerCell)); + var cellWidth = Math.Max(MinCharsPerCell, Math.Min($"{value}".Length, MaxCharsPerCell)); if (columnsWidth[c] < cellWidth) columnsWidth[c] = cellWidth; c += 1; @@ -82,11 +81,10 @@ public async Task ExportAsync(IEnumerable data }); // Create rows - uint colIndex = 1; uint rowIndex = 1; foreach (var item in dataList) { - colIndex = 1; + uint colIndex = 1; rowIndex++; var result = headers.Select(header => mappers[header](item)); @@ -123,18 +121,7 @@ static bool IsNumber(object? value) { if (value == null) return false; - else - return value is sbyte - || value is byte - || value is short - || value is ushort - || value is int - || value is uint - || value is long - || value is ulong - || value is float - || value is double - || value is decimal; + return value is sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal; } static IContainer BlockCell(IContainer container) diff --git a/src/Infrastructure/Services/PaddleOCR/DocumentOcrJob.cs b/src/Infrastructure/Services/PaddleOCR/DocumentOcrJob.cs index d9ea3d435..da8681341 100644 --- a/src/Infrastructure/Services/PaddleOCR/DocumentOcrJob.cs +++ b/src/Infrastructure/Services/PaddleOCR/DocumentOcrJob.cs @@ -1,22 +1,14 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Diagnostics; using System.Drawing; -using System.IO; -using System.Linq; -using System.Net.Http; using System.Net.Http.Json; -using System.Text; using System.Text.Json; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; using CleanArchitecture.Blazor.Application.Common.Interfaces.Serialization; using CleanArchitecture.Blazor.Application.Features.Documents.Caching; using CleanArchitecture.Blazor.Application.Services.PaddleOCR; +using CleanArchitecture.Blazor.Domain.Enums; using CleanArchitecture.Blazor.Infrastructure.Hubs; using Microsoft.AspNetCore.SignalR; @@ -44,7 +36,7 @@ ILogger logger _logger = logger; _timer=new Stopwatch(); } - private string readbase64string(string path) + private string ReadBase64String(string path) { using (Image image = Image.FromFile(path)) { @@ -76,21 +68,21 @@ public async Task Recognition(int id, CancellationToken cancellationToken) await _hubContext.Clients.All.Start(doc.Title!); DocumentCacheKey.SharedExpiryTokenSource().Cancel(); if (string.IsNullOrEmpty(doc.URL)) return; - var imgfile = Path.Combine(Directory.GetCurrentDirectory(), doc.URL); - if (!File.Exists(imgfile)) return; - string base64string = readbase64string(imgfile); + var imgFile = Path.Combine(Directory.GetCurrentDirectory(), doc.URL); + if (!File.Exists(imgFile)) return; + string base64String = ReadBase64String(imgFile); - var response = client.PostAsJsonAsync("", new { images = new string[] { base64string } }).Result; + var response = client.PostAsJsonAsync("", new { images = new string[] { base64String } }).Result; if (response.StatusCode == System.Net.HttpStatusCode.OK) { var result = await response.Content.ReadAsStringAsync(); - var ocr_result = JsonSerializer.Deserialize(result); - var ocr_status = ocr_result!.status; + var ocrResult = JsonSerializer.Deserialize(result); + var ocrStatus = ocrResult!.Status; doc.Status = JobStatus.Done; - doc.Description = "recognize the result: " + ocr_status; - if (ocr_result.status == "000") + doc.Description = "recognize the result: " + ocrStatus; + if (ocrResult.Status == "000") { - var content = _serializer.Serialize(ocr_result.results); + var content = _serializer.Serialize(ocrResult.Results); doc!.Content = content; } @@ -99,7 +91,7 @@ public async Task Recognition(int id, CancellationToken cancellationToken) DocumentCacheKey.SharedExpiryTokenSource().Cancel(); _timer.Stop(); var elapsedMilliseconds = _timer.ElapsedMilliseconds; - _logger.LogInformation("Id: {id}, elapsed: {elapsedMilliseconds}, recognize the result: {@result},{@content}", id, elapsedMilliseconds, ocr_result, doc.Content); + _logger.LogInformation("Id: {Id}, elapsed: {ElapsedMilliseconds}, recognize the result: {@Result},{@Content}", id, elapsedMilliseconds, ocrResult, doc.Content); } @@ -107,7 +99,7 @@ public async Task Recognition(int id, CancellationToken cancellationToken) } catch (Exception ex) { - _logger.LogError(ex, $"{id}: recognize error {ex.Message}"); + _logger.LogError(ex, "{Id}: recognize error {ExMessage}", id, ex.Message); } } @@ -120,11 +112,11 @@ class result public string text { get; set; } = String.Empty; public List text_region { get; set; } = new(); } -class ocr_result +class OcrResult { - public string msg { get; set; } = String.Empty; - public List results { get; set; } = new(); - public string status { get; set; }=String.Empty; + public string Msg { get; set; } = String.Empty; + public List Results { get; set; } = new(); + public string Status { get; set; }=String.Empty; } diff --git a/src/Infrastructure/Services/Serialization/SystemTextJsonSerializer.cs b/src/Infrastructure/Services/Serialization/SystemTextJsonSerializer.cs index b9b0c92f3..1e65a7e74 100644 --- a/src/Infrastructure/Services/Serialization/SystemTextJsonSerializer.cs +++ b/src/Infrastructure/Services/Serialization/SystemTextJsonSerializer.cs @@ -1,7 +1,4 @@ -using System.Text.Encodings.Web; using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.Unicode; using CleanArchitecture.Blazor.Application.Common.Interfaces.Serialization; namespace CleanArchitecture.Blazor.Infrastructure.Services.Serialization; diff --git a/src/Infrastructure/Services/UploadService.cs b/src/Infrastructure/Services/UploadService.cs index 0b5e48521..a54838ab7 100644 --- a/src/Infrastructure/Services/UploadService.cs +++ b/src/Infrastructure/Services/UploadService.cs @@ -38,7 +38,7 @@ public async Task UploadAsync(UploadRequest request) } } - private static string _numberPattern = " ({0})"; + private static readonly string NumberPattern = " ({0})"; public static string NextAvailableFilename(string path) { @@ -48,10 +48,10 @@ public static string NextAvailableFilename(string path) // If path has extension then insert the number pattern just before the extension and return next filename if (Path.HasExtension(path)) - return GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path)), _numberPattern)); + return GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path)), NumberPattern)); // Otherwise just append the pattern to the path and return next filename - return GetNextFilename(path + _numberPattern); + return GetNextFilename(path + NumberPattern); } private static string GetNextFilename(string pattern) diff --git a/src/Infrastructure/_Imports.cs b/src/Infrastructure/_Imports.cs index a588460fa..91990d4ff 100644 --- a/src/Infrastructure/_Imports.cs +++ b/src/Infrastructure/_Imports.cs @@ -9,20 +9,13 @@ global using Microsoft.Extensions.Logging; global using Microsoft.AspNetCore.Identity.EntityFrameworkCore; global using Microsoft.EntityFrameworkCore; -global using CleanArchitecture.Blazor.Domain; global using CleanArchitecture.Blazor.Domain.Common; global using CleanArchitecture.Blazor.Domain.Entities; global using CleanArchitecture.Blazor.Domain.Entities.Audit; -global using CleanArchitecture.Blazor.Domain.Entities.Log; global using CleanArchitecture.Blazor.Infrastructure.Persistence.Extensions; -global using CleanArchitecture.Blazor.Application.Common.Exceptions; global using CleanArchitecture.Blazor.Application.Common.Models; global using CleanArchitecture.Blazor.Application.Common.Interfaces; global using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity; -global using CleanArchitecture.Blazor.Application.Settings; -global using CleanArchitecture.Blazor.Application.Configurations; -global using CleanArchitecture.Blazor.Infrastructure.Constants; -global using CleanArchitecture.Blazor.Application.Constants; global using CleanArchitecture.Blazor.Domain.Identity; global using CleanArchitecture.Blazor.Infrastructure.Middlewares; global using CleanArchitecture.Blazor.Infrastructure.Persistence; diff --git a/tests/Application.IntegrationTests/KeyValues/Commands/AddEditKeyValueCommandTests.cs b/tests/Application.IntegrationTests/KeyValues/Commands/AddEditKeyValueCommandTests.cs index e32306c8a..8c3c551ab 100644 --- a/tests/Application.IntegrationTests/KeyValues/Commands/AddEditKeyValueCommandTests.cs +++ b/tests/Application.IntegrationTests/KeyValues/Commands/AddEditKeyValueCommandTests.cs @@ -1,13 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; -using CleanArchitecture.Blazor.Application.Common.Exceptions; +using System.Threading.Tasks; using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.AddEdit; -using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.Delete; using CleanArchitecture.Blazor.Domain.Entities; +using CleanArchitecture.Blazor.Domain.Enums; using FluentAssertions; using NUnit.Framework; @@ -27,11 +21,11 @@ public void ShouldThrowValidationException() [Test] public async Task InsertItem() { - var addcommand = new AddEditKeyValueCommand() { Name= Domain.Picklist.Brand, Text="Test",Value="Test",Description= "Description" }; - var result = await SendAsync(addcommand); + var addCommand = new AddEditKeyValueCommand() { Name= Picklist.Brand, Text="Test",Value="Test",Description= "Description" }; + var result = await SendAsync(addCommand); var find = await FindAsync(result.Data); find.Should().NotBeNull(); - find.Name.Should().Be(Domain.Picklist.Brand); + find.Name.Should().Be(Picklist.Brand); find.Text.Should().Be("Test"); find.Value.Should().Be("Test"); @@ -39,14 +33,14 @@ public async Task InsertItem() [Test] public async Task UpdateItem() { - var addcommand = new AddEditKeyValueCommand() { Name = Domain.Picklist.Brand, Text = "Test", Value = "Test", Description = "Description" }; - var result = await SendAsync(addcommand); + var addCommand = new AddEditKeyValueCommand() { Name = Picklist.Brand, Text = "Test", Value = "Test", Description = "Description" }; + var result = await SendAsync(addCommand); var find = await FindAsync(result.Data); - var editcommand = new AddEditKeyValueCommand() { Id=find.Id, Name = Domain.Picklist.Brand, Text = "Test1", Value = "Test1", Description = "Description1" }; - await SendAsync(editcommand); + var editCommand = new AddEditKeyValueCommand() { Id=find.Id, Name = Picklist.Brand, Text = "Test1", Value = "Test1", Description = "Description1" }; + await SendAsync(editCommand); var updated = await FindAsync(find.Id); updated.Should().NotBeNull(); - updated.Name.Should().Be(Domain.Picklist.Brand); + updated.Name.Should().Be(Picklist.Brand); updated.Text.Should().Be("Test1"); updated.Value.Should().Be("Test1"); updated.Description.Should().Be("Description1"); diff --git a/tests/Application.IntegrationTests/KeyValues/Commands/DeleteKeyValueTests.cs b/tests/Application.IntegrationTests/KeyValues/Commands/DeleteKeyValueTests.cs index bf39c3357..5676568bd 100644 --- a/tests/Application.IntegrationTests/KeyValues/Commands/DeleteKeyValueTests.cs +++ b/tests/Application.IntegrationTests/KeyValues/Commands/DeleteKeyValueTests.cs @@ -1,14 +1,13 @@ - -using FluentAssertions; using System.Threading.Tasks; -using NUnit.Framework; -using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.Delete; -using CleanArchitecture.Blazor.Application.Common.Exceptions; +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.AddEdit; +using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.Delete; using CleanArchitecture.Blazor.Domain.Entities; -using CleanArchitecture.Blazor.Domain; +using CleanArchitecture.Blazor.Domain.Enums; +using FluentAssertions; +using NUnit.Framework; -namespace CleanArchitecture.Application.IntegrationTests.KeyValues.Commands +namespace CleanArchitecture.Blazor.Application.IntegrationTests.KeyValues.Commands { using static Testing; @@ -26,14 +25,14 @@ public void ShouldRequireValidKeyValueId() [Test] public async Task ShouldDeleteKeyValue() { - var addcommand = new AddEditKeyValueCommand() + var addCommand = new AddEditKeyValueCommand() { Name = Picklist.Brand, Text= "Word", Value = "Word", Description = "For Test" }; - var result= await SendAsync(addcommand); + var result= await SendAsync(addCommand); await SendAsync(new DeleteKeyValueCommand(new int[] { result.Data })); diff --git a/tests/Application.IntegrationTests/KeyValues/Queries/ExportKeyValuesQueryTests.cs b/tests/Application.IntegrationTests/KeyValues/Queries/ExportKeyValuesQueryTests.cs index 100071e87..fbd147f1c 100644 --- a/tests/Application.IntegrationTests/KeyValues/Queries/ExportKeyValuesQueryTests.cs +++ b/tests/Application.IntegrationTests/KeyValues/Queries/ExportKeyValuesQueryTests.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; -using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.ByName; +using System.Threading.Tasks; using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.Export; using FluentAssertions; using NUnit.Framework; diff --git a/tests/Application.IntegrationTests/KeyValues/Queries/KeyValuesQueryTests.cs b/tests/Application.IntegrationTests/KeyValues/Queries/KeyValuesQueryTests.cs index 708fa32f4..29f3cd21e 100644 --- a/tests/Application.IntegrationTests/KeyValues/Queries/KeyValuesQueryTests.cs +++ b/tests/Application.IntegrationTests/KeyValues/Queries/KeyValuesQueryTests.cs @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.ByName; -using CleanArchitecture.Blazor.Domain; +using CleanArchitecture.Blazor.Domain.Enums; using FluentAssertions; using NUnit.Framework; -namespace CleanArchitecture.Application.IntegrationTests.KeyValues.Queries +namespace CleanArchitecture.Blazor.Application.IntegrationTests.KeyValues.Queries { using static Testing; public class KeyValuesQueryTests : TestBase diff --git a/tests/Application.IntegrationTests/KeyValues/Queries/KeyValuesWithPaginationQueryTests.cs b/tests/Application.IntegrationTests/KeyValues/Queries/KeyValuesWithPaginationQueryTests.cs index 20653d120..4a040948e 100644 --- a/tests/Application.IntegrationTests/KeyValues/Queries/KeyValuesWithPaginationQueryTests.cs +++ b/tests/Application.IntegrationTests/KeyValues/Queries/KeyValuesWithPaginationQueryTests.cs @@ -1,12 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; -using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.Export; +using System.Threading.Tasks; using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.PaginationQuery; using CleanArchitecture.Blazor.Domain.Entities; +using CleanArchitecture.Blazor.Domain.Enums; using NUnit.Framework; namespace CleanArchitecture.Blazor.Application.IntegrationTests.KeyValues.Queries; @@ -14,13 +9,13 @@ namespace CleanArchitecture.Blazor.Application.IntegrationTests.KeyValues.Querie internal class KeyValuesWithPaginationQueryTests: TestBase { [SetUp] - public async Task initData() + public async Task InitData() { - await AddAsync(new KeyValue() { Name = Domain.Picklist.Brand, Text = "Text1", Value = "Value1" ,Description= "Test Description" }); - await AddAsync(new KeyValue() { Name = Domain.Picklist.Brand, Text = "Text2", Value = "Value2", Description = "Test Description" }); - await AddAsync(new KeyValue() { Name = Domain.Picklist.Brand, Text = "Text3", Value = "Value3", Description = "Test Description" }); - await AddAsync(new KeyValue() { Name = Domain.Picklist.Brand, Text = "Text4", Value = "Value4", Description = "Test Description" }); - await AddAsync(new KeyValue() { Name = Domain.Picklist.Brand, Text = "Text5", Value = "Value5", Description = "Test Description" }); + await AddAsync(new KeyValue() { Name = Picklist.Brand, Text = "Text1", Value = "Value1" ,Description= "Test Description" }); + await AddAsync(new KeyValue() { Name = Picklist.Brand, Text = "Text2", Value = "Value2", Description = "Test Description" }); + await AddAsync(new KeyValue() { Name = Picklist.Brand, Text = "Text3", Value = "Value3", Description = "Test Description" }); + await AddAsync(new KeyValue() { Name = Picklist.Brand, Text = "Text4", Value = "Value4", Description = "Test Description" }); + await AddAsync(new KeyValue() { Name = Picklist.Brand, Text = "Text5", Value = "Value5", Description = "Test Description" }); } [Test] @@ -31,7 +26,7 @@ public async Task ShouldNotEmptyQuery() Assert.AreEqual(5, result.TotalItems); } [Test] - public async Task ShouldNotEmptyKewordQuery() + public async Task ShouldNotEmptyKeywordQuery() { var query = new KeyValuesWithPaginationQuery() { Keyword="1"}; var result = await SendAsync(query); diff --git a/tests/Application.IntegrationTests/Products/Commands/AddEditProductCommandTests.cs b/tests/Application.IntegrationTests/Products/Commands/AddEditProductCommandTests.cs index df9f4ac19..3481a8b92 100644 --- a/tests/Application.IntegrationTests/Products/Commands/AddEditProductCommandTests.cs +++ b/tests/Application.IntegrationTests/Products/Commands/AddEditProductCommandTests.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; -using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.AddEdit; +using System.Threading.Tasks; using CleanArchitecture.Blazor.Application.Features.Products.Commands.AddEdit; using CleanArchitecture.Blazor.Domain.Entities; using FluentAssertions; @@ -25,8 +19,8 @@ public void ShouldThrowValidationException() [Test] public async Task InsertItem() { - var addcommand = new AddEditProductCommand() { Name = "Test", Brand="Brand", Price=100m, Unit="EA", Description = "Description" }; - var result = await SendAsync(addcommand); + var addCommand = new AddEditProductCommand() { Name = "Test", Brand="Brand", Price=100m, Unit="EA", Description = "Description" }; + var result = await SendAsync(addCommand); var find = await FindAsync(result.Data); find.Should().NotBeNull(); find.Name.Should().Be("Test"); @@ -37,11 +31,11 @@ public async Task InsertItem() [Test] public async Task UpdateItem() { - var addcommand = new AddEditProductCommand() { Name = "Test", Brand = "Brand", Price = 100m, Unit = "EA", Description = "Description" }; - var result = await SendAsync(addcommand); + var addCommand = new AddEditProductCommand() { Name = "Test", Brand = "Brand", Price = 100m, Unit = "EA", Description = "Description" }; + var result = await SendAsync(addCommand); var find = await FindAsync(result.Data); - var editcommand = new AddEditProductCommand() { Id = find.Id, Name = "Test1", Brand = "Brand1", Price =200m, Unit = "KG", Pictures= addcommand.Pictures, Description = "Description1" }; - await SendAsync(editcommand); + var editCommand = new AddEditProductCommand() { Id = find.Id, Name = "Test1", Brand = "Brand1", Price =200m, Unit = "KG", Pictures= addCommand.Pictures, Description = "Description1" }; + await SendAsync(editCommand); var updated = await FindAsync(find.Id); updated.Should().NotBeNull(); updated.Id.Should().Be(find.Id); diff --git a/tests/Application.IntegrationTests/Products/Commands/DeleteProductCommandTests.cs b/tests/Application.IntegrationTests/Products/Commands/DeleteProductCommandTests.cs index 373dcfb8b..3ea56f156 100644 --- a/tests/Application.IntegrationTests/Products/Commands/DeleteProductCommandTests.cs +++ b/tests/Application.IntegrationTests/Products/Commands/DeleteProductCommandTests.cs @@ -1,12 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Linq; using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; -using CleanArchitecture.Blazor.Application.Common.Exceptions; -using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.AddEdit; -using CleanArchitecture.Blazor.Application.Features.KeyValues.Commands.Delete; +using CleanArchitecture.Blazor.Application.Common.ExceptionHandlers; using CleanArchitecture.Blazor.Application.Features.Products.Commands.AddEdit; using CleanArchitecture.Blazor.Application.Features.Products.Commands.Delete; using CleanArchitecture.Blazor.Application.Features.Products.Queries.GetAll; @@ -30,8 +24,8 @@ public void ShouldRequireValidKeyValueId() [Test] public async Task ShouldDeleteOne() { - var addcommand = new AddEditProductCommand() { Name = "Test", Brand = "Brand", Price = 100m, Unit = "EA", Description = "Description" }; - var result = await SendAsync(addcommand); + var addCommand = new AddEditProductCommand() { Name = "Test", Brand = "Brand", Price = 100m, Unit = "EA", Description = "Description" }; + var result = await SendAsync(addCommand); await SendAsync(new DeleteProductCommand(new int[] { result.Data })); @@ -57,8 +51,8 @@ public async Task ShouldDeleteAll() var deleted = await SendAsync(new DeleteProductCommand(id)); deleted.Succeeded.Should().BeTrue(); - var deleteresult = await SendAsync(query); - deleteresult.Should().BeNullOrEmpty(); + var deleteResult = await SendAsync(query); + deleteResult.Should().BeNullOrEmpty(); } diff --git a/tests/Application.IntegrationTests/Products/Commands/ImportProductsCommandTests.cs b/tests/Application.IntegrationTests/Products/Commands/ImportProductsCommandTests.cs index 81bbb27e7..93782745a 100644 --- a/tests/Application.IntegrationTests/Products/Commands/ImportProductsCommandTests.cs +++ b/tests/Application.IntegrationTests/Products/Commands/ImportProductsCommandTests.cs @@ -1,11 +1,6 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; +using System.IO; using System.Reflection; -using System.Text; using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; using CleanArchitecture.Blazor.Application.Features.Products.Commands.Import; using FluentAssertions; using NUnit.Framework; @@ -27,8 +22,8 @@ public async Task DownloadTemplate() public async Task ImportDataFromExcel() { var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - var excelfile = Path.Combine(dir,"../../../", "Products", "ImportExcel", "Products.xlsx"); - var data = File.ReadAllBytes(excelfile); + var excelFile = Path.Combine(dir,"../../../", "Products", "ImportExcel", "Products.xlsx"); + var data = File.ReadAllBytes(excelFile); var cmd = new ImportProductsCommand("Products.xlsx", data); var result = await SendAsync(cmd); result.Succeeded.Should().BeTrue(); diff --git a/tests/Application.IntegrationTests/Products/Queries/ExportProductsQueryTests.cs b/tests/Application.IntegrationTests/Products/Queries/ExportProductsQueryTests.cs index 4c2ecbd25..6589d3bba 100644 --- a/tests/Application.IntegrationTests/Products/Queries/ExportProductsQueryTests.cs +++ b/tests/Application.IntegrationTests/Products/Queries/ExportProductsQueryTests.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; -using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.Export; +using System.Threading.Tasks; using CleanArchitecture.Blazor.Application.Features.Products.Queries.Export; using FluentAssertions; using NUnit.Framework; diff --git a/tests/Application.IntegrationTests/Products/Queries/GetAllProductsQueryTests.cs b/tests/Application.IntegrationTests/Products/Queries/GetAllProductsQueryTests.cs index 599276972..39ef23686 100644 --- a/tests/Application.IntegrationTests/Products/Queries/GetAllProductsQueryTests.cs +++ b/tests/Application.IntegrationTests/Products/Queries/GetAllProductsQueryTests.cs @@ -1,13 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Linq; using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; -using CleanArchitecture.Blazor.Application.Features.Products.Queries.Export; using CleanArchitecture.Blazor.Application.Features.Products.Queries.GetAll; using CleanArchitecture.Blazor.Domain.Entities; -using FluentAssertions; using NUnit.Framework; namespace CleanArchitecture.Blazor.Application.IntegrationTests.Products.Queries; @@ -35,8 +29,8 @@ public async Task ShouldQueryById() var query = new GetAllProductsQuery(); var result = await SendAsync(query); var id= result.Last().Id; - var productquery = new GetProductQuery() { Id = id }; - var product = await SendAsync(productquery); + var getProductQuery = new GetProductQuery() { Id = id }; + var product = await SendAsync(getProductQuery); Assert.AreEqual(id, product.Id); } } diff --git a/tests/Application.IntegrationTests/Products/Queries/ProductsPaginationQueryTests.cs b/tests/Application.IntegrationTests/Products/Queries/ProductsPaginationQueryTests.cs index cd9726928..e1cda6786 100644 --- a/tests/Application.IntegrationTests/Products/Queries/ProductsPaginationQueryTests.cs +++ b/tests/Application.IntegrationTests/Products/Queries/ProductsPaginationQueryTests.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; -using CleanArchitecture.Blazor.Application.Features.KeyValues.Queries.PaginationQuery; +using System.Threading.Tasks; using CleanArchitecture.Blazor.Application.Features.Products.Queries.Pagination; using CleanArchitecture.Blazor.Domain.Entities; using NUnit.Framework; @@ -30,7 +24,7 @@ public async Task ShouldNotEmptyQuery() Assert.AreEqual(5, result.TotalItems); } [Test] - public async Task ShouldNotEmptyKewordQuery() + public async Task ShouldNotEmptyKeywordQuery() { var query = new ProductsWithPaginationQuery() { Keyword = "1" }; var result = await SendAsync(query); diff --git a/tests/Application.IntegrationTests/Services/PicklistServiceTests.cs b/tests/Application.IntegrationTests/Services/PicklistServiceTests.cs index b6f6c4d06..8e50dd892 100644 --- a/tests/Application.IntegrationTests/Services/PicklistServiceTests.cs +++ b/tests/Application.IntegrationTests/Services/PicklistServiceTests.cs @@ -1,11 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Linq; using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; -using CleanArchitecture.Blazor.Application.Features.Products.Queries.Export; using CleanArchitecture.Blazor.Domain.Entities; +using CleanArchitecture.Blazor.Domain.Enums; using NUnit.Framework; namespace CleanArchitecture.Blazor.Application.IntegrationTests.Services; @@ -15,10 +11,10 @@ public class PicklistServiceTests : TestBase [SetUp] public async Task InitData() { - await AddAsync(new KeyValue() { Name = Domain.Picklist.Brand, Text="Text1",Value="Value1" }); - await AddAsync(new KeyValue() { Name = Domain.Picklist.Brand, Text = "Text2", Value = "Value2" }); - await AddAsync(new KeyValue() { Name = Domain.Picklist.Brand, Text = "Text3", Value = "Value3" }); - await AddAsync(new KeyValue() { Name = Domain.Picklist.Brand, Text = "Text4", Value = "Value4" }); + await AddAsync(new KeyValue() { Name = Picklist.Brand, Text="Text1",Value="Value1" }); + await AddAsync(new KeyValue() { Name = Picklist.Brand, Text = "Text2", Value = "Value2" }); + await AddAsync(new KeyValue() { Name = Picklist.Brand, Text = "Text3", Value = "Value3" }); + await AddAsync(new KeyValue() { Name = Picklist.Brand, Text = "Text4", Value = "Value4" }); } [Test] public async Task ShouldLoadDataSource() @@ -32,7 +28,7 @@ public async Task ShouldLoadDataSource() [Test] public async Task ShouldUpdateDataSource() { - await AddAsync(new KeyValue() { Name = Domain.Picklist.Brand, Text = "Text5", Value = "Value5" }); + await AddAsync(new KeyValue() { Name = Picklist.Brand, Text = "Text5", Value = "Value5" }); var picklist = CreatePicklistService(); await picklist.Refresh(); var count = picklist.DataSource.Count(); diff --git a/tests/Application.IntegrationTests/Services/TenantsServiceTests.cs b/tests/Application.IntegrationTests/Services/TenantsServiceTests.cs index 1e55ffd07..109ead680 100644 --- a/tests/Application.IntegrationTests/Services/TenantsServiceTests.cs +++ b/tests/Application.IntegrationTests/Services/TenantsServiceTests.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Linq; using System.Threading.Tasks; -using CleanArchitecture.Application.IntegrationTests; -using CleanArchitecture.Blazor.Application.Features.Products.Queries.Export; using CleanArchitecture.Blazor.Domain.Entities; using NUnit.Framework; diff --git a/tests/Application.IntegrationTests/TestBase.cs b/tests/Application.IntegrationTests/TestBase.cs index e4bb3f59c..ae87bd6a6 100644 --- a/tests/Application.IntegrationTests/TestBase.cs +++ b/tests/Application.IntegrationTests/TestBase.cs @@ -1,7 +1,7 @@ -using NUnit.Framework; -using System.Threading.Tasks; +using System.Threading.Tasks; +using NUnit.Framework; -namespace CleanArchitecture.Application.IntegrationTests +namespace CleanArchitecture.Blazor.Application.IntegrationTests { using static Testing; diff --git a/tests/Application.IntegrationTests/Testing.cs b/tests/Application.IntegrationTests/Testing.cs index 90d4cc93f..d073bc459 100644 --- a/tests/Application.IntegrationTests/Testing.cs +++ b/tests/Application.IntegrationTests/Testing.cs @@ -1,9 +1,12 @@ -using CleanArchitecture.Blazor.Application; +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; using CleanArchitecture.Blazor.Application.Common.Interfaces; using CleanArchitecture.Blazor.Application.Common.Interfaces.MultiTenant; +using CleanArchitecture.Blazor.Domain.Identity; using CleanArchitecture.Blazor.Infrastructure; using CleanArchitecture.Blazor.Infrastructure.Extensions; -using CleanArchitecture.Blazor.Domain.Identity; using CleanArchitecture.Blazor.Infrastructure.Persistence; using MediatR; using Microsoft.AspNetCore.Hosting; @@ -15,10 +18,8 @@ using NUnit.Framework; using Respawn; using Respawn.Graph; -using System; -using System.IO; -using System.Linq; -using System.Threading.Tasks; + +namespace CleanArchitecture.Blazor.Application.IntegrationTests; [SetUpFixture] public class Testing @@ -49,7 +50,7 @@ public async Task RunBeforeAnyTests() w.ApplicationName == "Blazor.Server.UI")); services.AddInfrastructureServices(_configuration) - .AddApplicationServices(); + .AddApplicationServices(); //services.AddLogging(); @@ -193,4 +194,4 @@ public static ITenantService CreateTenantsService() public void RunAfterAnyTests() { } -} +} \ No newline at end of file diff --git a/tests/Application.UnitTests/Common/Behaviours/RequestLoggerTests.cs b/tests/Application.UnitTests/Common/Behaviours/RequestLoggerTests.cs index 385c4126c..273564e0e 100644 --- a/tests/Application.UnitTests/Common/Behaviours/RequestLoggerTests.cs +++ b/tests/Application.UnitTests/Common/Behaviours/RequestLoggerTests.cs @@ -1,3 +1,5 @@ +using System.Threading; +using System.Threading.Tasks; using CleanArchitecture.Blazor.Application.Common.Behaviours; using CleanArchitecture.Blazor.Application.Common.Interfaces; using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity; @@ -5,8 +7,6 @@ using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; -using System.Threading; -using System.Threading.Tasks; namespace CleanArchitecture.Blazor.Application.UnitTests.Common.Behaviours; diff --git a/tests/Application.UnitTests/Common/Exceptions/ValidationExceptionTests.cs b/tests/Application.UnitTests/Common/Exceptions/ValidationExceptionTests.cs index 428a129b5..333e8858b 100644 --- a/tests/Application.UnitTests/Common/Exceptions/ValidationExceptionTests.cs +++ b/tests/Application.UnitTests/Common/Exceptions/ValidationExceptionTests.cs @@ -1,9 +1,8 @@ -using CleanArchitecture.Blazor.Application.Common.Exceptions; +using System.Collections.Generic; using FluentAssertions; using FluentValidation; using FluentValidation.Results; using NUnit.Framework; -using System.Collections.Generic; namespace CleanArchitecture.Blazor.Application.UnitTests.Common.Exceptions; @@ -26,7 +25,7 @@ public void SingleValidationFailureCreatesASingleElementErrorDictionary() } [Test] - public void MulitpleValidationFailureForMultiplePropertiesCreatesAMultipleElementErrorDictionaryEachWithMultipleValues() + public void MultipleValidationFailureForMultiplePropertiesCreatesAMultipleElementErrorDictionaryEachWithMultipleValues() { var failures = new List { diff --git a/tests/Application.UnitTests/Common/Mappings/MappingTests.cs b/tests/Application.UnitTests/Common/Mappings/MappingTests.cs index 8365de9ec..332378af8 100644 --- a/tests/Application.UnitTests/Common/Mappings/MappingTests.cs +++ b/tests/Application.UnitTests/Common/Mappings/MappingTests.cs @@ -1,14 +1,13 @@ +using System; +using System.Runtime.Serialization; using AutoMapper; using CleanArchitecture.Blazor.Application.Common.Mappings; +using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; using CleanArchitecture.Blazor.Application.Features.Documents.DTOs; -using CleanArchitecture.Blazor.Application.Features.Products.DTOs; using CleanArchitecture.Blazor.Application.Features.KeyValues.DTOs; +using CleanArchitecture.Blazor.Application.Features.Products.DTOs; using CleanArchitecture.Blazor.Domain.Entities; - using NUnit.Framework; -using System; -using System.Runtime.Serialization; -using CleanArchitecture.Blazor.Application.Features.Customers.DTOs; namespace CleanArchitecture.Blazor.Application.UnitTests.Common.Mappings; diff --git a/tests/Application.UnitTests/Constants/ConstantStringTests.cs b/tests/Application.UnitTests/Constants/ConstantStringTests.cs index d678dcece..760b0f802 100644 --- a/tests/Application.UnitTests/Constants/ConstantStringTests.cs +++ b/tests/Application.UnitTests/Constants/ConstantStringTests.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using CleanArchitecture.Blazor.Application.Constants; +using CleanArchitecture.Blazor.Application.Constants; using NUnit.Framework; namespace CleanArchitecture.Blazor.Application.UnitTests.Constants; @@ -12,35 +7,35 @@ public class ConstantStringTests [Test] public void Test() { - Assert.AreEqual("Refresh", ConstantString.REFRESH); - Assert.AreEqual("Edit", ConstantString.EDIT); - Assert.AreEqual("Delete", ConstantString.DELETE); - Assert.AreEqual("Add", ConstantString.ADD); - Assert.AreEqual("Create", ConstantString.NEW); - Assert.AreEqual("Export to Excel", ConstantString.EXPORT); - Assert.AreEqual("Import from Excel", ConstantString.IMPORT); - Assert.AreEqual("Actions", ConstantString.ACTIONS); - Assert.AreEqual("Save", ConstantString.SAVE); - Assert.AreEqual("Save Changes", ConstantString.SAVECHANGES); - Assert.AreEqual("Cancel", ConstantString.CANCEL); - Assert.AreEqual("Close", ConstantString.CLOSE); - Assert.AreEqual("Search", ConstantString.SEARCH); - Assert.AreEqual("Clear", ConstantString.CLEAR); - Assert.AreEqual("Reset", ConstantString.RESET); - Assert.AreEqual("OK", ConstantString.OK); - Assert.AreEqual("Confirm", ConstantString.CONFIRM); - Assert.AreEqual("Yes", ConstantString.YES); - Assert.AreEqual("No", ConstantString.NO); - Assert.AreEqual("Next", ConstantString.NEXT); - Assert.AreEqual("Previous", ConstantString.PREVIOUS); - Assert.AreEqual("Upload", ConstantString.UPLOAD); - Assert.AreEqual("Download", ConstantString.DOWNLOAD); - Assert.AreEqual("Uploading...", ConstantString.UPLOADING); - Assert.AreEqual("Downloading...", ConstantString.DOWNLOADING); - Assert.AreEqual("No Allowed", ConstantString.NOALLOWED); - Assert.AreEqual("Sign in with {0}", ConstantString.SIGNINWITH); - Assert.AreEqual("Logout", ConstantString.LOGOUT); - Assert.AreEqual("Sign In", ConstantString.SIGNIN); + Assert.AreEqual("Refresh", ConstantString.Refresh); + Assert.AreEqual("Edit", ConstantString.Edit); + Assert.AreEqual("Delete", ConstantString.Delete); + Assert.AreEqual("Add", ConstantString.Add); + Assert.AreEqual("Create", ConstantString.New); + Assert.AreEqual("Export to Excel", ConstantString.Export); + Assert.AreEqual("Import from Excel", ConstantString.Import); + Assert.AreEqual("Actions", ConstantString.Actions); + Assert.AreEqual("Save", ConstantString.Save); + Assert.AreEqual("Save Changes", ConstantString.SaveChanges); + Assert.AreEqual("Cancel", ConstantString.Cancel); + Assert.AreEqual("Close", ConstantString.Close); + Assert.AreEqual("Search", ConstantString.Search); + Assert.AreEqual("Clear", ConstantString.Clear); + Assert.AreEqual("Reset", ConstantString.Reset); + Assert.AreEqual("OK", ConstantString.Ok); + Assert.AreEqual("Confirm", ConstantString.Confirm); + Assert.AreEqual("Yes", ConstantString.Yes); + Assert.AreEqual("No", ConstantString.No); + Assert.AreEqual("Next", ConstantString.Next); + Assert.AreEqual("Previous", ConstantString.Previous); + Assert.AreEqual("Upload", ConstantString.Upload); + Assert.AreEqual("Download", ConstantString.Download); + Assert.AreEqual("Uploading...", ConstantString.Uploading); + Assert.AreEqual("Downloading...", ConstantString.Downloading); + Assert.AreEqual("No Allowed", ConstantString.NoAllowed); + Assert.AreEqual("Sign in with {0}", ConstantString.SigninWith); + Assert.AreEqual("Logout", ConstantString.Logout); + Assert.AreEqual("Sign In", ConstantString.Signin); Assert.AreEqual("Microsoft", ConstantString.Microsoft); Assert.AreEqual("Facebook", ConstantString.Facebook); Assert.AreEqual("Google", ConstantString.Google); diff --git a/tests/Domain.UnitTests/ValueObjects/ColourTests.cs b/tests/Domain.UnitTests/ValueObjects/ColourTests.cs index ff008664a..4a1355737 100644 --- a/tests/Domain.UnitTests/ValueObjects/ColourTests.cs +++ b/tests/Domain.UnitTests/ValueObjects/ColourTests.cs @@ -13,7 +13,7 @@ public class ColourTests [Test] public void ShouldReturnCorrectColourCode() { - var code = "#FFFFFF"; + const string code = "#FFFFFF"; var colour = Colour.From(code);