Skip to content

Commit

Permalink
Refactor default value handling and update type consistency.
Browse files Browse the repository at this point in the history
Replaced occurrences of `default` with explicit default values like `0`, `null`, or `Guid.Empty` for improved clarity and consistent behavior. Updated type usage in method parameters and conditional checks to align with modern coding standards to prevent ambiguities.
  • Loading branch information
pavelbannov committed Dec 13, 2024
1 parent 487ca56 commit 0395c14
Show file tree
Hide file tree
Showing 117 changed files with 246 additions and 272 deletions.
2 changes: 1 addition & 1 deletion common/ASC.Api.Core/Auth/AuthHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
Context.Request.Headers.TryGetValue("Authorization", out var headers);

var header = headers.FirstOrDefault();
string header = headers;

if (string.IsNullOrEmpty(header))
{
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()

var claims = new List<Claim>
{
new(ClaimTypes.Role, emailValidationKeyModel.Type.ToString()),AuthConstants.Claim_ScopeRootWrite
new(ClaimTypes.Role, emailValidationKeyModel.Type.Value.ToStringFast()),AuthConstants.Claim_ScopeRootWrite
};

if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Ok)
Expand Down
4 changes: 2 additions & 2 deletions common/ASC.Api.Core/Core/BaseStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ bool EnableNoLimiter(IPAddress address)
{
permitLimit = _configuration.GetSection("core:hosting:rateLimiterOptions:defaultConcurrencyWriteRequests").Get<int>();

if (permitLimit == default)
if (permitLimit == 0)
{
permitLimit = 15;
}
Expand Down Expand Up @@ -427,7 +427,7 @@ bool EnableNoLimiter(IPAddress address)
{
options.ForwardDefaultSelector = context =>
{
var authorizationHeader = context.Request.Headers[HeaderNames.Authorization].FirstOrDefault();
string authorizationHeader = context.Request.Headers[HeaderNames.Authorization];

if (string.IsNullOrEmpty(authorizationHeader))
{
Expand Down
4 changes: 2 additions & 2 deletions common/ASC.Api.Core/Core/Validate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static T If<T>(this T item, Func<T, bool> @if, Func<T> then) where T : cl

public static T IfNull<T>(this T item, Func<T> func) where T : class
{
return item.If(x => x == default(T), func);
return item.If(x => x == null, func);
}

public static T ThrowIfNull<T>(this T item, Exception e) where T : class
Expand All @@ -50,6 +50,6 @@ public static T NotFoundIfNull<T>(this T item, string message = "Item not found"

public static T? NullIfDefault<T>(this T item) where T : struct
{
return EqualityComparer<T>.Default.Equals(item, default) ? default(T?) : item;
return EqualityComparer<T>.Default.Equals(item, default) ? null : item;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public class TokenIntrospectionRequest
/// <value>
/// The token.
/// </value>
public string Token { get; set; } = default!;
public string Token { get; set; } = null!;

/// <summary>
/// Gets or sets the endpoint address
Expand Down
4 changes: 2 additions & 2 deletions common/ASC.Api.Core/Middleware/LoggerMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ public async Task Invoke(HttpContext context,

var state = new Dictionary<string, object>
{
new("tenantId", tenant.Id),
new("tenantAlias", tenant.GetTenantDomain(coreSettings, false))
new KeyValuePair<string, object>("tenantId", tenant.Id),
new KeyValuePair<string, object>("tenantAlias", tenant.GetTenantDomain(coreSettings, false))
};

if (tenant.MappedDomain != null)
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ private static Guid FindProduct(ControllerActionDescriptor method)
{
if (method == null || string.IsNullOrEmpty(method.ControllerName))
{
return default;
return Guid.Empty;
}

var name = method.ControllerName.ToLower();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public EmailValidationKeyModel GetModel()
{
var request = QueryHelpers.ParseQuery(httpContextAccessor.HttpContext.Request.Headers["confirm"]);

var type = request.TryGetValue("type", out var value) ? value.FirstOrDefault() : null;
var type = request.TryGetValue("type", out var value) ? (string)value : null;

ConfirmType? cType = null;
if (ConfirmTypeExtensions.TryParse(type, out var confirmType))
Expand Down
10 changes: 5 additions & 5 deletions common/ASC.Api.Core/Security/InvitationValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public string MakeIndividualLinkKey(Guid linkId, Guid createBy)
return signature.Create(linkId + "." + createBy);
}

public async Task<LinkValidationResult> ValidateAsync(string key, string email, EmployeeType employeeType, Guid? userId = default)
public async Task<LinkValidationResult> ValidateAsync(string key, string email, EmployeeType employeeType, Guid? userId = null)
{
var result = new LinkValidationResult
{
Expand Down Expand Up @@ -161,20 +161,20 @@ public async Task<LinkValidationResult> ValidateAsync(string key, string email,
private (EmailValidationKeyProvider.ValidationResult, Guid) ValidateCommonWithRoomLink(string key, Guid? userId = null)
{
var linkId = signature.Read<Guid>(key);
if (linkId == default && userId.HasValue)
if (linkId == Guid.Empty && userId.HasValue)
{
var combined = signature.Read<string>(key);
if (!string.IsNullOrEmpty(combined))
{
var split = combined.Split('.');
if (split.Length == 2 && Guid.TryParse(split[0], out linkId) && Guid.TryParse(split[1], out var uId) && !Equals(uId, userId.Value))
if (split.Length == 2 && Guid.TryParse(split[0], out linkId) && Guid.TryParse(split[1], out var uId) && !uId.Equals(userId.Value))
{
linkId = default;
linkId = Guid.Empty;
}
}
}

return linkId == default ? (EmailValidationKeyProvider.ValidationResult.Invalid, default) : (EmailValidationKeyProvider.ValidationResult.Ok, linkId);
return linkId == Guid.Empty ? (EmailValidationKeyProvider.ValidationResult.Invalid, default) : (EmailValidationKeyProvider.ValidationResult.Ok, linkId);
}

private async Task<DbAuditEvent> GetLinkVisitMessageAsync(int tenantId, string email, string key)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ public interface IDistributedTaskQueueFactory
{
DistributedTaskQueue CreateQueue<T>(int timeUntilUnregisterInSeconds = 60) where T : DistributedTask;
DistributedTaskQueue CreateQueue(Type type, int timeUntilUnregisterInSeconds = 60);
DistributedTaskQueue CreateQueue(string name = default, int timeUntilUnregisterInSeconds = 60);
DistributedTaskQueue CreateQueue(string name = null, int timeUntilUnregisterInSeconds = 60);
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public DistributedTaskQueue CreateQueue(Type type, int timeUntilUnregisterInSeco
return CreateQueue(type.FullName, timeUntilUnregisterInSeconds);
}

public DistributedTaskQueue CreateQueue(string name = default, int timeUntilUnregisterInSeconds = 60)
public DistributedTaskQueue CreateQueue(string name = null, int timeUntilUnregisterInSeconds = 60)
{
var option = options.Get(name);
var queue = serviceProvider.GetRequiredService<DistributedTaskQueue>();
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Common/Threading/DistributedTaskQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class DistributedTaskQueue(IServiceProvider serviceProvider,
ILogger<DistributedTaskQueue> logger)
{
public const string QUEUE_DEFAULT_PREFIX = "asc_distributed_task_queue_";
public static readonly int INSTANCE_ID = Process.GetCurrentProcess().Id;
public static readonly int INSTANCE_ID = Environment.ProcessId;

private readonly ConcurrentDictionary<string, CancellationTokenSource> _cancelations = new();
private bool _subscribed;
Expand Down
3 changes: 3 additions & 0 deletions common/ASC.Common/Utils/CommonFileSizeComment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ public class CommonFileSizeComment
/// <summary>
/// Generates a string the file size
/// </summary>
/// <param
/// name="fileSizePostfix">
/// </param>
/// <param name="size">Size in bytes</param>
/// <returns>10 b, 100 Kb, 25 Mb, 1 Gb</returns>
public static string FilesSizeToString(string fileSizePostfix, long size)
Expand Down
7 changes: 3 additions & 4 deletions common/ASC.Common/Utils/SwaggerCustomDocumentFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,13 @@
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace ASC.Api.Core.Extensions;

public class HideRouteDocumentFilter(string routeToHide) : IDocumentFilter
{
public void Apply(OpenApiDocument document, DocumentFilterContext context)
{
if (document.Paths.ContainsKey(routeToHide))
{
document.Paths.Remove(routeToHide);
}
document.Paths.Remove(routeToHide);
}
}

Expand Down
12 changes: 4 additions & 8 deletions common/ASC.Common/Utils/SwaggerCustomFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,6 @@ private OpenApiSchema UpdateSchema(Type checkType, OpenApiSchema result)
var timeSpan = TimeSpan.Zero.ToString();
result.Example = new OpenApiString(timeSpan);
}
else
{
}

return result;
}
Expand Down Expand Up @@ -312,14 +309,13 @@ private IOpenApiAny GenerateFakeData(PropertyInfo propertyInfo)
{
return new OpenApiString(faker.Random.Int(1, 10000).ToString());
}
else if(propertyInfo.PropertyType == typeof(int))

if(propertyInfo.PropertyType == typeof(int))
{
return new OpenApiInteger(faker.Random.Int(1, 10000));
}
else
{
return new OpenApiString(Guid.NewGuid().ToString());
}

return new OpenApiString(Guid.NewGuid().ToString());
default:
return null;
}
Expand Down
2 changes: 2 additions & 0 deletions common/ASC.Common/Utils/SwaggerCustomOperationFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@

using Swashbuckle.AspNetCore.SwaggerGen;

namespace ASC.Api.Core.Extensions;

public class SwaggerCustomOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/BaseCommonLinkUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public string ServerRootPath
// first, take from current request
if (_httpContextAccessor?.HttpContext?.Request != null && !serverUriForce)
{
var origin = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Origin].FirstOrDefault();
string origin = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Origin];

var u = string.IsNullOrEmpty(origin) ? _httpContextAccessor.HttpContext.Request.Url() : new Uri(origin);

Expand Down
12 changes: 6 additions & 6 deletions common/ASC.Core.Common/Billing/TariffService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@ private async Task<bool> SaveBillingInfoAsync(int tenant, Tariff tariffInfo)
CreateOn = DateTime.UtcNow
};

if (efTariff.Id == default)
if (efTariff.Id == 0)
{
efTariff.Id = (-tenant);
tariffInfo.Id = efTariff.Id;
Expand Down Expand Up @@ -734,7 +734,7 @@ private async Task<Tariff> CalculateTariffAsync(int tenantId, Tariff tariff)
fromDate = DateTime.UtcNow.Date;
}

tariff.DueDate = trialPeriod != default ? fromDate.Date.AddDays(trialPeriod) : DateTime.MaxValue;
tariff.DueDate = trialPeriod != 0 ? fromDate.Date.AddDays(trialPeriod) : DateTime.MaxValue;
}
else
{
Expand Down Expand Up @@ -836,17 +836,17 @@ private async Task NotifyWebSocketAsync(Tariff currenTariff, Tariff newTariff)
var maxTotalSize = updatedQuota.MaxTotalSize;
var maxTotalSizeFeatureName = updatedQuota.GetFeature<MaxTotalSizeFeature>().Name;

_ = quotaSocketManager.ChangeQuotaFeatureValue(maxTotalSizeFeatureName, maxTotalSize);
_ = quotaSocketManager.ChangeQuotaFeatureValueAsync(maxTotalSizeFeatureName, maxTotalSize);

var maxPaidUsers = updatedQuota.CountRoomAdmin;
var maxPaidUsersFeatureName = updatedQuota.GetFeature<CountPaidUserFeature>().Name;

_ = quotaSocketManager.ChangeQuotaFeatureValue(maxPaidUsersFeatureName, maxPaidUsers);
_ = quotaSocketManager.ChangeQuotaFeatureValueAsync(maxPaidUsersFeatureName, maxPaidUsers);

var maxRoomCount = updatedQuota.CountRoom == int.MaxValue ? -1 : updatedQuota.CountRoom;
var maxRoomCountFeatureName = updatedQuota.GetFeature<CountRoomFeature>().Name;

_ = quotaSocketManager.ChangeQuotaFeatureValue(maxRoomCountFeatureName, maxRoomCount);
_ = quotaSocketManager.ChangeQuotaFeatureValueAsync(maxRoomCountFeatureName, maxRoomCount);

if (currenTariff != null)
{
Expand All @@ -857,7 +857,7 @@ private async Task NotifyWebSocketAsync(Tariff currenTariff, Tariff newTariff)
{
var freeFeatureName = updatedQuota.GetFeature<FreeFeature>().Name;

_ = quotaSocketManager.ChangeQuotaFeatureValue(freeFeatureName, free);
_ = quotaSocketManager.ChangeQuotaFeatureValueAsync(freeFeatureName, free);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ private SubscriptionsStore GetSubsciptionsStore(int tenant, string sourceId, str

public static string GetKey(int tenant, string sourceId, string actionId)
{
return string.Format("sub/{0}/{1}/{2}", tenant, sourceId, actionId);
return $"sub/{tenant}/{sourceId}/{actionId}";
}
}

Expand Down
4 changes: 2 additions & 2 deletions common/ASC.Core.Common/Context/Impl/TenantManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ private async Task<Tenant> GetCurrentTenantFromDbAsync(bool throwIfNotFound, Htt

if (tenant == null)
{
var origin = context.Request.Headers[HeaderNames.Origin].FirstOrDefault();
string origin = context.Request.Headers.Origin;

if (!string.IsNullOrEmpty(origin))
{
Expand Down Expand Up @@ -246,7 +246,7 @@ public async Task SetCurrentTenantAsync()

if (tenant == null)
{
var origin = context.Request.Headers[HeaderNames.Origin].FirstOrDefault();
string origin = context.Request.Headers.Origin;

if (!string.IsNullOrEmpty(origin))
{
Expand Down
4 changes: 2 additions & 2 deletions common/ASC.Core.Common/Context/SecurityContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ public async Task AuthenticateMeWithoutCookieAsync(IAccount account, List<Claim>
{
if (account == null || account.Equals(Constants.Guest))
{
if (session == default || session == Constants.Guest.ID)
if (session == Guid.Empty || session == Constants.Guest.ID)
{
throw new InvalidCredentialException(nameof(account));
}
Expand Down Expand Up @@ -322,7 +322,7 @@ public async Task DemandPermissionsAsync(ISecurityObject securityObject, IAction
public class AuthContext(IHttpContextAccessor httpContextAccessor)
{
private IHttpContextAccessor HttpContextAccessor { get; } = httpContextAccessor;
private static readonly List<string> _typesCheck = [ConfirmType.LinkInvite.ToString(), ConfirmType.EmpInvite.ToString()];
private static readonly List<string> _typesCheck = [ConfirmType.LinkInvite.ToStringFast(), ConfirmType.EmpInvite.ToStringFast()];

public IAccount CurrentAccount => Principal?.Identity as IAccount ?? Constants.Guest;

Expand Down
4 changes: 2 additions & 2 deletions common/ASC.Core.Common/Core/AzRecord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class AzRecord : IMapFrom<Acl>

public AzRecord() { }

public AzRecord(Guid subjectId, Guid actionId, AceType reaction, string fullId = default)
public AzRecord(Guid subjectId, Guid actionId, AceType reaction, string fullId = null)
{
Subject = subjectId;
Action = actionId;
Expand Down Expand Up @@ -94,7 +94,7 @@ public static implicit operator AzRecordCache(AzRecord cache)
SubjectId = cache.Subject.ToString(),
ActionId = cache.Action.ToString(),
ObjectId = cache.Object,
Reaction = cache.AceType.ToString(),
Reaction = cache.AceType.ToStringFast(),
Tenant = cache.TenantId
};
}
Expand Down
2 changes: 2 additions & 0 deletions common/ASC.Core.Common/Core/IPAddressRange.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@

using System.Net.Sockets;

namespace ASC.Core;

public class IPAddressRange(IPAddress lower, IPAddress upper)
{
private readonly AddressFamily _addressFamily = lower.AddressFamily;
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/Notify/Senders/AWSSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public override async Task<NoticeSendResult> SendAsync(NotifyMessage m)
result = await SendMessage(m);
}

_logger.Debug(result.ToString());
_logger.Debug(result.ToStringFast());
}
catch (Exception e)
{
Expand Down
1 change: 1 addition & 0 deletions common/ASC.Core.Common/Notify/Senders/NoticeSendResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

namespace ASC.Core.Notify.Senders;

[EnumExtensions]
public enum NoticeSendResult
{
OK,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,7 @@ public class FootNoteFormatterState(TextileFormatter f) : SimpleBlockFormatterSt

public override void Enter()
{
Formatter.Output.Write(
string.Format("<p id=\"fn{0}\"{1}><sup>{2}</sup> ",
_noteID,
FormattedStylesAndAlignment("p"),
_noteID));
Formatter.Output.Write($"<p id=\"fn{_noteID}\"{FormattedStylesAndAlignment("p")}><sup>{_noteID}</sup> ");
}

public override void Exit()
Expand Down
8 changes: 4 additions & 4 deletions common/ASC.Core.Common/Quota/QuotaSocketManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ public class QuotaSocketManager(
: SocketServiceClient(tariffService, tenantManager, channelWriter, machinePseudoKeys, configuration)
{
protected override string Hub => "files";

public async Task ChangeQuotaUsedValueAsync(string featureId, object value)
public async Task ChangeQuotaUsedValueAsync<T>(string featureId, T value)
{
var room = GetQuotaRoom();

await MakeRequest("change-quota-used-value", new { room, featureId, value });
}

Expand All @@ -51,7 +51,7 @@ public async Task ChangeCustomQuotaUsedValueAsync(int tenantId, string customQuo
await MakeRequest("change-user-quota-used-value", new { room, customQuotaFeature, enableQuota, usedSpace, quotaLimit, userIds });
}

public async Task ChangeQuotaFeatureValue(string featureId, object value)
public async Task ChangeQuotaFeatureValueAsync<T>(string featureId, T value)
{
var room = GetQuotaRoom();

Expand Down
Loading

0 comments on commit 0395c14

Please sign in to comment.