Skip to content

Commit

Permalink
Refactor async methods and improve code formatting
Browse files Browse the repository at this point in the history
Updated various async methods by refactoring code for improved readability and consistency. This includes changing types from IReadOnlyDictionary to Dictionary in a few places, handling stream operations with 'await using', and ensuring consistent formatting and indentation across the code. Additionally, enhanced error handling in file operations and addressed deprecated synchronous calls by transitioning to asynchronous patterns.
  • Loading branch information
pavelbannov committed Dec 8, 2024
1 parent 421ed69 commit c1148e2
Show file tree
Hide file tree
Showing 72 changed files with 369 additions and 441 deletions.
4 changes: 2 additions & 2 deletions common/ASC.ActiveDirectory/Base/Data/LdapLogin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public static LdapLogin ParseLogin(string login)
string username;
string domain = null;

if (login.Contains("\\"))
if (login.Contains('\\'))
{
var splited = login.Split('\\');

Expand All @@ -58,7 +58,7 @@ public static LdapLogin ParseLogin(string login)
username = splited[1];

}
else if (login.Contains("@"))
else if (login.Contains('@'))
{
var splited = login.Split('@');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ public async Task<UserInfo> ToUserInfoAsync(LdapObject ldapUser, LdapUserImporte

if (string.IsNullOrEmpty(mail))
{
user.Email = userName.Contains("@") ? userName : string.Format("{0}@{1}", userName, ldapUserImporter.LDAPDomain);
user.Email = userName.Contains('@') ? userName : string.Format("{0}@{1}", userName, ldapUserImporter.LDAPDomain);
user.ActivationStatus = EmployeeActivationStatus.AutoGenerated;
}
else
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.ActiveDirectory/Base/LdapUserImporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -721,7 +721,7 @@ public async Task<List<Tuple<UserInfo, LdapObject>>> FindLdapUsersAsync(string l

string email = null;

if (!string.IsNullOrEmpty(Settings.MailAttribute) && !string.IsNullOrEmpty(ldapLogin.Domain) && login.Contains("@"))
if (!string.IsNullOrEmpty(Settings.MailAttribute) && !string.IsNullOrEmpty(ldapLogin.Domain) && login.Contains('@'))
{
email = ldapLogin.ToString();
exps.Add(Expression.Equal(Settings.MailAttribute, email));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,13 @@ public static class LdapUserMapping
{
public static readonly List<string> Fields =
[
Enum.GetName(typeof(LdapItemChangeKey), LdapItemChangeKey.FirstName),
Enum.GetName(typeof(LdapItemChangeKey), LdapItemChangeKey.LastName),
Enum.GetName(typeof(LdapItemChangeKey), LdapItemChangeKey.Mail),
Enum.GetName(typeof(LdapItemChangeKey), LdapItemChangeKey.Phone),
Enum.GetName(typeof(LdapItemChangeKey), LdapItemChangeKey.Title),
Enum.GetName(typeof(LdapItemChangeKey), LdapItemChangeKey.Location),
Enum.GetName(typeof(LdapItemChangeKey), LdapItemChangeKey.Sid),
Enum.GetName(typeof(LdapItemChangeKey), LdapItemChangeKey.Member)
Enum.GetName(LdapItemChangeKey.FirstName),
Enum.GetName(LdapItemChangeKey.LastName),
Enum.GetName(LdapItemChangeKey.Mail),
Enum.GetName(LdapItemChangeKey.Phone),
Enum.GetName(LdapItemChangeKey.Title),
Enum.GetName(LdapItemChangeKey.Location),
Enum.GetName(LdapItemChangeKey.Sid),
Enum.GetName(LdapItemChangeKey.Member)
];
}
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ protected override async Task DoJob()
case LdapOperationType.Save:
case LdapOperationType.SaveTest:

logger.InfoStartOperation(Enum.GetName(typeof(LdapOperationType), _operationType));
logger.InfoStartOperation(Enum.GetName(_operationType));

await SetProgress(1, _resource.LdapSettingsStatusCheckingLdapSettings);

Expand Down Expand Up @@ -180,7 +180,7 @@ protected override async Task DoJob()
break;
case LdapOperationType.Sync:
case LdapOperationType.SyncTest:
logger.InfoStartOperation(Enum.GetName(typeof(LdapOperationType), _operationType));
logger.InfoStartOperation(Enum.GetName(_operationType));

_novellLdapUserImporter.Init(_ldapSettings, _resource);
break;
Expand Down Expand Up @@ -570,7 +570,7 @@ private async Task GiveUsersRights(Dictionary<LdapSettings.AccessRight, string>

var cleared = false;

foreach (var r in Enum.GetValues(typeof(LdapSettings.AccessRight)).Cast<LdapSettings.AccessRight>())
foreach (var r in Enum.GetValues<LdapSettings.AccessRight>())
{
var prodId = LdapSettings.AccessRightsGuids[r];

Expand Down
6 changes: 3 additions & 3 deletions common/ASC.ActiveDirectory/LdapUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public static bool IsLoginAccepted(LdapLogin ldapLogin, UserInfo ldapUser, strin
return false;
}

var alterEmail = ldapUser.UserName.Contains("@")
var alterEmail = ldapUser.UserName.Contains('@')
? ldapUser.UserName
: string.Format("{0}@{1}", ldapUser.UserName, ldapDomain);

Expand All @@ -102,7 +102,7 @@ private static string GetLdapAccessableEmail(string email)
return email;
}

var dotIndex = login.Domain.LastIndexOf(".", StringComparison.Ordinal);
var dotIndex = login.Domain.LastIndexOf('.');

var accessableEmail = dotIndex > -1 ? string.Format("{0}@{1}", login.Username, login.Domain.Remove(dotIndex)) : email;

Expand Down Expand Up @@ -185,7 +185,7 @@ public static string GetUserInfoString(this UserInfo userInfo)
userInfo.Title,
userInfo.Location,
userInfo.GetContactsString(),
Enum.GetName(typeof(EmployeeStatus), userInfo.Status));
Enum.GetName(userInfo.Status));
}

public static string UnescapeLdapString(string ldapString)
Expand Down
12 changes: 6 additions & 6 deletions common/ASC.ActiveDirectory/Novell/NovellLdapHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,14 +180,14 @@ public override List<LdapObject> GetUsers(string filter = null, int limit = -1)

try
{
if (!string.IsNullOrEmpty(Settings.UserFilter) && !Settings.UserFilter.StartsWith("(") &&
!Settings.UserFilter.EndsWith(")"))
if (!string.IsNullOrEmpty(Settings.UserFilter) && !Settings.UserFilter.StartsWith('(') &&
!Settings.UserFilter.EndsWith(')'))
{
Settings.UserFilter = string.Format("({0})", Settings.UserFilter);
}

if (!string.IsNullOrEmpty(filter) && !filter.StartsWith("(") &&
!filter.EndsWith(")"))
if (!string.IsNullOrEmpty(filter) && !filter.StartsWith('(') &&
!filter.EndsWith(')'))
{
filter = string.Format("({0})", Settings.UserFilter);
}
Expand Down Expand Up @@ -250,8 +250,8 @@ public override List<LdapObject> GetGroups(Criteria criteria = null)

try
{
if (!string.IsNullOrEmpty(Settings.GroupFilter) && !Settings.GroupFilter.StartsWith("(") &&
!Settings.GroupFilter.EndsWith(")"))
if (!string.IsNullOrEmpty(Settings.GroupFilter) && !Settings.GroupFilter.StartsWith('(') &&
!Settings.GroupFilter.EndsWith(')'))
{
Settings.GroupFilter = string.Format("({0})", Settings.GroupFilter);
}
Expand Down
9 changes: 2 additions & 7 deletions common/ASC.Api.Core/Auth/AuthorizationPolicyProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,9 @@
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode

namespace ASC.Api.Core.Auth;
public class AuthorizationPolicyProvider : IAuthorizationPolicyProvider
public class AuthorizationPolicyProvider(IOptions<AuthorizationOptions> options) : IAuthorizationPolicyProvider
{
public AuthorizationPolicyProvider(IOptions<AuthorizationOptions> options)
{
FallbackPolicyProvider = new DefaultAuthorizationPolicyProvider(options);
}

public DefaultAuthorizationPolicyProvider FallbackPolicyProvider { get; }
public DefaultAuthorizationPolicyProvider FallbackPolicyProvider { get; } = new(options);

public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
{
Expand Down
53 changes: 19 additions & 34 deletions common/ASC.Api.Core/Auth/JwtBearerAuthHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,38 +36,23 @@
namespace ASC.Api.Core.Auth;

[Scope]
public class JwtBearerAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
public class JwtBearerAuthHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
SecurityContext securityContext,
IHttpContextAccessor httpContextAccessor,
BaseCommonLinkUtility baseCommonLinkUtility,
IConfiguration configuration,
IHttpClientFactory httpClientFactory)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
private readonly SecurityContext _securityContext;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IConfiguration _configuration;
private readonly BaseCommonLinkUtility _linkUtility;
private readonly ILogger<JwtBearerAuthHandler> _logger;
private readonly IHttpClientFactory _httpClientFactory;

public JwtBearerAuthHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
SecurityContext securityContext,
IHttpContextAccessor httpContextAccessor,
BaseCommonLinkUtility baseCommonLinkUtility,
IConfiguration configuration,
IHttpClientFactory httpClientFactory)
: base(options, logger, encoder)
{
_securityContext = securityContext;
_httpContextAccessor = httpContextAccessor;
_configuration = configuration;
_linkUtility = baseCommonLinkUtility;
_logger = logger.CreateLogger<JwtBearerAuthHandler>();
_httpClientFactory = httpClientFactory;
}
private readonly ILogger<JwtBearerAuthHandler> _logger = logger.CreateLogger<JwtBearerAuthHandler>();

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var serverRootPath = _linkUtility.ServerRootPath;
var authority = _configuration["core:oidc:authority"];
var serverRootPath = baseCommonLinkUtility.ServerRootPath;
var authority = configuration["core:oidc:authority"];

if (string.IsNullOrEmpty(authority))
{
Expand All @@ -82,8 +67,8 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
var audience = serverRootPath;
var httpDocumentRetriever = new HttpDocumentRetriever();

var showPIIEnable = bool.TryParse(_configuration["core:oidc:showPII"], out var showPII) && showPII;
var requireHttpsEnable = bool.TryParse(_configuration["core:oidc:requireHttps"], out var requireHttps) && requireHttps;
var showPIIEnable = bool.TryParse(configuration["core:oidc:showPII"], out var showPII) && showPII;
var requireHttpsEnable = bool.TryParse(configuration["core:oidc:requireHttps"], out var requireHttps) && requireHttps;

IdentityModelEventSource.ShowPII = showPIIEnable;
httpDocumentRetriever.RequireHttps = requireHttpsEnable;
Expand All @@ -92,7 +77,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
new OpenIdConnectConfigurationRetriever(),
httpDocumentRetriever);

var accessToken = _httpContextAccessor?.HttpContext?.Request.Headers["Authorization"].ToString();
var accessToken = httpContextAccessor?.HttpContext?.Request.Headers["Authorization"].ToString();

if (string.IsNullOrEmpty(accessToken))
{
Expand All @@ -108,7 +93,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()

JwtSecurityToken validatedToken;

var validationTokenEnable = !(bool.TryParse(_configuration["core:oidc:disableValidateToken"], out var disableValidateToken) && disableValidateToken);
var validationTokenEnable = !(bool.TryParse(configuration["core:oidc:disableValidateToken"], out var disableValidateToken) && disableValidateToken);

if (validationTokenEnable)
{
Expand All @@ -135,7 +120,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()

try
{
await _securityContext.AuthenticateMeWithoutCookieAsync(userId, validatedToken.Claims.ToList());
await securityContext.AuthenticateMeWithoutCookieAsync(userId, validatedToken.Claims.ToList());
}
catch (Exception ex)
{
Expand Down Expand Up @@ -184,7 +169,7 @@ private async Task<JwtSecurityToken> ValidateToken(string token,
_ = new JwtSecurityTokenHandler()
.ValidateToken(token, validationParameters, out var rawValidatedToken);

var httpClient = _httpClientFactory.CreateClient();
var httpClient = httpClientFactory.CreateClient();

var response = await httpClient.IntrospectTokenAsync(new TokenIntrospectionRequest
{
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Common/Caching/RedisCacheNotify.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ private List<Action<T>> GetInvocationList(CacheNotifyAction action)
{
var result = new List<Action<T>>();

foreach (var val in (CacheNotifyAction[])Enum.GetValues(typeof(CacheNotifyAction)))
foreach (var val in Enum.GetValues<CacheNotifyAction>())
{
if (!(val == action || Enum.IsDefined(typeof(CacheNotifyAction), (val & action))))
{
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Common/Data/TypeExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static string GetFormattedName(this Type type)
var genericArguments = type.GetGenericArguments()
.Select(x => x.Name)
.Aggregate((x1, x2) => $"{x1}, {x2}");
return $"{type.Name[..type.Name.IndexOf("`")]}"
return $"{type.Name[..type.Name.IndexOf('`')]}"
+ $"<{genericArguments}>";
}
return type.Name;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,13 @@

namespace ASC.Common.Threading.DistributedLock.RedisLock;

public class RedisLockHandle : LockHandleBase
public class RedisLockHandle(IDistributedSynchronizationHandle handle) : LockHandleBase
{
private readonly IDistributedSynchronizationHandle _handle;

public RedisLockHandle(IDistributedSynchronizationHandle handle)
{
_handle = handle;
}

public override void Dispose()
{
CheckDispose();

_handle?.Dispose();
handle?.Dispose();

_disposed = true;
}
Expand All @@ -48,9 +41,9 @@ public override async ValueTask DisposeAsync()
{
CheckDispose();

if (_handle != null)
if (handle != null)
{
await _handle.DisposeAsync();
await handle.DisposeAsync();
}

_disposed = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,15 @@

namespace ASC.Common.Threading.DistributedLock.ZooKeeperLock;

public class ZooKeeperLockHandle : LockHandleBase
public class ZooKeeperLockHandle(IDistributedSynchronizationHandle handle) : LockHandleBase
{
private readonly IDistributedSynchronizationHandle _handle;

public ZooKeeperLockHandle(IDistributedSynchronizationHandle handle)
{
_handle = handle;
}

public override async ValueTask DisposeAsync()
{
CheckDispose();

if (_handle != null)
if (handle != null)
{
await _handle.DisposeAsync();
await handle.DisposeAsync();
}

_disposed = true;
Expand All @@ -51,7 +44,7 @@ public override void Dispose()
{
CheckDispose();

_handle?.Dispose();
handle?.Dispose();

_disposed = true;
}
Expand Down
15 changes: 4 additions & 11 deletions common/ASC.Common/Utils/SwaggerCustomDocumentFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,13 @@
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class HideRouteDocumentFilter : IDocumentFilter
public class HideRouteDocumentFilter(string routeToHide) : IDocumentFilter
{
private readonly string _routeToHide;

public HideRouteDocumentFilter(string RouteToHide)
{
_routeToHide = RouteToHide;
}

public void Apply(OpenApiDocument document, DocumentFilterContext context)
{
if (document.Paths.ContainsKey(_routeToHide))
if (document.Paths.ContainsKey(routeToHide))
{
document.Paths.Remove(_routeToHide);
document.Paths.Remove(routeToHide);
}
}
}
Expand All @@ -62,7 +55,7 @@ public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)

public class TagDescriptionsDocumentFilter : IDocumentFilter
{
private readonly Dictionary<string, string> _tagDescriptions = new Dictionary<string, string>
private readonly Dictionary<string, string> _tagDescriptions = new()
{
{ "People", "Operations for working with people" },
{ "Portal", "Operations for working with portal" },
Expand Down
11 changes: 3 additions & 8 deletions common/ASC.Common/Utils/SwaggerEnumFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,8 @@
namespace ASC.Api.Core.Extensions;

[AttributeUsage(AttributeTargets.All)]
public class SwaggerEnumAttribute : Attribute
public class SwaggerEnumAttribute(string description = null) : Attribute
{
public SwaggerEnumAttribute(string description = null)
{
Ignore = false;
Description = description;
}
public bool Ignore { get; set; }
public string Description { get; set; }
public bool Ignore { get; set; }
public string Description { get; set; } = description;
}
Loading

0 comments on commit c1148e2

Please sign in to comment.