Skip to content

Commit

Permalink
Refactor code to align with modern C# practices
Browse files Browse the repository at this point in the history
Updated switch statements to expression-bodied syntax, replaced IndexOf with Contains for readability, and leveraged pattern matching and simplified expressions where applicable. Additional minor adjustments include using `Lock` instead of `object` for thread-safety and improving header handling in HTTP context usage.
  • Loading branch information
pavelbannov committed Dec 11, 2024
1 parent 6f562da commit 487ca56
Show file tree
Hide file tree
Showing 76 changed files with 194 additions and 227 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ private List<string> GetContacts(LdapObject ldapUser, Mapping key, LdapSettings
return GetAttributes(ldapUser, bindings[0]);
}

private void PopulateContacts(ICollection<string> contacts, string type, List<string> values)
private static void PopulateContacts(List<string> contacts, string type, List<string> values)
{
if (values == null || values.Count == 0)
{
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 @@ -220,7 +220,7 @@ private async Task<List<UserInfo>> GetGroupUsersAsync(GroupInfo groupInfo, bool

const string GROUP_MEMBERSHIP = "groupMembership";

private IEnumerable<LdapObject> GetLdapUserGroups(LdapObject ldapUser)
private List<LdapObject> GetLdapUserGroups(LdapObject ldapUser)
{
var ldapUserGroups = new List<LdapObject>();
try
Expand Down
7 changes: 3 additions & 4 deletions common/ASC.ActiveDirectory/LdapUserManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,7 @@ private async Task<UserInfoAndLdapChangeCollectionWrapper> SyncLDAPUserAsync(Use
wrapper.LdapChangeCollection.SetSkipUserChange(ldapUserInfo);
}

logger.DebugSyncUserLdapFailedWithStatus(ldapUserInfo.Sid, ldapUserInfo.UserName,
Enum.GetName(typeof(EmployeeStatus), ldapUserInfo.Status));
logger.DebugSyncUserLdapFailedWithStatus(ldapUserInfo.Sid, ldapUserInfo.UserName, Enum.GetName(ldapUserInfo.Status));

return wrapper;
}
Expand Down Expand Up @@ -358,9 +357,9 @@ [new DirectRecipient(ldapUserInfo.Email, null, [ldapUserInfo.Email], false)],
private const string EXT_PHONE = "extphone";
private const string EXT_SKYPE = "extskype";

private static void UpdateLdapUserContacts(UserInfo ldapUser, IReadOnlyList<string> portalUserContacts)
private static void UpdateLdapUserContacts(UserInfo ldapUser, List<string> portalUserContacts)
{
if (portalUserContacts == null || !portalUserContacts.Any())
if (portalUserContacts == null || portalUserContacts.Count == 0)
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public string[] GetAttributeArrayValue(LdapEntry ldapEntry, string attributeName
return attribute?.StringValueArray;
}

private static string DecodeSid(IReadOnlyList<byte> sid)
private static string DecodeSid(byte[] sid)
{
var strSid = new StringBuilder("S-");

Expand All @@ -95,7 +95,7 @@ private static string DecodeSid(IReadOnlyList<byte> sid)
authority |= ((long)sid[i]) << (8 * (5 - (i - 2)));
}

strSid.Append("-");
strSid.Append('-');
strSid.Append(authority);

//iterate all the sub-auths
Expand All @@ -110,7 +110,7 @@ private static string DecodeSid(IReadOnlyList<byte> sid)
subAuthority |= (long)(sid[offset + k] & 0xFF) << (8 * k);
}

strSid.Append("-");
strSid.Append('-');
strSid.Append(subAuthority);

offset += size;
Expand Down
6 changes: 3 additions & 3 deletions common/ASC.ActiveDirectory/Novell/NovellLdapHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public override string SearchDomain()
{
var dn = capability.FirstOrDefault(dc =>
!string.IsNullOrEmpty(dc) &&
dc.IndexOf("dc=", StringComparison.InvariantCultureIgnoreCase) != -1);
dc.Contains("dc=", StringComparison.InvariantCultureIgnoreCase));

var domain = LdapUtils.DistinguishedNameToDomain(dn);

Expand All @@ -88,7 +88,7 @@ public override string SearchDomain()
{
var dn = capability1.FirstOrDefault(dc =>
!string.IsNullOrEmpty(dc) &&
dc.IndexOf("dc=", StringComparison.InvariantCultureIgnoreCase) != -1);
dc.Contains("dc=", StringComparison.InvariantCultureIgnoreCase));

var domain = LdapUtils.DistinguishedNameToDomain(dn);

Expand All @@ -102,7 +102,7 @@ public override string SearchDomain()
{
var dn = dnList.FirstOrDefault(dc =>
!string.IsNullOrEmpty(dc) &&
dc.IndexOf("dc=", StringComparison.InvariantCultureIgnoreCase) != -1);
dc.Contains("dc=", StringComparison.InvariantCultureIgnoreCase));

var domain = LdapUtils.DistinguishedNameToDomain(dn);

Expand Down
2 changes: 1 addition & 1 deletion common/ASC.ActiveDirectory/Novell/NovellLdapSearcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class NovellLdapSearcher(IConfiguration configuration,
{
protected readonly ILogger<NovellLdapSearcher> _logger = logger;
private LdapCertificateConfirmRequest _certificateConfirmRequest;
private static readonly object _rootSync = new();
private static readonly Lock _rootSync = new();
private LdapConnection _ldapConnection;

public string Login { get; private set; }
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Api.Core/Auth/AuthorizationExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static class AuthorizationExtension
{ "GET api/[0-9].[0-9]/people/@self", "accounts.self:read" },
{ "(POST|PUT|DELETE|UPDATE) api/[0-9].[0-9]/people/@self", "account.self:write" },
{ "GET api/[0-9].[0-9]/people", "accounts:read" },
{ "(POST|PUT|DELETE|UPDATE) api/[0-9].[0-9]/people", "accounts:write" },
{ "(POST|PUT|DELETE|UPDATE) api/[0-9].[0-9]/people", "accounts:write" }
};

private static readonly string[] _allScopes =
Expand Down
9 changes: 6 additions & 3 deletions common/ASC.Api.Core/Auth/BasicAuthHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

namespace ASC.Api.Core.Auth;

public class BasicAuthHandler(
public partial class BasicAuthHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
Expand All @@ -47,8 +47,8 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
}

// Get authorization key
var authorizationHeader = Request.Headers["Authorization"].ToString();
var authHeaderRegex = new Regex(@"Basic (.*)");
var authorizationHeader = Request.Headers.Authorization.ToString();
var authHeaderRegex = BasicRegex();

if (!authHeaderRegex.IsMatch(authorizationHeader))
{
Expand Down Expand Up @@ -79,4 +79,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()

return AuthenticateResult.Success(new AuthenticationTicket(Context.User, Scheme.Name));
}

[GeneratedRegex(@"Basic (.*)")]
private static partial Regex BasicRegex();
}
4 changes: 2 additions & 2 deletions common/ASC.Api.Core/Auth/CookieAuthHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
try
{
var authorization = httpContextAccessor.HttpContext.Request.Cookies[cookiesManager.GetAscCookiesName()] ?? httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString();
var authorization = httpContextAccessor.HttpContext.Request.Cookies[cookiesManager.GetAscCookiesName()] ?? httpContextAccessor.HttpContext.Request.Headers.Authorization.ToString();

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

authorization = authorization.Trim();

if (0 <= authorization.IndexOf("Bearer", 0))
if (0 <= authorization.IndexOf("Bearer", 0, StringComparison.Ordinal))
{
authorization = authorization["Bearer ".Length..];
}
Expand Down
9 changes: 4 additions & 5 deletions common/ASC.Api.Core/Auth/JwtBearerAuthHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
authority = $"{serverRootPath}{authority}";
}

var audience = serverRootPath;
var httpDocumentRetriever = new HttpDocumentRetriever();

var showPIIEnable = bool.TryParse(configuration["core:oidc:showPII"], out var showPII) && showPII;
Expand All @@ -77,7 +76,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 @@ -86,7 +85,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()

accessToken = accessToken.Trim();

if (0 <= accessToken.IndexOf("Bearer", 0))
if (0 <= accessToken.IndexOf("Bearer", 0, StringComparison.Ordinal))
{
accessToken = accessToken["Bearer ".Length..];
}
Expand All @@ -97,7 +96,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()

if (validationTokenEnable)
{
validatedToken = await ValidateToken(accessToken, authority, audience, configurationManager);
validatedToken = await ValidateToken(accessToken, authority, serverRootPath, configurationManager);
}
else
{
Expand Down Expand Up @@ -161,7 +160,7 @@ private async Task<JwtSecurityToken> ValidateToken(string token,
ValidIssuer = issuer,
ValidAlgorithms = [SecurityAlgorithms.EcdsaSha256, SecurityAlgorithms.RsaSha256],

ClockSkew = TimeSpan.FromMinutes(2),
ClockSkew = TimeSpan.FromMinutes(2)
};

try
Expand Down
8 changes: 4 additions & 4 deletions common/ASC.Api.Core/Core/ApiDateTime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ public sealed class ApiDateTime : IComparable<ApiDateTime>, IComparable
/// </summary>
public DateTime UtcTime { get; private set; }

/// <summary>
/// TimeZoneOffset
/// </summary>
/// <summary>
/// TimeZoneOffset
/// </summary>
[SwaggerSchemaCustom(Example = "00:00:00")]
public TimeSpan TimeZoneOffset { get; private set; }

Expand Down Expand Up @@ -109,7 +109,7 @@ public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tena
return new ApiDateTime(dateTime, tzOffset);
}

if (!data.EndsWith("Z", true, CultureInfo.InvariantCulture))
if (!data.EndsWith('Z'))
{
tz ??= GetTimeZoneInfo(tenantManager, timeZoneConverter);

Expand Down
4 changes: 2 additions & 2 deletions common/ASC.Api.Core/Cors/DynamicCorsPolicyResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ public async Task<bool> ResolveForOrigin(string origin)

private async Task<IEnumerable<string>> GetOriginsFromOAuth2App()
{
var accessToken = _context.Request.Headers["Authorization"].ToString();
var accessToken = _context.Request.Headers.Authorization.ToString();

if (accessToken == null || accessToken.IndexOf("Bearer", 0) == -1)
if (string.IsNullOrEmpty(accessToken) || accessToken.IndexOf("Bearer", 0, StringComparison.Ordinal) == -1)
{
return new List<string>();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public async Task<CorsResult> EvaluatePolicy(HttpContext context, CorsPolicy pol
var corsResult = new CorsResult
{
IsPreflightRequest = isPreflightRequest,
IsOriginAllowed = await IsOriginAllowed(policy, origin),
IsOriginAllowed = await IsOriginAllowed(policy, origin)
};

if (isPreflightRequest)
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Api.Core/Extensions/HostExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ namespace ASC.Api.Core.Extensions;

public static class HostExtension
{
public static async Task RunWithTasksAsync(this WebApplication webHost, CancellationToken cancellationToken = default, bool awaitTasks = true)
public static async Task RunWithTasksAsync(this WebApplication webHost, bool awaitTasks = true, CancellationToken cancellationToken = default)
{
CustomSynchronizationContext.CreateContext();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ public static IServiceCollection AddEventBus(this IServiceCollection services, I


private static readonly List<string> _registeredActivePassiveHostedService = [];
private static readonly object _locker = new();
private static readonly Lock _locker = new();

/// <remarks>
/// Add a IHostedService for given type.
Expand Down
1 change: 1 addition & 0 deletions common/ASC.Api.Core/Routing/ConstraintRouteAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

namespace ASC.Api.Core.Routing;

[AttributeUsage(AttributeTargets.Class)]
public class ConstraintRouteAttribute(string constraint) : Attribute
{
public IRouteConstraint GetRouteConstraint()
Expand Down
5 changes: 1 addition & 4 deletions common/ASC.Common/Security/AscRandom.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,7 @@ public AscRandom(int seed)

public override int Next(int maxValue)
{
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxValue));
}
ArgumentOutOfRangeException.ThrowIfNegative(maxValue);

return (int)(InternalSample() * 4.6566128752457969E-10 * maxValue);
}
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/Caching/CachedTenantService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ internal class TenantStore
{
private readonly Dictionary<int, Tenant> _byId = new();
private readonly Dictionary<string, Tenant> _byDomain = new();
private readonly object _locker = new();
private readonly Lock _locker = new();

public Tenant Get(int id)
{
Expand Down
4 changes: 2 additions & 2 deletions common/ASC.Core.Common/Context/Impl/AuthorizationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ public async Task RemoveAllAcesAsync(ISecurityObjectId id)
}
}

private IEnumerable<AzRecord> DistinctAces(IEnumerable<AzRecord> inheritAces)
private static IEnumerable<AzRecord> DistinctAces(IEnumerable<AzRecord> inheritAces)
{
var aces = new Dictionary<string, AzRecord>();
foreach (var a in inheritAces)
{
aces[string.Format("{0}{1}{2:D}", a.Subject, a.Action, a.AceType)] = a;
aces[$"{a.Subject}{a.Action}{a.AceType:D}"] = a;
}

return aces.Values;
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/Context/WorkContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public class WorkContext(IConfiguration configuration,
TelegramSender notifyTelegramSender,
PushSender notifyPushSender)
{
private static readonly object _syncRoot = new();
private static readonly Lock _syncRoot = new();
private bool _notifyStarted;
private static bool? _isMono;

Expand Down
4 changes: 3 additions & 1 deletion common/ASC.Core.Common/Core/ArabicNumeralHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ namespace ASC.Core.Common;

public static class ArabicNumeralHelper
{
private static readonly string[] _langs = ["ar-lb", "ar-SA"];

public static string ConvertNumerals(this DateTime input, string format)
{
if (!new[] { "ar-lb", "ar-SA" }.Contains(Thread.CurrentThread.CurrentCulture.Name))
if (!_langs.Contains(Thread.CurrentThread.CurrentCulture.Name))
{
return input.ToString(format, Thread.CurrentThread.CurrentCulture);
}
Expand Down
5 changes: 3 additions & 2 deletions common/ASC.Core.Common/Core/SubscriptionMethod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public class SubscriptionMethod : IMapFrom<DbSubscriptionMethod>
[ProtoMember(5)]
public string[] Methods { get; set; }

private static readonly char[] _separator = ['|'];

public static implicit operator SubscriptionMethod(SubscriptionMethodCache cache)
{
return new SubscriptionMethod
Expand All @@ -71,7 +73,6 @@ public static implicit operator SubscriptionMethodCache(SubscriptionMethod cache
public void Mapping(Profile profile)
{
profile.CreateMap<DbSubscriptionMethod, SubscriptionMethod>()
.ForMember(dest => dest.Methods, opt => opt
.MapFrom(src => src.Sender.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)));
.ForMember(dest => dest.Methods, opt => opt.MapFrom(src => src.Sender.Split(_separator, StringSplitOptions.RemoveEmptyEntries)));
}
}
3 changes: 1 addition & 2 deletions common/ASC.Core.Common/EF/Context/BaseDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ public override Task<int> SaveChangesAsync(CancellationToken cancellationToken =
private void ValidateEntries()
{
var entities = from e in ChangeTracker.Entries()
where e.State == EntityState.Added
|| e.State == EntityState.Modified
where e.State is EntityState.Added or EntityState.Modified
select e.Entity;
foreach (var entity in entities)
{
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/EF/Model/User/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public static ModelBuilderWrapper AddUser(this ModelBuilderWrapper modelBuilder)
ActivationStatus = 0,
WorkFromDate = new DateTime(2021, 3, 9, 9, 52, 55, 764, DateTimeKind.Utc).AddTicks(9157),
LastModified = new DateTime(2021, 3, 9, 9, 52, 55, 765, DateTimeKind.Utc).AddTicks(1420),
CreateDate = new DateTime(2022, 7, 8),
CreateDate = new DateTime(2022, 7, 8)
});

return modelBuilder;
Expand Down
7 changes: 3 additions & 4 deletions common/ASC.Core.Common/Notify/Cron/CronExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,16 +233,15 @@ protected void BuildExpression(string expression)
break;
}

if (exprOn == DayOfMonth && expr.IndexOf('L') != -1 && expr.Length > 1 && expr.IndexOf(',') >= 0)
if (exprOn == DayOfMonth && expr.Contains('L') && expr.Length > 1 && expr.Contains(','))
{
throw new FormatException(
"Support for specifying 'L' and 'LW' with other days of the month is not implemented");
}

if (exprOn == DayOfWeek && expr.IndexOf('L') != -1 && expr.Length > 1 && expr.IndexOf(',') >= 0)
if (exprOn == DayOfWeek && expr.Contains('L') && expr.Length > 1 && expr.Contains(','))
{
throw new FormatException(
"Support for specifying 'L' with other days of the week is not implemented");
throw new FormatException("Support for specifying 'L' with other days of the week is not implemented");
}
var vTok = expr.Split(',');
foreach (var v in vTok)
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ namespace ASC.Notify.Engine;
class InterceptorStorage
{
private readonly string _callContextPrefix = "InterceptorStorage.CALLCONTEXT_KEY." + Guid.NewGuid();
private readonly object _syncRoot = new();
private readonly Lock _syncRoot = new();
private readonly Dictionary<string, ISendInterceptor> _globalInterceptors = new(10);

private Dictionary<string, ISendInterceptor> CallInterceptors
Expand Down
Loading

0 comments on commit 487ca56

Please sign in to comment.