Skip to content

Commit

Permalink
Refactor code for improved readability and efficiency
Browse files Browse the repository at this point in the history
Refactored usage of using directives and simplified type name references for clarity. Optimized logic in several functions by removing unnecessary variable declarations and improving inline assignments. Removed unused channels and updated constructors for improved efficiency, while consolidating and simplifying redundancy in file operation methods.
  • Loading branch information
pavelbannov committed Dec 6, 2024
1 parent cce547f commit 421ed69
Show file tree
Hide file tree
Showing 27 changed files with 35 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ public static async Task<TokenIntrospectionResponse> IntrospectTokenAsync(this H
{ "token", request.Token }
};

using var req = new HttpRequestMessage(HttpMethod.Post, request.Address) { Content = new FormUrlEncodedContent(dict) };
using var req = new HttpRequestMessage(HttpMethod.Post, request.Address);
req.Content = new FormUrlEncodedContent(dict);
using var response = await client.SendAsync(req, cancellationToken);

response.EnsureSuccessStatusCode();
Expand Down
2 changes: 0 additions & 2 deletions common/ASC.Api.Core/Model/EmployeeFullDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode

using System.ComponentModel.DataAnnotations;

namespace ASC.Web.Api.Models;

public class EmployeeFullDto : EmployeeDto
Expand Down
2 changes: 0 additions & 2 deletions common/ASC.Api.Core/Security/EmailValidationKeyModelHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@

using System.Net.Mail;

using static ASC.Security.Cryptography.EmailValidationKeyProvider;

using SecurityContext = ASC.Core.SecurityContext;
using ValidationResult = ASC.Security.Cryptography.EmailValidationKeyProvider.ValidationResult;

Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Common/Utils/JsonWebToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private static (IJsonSerializer, IJwtAlgorithm, IBase64UrlEncoder) GetSettings()
}
}

public class DictionaryStringObjectJsonConverter : System.Text.Json.Serialization.JsonConverter<Dictionary<string, object>>
public class DictionaryStringObjectJsonConverter : JsonConverter<Dictionary<string, object>>
{
public override Dictionary<string, object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Expand Down
2 changes: 0 additions & 2 deletions common/ASC.Common/Utils/SwaggerCustomFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
schema.Example = GetExample(swaggerSchemaCustomAttribute.Example);
}
return;
}
else
{
Expand All @@ -81,7 +80,6 @@ public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
schema.Example = example;
}
return;
}
}

Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/Billing/License/License.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public static License Parse(string licenseString)
}
}

public class LicenseConverter : System.Text.Json.Serialization.JsonConverter<object>
public class LicenseConverter : JsonConverter<object>
{
public override bool CanConvert(Type typeToConvert)
{
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/Core/EmployeeType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
namespace ASC.Core.Users;

[Flags]
[System.Text.Json.Serialization.JsonConverter(typeof(JsonStringEnumConverter<EmployeeType>))]
[JsonConverter(typeof(JsonStringEnumConverter<EmployeeType>))]
[EnumExtensions]
public enum EmployeeType
{
Expand Down
2 changes: 0 additions & 2 deletions common/ASC.Core.Common/EF/Context/BaseDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode

using Microsoft.EntityFrameworkCore.ChangeTracking;

using ValidationResult = System.ComponentModel.DataAnnotations.ValidationResult;

namespace ASC.Core.Common.EF;
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@
global using Textile;
global using Textile.Blocks;
global using Textile.States;
global using static ASC.Security.Cryptography.EmailValidationKeyProvider;

global using AppOptions = FirebaseAdmin.AppOptions;
global using FirebaseAdminMessaging = FirebaseAdmin.Messaging;
global using FirebaseApp = FirebaseAdmin.FirebaseApp;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ namespace ASC.Core.Common.Log;
internal static partial class EmailValidationKeyProviderLogger
{
[LoggerMessage(LogLevel.Debug, "validation result: {result}, source: {email} with key: {key} interval: {interval} tenant: {tenantId}")]
public static partial void DebugValidationResult(this ILogger<EmailValidationKeyProvider> logger, EmailValidationKeyProvider.ValidationResult result, string email, string key, TimeSpan interval, int tenantId);
public static partial void DebugValidationResult(this ILogger<EmailValidationKeyProvider> logger, ValidationResult result, string email, string key, TimeSpan interval, int tenantId);

[LoggerMessage(LogLevel.Debug, "Failed to format tenant specific email")]
public static partial void CriticalFormatEmail(this ILogger<EmailValidationKeyProvider> logger, Exception exception);
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/Users/ConfirmTypeEnum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ namespace ASC.Web.Studio.Utility;
// portal-continue - confirm portal continuation - Tenant.SetStatus(TenantStatus.Active)
// portal-remove - confirm portal deletation - Tenant.SetStatus(TenantStatus.RemovePending)
// DnsChange - change Portal Address and/or Custom domain name
[System.Text.Json.Serialization.JsonConverter(typeof(JsonStringEnumConverter<ConfirmType>))]
[JsonConverter(typeof(JsonStringEnumConverter<ConfirmType>))]
[EnumExtensions]
public enum ConfirmType
{
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.Core.Common/Users/DarkThemeSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public DarkThemeSettings GetDefault()
}


[System.Text.Json.Serialization.JsonConverter(typeof(JsonStringEnumConverter<DarkThemeSettingsType>))]
[JsonConverter(typeof(JsonStringEnumConverter<DarkThemeSettingsType>))]
public enum DarkThemeSettingsType
{
[SwaggerEnum("Base")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ record = await _backupRepository.GetBackupRecordAsync(md5Hash, TenantId);
await _tenantManager.RestoreTenantAsync(tenant.Id, restoredTenant);
TenantId = restoredTenant.Id;

await _tariffService.GetTariffAsync(tenant.Id, true);
await _tariffService.GetTariffAsync(tenant.Id);
await _tenantManager.GetCurrentTenantQuotaAsync(true);
await _notifyHelper.SendAboutRestoreCompletedAsync(restoredTenant, Notify);
}
Expand Down
2 changes: 1 addition & 1 deletion common/ASC.FederatedLogin/OAuth20Token.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public class OAuth20Token
/// <summary>
/// Origin json
/// </summary>
[System.Text.Json.Serialization.JsonIgnore]
[JsonIgnore]
public string OriginJson { get; set; }

/// <summary>
Expand Down
2 changes: 0 additions & 2 deletions common/ASC.MessagingSystem/Core/HistorySocketManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode

using System.Threading.Channels;

namespace ASC.MessagingSystem.Core;

public class HistorySocketManager(
Expand Down
2 changes: 0 additions & 2 deletions common/ASC.MessagingSystem/Core/MessageService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,4 @@ public class EventDescription<T>
public string FromParentTitle { get; set; }
public int? FromParentType { get; set; }
public int? FromFolderId { get; set; }

public EventDescription() { }
}
1 change: 0 additions & 1 deletion common/ASC.MessagingSystem/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
global using ASC.Common.Threading;
global using ASC.Core;
global using ASC.Core.Billing;
global using ASC.Core.Common.EF;
global using ASC.Core.Common.EF.Model;
global using ASC.Core.Common.Messaging;
global using ASC.Core.Notify.Socket;
Expand Down
2 changes: 1 addition & 1 deletion common/services/ASC.Data.Backup/Api/BackupController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ public async Task<BackupProgress> StartBackupRestoreAsync(BackupRestoreDto inDto

var tenantId = tenantManager.GetCurrentTenantId();

var storageType = inDto.StorageType == null ? BackupStorageType.Documents : (BackupStorageType)(inDto.StorageType.Value);
var storageType = inDto.StorageType ?? BackupStorageType.Documents;
if (storageType is BackupStorageType.Documents or BackupStorageType.ThridpartyDocuments && storageParams.ContainsKey("filePath"))
{
if (int.TryParse(storageParams["filePath"], out var fId))
Expand Down
2 changes: 0 additions & 2 deletions products/ASC.Files/Core/Core/Thirdparty/WebDav/WebDavEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,4 @@ public class WebDavEntry
public DateTime CreationDate { get; set; }
public DateTime LastModifiedDate { get; set; }
public bool IsCollection { get; set; }

public WebDavEntry() { }
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,15 @@ public class WatermarkManager
private readonly IDaoFactory _daoFactory;
private readonly FileSecurity _fileSecurity;
private readonly RoomLogoManager _roomLogoManager;
private readonly FilesMessageService _filesMessageService;

public WatermarkManager(
IDaoFactory daoFactory,
FileSecurity fileSecurity,
RoomLogoManager roomLogoManager,
FilesMessageService filesMessageService)
RoomLogoManager roomLogoManager)
{
_daoFactory = daoFactory;
_fileSecurity = fileSecurity;
_roomLogoManager = roomLogoManager;
_filesMessageService = filesMessageService;
}

public async Task<WatermarkSettings> SetWatermarkAsync<T>(Folder<T> room, WatermarkRequestDto watermarkRequestDto)
Expand Down
37 changes: 17 additions & 20 deletions products/ASC.Files/Core/Utils/EntryManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1832,24 +1832,21 @@ public async Task<File<T>> UpdateToVersionFileAsync<T>(T fileId, int version, bo

if (file.ThumbnailStatus == Thumbnail.Created)
{
var copyThumbnailsAsync = async () =>
async Task CopyThumbnailsAsync()
{
await using var scope = serviceProvider.CreateAsyncScope();
var _fileDao = scope.ServiceProvider.GetService<IDaoFactory>().GetFileDao<T>();
var _globalStoreLocal = scope.ServiceProvider.GetService<GlobalStore>();
var dao = scope.ServiceProvider.GetService<IDaoFactory>().GetFileDao<T>();
var globalStoreLocal = scope.ServiceProvider.GetService<GlobalStore>();

foreach (var size in thumbnailSettings.Sizes)
{
await (await _globalStoreLocal.GetStoreAsync()).CopyAsync(String.Empty,
_fileDao.GetUniqThumbnailPath(file, size.Width, size.Height),
String.Empty,
_fileDao.GetUniqThumbnailPath(newFile, size.Width, size.Height));
}
foreach (var size in thumbnailSettings.Sizes)
{
await (await globalStoreLocal.GetStoreAsync()).CopyAsync(String.Empty, dao.GetUniqThumbnailPath(file, size.Width, size.Height), String.Empty, dao.GetUniqThumbnailPath(newFile, size.Width, size.Height));
}

await _fileDao.SetThumbnailStatusAsync(newFile, Thumbnail.Created);
};
await dao.SetThumbnailStatusAsync(newFile, Thumbnail.Created);
}

_ = Task.Run(() => copyThumbnailsAsync().GetAwaiter().GetResult());
_ = Task.Run(() => CopyThumbnailsAsync().GetAwaiter().GetResult());
}


Expand Down Expand Up @@ -2097,15 +2094,15 @@ private async Task<T> CreateFormFillingFolder<T>(string sourceTitle, T parentId,
private async Task<T> CreateCsvResult<T>(T resultsFolderId, Guid createBy, string sourceTitle, IFileDao<T> fileDao)
{
using var textStream = new MemoryStream(Encoding.UTF8.GetBytes(""));
var csvFile = serviceProvider.GetService<File<T>>();
csvFile.ParentId = resultsFolderId;
csvFile.Title = Global.ReplaceInvalidCharsAndTruncate(sourceTitle + ".csv");
csvFile.CreateBy = createBy;
var csvFile = serviceProvider.GetService<File<T>>();
csvFile.ParentId = resultsFolderId;
csvFile.Title = Global.ReplaceInvalidCharsAndTruncate(sourceTitle + ".csv");
csvFile.CreateBy = createBy;

var file = await fileDao.SaveFileAsync(csvFile, textStream, false);
var file = await fileDao.SaveFileAsync(csvFile, textStream, false);

return file.Id;
}
return file.Id;
}
private async Task<EntryProperties<T>> InitFormFillingProperties<T>(T roomId, string sourceTitle, T sourceFileId, T inProcessFormFolderId, T readyFormFolderId, Guid createBy, EntryProperties<T> properties, IFileDao<T> fileDao, IFolderDao<T> folderDao)
{
var templatesFolderTask = CreateFormFillingFolder(sourceTitle, inProcessFormFolderId, FolderType.FormFillingFolderInProgress, createBy, folderDao);
Expand Down
2 changes: 1 addition & 1 deletion web/ASC.Web.Api/Api/AuthenticationController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ private async Task<UserInfoWrapper> GetUserAsync(AuthRequestsDto inDto)

var checkKeyResult = await emailValidationKeyModelHelper.ValidateAsync(new EmailValidationKeyModel { Key = inDto.ConfirmData.Key, Email = email, Type = ConfirmType.Auth, First = inDto.ConfirmData.First.ToString() });

if (checkKeyResult == Security.Cryptography.EmailValidationKeyProvider.ValidationResult.Ok)
if (checkKeyResult == ValidationResult.Ok)
{
user = email.Contains("@")
? await userManager.GetUserByEmailAsync(email)
Expand Down
2 changes: 1 addition & 1 deletion web/ASC.Web.Api/Api/PortalController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -713,7 +713,7 @@ public async Task SendCongratulationsAsync([FromQuery] SendCongratulationsDto in

switch (checkKeyResult)
{
case EmailValidationKeyProvider.ValidationResult.Ok:
case ValidationResult.Ok:
var currentUser = await userManager.GetUsersAsync(inDto.Userid);

await studioNotifyService.SendCongratulationsAsync(currentUser);
Expand Down
2 changes: 1 addition & 1 deletion web/ASC.Web.Api/Api/Settings/SecurityController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ public async IAsyncEnumerable<EmployeeDto> GetProductAdministrators(ProductIdReq
public async Task<object> IsProductAdministratorAsync(UserProductIdsRequestDto inDto)
{
var result = await webItemSecurity.IsProductAdministratorAsync(inDto.ProductId, inDto.UserId);
return new { ProductId = inDto.ProductId, UserId = inDto.UserId, Administrator = result };
return new { inDto.ProductId, inDto.UserId, Administrator = result };
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion web/ASC.Web.Api/ApiModels/ResponseDto/ConfirmDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class ConfirmDto : IMapFrom<Validation>
/// <summary>
/// Result
/// </summary>
public EmailValidationKeyProvider.ValidationResult Result { get; set; }
public ValidationResult Result { get; set; }

/// <summary>
/// Room id
Expand Down
1 change: 0 additions & 1 deletion web/ASC.Web.Core/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
global using System.Net;
global using System.Net.Http.Headers;
global using System.Net.Mail;
global using ASC.Core.Common.EF;
global using System.Net.Mime;
global using System.Reflection;
global using System.Runtime.Serialization;
Expand Down
2 changes: 1 addition & 1 deletion web/ASC.Web.Core/Utility/PasswordSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ private static string GetPasswordHelpMessage(PasswordSettings passwordSettings)
var text = new StringBuilder();

text.Append($"{Resource.ErrorPasswordMessage} ");
text.AppendFormat(Resource.ErrorPasswordLength, passwordSettings.MinLength, PasswordSettingsManager.MaxLength);
text.AppendFormat(Resource.ErrorPasswordLength, passwordSettings.MinLength, MaxLength);
text.Append($", {Resource.ErrorPasswordOnlyLatinLetters}");
text.Append($", {Resource.ErrorPasswordNoSpaces}");

Expand Down

0 comments on commit 421ed69

Please sign in to comment.