From 352a8b61ff2dfa7a6f3d5fd90f30aea0b2e83771 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 14:54:10 +0300 Subject: [PATCH 001/167] analizators/s5034 --- products/ASC.Files/Core/Core/Entries/ChunkedUploadSession.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/ASC.Files/Core/Core/Entries/ChunkedUploadSession.cs b/products/ASC.Files/Core/Core/Entries/ChunkedUploadSession.cs index 12d60adc64..dbf971f48f 100644 --- a/products/ASC.Files/Core/Core/Entries/ChunkedUploadSession.cs +++ b/products/ASC.Files/Core/Core/Entries/ChunkedUploadSession.cs @@ -76,7 +76,7 @@ namespace ASC.Files.Core public static ChunkedUploadSession Deserialize(Stream stream, FileHelper fileHelper) { - var chunkedUploadSession = JsonSerializer.DeserializeAsync>(stream).Result; + var chunkedUploadSession = JsonSerializer.Deserialize>(stream); chunkedUploadSession.File.FileHelper = fileHelper; chunkedUploadSession.TransformItems(); return chunkedUploadSession; From 0a786bbfa3231a951bb8b6f0c0130321d5a5e0a1 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 15:00:48 +0300 Subject: [PATCH 002/167] analizators/s4830 --- .../Notify/Senders/SmtpSender.cs | 3 -- .../Core/HttpHandlers/FileHandler.ashx.cs | 10 +----- .../DocumentService/DocumentServiceTracker.cs | 31 ++----------------- products/ASC.Files/Core/Utils/EntryManager.cs | 5 --- .../ASC.Files/Core/Utils/FileConverter.cs | 11 +------ .../ASC.Files/Core/Utils/MailMergeTask.cs | 6 ---- .../Server/Helpers/FilesControllerHelper.cs | 6 ---- .../ASC.Files/Service/Thumbnail/Builder.cs | 8 +---- web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs | 3 -- web/ASC.Web.Core/Files/DocumentService.cs | 18 ----------- 10 files changed, 6 insertions(+), 95 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs index 5fd7cc11d7..059a69b4da 100644 --- a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs @@ -288,9 +288,6 @@ namespace ASC.Core.Notify.Senders { Timeout = NETWORK_TIMEOUT }; - - if (sslCertificatePermit) - smtpClient.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; return smtpClient; } diff --git a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs index 0a17496f97..7575a48260 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -1177,15 +1177,7 @@ namespace ASC.Web.Files file.Comment = FilesCommonResource.CommentCreate; var request = new HttpRequestMessage(); - request.RequestUri = new Uri(fileUri); - - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } - - + request.RequestUri = new Uri(fileUri); var fileDao = DaoFactory.GetFileDao(); using var httpClient = new HttpClient(); diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs index 2cab654676..7278d24d28 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -498,12 +498,6 @@ namespace ASC.Web.Files.Services.DocumentService case MailMergeType.AttachPdf: var requestDownload = new HttpRequestMessage(); requestDownload.RequestUri = new Uri(DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); - - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } using (var responseDownload = httpClient.Send(requestDownload)) using (var streamDownload = responseDownload.Content.ReadAsStream()) @@ -536,14 +530,7 @@ namespace ASC.Web.Files.Services.DocumentService case MailMergeType.Html: var httpRequest = new HttpRequestMessage(); - httpRequest.RequestUri = new Uri(DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); - - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } - + httpRequest.RequestUri = new Uri(DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); using (var httpResponse = httpClient.Send(httpRequest)) using (var stream = httpResponse.Content.ReadAsStream()) @@ -609,13 +596,7 @@ namespace ASC.Web.Files.Services.DocumentService var store = GlobalStore.GetStore(); var request = new HttpRequestMessage(); - request.RequestUri = new Uri(downloadUri); - - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } + request.RequestUri = new Uri(downloadUri); using (var httpClient = new HttpClient()) using (var response = httpClient.Send(request)) @@ -642,13 +623,7 @@ namespace ASC.Web.Files.Services.DocumentService { var fileDao = DaoFactory.GetFileDao(); var request = new HttpRequestMessage(); - request.RequestUri = new Uri(differenceUrl); - - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } + request.RequestUri = new Uri(differenceUrl); using var httpClient = new HttpClient(); using var response = httpClient.Send(request); diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index 05f85564ba..bc487297c7 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -1004,11 +1004,6 @@ namespace ASC.Web.Files.Utils } else { - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } var request = new HttpRequestMessage(); request.RequestUri = new Uri(downloadUri); diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index bff69bf781..05c79adf4f 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -680,11 +680,7 @@ namespace ASC.Web.Files.Utils var docKey = DocumentServiceHelper.GetDocKey(file); fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri); DocumentServiceConnector.GetConvertedUri(fileUri, file.ConvertedExtension, toExtension, docKey, null, null, null, false, out var convertUri); - - if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null) - { - ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; //HACK: http://ubuntuforums.org/showthread.php?t=1841740 - } + var request = new HttpRequestMessage(); request.RequestUri = new Uri(convertUri); @@ -858,11 +854,6 @@ namespace ASC.Web.Files.Utils using var httpClient = new HttpClient(); - if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null) - { - ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; //HACK: http://ubuntuforums.org/showthread.php?t=1841740 - } - try { using var response = httpClient.Send(request); diff --git a/products/ASC.Files/Core/Utils/MailMergeTask.cs b/products/ASC.Files/Core/Utils/MailMergeTask.cs index 34d67a0845..b08b2c9c93 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -140,12 +140,6 @@ namespace ASC.Web.Files.Utils request.Headers.Add("Content-Type", MimeMapping.GetMimeMapping(mailMergeTask.AttachTitle)); request.Content = new StreamContent(mailMergeTask.Attach); - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } - string responseAttachString; using var httpClient = new HttpClient(); using var response = httpClient.Send(request); diff --git a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs index cc8e8bc792..1ba4b8f40a 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -270,12 +270,6 @@ namespace ASC.Files.Helpers request.Headers.Add(HttpRequestExtensions.UrlRewriterHeader, rewriterHeader.ToString()); } - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } - using var response = httpClient.Send(request); using var responseStream = response.Content.ReadAsStream(); using var streamReader = new StreamReader(responseStream); diff --git a/products/ASC.Files/Service/Thumbnail/Builder.cs b/products/ASC.Files/Service/Thumbnail/Builder.cs index 7770a93606..653aea5908 100644 --- a/products/ASC.Files/Service/Thumbnail/Builder.cs +++ b/products/ASC.Files/Service/Thumbnail/Builder.cs @@ -287,13 +287,7 @@ namespace ASC.Files.ThumbnailBuilder logger.DebugFormat("SaveThumbnail: FileId: {0}. ThumbnailUrl {1}.", file.ID, thumbnailUrl); var request = new HttpRequestMessage(); - request.RequestUri = new Uri(thumbnailUrl); - - //HACK: http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null) - { - ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; - } + request.RequestUri = new Uri(thumbnailUrl); using var httpClient = new HttpClient(); using var response = httpClient.Send(request); diff --git a/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs b/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs index 759ab0693a..e678767dae 100644 --- a/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs +++ b/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs @@ -229,9 +229,6 @@ namespace ASC.Api.Settings.Smtp Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds }; - if (sslCertificatePermit) - client.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; - return client; } diff --git a/web/ASC.Web.Core/Files/DocumentService.cs b/web/ASC.Web.Core/Files/DocumentService.cs index fbb78005e8..9ca0b2ef15 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -171,12 +171,6 @@ namespace ASC.Web.Core.Files request.Content = new StringContent(bodyString, Encoding.UTF8, "application/json"); - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } - string dataResponse; HttpResponseMessage response = null; Stream responseStream = null; @@ -279,12 +273,6 @@ namespace ASC.Web.Core.Files request.Content = new StringContent(bodyString, Encoding.UTF8, "application/json"); - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } - string dataResponse; using (var response = httpClient.Send(request)) using (var stream = response.Content.ReadAsStream()) @@ -361,12 +349,6 @@ namespace ASC.Web.Core.Files request.Content = new StringContent(bodyString, Encoding.UTF8, "application/json"); - // hack. http://ubuntuforums.org/showthread.php?t=1841740 - if (WorkContext.IsMono) - { - ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; - } - string dataResponse = null; using (var response = httpClient.Send(request)) From af1c812cac84f7b193f6f32a37c09ac87eec846a Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 15:03:12 +0300 Subject: [PATCH 003/167] analizators/s4586 --- .../ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs index 36aea72403..971a6246fc 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs @@ -82,7 +82,7 @@ namespace ASC.Files.Thirdparty public Task GetThumbnailAsync(File file) { - return null; + return Task.FromResult(null); } public virtual Stream GetFileStream(File file) From c3321206bd72a477c683628d18f3e9c85dafab9b Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 16:08:11 +0300 Subject: [PATCH 004/167] analizators/s4487 --- common/ASC.Data.Backup.Core/Core/DbHelper.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/common/ASC.Data.Backup.Core/Core/DbHelper.cs b/common/ASC.Data.Backup.Core/Core/DbHelper.cs index 165bc97dfc..c7a45cadb3 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -30,15 +30,13 @@ namespace ASC.Data.Backup private readonly DataTable columns; private readonly bool mysql; private readonly IDictionary whereExceptions = new Dictionary(); - private readonly ILog log; - private readonly BackupsContext backupsContext; + private readonly ILog log; private readonly TenantDbContext tenantDbContext; private readonly CoreDbContext coreDbContext; - public DbHelper(IOptionsMonitor options, ConnectionStringSettings connectionString, BackupsContext backupsContext, TenantDbContext tenantDbContext, CoreDbContext coreDbContext) + public DbHelper(IOptionsMonitor options, ConnectionStringSettings connectionString, TenantDbContext tenantDbContext, CoreDbContext coreDbContext) { - log = options.CurrentValue; - this.backupsContext = backupsContext; + log = options.CurrentValue; this.tenantDbContext = tenantDbContext; this.coreDbContext = coreDbContext; var file = connectionString.ElementInformation.Source; From ee79cecf360200fbd58d49082329ee2bb252c5fe Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 16:19:53 +0300 Subject: [PATCH 005/167] analizators/s4457 --- .../Core/Services/FFmpegService/FFmpeg.cs | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs index 63e2a93e70..14686197a3 100644 --- a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs +++ b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs @@ -33,11 +33,16 @@ namespace ASC.Web.Files.Services.FFmpegService return MustConvertable.Contains(extension.TrimStart('.')); } - public async Task Convert(Stream inputStream, string inputFormat) + public Task Convert(Stream inputStream, string inputFormat) { if (inputStream == null) throw new ArgumentException(); if (string.IsNullOrEmpty(inputFormat)) throw new ArgumentException(); + return ConvertInternal(inputStream, inputFormat); + } + + private async Task ConvertInternal(Stream inputStream, string inputFormat) + { var startInfo = PrepareFFmpeg(inputFormat); Process process; @@ -50,7 +55,7 @@ namespace ASC.Web.Files.Services.FFmpegService await ProcessLog(process.StandardError.BaseStream); return process.StandardOutput.BaseStream; - } + } } public FFmpegService(IOptionsMonitor optionsMonitor, IConfiguration configuration) @@ -116,13 +121,18 @@ namespace ASC.Web.Files.Services.FFmpegService return startInfo; } - private static async Task StreamCopyToAsync(Stream srcStream, Stream dstStream, bool closeSrc = false, bool closeDst = false) + private static Task StreamCopyToAsync(Stream srcStream, Stream dstStream, bool closeSrc = false, bool closeDst = false) { - const int bufs = 2048 * 4; - if (srcStream == null) throw new ArgumentNullException("srcStream"); if (dstStream == null) throw new ArgumentNullException("dstStream"); + return StreamCopyToAsyncInternal(srcStream, dstStream, closeSrc, closeDst); + } + + private static async Task StreamCopyToAsyncInternal(Stream srcStream, Stream dstStream, bool closeSrc, bool closeDst) + { + const int bufs = 2048 * 4; + var buffer = new byte[bufs]; int readed; var total = 0; @@ -146,7 +156,7 @@ namespace ASC.Web.Files.Services.FFmpegService dstStream.Close(); } - return total; + return total; } private async Task ProcessLog(Stream stream) From 28e1c652d9a0f75dd043844ff71b6793fc4f2be4 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 16:39:44 +0300 Subject: [PATCH 006/167] analizators/s4456 --- .../ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs b/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs index c8243c9104..23e6934fc4 100644 --- a/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs +++ b/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs @@ -86,6 +86,11 @@ namespace ASC.Data.Backup.Extensions if (partLength <= 0) throw new ArgumentOutOfRangeException("partLength", partLength, "Length must be positive integer"); + return MakePartsIterator(collection, partLength); + } + + private static IEnumerable> MakePartsIterator(this IEnumerable collection, int partLength) + { var part = new List(partLength); foreach (var entry in collection) From 6cd3a7bfe188ecb6bf17f625ff2ccd2030e40257 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 17:03:05 +0300 Subject: [PATCH 007/167] analizators/s4201 --- common/ASC.Common/Collections/CachedDictionaryBase.cs | 2 +- products/ASC.Files/Core/Utils/FileConverter.cs | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/common/ASC.Common/Collections/CachedDictionaryBase.cs b/common/ASC.Common/Collections/CachedDictionaryBase.cs index 9f6b15018a..6ffa5009ce 100644 --- a/common/ASC.Common/Collections/CachedDictionaryBase.cs +++ b/common/ASC.Common/Collections/CachedDictionaryBase.cs @@ -106,7 +106,7 @@ namespace ASC.Collections protected virtual bool FitsCondition(object cached) { - return cached != null && cached is T; + return cached is T; } public virtual T Get(string rootkey, string key, Func defaults) diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index 05c79adf4f..92746740ab 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -265,8 +265,7 @@ namespace ASC.Web.Files.Utils } catch (Exception exception) { - var password = exception.InnerException != null - && (exception.InnerException is DocumentService.DocumentServiceException documentServiceException) + var password = exception.InnerException is DocumentService.DocumentServiceException documentServiceException && documentServiceException.Code == DocumentService.DocumentServiceException.ErrorCode.ConvertPassword; logger.Error(string.Format("Error convert {0} with url {1}", file.ID, fileUri), exception); From 895e888ad3c2f1ec2db846ad7c376e9f7e7e3911 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 17:04:52 +0300 Subject: [PATCH 008/167] analizators/s4144 --- .../Server/Controllers/PeopleController.cs | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index 17d7da9cde..613d88a16a 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -892,26 +892,14 @@ namespace ASC.Employee.Core.Controllers [Update("{userid}/contacts")] public EmployeeWraperFull UpdateMemberContactsFromBody(string userid, [FromBody] UpdateMemberModel memberModel) { - return UpdateMemberContacts(userid, memberModel); + return SetMemberContacts(userid, memberModel); } [Update("{userid}/contacts")] [Consumes("application/x-www-form-urlencoded")] public EmployeeWraperFull UpdateMemberContactsFromForm(string userid, [FromForm] UpdateMemberModel memberModel) { - return UpdateMemberContacts(userid, memberModel); - } - - private EmployeeWraperFull UpdateMemberContacts(string userid, UpdateMemberModel memberModel) - { - var user = GetUserInfo(userid); - - if (UserManager.IsSystemUser(user.ID)) - throw new SecurityException(); - - UpdateContacts(memberModel.Contacts, user); - UserManager.SaveUserInfo(user); - return EmployeeWraperFullHelper.GetFull(user); + return SetMemberContacts(userid, memberModel); } [Create("{userid}/contacts")] From 5e91416c539197397166e23d429be074e30feb57 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 18:44:54 +0300 Subject: [PATCH 009/167] analizators/s4035 --- common/ASC.Api.Core/Core/ApiDateTime.cs | 2 +- common/ASC.VoipService/VoipModel.cs | 2 +- products/ASC.Files/Core/Core/Entries/FileEntry.cs | 2 +- products/ASC.Files/Core/Core/Entries/Tag.cs | 2 +- web/ASC.Web.Core/Users/UserPhotoManager.cs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/common/ASC.Api.Core/Core/ApiDateTime.cs b/common/ASC.Api.Core/Core/ApiDateTime.cs index 8a4e79495e..125aead66e 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -37,7 +37,7 @@ using ASC.Core; namespace ASC.Api.Core { [TypeConverter(typeof(ApiDateTimeTypeConverter))] - public class ApiDateTime : IComparable, IComparable + public sealed class ApiDateTime : IComparable, IComparable { internal static readonly string[] Formats = new[] { diff --git a/common/ASC.VoipService/VoipModel.cs b/common/ASC.VoipService/VoipModel.cs index 035cc31388..670da6de85 100644 --- a/common/ASC.VoipService/VoipModel.cs +++ b/common/ASC.VoipService/VoipModel.cs @@ -90,7 +90,7 @@ namespace ASC.VoipService } } - public class WorkingHours + public sealed class WorkingHours { public bool Enabled { get; set; } public TimeSpan? From { get; set; } diff --git a/products/ASC.Files/Core/Core/Entries/FileEntry.cs b/products/ASC.Files/Core/Core/Entries/FileEntry.cs index 7172fa396f..e6702feaf5 100644 --- a/products/ASC.Files/Core/Core/Entries/FileEntry.cs +++ b/products/ASC.Files/Core/Core/Entries/FileEntry.cs @@ -155,7 +155,7 @@ namespace ASC.Files.Core return obj is FileEntry f && Equals(f.ID, ID); } - public bool Equals(FileEntry obj) + public virtual bool Equals(FileEntry obj) { return Equals(obj.ID, ID); } diff --git a/products/ASC.Files/Core/Core/Entries/Tag.cs b/products/ASC.Files/Core/Core/Entries/Tag.cs index 8f4f8668e3..246c824594 100644 --- a/products/ASC.Files/Core/Core/Entries/Tag.cs +++ b/products/ASC.Files/Core/Core/Entries/Tag.cs @@ -42,7 +42,7 @@ namespace ASC.Files.Core [Serializable] [DebuggerDisplay("{TagName} ({Id}) entry {EntryType} ({EntryId})")] - public class Tag + public sealed class Tag { public string TagName { get; set; } diff --git a/web/ASC.Web.Core/Users/UserPhotoManager.cs b/web/ASC.Web.Core/Users/UserPhotoManager.cs index e60b91b47a..8680bd8e50 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -50,7 +50,7 @@ using SixLabors.ImageSharp.Processing; namespace ASC.Web.Core.Users { [Transient] - public class ResizeWorkerItem : DistributedTask + public sealed class ResizeWorkerItem : DistributedTask { public ResizeWorkerItem() { From f2442663784c2e2d2c3c5ede743668d646c0f5f2 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 18:50:54 +0300 Subject: [PATCH 010/167] analizators/s3966 --- .../WCFService/FileOperations/FileDownloadOperation.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs index d38c6f4e74..87f0181094 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs @@ -87,7 +87,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations using var scope = ThirdPartyOperation.CreateScope(); var scopeClass = scope.ServiceProvider.GetService(); var (globalStore, filesLinkUtility, _, _, _) = scopeClass; - var stream = TempStream.Create(); + using var stream = TempStream.Create(); (ThirdPartyOperation as FileDownloadOperation).CompressToZip(stream, scope); (DaoOperation as FileDownloadOperation).CompressToZip(stream, scope); @@ -294,8 +294,6 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations { if (CancellationToken.IsCancellationRequested) { - compressTo.Dispose(); - stream.Dispose(); CancellationToken.ThrowIfCancellationRequested(); } From a40b06648a998f5d717252a767af797968d3850e Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 28 Dec 2021 19:01:12 +0300 Subject: [PATCH 011/167] analizators/s3963 --- .../Threading/DistributedTaskQueue.cs | 8 +----- .../Context/Impl/SubscriptionManager.cs | 10 ++----- .../Notify/Signalr/SignalrServiceClient.cs | 7 +---- .../Properties/launchSettings.json | 27 +++++++++++++++++++ web/ASC.Web.Core/Users/CustomNamingPeople.cs | 9 +------ 5 files changed, 32 insertions(+), 29 deletions(-) create mode 100644 common/ASC.Webhooks.Core/Properties/launchSettings.json diff --git a/common/ASC.Common/Threading/DistributedTaskQueue.cs b/common/ASC.Common/Threading/DistributedTaskQueue.cs index dbe2954ada..1801ead832 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -135,7 +135,7 @@ namespace ASC.Common.Threading public class DistributedTaskQueue { - public static readonly int InstanceId; + public static readonly int InstanceId = Process.GetCurrentProcess().Id; private string key; private TaskScheduler Scheduler { get; set; } = TaskScheduler.Default; @@ -157,12 +157,6 @@ namespace ASC.Common.Threading public DistributedTaskCacheNotify DistributedTaskCacheNotify { get; set; } - static DistributedTaskQueue() - { - InstanceId = Process.GetCurrentProcess().Id; - } - - public void QueueTask(DistributedTaskProgress taskProgress) { QueueTask((a, b) => taskProgress.RunJob(), taskProgress); diff --git a/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs b/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs index 531267bd95..c2a048e892 100644 --- a/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs +++ b/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs @@ -42,19 +42,13 @@ namespace ASC.Core private TenantManager TenantManager { get; } private ICache Cache { get; set; } - public static readonly object CacheLocker; - public static readonly List Groups; - - static SubscriptionManager() - { - CacheLocker = new object(); - Groups = new List + public static readonly object CacheLocker = new object(); + public static readonly List Groups = Groups = new List { Constants.Admin.ID, Constants.Everyone.ID, Constants.User.ID }; - } public SubscriptionManager(ISubscriptionService service, TenantManager tenantManager, ICache cache) { diff --git a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs index b7000b5c1a..0793bde618 100644 --- a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs @@ -106,7 +106,7 @@ namespace ASC.Core.Notify.Signalr [Scope(typeof(ConfigureSignalrServiceClient))] public class SignalrServiceClient { - private static readonly TimeSpan Timeout; + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(1); internal ILog Log; private static DateTime lastErrorTime; public bool EnableSignalr; @@ -121,11 +121,6 @@ namespace ASC.Core.Notify.Signalr internal TenantManager TenantManager { get; set; } internal CoreSettings CoreSettings { get; set; } - static SignalrServiceClient() - { - Timeout = TimeSpan.FromSeconds(1); - } - public SignalrServiceClient() { diff --git a/common/ASC.Webhooks.Core/Properties/launchSettings.json b/common/ASC.Webhooks.Core/Properties/launchSettings.json new file mode 100644 index 0000000000..f05963afcc --- /dev/null +++ b/common/ASC.Webhooks.Core/Properties/launchSettings.json @@ -0,0 +1,27 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:49337/", + "sslPort": 44374 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "ASC.Webhooks.Core": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:5001;http://localhost:5000" + } + } +} \ No newline at end of file diff --git a/web/ASC.Web.Core/Users/CustomNamingPeople.cs b/web/ASC.Web.Core/Users/CustomNamingPeople.cs index 7d16a6d47d..512f33a7c8 100644 --- a/web/ASC.Web.Core/Users/CustomNamingPeople.cs +++ b/web/ASC.Web.Core/Users/CustomNamingPeople.cs @@ -164,19 +164,12 @@ namespace ASC.Web.Core.Users [Scope] public class CustomNamingPeople { - private static object Locked; + private static object Locked = new object(); private static bool loaded = false; private static readonly List items = new List(); private SettingsManager SettingsManager { get; } - static CustomNamingPeople() - { - Locked = new object(); - loaded = false; - items = new List(); - } - public CustomNamingPeople(SettingsManager settingsManager) { SettingsManager = settingsManager; From 877095f5259ed64620de41dda4eb4e380d92a921 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Wed, 29 Dec 2021 17:40:19 +0300 Subject: [PATCH 012/167] analizators/s3923 --- .../Services/WCFService/FileOperations/FileDownloadOperation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs index 87f0181094..61dc933b5b 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs @@ -153,7 +153,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations base.FillDistributedTask(); - TaskInfo.SetProperty(PROGRESS, progress < 100 ? progress : progress); + TaskInfo.SetProperty(PROGRESS, progress); TaskInfo.PublishChanges(); } } From facc97b01c412a9f2d44e6516dcdac83b80a0724 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Wed, 29 Dec 2021 17:41:02 +0300 Subject: [PATCH 013/167] analizators/s4423 --- common/ASC.Core.Common/Billing/CouponManager.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/common/ASC.Core.Common/Billing/CouponManager.cs b/common/ASC.Core.Common/Billing/CouponManager.cs index 6c801e33f0..b3b990122f 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -153,7 +153,6 @@ namespace ASC.Core.Common.Billing private HttpClient PrepaireClient() { - ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; const string applicationJson = "application/json"; using var httpClient = new HttpClient { BaseAddress = BaseAddress, Timeout = TimeSpan.FromMinutes(3) }; httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", applicationJson); From 632783b13053d4207a1d765c88fb1866f9e9e359 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Wed, 29 Dec 2021 18:12:39 +0300 Subject: [PATCH 014/167] analizators/s4275 --- .../Context/Impl/CoreConfiguration.cs | 31 +++++++++++-------- products/ASC.Files/Core/Core/Entries/File.cs | 4 ++- .../ASC.Files/Core/Core/Entries/FileEntry.cs | 25 +++++++++++---- .../ASC.Files/Core/Core/Entries/FileHelper.cs | 10 ------ .../ASC.Files/Core/Core/Entries/Folder.cs | 4 ++- .../ASC.Files/Core/ThirdPartyApp/BoxApp.cs | 4 +-- .../Core/ThirdPartyApp/GoogleDriveApp.cs | 4 +-- 7 files changed, 47 insertions(+), 35 deletions(-) diff --git a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs index 76f919a932..ade6cd21b5 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -43,15 +43,27 @@ namespace ASC.Core [Singletone] public class CoreBaseSettings { - private bool? standalone; + private bool? standalone; + private string basedomain; private bool? personal; private bool? customMode; - private IConfiguration Configuration { get; } + private IConfiguration Configuration { get; } public CoreBaseSettings(IConfiguration configuration) { Configuration = configuration; + } + public string Basedomain + { + get + { + if (basedomain == null) + { + basedomain = Configuration["core:base-domain"] ?? string.Empty; + } + return basedomain; + } } public bool Standalone @@ -108,31 +120,24 @@ namespace ASC.Core [Scope(typeof(ConfigureCoreSettings))] public class CoreSettings { - private string basedomain; - public string BaseDomain { get { - if (basedomain == null) - { - basedomain = Configuration["core:base-domain"] ?? string.Empty; - } - string result; - if (CoreBaseSettings.Standalone || string.IsNullOrEmpty(basedomain)) + if (CoreBaseSettings.Standalone || string.IsNullOrEmpty(CoreBaseSettings.Basedomain)) { - result = GetSetting("BaseDomain") ?? basedomain; + result = GetSetting("BaseDomain") ?? CoreBaseSettings.Basedomain; } else { - result = basedomain; + result = CoreBaseSettings.Basedomain; } return result; } set { - if (CoreBaseSettings.Standalone || string.IsNullOrEmpty(basedomain)) + if (CoreBaseSettings.Standalone || string.IsNullOrEmpty(CoreBaseSettings.Basedomain)) { SaveSetting("BaseDomain", value); } diff --git a/products/ASC.Files/Core/Core/Entries/File.cs b/products/ASC.Files/Core/Core/Entries/File.cs index 687f2dcbe5..13bc6274b5 100644 --- a/products/ASC.Files/Core/Core/Entries/File.cs +++ b/products/ASC.Files/Core/Core/Entries/File.cs @@ -30,6 +30,7 @@ using System.Text.Json.Serialization; using ASC.Common; using ASC.Web.Core.Files; +using ASC.Web.Files.Classes; using ASC.Web.Studio.Core; namespace ASC.Files.Core @@ -68,9 +69,10 @@ namespace ASC.Files.Core FileEntryType = FileEntryType.File; } - public File(FileHelper fileHelper): this() + public File(FileHelper fileHelper, Global global): this() { FileHelper = fileHelper; + Global = global; } public int Version { get; set; } diff --git a/products/ASC.Files/Core/Core/Entries/FileEntry.cs b/products/ASC.Files/Core/Core/Entries/FileEntry.cs index e6702feaf5..1370b91d3e 100644 --- a/products/ASC.Files/Core/Core/Entries/FileEntry.cs +++ b/products/ASC.Files/Core/Core/Entries/FileEntry.cs @@ -28,6 +28,7 @@ using System; using System.Text.Json.Serialization; using ASC.Files.Core.Security; +using ASC.Web.Files.Classes; namespace ASC.Files.Core { @@ -37,14 +38,18 @@ namespace ASC.Files.Core [JsonIgnore] public FileHelper FileHelper { get; set; } + [JsonIgnore] + public Global Global { get; set; } + protected FileEntry() { } - public FileEntry(FileHelper fileHelper) + public FileEntry(FileHelper fileHelper, Global global) { FileHelper = fileHelper; + Global = global; } public virtual string Title { get; set; } @@ -52,12 +57,20 @@ namespace ASC.Files.Core public Guid CreateBy { get; set; } [JsonIgnore] - public string CreateByString { get => FileHelper.GetCreateByString(this); } + public string CreateByString + { + get => !CreateBy.Equals(Guid.Empty) ? Global.GetUserName(CreateBy) : _createByString; + set => _createByString = value; + } public Guid ModifiedBy { get; set; } [JsonIgnore] - public string ModifiedByString { get => FileHelper.GetModifiedByString(this); } + public string ModifiedByString + { + get => !ModifiedBy.Equals(Guid.Empty) ? Global.GetUserName(ModifiedBy) : _modifiedByString; + set => _modifiedByString = value; + } [JsonIgnore] public string CreateOnString @@ -99,8 +112,8 @@ namespace ASC.Files.Core public FileEntryType FileEntryType; - public string _modifiedByString; - public string _createByString; + private string _modifiedByString; + private string _createByString; public override string ToString() { @@ -127,7 +140,7 @@ namespace ASC.Files.Core } - protected FileEntry(FileHelper fileHelper) : base(fileHelper) + protected FileEntry(FileHelper fileHelper, Global global) : base(fileHelper, global) { } diff --git a/products/ASC.Files/Core/Core/Entries/FileHelper.cs b/products/ASC.Files/Core/Core/Entries/FileHelper.cs index 07700232a1..db899371b3 100644 --- a/products/ASC.Files/Core/Core/Entries/FileHelper.cs +++ b/products/ASC.Files/Core/Core/Entries/FileHelper.cs @@ -54,16 +54,6 @@ namespace ASC.Files.Core Global = global; } - internal string GetCreateByString(FileEntry fileEntry) - { - return !fileEntry.CreateBy.Equals(Guid.Empty) ? Global.GetUserName(fileEntry.CreateBy) : fileEntry._createByString; - } - - internal string GetModifiedByString(FileEntry fileEntry) - { - return !fileEntry.ModifiedBy.Equals(Guid.Empty) ? Global.GetUserName(fileEntry.ModifiedBy) : fileEntry._modifiedByString; - } - internal string GetTitle(File file) { return string.IsNullOrEmpty(file.ConvertedType) diff --git a/products/ASC.Files/Core/Core/Entries/Folder.cs b/products/ASC.Files/Core/Core/Entries/Folder.cs index 2040de017b..6a68c1b62d 100644 --- a/products/ASC.Files/Core/Core/Entries/Folder.cs +++ b/products/ASC.Files/Core/Core/Entries/Folder.cs @@ -28,6 +28,7 @@ using System; using System.Diagnostics; using ASC.Common; +using ASC.Web.Files.Classes; namespace ASC.Files.Core { @@ -89,9 +90,10 @@ namespace ASC.Files.Core FileEntryType = FileEntryType.Folder; } - public Folder(FileHelper fileHelper) : this() + public Folder(FileHelper fileHelper, Global global) : this() { FileHelper = fileHelper; + Global = global; } public override string UniqID diff --git a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs index 839c78c43e..5f4209567c 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -219,13 +219,13 @@ namespace ASC.Web.Files.ThirdPartyApp var modifiedBy = jsonFile.Value("modified_by"); if (modifiedBy != null) { - file._modifiedByString = modifiedBy.Value("name"); + file.ModifiedByString = modifiedBy.Value("name"); } var createdBy = jsonFile.Value("created_by"); if (createdBy != null) { - file._createByString = createdBy.Value("name"); + file.CreateByString = createdBy.Value("name"); } diff --git a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs index 929d38b689..63461d7b7e 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -234,13 +234,13 @@ namespace ASC.Web.Files.ThirdPartyApp file.CreateOn = TenantUtil.DateTimeFromUtc(jsonFile.Value("createdTime")); file.ModifiedOn = TenantUtil.DateTimeFromUtc(jsonFile.Value("modifiedTime")); file.ContentLength = Convert.ToInt64(jsonFile.Value("size")); - file._modifiedByString = jsonFile["lastModifyingUser"]["displayName"].Value(); + file.ModifiedByString = jsonFile["lastModifyingUser"]["displayName"].Value(); file.ProviderKey = "Google"; var owners = jsonFile["owners"]; if (owners != null) { - file._createByString = owners[0]["displayName"].Value(); + file.CreateByString = owners[0]["displayName"].Value(); } editable = jsonFile["capabilities"]["canEdit"].Value(); From 973f8a41b9ae020cfd511cf8a449a6b747585d47 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Wed, 29 Dec 2021 18:47:35 +0300 Subject: [PATCH 015/167] analizators/s2259 --- common/ASC.Core.Common/BaseCommonLinkUtility.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/common/ASC.Core.Common/BaseCommonLinkUtility.cs b/common/ASC.Core.Common/BaseCommonLinkUtility.cs index 75c153b414..f2a63c9f0c 100644 --- a/common/ASC.Core.Common/BaseCommonLinkUtility.cs +++ b/common/ASC.Core.Common/BaseCommonLinkUtility.cs @@ -90,6 +90,9 @@ namespace ASC.Core.Common if (HttpContextAccessor?.HttpContext?.Request != null) { var u = HttpContextAccessor?.HttpContext.Request.GetUrlRewriter(); + + if (u == null) throw new ArgumentNullException("u"); + uriBuilder = new UriBuilder(u.Scheme, LOCALHOST, u.Port); } _serverRoot = uriBuilder; @@ -125,6 +128,9 @@ namespace ASC.Core.Common if (HttpContextAccessor?.HttpContext?.Request != null) { var u = HttpContextAccessor?.HttpContext?.Request.GetUrlRewriter(); + + if (u == null) throw new ArgumentNullException("u"); + result = new UriBuilder(u.Scheme, u.Host, u.Port); if (CoreBaseSettings.Standalone && !result.Uri.IsLoopback) From abd72b9e0de7a1747e6794718884a3bd5efc56f6 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Wed, 29 Dec 2021 18:49:02 +0300 Subject: [PATCH 016/167] analizators/s3903 --- common/ASC.Common/Data/StreamExtension.cs | 38 +++++++++++++---------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/common/ASC.Common/Data/StreamExtension.cs b/common/ASC.Common/Data/StreamExtension.cs index c856976971..c27b05eee1 100644 --- a/common/ASC.Common/Data/StreamExtension.cs +++ b/common/ASC.Common/Data/StreamExtension.cs @@ -27,22 +27,26 @@ using System; using System.IO; -public static class StreamExtension -{ - public const int BufferSize = 2048; //NOTE: set to 2048 to fit in minimum tcp window - - public static void StreamCopyTo(this Stream srcStream, Stream dstStream, int length) - { - if (srcStream == null) throw new ArgumentNullException("srcStream"); - if (dstStream == null) throw new ArgumentNullException("dstStream"); - var buffer = new byte[BufferSize]; - int totalRead = 0; - int readed; - while ((readed = srcStream.Read(buffer, 0, length - totalRead > BufferSize ? BufferSize : length - totalRead)) > 0 && totalRead < length) +namespace ASC.Common.Data +{ + public static class StreamExtension + { + public const int BufferSize = 2048; //NOTE: set to 2048 to fit in minimum tcp window + + public static void StreamCopyTo(this Stream srcStream, Stream dstStream, int length) { - dstStream.Write(buffer, 0, readed); - totalRead += readed; - } - } -} + if (srcStream == null) throw new ArgumentNullException("srcStream"); + if (dstStream == null) throw new ArgumentNullException("dstStream"); + + var buffer = new byte[BufferSize]; + int totalRead = 0; + int readed; + while ((readed = srcStream.Read(buffer, 0, length - totalRead > BufferSize ? BufferSize : length - totalRead)) > 0 && totalRead < length) + { + dstStream.Write(buffer, 0, readed); + totalRead += readed; + } + } + } +} \ No newline at end of file From 2a82bc884e8120fbda7c241dc4d0c78a91c95820 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 30 Dec 2021 12:44:25 +0300 Subject: [PATCH 017/167] analizators/s2583 --- common/ASC.Core.Common/Billing/BillingClient.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/ASC.Core.Common/Billing/BillingClient.cs b/common/ASC.Core.Common/Billing/BillingClient.cs index 297c40b75e..43deeb9523 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -272,7 +272,7 @@ namespace ASC.Core.Billing return result; } - var @params = (parameters ?? Enumerable.Empty>()).Select(p => string.Format("{0}: {1}", p.Item1, p.Item2)); + var @params = parameters.Select(p => string.Format("{0}: {1}", p.Item1, p.Item2)); var info = new { Method = method, PortalId = portalId, Params = string.Join(", ", @params) }; if (result.Contains("{\"Message\":\"error: cannot find ")) { From e2857e87f53d48e41e9b9289ca10f2a9e1dfbd1f Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 30 Dec 2021 12:52:44 +0300 Subject: [PATCH 018/167] analizators/s2997 --- common/ASC.Core.Common/Billing/CouponManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/ASC.Core.Common/Billing/CouponManager.cs b/common/ASC.Core.Common/Billing/CouponManager.cs index b3b990122f..fc8bcd932c 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -154,7 +154,7 @@ namespace ASC.Core.Common.Billing private HttpClient PrepaireClient() { const string applicationJson = "application/json"; - using var httpClient = new HttpClient { BaseAddress = BaseAddress, Timeout = TimeSpan.FromMinutes(3) }; + var httpClient = new HttpClient { BaseAddress = BaseAddress, Timeout = TimeSpan.FromMinutes(3) }; httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", applicationJson); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", applicationJson); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("X-Avangate-Authentication", CreateAuthHeader()); From 555ca30c99087d1ff3432a8af5ed7a775ecec8af Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 30 Dec 2021 13:23:01 +0300 Subject: [PATCH 019/167] analizators/s2259 --- common/ASC.Core.Common/Context/SecurityContext.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/common/ASC.Core.Common/Context/SecurityContext.cs b/common/ASC.Core.Common/Context/SecurityContext.cs index b0ca20ff20..b602aed346 100644 --- a/common/ASC.Core.Common/Context/SecurityContext.cs +++ b/common/ASC.Core.Common/Context/SecurityContext.cs @@ -134,6 +134,9 @@ namespace ASC.Core if (HttpContextAccessor?.HttpContext != null) { var request = HttpContextAccessor?.HttpContext.Request; + + if (request == null) throw new ArgumentNullException("request"); + ipFrom = "from " + (request.Headers["X-Forwarded-For"].ToString() ?? request.GetUserHostAddress()); address = "for " + request.GetUrlRewriter(); } @@ -189,6 +192,9 @@ namespace ASC.Core if (HttpContextAccessor?.HttpContext != null) { var request = HttpContextAccessor?.HttpContext.Request; + + if (request == null) throw new ArgumentNullException("request"); + address = "for " + request.GetUrlRewriter(); ipFrom = "from " + (request.Headers["X-Forwarded-For"].ToString() ?? request.GetUserHostAddress()); } From 3d33fecf776dad955d3b3aa04969a43d2ace891c Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 30 Dec 2021 14:00:03 +0300 Subject: [PATCH 020/167] analizators/s2259 --- common/ASC.Api.Core/Middleware/TenantStatusFilter.cs | 2 +- common/ASC.MessagingSystem/MessageFactory.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs b/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs index 8eda940670..8a04954c49 100644 --- a/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs +++ b/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs @@ -34,7 +34,7 @@ namespace ASC.Api.Core.Middleware if (tenant == null) { context.Result = new StatusCodeResult((int)HttpStatusCode.NotFound); - log.WarnFormat("Tenant {0} not found", tenant.TenantId); + log.WarnFormat("Current tenant not found"); return; } diff --git a/common/ASC.MessagingSystem/MessageFactory.cs b/common/ASC.MessagingSystem/MessageFactory.cs index 2bf1429307..4c54aa06a2 100644 --- a/common/ASC.MessagingSystem/MessageFactory.cs +++ b/common/ASC.MessagingSystem/MessageFactory.cs @@ -73,7 +73,7 @@ namespace ASC.MessagingSystem Action = action, Description = description, Target = target, - UAHeader = request.Headers[userAgentHeader].FirstOrDefault() + UAHeader = request?.Headers[userAgentHeader].FirstOrDefault() }; } catch (Exception ex) From 8f53895e3db723e1985b24692c4cdbc30634f974 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 30 Dec 2021 14:03:05 +0300 Subject: [PATCH 021/167] analizators/s2201 --- common/ASC.Core.Common/Data/DbTenantService.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/common/ASC.Core.Common/Data/DbTenantService.cs b/common/ASC.Core.Common/Data/DbTenantService.cs index 59b26e36c8..d703aa1ffb 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -231,9 +231,8 @@ namespace ASC.Core.Data //new password result = result.Concat(q.Select(FromTenantUserToTenant)).ToList(); - result.Distinct(); - return result; + return result.Distinct(); } } From 62735392074910db4f1c18a37177082bbed565d5 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 30 Dec 2021 14:03:50 +0300 Subject: [PATCH 022/167] analizators/s2583 --- common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index 5666d80941..900beb4513 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -357,8 +357,6 @@ namespace ASC.ElasticSearch lock (Locker) { - if (isExist) return true; - isExist = Client.Instance.Indices.Exists(data.IndexName).Exists; BaseIndexerHelper.IsExist.TryUpdate(data.IndexName, IsExist, false); From 1c29b81a9a95cec64e001bddfc170c5dc045f6bb Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 30 Dec 2021 15:01:20 +0300 Subject: [PATCH 023/167] analizators/s1848 --- products/ASC.Calendar/Server/BusinessObjects/Calendar.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/ASC.Calendar/Server/BusinessObjects/Calendar.cs b/products/ASC.Calendar/Server/BusinessObjects/Calendar.cs index 1075f46948..716b996328 100644 --- a/products/ASC.Calendar/Server/BusinessObjects/Calendar.cs +++ b/products/ASC.Calendar/Server/BusinessObjects/Calendar.cs @@ -81,7 +81,7 @@ namespace ASC.Calendar.BusinessObjects } public static List GetEventWrappers(this BaseCalendar calendar, Guid userId, ApiDateTime startDate, ApiDateTime endDate, EventWrapperHelper eventWrapperHelper) - {new List(); + { var result = new List(); if (calendar != null) { From 6c32e34b409ba3fd4c66b069a6117b552fb9824f Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 30 Dec 2021 15:04:47 +0300 Subject: [PATCH 024/167] analizators/s1848 --- .../ASC.CRM/Server/Classes/ContactPhotoManager.cs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs b/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs index 4d3264e78f..e0eb541fe1 100644 --- a/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs +++ b/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs @@ -349,14 +349,11 @@ namespace ASC.Web.CRM.Classes lock (locker) { - _resizeQueue.GetTasks().Where(item => item.ContactID == contactID) - .All(item => - { - _resizeQueue.RemoveTask(item.Id); - - return true; - }); - + foreach(var item in _resizeQueue.GetTasks().Where(item => item.ContactID == contactID)) + { + _resizeQueue.RemoveTask(item.Id); + } + var photoDirectory = !isTmpDir ? BuildFileDirectory(contactID) : (String.IsNullOrEmpty(tmpDirName) ? BuildFileTmpDirectory(contactID) : BuildFileTmpDirectory(tmpDirName)); From b9ae9b7335a34a5f0cd91e9e40c03dca45705f94 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 30 Dec 2021 15:12:44 +0300 Subject: [PATCH 025/167] analizators/s2583 --- products/ASC.CRM/Server/Core/Dao/ContactDao.cs | 2 +- .../Server/Mapping/TypeConverter/ContactDtoTypeConverter.cs | 2 -- products/ASC.People/Server/Controllers/PeopleController.cs | 2 -- 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/products/ASC.CRM/Server/Core/Dao/ContactDao.cs b/products/ASC.CRM/Server/Core/Dao/ContactDao.cs index 99804b5f7e..b8b095a5fc 100644 --- a/products/ASC.CRM/Server/Core/Dao/ContactDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/ContactDao.cs @@ -929,7 +929,7 @@ namespace ASC.CRM.Core.Dao } } - return GetContacts(title, null, -1, -1, isCompany ? ContactListViewType.Company : ContactListViewType.Person, DateTime.MinValue, DateTime.MinValue, 0, 0, null); + return GetContacts(title, null, -1, -1, ContactListViewType.Person, DateTime.MinValue, DateTime.MinValue, 0, 0, null); } public void RemoveMember(int[] peopleID) diff --git a/products/ASC.CRM/Server/Mapping/TypeConverter/ContactDtoTypeConverter.cs b/products/ASC.CRM/Server/Mapping/TypeConverter/ContactDtoTypeConverter.cs index f1a6ef2262..9ceaee8d81 100644 --- a/products/ASC.CRM/Server/Mapping/TypeConverter/ContactDtoTypeConverter.cs +++ b/products/ASC.CRM/Server/Mapping/TypeConverter/ContactDtoTypeConverter.cs @@ -219,8 +219,6 @@ namespace ASC.CRM.Mapping { if (source == null) return null; - if (source == null) return null; - var contactBaseDto = context.Mapper.Map(source); var result = new ContactBaseWithPhoneDto diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index 613d88a16a..06143f600a 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -1484,8 +1484,6 @@ namespace ASC.Employee.Core.Controllers if (user.IsActive) continue; var viewer = UserManager.GetUsers(SecurityContext.CurrentAccount.ID); - if (user == null) throw new Exception(Resource.ErrorUserNotFound); - if (viewer == null) throw new Exception(Resource.ErrorAccessDenied); if (viewer.IsAdmin(UserManager) || viewer.ID == user.ID) From 50698af6498881e5601ae916b4150ffd182f8607 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 30 Dec 2021 15:28:14 +0300 Subject: [PATCH 026/167] analizators/s3168 --- products/ASC.CRM/Server/Utils/ReportHelper.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/products/ASC.CRM/Server/Utils/ReportHelper.cs b/products/ASC.CRM/Server/Utils/ReportHelper.cs index 6cf7eed67d..198f1f7e0c 100644 --- a/products/ASC.CRM/Server/Utils/ReportHelper.cs +++ b/products/ASC.CRM/Server/Utils/ReportHelper.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.Net.Http; using System.Text.Json; +using System.Threading.Tasks; using ASC.Common; using ASC.Core; @@ -221,7 +222,7 @@ namespace ASC.Web.CRM.Classes .Replace("${reportData}", JsonSerializer.Serialize(data)); } - private async void SaveReportFile(ReportState state, string url) + private async Task SaveReportFile(ReportState state, string url) { using var httpClient = new HttpClient(); var responseData = await httpClient.GetByteArrayAsync(url); From 579e867b2c3b6bfae2701135d64385ddb6a42e9d Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Mon, 10 Jan 2022 11:18:55 +0300 Subject: [PATCH 027/167] analizators/s3168 --- .../Services/DocumentService/DocbuilderReportsUtility.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs index 3f62330780..1ea0b2a1b6 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs @@ -63,13 +63,13 @@ namespace ASC.Web.Files.Services.DocumentService public string Script { get; } public int ReportType { get; } public ReportOrigin Origin { get; } - public Action SaveFileAction { get; } + public Func SaveFileAction { get; } public object Obj { get; } public int TenantId { get; } public Guid UserId { get; } public ReportStateData(string fileName, string tmpFileName, string script, int reportType, ReportOrigin origin, - Action saveFileAction, object obj, + Func saveFileAction, object obj, int tenantId, Guid userId) { FileName = fileName; @@ -98,7 +98,7 @@ namespace ASC.Web.Files.Services.DocumentService internal string BuilderKey { get; set; } internal string Script { get; set; } internal string TmpFileName { get; set; } - internal Action SaveFileAction { get; set; } + internal Func SaveFileAction { get; set; } internal int TenantId { get; set; } internal Guid UserId { get; set; } From d7a1f73c4899fd338845401292d4aed72e77498b Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Mon, 10 Jan 2022 11:45:40 +0300 Subject: [PATCH 028/167] analizators/s4035 --- common/ASC.VoipService/VoipModel.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/ASC.VoipService/VoipModel.cs b/common/ASC.VoipService/VoipModel.cs index 670da6de85..13c4b5498a 100644 --- a/common/ASC.VoipService/VoipModel.cs +++ b/common/ASC.VoipService/VoipModel.cs @@ -105,7 +105,7 @@ namespace ASC.VoipService } - protected bool Equals(WorkingHours other) + private bool Equals(WorkingHours other) { return Enabled.Equals(other.Enabled) && From.Equals(other.From) && To.Equals(other.To); } From a671732da5b7d112253b014e32a15bde95a74a66 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Mon, 10 Jan 2022 12:24:21 +0300 Subject: [PATCH 029/167] analizators/SCS0005 --- common/ASC.Common/Utils/RandomString.cs | 4 ++-- common/ASC.Core.Common/Encryption/EncryptionSettings.cs | 5 ++--- common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs | 5 ++--- products/ASC.Files/Core/Model/FileWrapper.cs | 2 +- products/ASC.Files/Core/Model/FolderWrapper.cs | 8 ++++---- web/ASC.Web.Core/Sms/SmsKeyStorage.cs | 3 ++- web/ASC.Web.Core/Users/UserManagerWrapper.cs | 7 +++---- 7 files changed, 16 insertions(+), 18 deletions(-) diff --git a/common/ASC.Common/Utils/RandomString.cs b/common/ASC.Common/Utils/RandomString.cs index 2a8d3bd77f..a7adf92428 100644 --- a/common/ASC.Common/Utils/RandomString.cs +++ b/common/ASC.Common/Utils/RandomString.cs @@ -25,6 +25,7 @@ using System; +using System.Security.Cryptography; using System.Text; namespace ASC.Common.Utils @@ -35,10 +36,9 @@ namespace ASC.Common.Utils { const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; var res = new StringBuilder(); - var rnd = new Random(); while (0 < length--) { - res.Append(valid[rnd.Next(valid.Length)]); + res.Append(valid[RandomNumberGenerator.GetInt32(valid.Length)]); } return res.ToString(); } diff --git a/common/ASC.Core.Common/Encryption/EncryptionSettings.cs b/common/ASC.Core.Common/Encryption/EncryptionSettings.cs index cdac5e98a1..559a939b45 100644 --- a/common/ASC.Core.Common/Encryption/EncryptionSettings.cs +++ b/common/ASC.Core.Common/Encryption/EncryptionSettings.cs @@ -172,16 +172,15 @@ namespace ASC.Core.Encryption if (num < numberOfNonAlphanumericCharacters) { - var random = new Random(); for (var j = 0; j < numberOfNonAlphanumericCharacters - num; j++) { int num3; do { - num3 = random.Next(0, length); + num3 = RandomNumberGenerator.GetInt32(0, length); } while (!char.IsLetterOrDigit(array2[num3])); - array2[num3] = punctuations[random.Next(0, punctuations.Length)]; + array2[num3] = punctuations[RandomNumberGenerator.GetInt32(0, punctuations.Length)]; } } diff --git a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs index 74d64519b6..e2ebfb5ff0 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -32,6 +32,7 @@ using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; +using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -776,9 +777,7 @@ namespace ASC.Data.Storage.GoogleCloud for (var i = 0; i < MAX_RETRIES; i++) { - var random = new Random(); - - millisecondsTimeout = Math.Min(Convert.ToInt32(Math.Pow(2, i)) + random.Next(0, 1000), 32 * 1000); + millisecondsTimeout = Math.Min(Convert.ToInt32(Math.Pow(2, i)) + RandomNumberGenerator.GetInt32(1000), 32 * 1000); try { diff --git a/products/ASC.Files/Core/Model/FileWrapper.cs b/products/ASC.Files/Core/Model/FileWrapper.cs index 39de1bef1b..cc9160abed 100644 --- a/products/ASC.Files/Core/Model/FileWrapper.cs +++ b/products/ASC.Files/Core/Model/FileWrapper.cs @@ -131,7 +131,7 @@ namespace ASC.Api.Documents //Updated = ApiDateTime.GetSample(), //Created = ApiDateTime.GetSample(), //CreatedBy = EmployeeWraper.GetSample(), - Id = new Random().Next(), + Id = 10, RootFolderType = FolderType.BUNCH, Shared = false, Title = "Some titile.txt", diff --git a/products/ASC.Files/Core/Model/FolderWrapper.cs b/products/ASC.Files/Core/Model/FolderWrapper.cs index 55519827df..6d5738bde6 100644 --- a/products/ASC.Files/Core/Model/FolderWrapper.cs +++ b/products/ASC.Files/Core/Model/FolderWrapper.cs @@ -80,14 +80,14 @@ namespace ASC.Api.Documents //Updated = ApiDateTime.GetSample(), //Created = ApiDateTime.GetSample(), //CreatedBy = EmployeeWraper.GetSample(), - Id = new Random().Next(), + Id = 10, RootFolderType = FolderType.BUNCH, Shared = false, Title = "Some titile", //UpdatedBy = EmployeeWraper.GetSample(), - FilesCount = new Random().Next(), - FoldersCount = new Random().Next(), - ParentId = new Random().Next(), + FilesCount = 5, + FoldersCount = 7, + ParentId = 10, IsShareable = null }; } diff --git a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs index c5dc7d9cf1..0d892d4398 100644 --- a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs +++ b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs @@ -27,6 +27,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Security.Cryptography; using ASC.Common; using ASC.Common.Caching; @@ -120,7 +121,7 @@ namespace ASC.Web.Core.Sms return false; } - key = new Random().Next((int)Math.Pow(10, KeyLength - 1), (int)Math.Pow(10, KeyLength)).ToString(CultureInfo.InvariantCulture); + key = RandomNumberGenerator.GetInt32((int)Math.Pow(10, KeyLength - 1), (int)Math.Pow(10, KeyLength)).ToString(CultureInfo.InvariantCulture); phoneKeys[key] = DateTime.UtcNow; KeyCache.Insert(cacheKey, phoneKeys, DateTime.UtcNow.Add(StoreInterval)); diff --git a/web/ASC.Web.Core/Users/UserManagerWrapper.cs b/web/ASC.Web.Core/Users/UserManagerWrapper.cs index 09133c0921..0b058d1ffc 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -27,6 +27,7 @@ using System; using System.Globalization; using System.Net.Mail; +using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; @@ -294,16 +295,14 @@ namespace ASC.Web.Core.Users return Guid.NewGuid().ToString(); } - private static readonly Random Rnd = new Random(); - internal static string GeneratePassword(int minLength, int maxLength, string noise) { - var length = Rnd.Next(minLength, maxLength + 1); + var length = RandomNumberGenerator.GetInt32(minLength, maxLength + 1); var pwd = string.Empty; while (length-- > 0) { - pwd += noise.Substring(Rnd.Next(noise.Length - 1), 1); + pwd += noise.Substring(RandomNumberGenerator.GetInt32(noise.Length - 1), 1); } return pwd; } From c43f2442821e94f8b2087be72f2bb0b61c9a6380 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Mon, 10 Jan 2022 18:13:30 +0300 Subject: [PATCH 030/167] analizators/U2U1003 --- .../Patterns/NVelocityPatternFormatter.cs | 2 +- common/ASC.Notify.Textile/JabberStyler.cs | 4 +-- .../Blocks/CapitalsBlockModifier.cs | 2 +- .../ASC.Textile/Blocks/CodeBlockModifier.cs | 2 +- .../ASC.Textile/Blocks/ImageBlockModifier.cs | 2 +- .../Server/Api/ContactInfosController.cs | 2 +- products/ASC.CRM/Server/Core/Dao/TagDao.cs | 2 +- .../Core/Core/Thirdparty/Box/BoxDaoBase.cs | 2 +- .../Core/Thirdparty/Dropbox/DropboxDaoBase.cs | 2 +- .../Thirdparty/OneDrive/OneDriveDaoBase.cs | 2 +- .../SharePoint/SharePointDaoBase.cs | 2 +- .../Thirdparty/Sharpbox/SharpBoxDaoBase.cs | 2 +- .../Notify/NotifyConfiguration.cs | 4 +-- .../Notify/StudioNotifyService.cs | 28 +++++++++---------- .../Notify/StudioPeriodicNotify.cs | 28 +++++++++---------- 15 files changed, 43 insertions(+), 43 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs b/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs index 49f726766c..486fbf9e3f 100644 --- a/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs +++ b/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs @@ -71,7 +71,7 @@ namespace ASC.Notify.Patterns base.AfterFormat(message); } - private static void EventCartridgeReferenceInsertion(object sender, ReferenceInsertionEventArgs e) + private void EventCartridgeReferenceInsertion(object sender, ReferenceInsertionEventArgs e) { if (!(e.OriginalValue is string originalString)) return; var lines = originalString.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); diff --git a/common/ASC.Notify.Textile/JabberStyler.cs b/common/ASC.Notify.Textile/JabberStyler.cs index 5a4265e0d5..690defa0db 100644 --- a/common/ASC.Notify.Textile/JabberStyler.cs +++ b/common/ASC.Notify.Textile/JabberStyler.cs @@ -72,7 +72,7 @@ namespace ASC.Notify.Textile message.Body = body; } - private static string EvalLink(Match match) + private string EvalLink(Match match) { if (match.Success) { @@ -88,7 +88,7 @@ namespace ASC.Notify.Textile return match.Value; } - private static string ArgMatchReplace(Match match) + private string ArgMatchReplace(Match match) { return match.Result("${arg}"); } diff --git a/common/ASC.Textile/Blocks/CapitalsBlockModifier.cs b/common/ASC.Textile/Blocks/CapitalsBlockModifier.cs index 546621a5bd..800d52cc0a 100644 --- a/common/ASC.Textile/Blocks/CapitalsBlockModifier.cs +++ b/common/ASC.Textile/Blocks/CapitalsBlockModifier.cs @@ -11,7 +11,7 @@ namespace Textile.Blocks return line; } - static private string CapitalsFormatMatchEvaluator(Match m) + private string CapitalsFormatMatchEvaluator(Match m) { return @"" + m.Groups["caps"].Value + @""; } diff --git a/common/ASC.Textile/Blocks/CodeBlockModifier.cs b/common/ASC.Textile/Blocks/CodeBlockModifier.cs index 476404a986..efb6e635ee 100644 --- a/common/ASC.Textile/Blocks/CodeBlockModifier.cs +++ b/common/ASC.Textile/Blocks/CodeBlockModifier.cs @@ -49,7 +49,7 @@ namespace Textile.Blocks return line; } - static public string CodeFormatMatchEvaluator(Match m) + public string CodeFormatMatchEvaluator(Match m) { var res = m.Groups["before"].Value + " 0) diff --git a/common/ASC.Textile/Blocks/ImageBlockModifier.cs b/common/ASC.Textile/Blocks/ImageBlockModifier.cs index a000ef4f76..b5ea663f66 100644 --- a/common/ASC.Textile/Blocks/ImageBlockModifier.cs +++ b/common/ASC.Textile/Blocks/ImageBlockModifier.cs @@ -36,7 +36,7 @@ namespace Textile.Blocks return line; } - static string ImageFormatMatchEvaluator(Match m) + string ImageFormatMatchEvaluator(Match m) { var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "img"); if (m.Groups["algn"].Length > 0) diff --git a/products/ASC.CRM/Server/Api/ContactInfosController.cs b/products/ASC.CRM/Server/Api/ContactInfosController.cs index bdefcc5b85..8ac80bf1e2 100644 --- a/products/ASC.CRM/Server/Api/ContactInfosController.cs +++ b/products/ASC.CRM/Server/Api/ContactInfosController.cs @@ -537,7 +537,7 @@ namespace ASC.CRM.Api return wrapper; } - private static ContactInfo FromContactInfoDto(ContactInfoDto contactInfoDto) + private ContactInfo FromContactInfoDto(ContactInfoDto contactInfoDto) { return new ContactInfo { diff --git a/products/ASC.CRM/Server/Core/Dao/TagDao.cs b/products/ASC.CRM/Server/Core/Dao/TagDao.cs index 4b1d290e9d..a3ef15ec09 100644 --- a/products/ASC.CRM/Server/Core/Dao/TagDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/TagDao.cs @@ -429,7 +429,7 @@ namespace ASC.CRM.Core.Dao tx.Commit(); } - private static string CorrectTag(string tag) + private string CorrectTag(string tag) { return tag == null ? null diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs index 3a0346f7cf..33ca8c75f7 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs @@ -311,7 +311,7 @@ namespace ASC.Files.Thirdparty.Box return requestTitle; } - private static string MatchEvaluator(Match match) + private string MatchEvaluator(Match match) { var index = Convert.ToInt32(match.Groups[2].Value); var staticText = match.Value.Substring(string.Format(" ({0})", index).Length); diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs index cae4a21698..f94366f4b4 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs @@ -303,7 +303,7 @@ namespace ASC.Files.Thirdparty.Dropbox return requestTitle; } - private static string MatchEvaluator(Match match) + private string MatchEvaluator(Match match) { var index = Convert.ToInt32(match.Groups[2].Value); var staticText = match.Value.Substring(string.Format(" ({0})", index).Length); diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs index 6d8c1ea275..666c1e4f21 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs @@ -268,7 +268,7 @@ namespace ASC.Files.Thirdparty.OneDrive return requestTitle; } - private static string MatchEvaluator(Match match) + private string MatchEvaluator(Match match) { var index = Convert.ToInt32(match.Groups[2].Value); var staticText = match.Value.Substring(string.Format(" ({0})", index).Length); diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoBase.cs index e495a3ed55..c193facc12 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoBase.cs @@ -77,7 +77,7 @@ namespace ASC.Files.Thirdparty.SharePoint return requestTitle; } - private static string MatchEvaluator(Match match) + private string MatchEvaluator(Match match) { var index = Convert.ToInt32(match.Groups[2].Value); var staticText = match.Value.Substring(string.Format(" ({0})", index).Length); diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs index 3cdc336b54..2216330cea 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs @@ -467,7 +467,7 @@ namespace ASC.Files.Thirdparty.Sharpbox return subFolders.Concat(files); } - private static string MatchEvaluator(Match match) + private string MatchEvaluator(Match match) { var index = Convert.ToInt32(match.Groups[2].Value); var staticText = match.Value.Substring(string.Format(" ({0})", index).Length); diff --git a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs index 0cd3f54935..ed9ba6e6a4 100644 --- a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs +++ b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs @@ -88,7 +88,7 @@ namespace ASC.Web.Studio.Core.Notify } } - private static void NotifyClientRegisterCallback(Context context, INotifyClient client) + private void NotifyClientRegisterCallback(Context context, INotifyClient client) { #region url correction @@ -250,7 +250,7 @@ namespace ASC.Web.Studio.Core.Notify #endregion } - private static void BeforeTransferRequest(NotifyEngine sender, NotifyRequest request, IServiceScope scope) + private void BeforeTransferRequest(NotifyEngine sender, NotifyRequest request, IServiceScope scope) { var aid = Guid.Empty; var aname = string.Empty; diff --git a/web/ASC.Web.Core/Notify/StudioNotifyService.cs b/web/ASC.Web.Core/Notify/StudioNotifyService.cs index 4a88999ee9..fe30c0aa20 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyService.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyService.cs @@ -181,7 +181,7 @@ namespace ASC.Web.Studio.Core.Notify var hash = Authentication.GetUserPasswordStamp(userInfo.ID).ToString("s"); var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(userInfo.Email, ConfirmType.PasswordChange, hash, userInfo.ID); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonChangePassword; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonChangePassword; var action = CoreBaseSettings.Personal ? (CoreBaseSettings.CustomMode ? Actions.PersonalCustomModePasswordChange : Actions.PersonalPasswordChange) @@ -202,7 +202,7 @@ namespace ASC.Web.Studio.Core.Notify { var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(email, ConfirmType.EmailChange, AuthContext.CurrentAccount.ID); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonChangeEmail; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonChangeEmail; var action = CoreBaseSettings.Personal ? (CoreBaseSettings.CustomMode ? Actions.PersonalCustomModeEmailChangeV115 : Actions.PersonalEmailChangeV115) @@ -220,7 +220,7 @@ namespace ASC.Web.Studio.Core.Notify { var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(email, ConfirmType.EmailActivation, null, user.ID); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonActivateEmail; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonActivateEmail; client.SendNoticeToAsync( Actions.ActivateEmail, @@ -290,7 +290,7 @@ namespace ASC.Web.Studio.Core.Notify { var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(userInfo.Email.ToLower(), ConfirmType.PhoneActivation); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonChangePhone; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonChangePhone; client.SendNoticeToAsync( Actions.PhoneChange, @@ -303,7 +303,7 @@ namespace ASC.Web.Studio.Core.Notify { var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(userInfo.Email.ToLower(), ConfirmType.TfaActivation); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonChangeTfa; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonChangeTfa; client.SendNoticeToAsync( Actions.TfaChange, @@ -326,7 +326,7 @@ namespace ASC.Web.Studio.Core.Notify var inviteUrl = CommonLinkUtility.GetConfirmationUrl(email, ConfirmType.EmpInvite, (int)emplType) + string.Format("&emplType={0}", (int)emplType); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonJoin; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonJoin; client.SendNoticeToAsync( Actions.JoinUsers, @@ -454,7 +454,7 @@ namespace ASC.Web.Studio.Core.Notify var confirmationUrl = GenerateActivationConfirmUrl(newUserInfo); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonAccept; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonAccept; client.SendNoticeToAsync( notifyAction, @@ -492,7 +492,7 @@ namespace ASC.Web.Studio.Core.Notify var confirmationUrl = GenerateActivationConfirmUrl(newUserInfo); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonAccept; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonAccept; client.SendNoticeToAsync( notifyAction, @@ -657,7 +657,7 @@ namespace ASC.Web.Studio.Core.Notify { var u = UserManager.GetUsers(t.OwnerId); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonDeactivatePortal; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonDeactivatePortal; client.SendNoticeToAsync( Actions.PortalDeactivate, @@ -672,7 +672,7 @@ namespace ASC.Web.Studio.Core.Notify { var u = UserManager.GetUsers(t.OwnerId); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonDeletePortal; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonDeletePortal; client.SendNoticeToAsync( Actions.PortalDelete, @@ -685,7 +685,7 @@ namespace ASC.Web.Studio.Core.Notify public void SendMsgPortalDeletionSuccess(UserInfo owner, string url) { - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonLeaveFeedback; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonLeaveFeedback; client.SendNoticeToAsync( Actions.PortalDeleteSuccessV115, @@ -701,7 +701,7 @@ namespace ASC.Web.Studio.Core.Notify { var u = UserManager.GetUsers(t.OwnerId); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonConfirmPortalAddressChange; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonConfirmPortalAddressChange; client.SendNoticeToAsync( Actions.DnsChange, @@ -716,7 +716,7 @@ namespace ASC.Web.Studio.Core.Notify public void SendMsgConfirmChangeOwner(UserInfo owner, UserInfo newOwner, string confirmOwnerUpdateUrl) { - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonConfirmPortalOwnerUpdate; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonConfirmPortalOwnerUpdate; client.SendNoticeToAsync( Actions.ConfirmOwnerChange, @@ -754,7 +754,7 @@ namespace ASC.Web.Studio.Core.Notify var confirmationUrl = CommonLinkUtility.GetConfirmationUrl(u.Email, ConfirmType.EmailActivation); confirmationUrl += "&first=true"; - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonConfirm; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonConfirm; client.SendNoticeToAsync( notifyAction, diff --git a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs index 8498d40d28..e1e8e5ac59 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -119,7 +119,7 @@ namespace ASC.Web.Studio.Core.Notify Func greenButtonText = () => string.Empty; - static string blueButtonText() => WebstudioNotifyPatternResource.ButtonRequestCallButton; + string blueButtonText() => WebstudioNotifyPatternResource.ButtonRequestCallButton; var greenButtonUrl = string.Empty; Func tableItemText1 = () => string.Empty; @@ -156,17 +156,17 @@ namespace ASC.Web.Studio.Core.Notify Func tableItemLearnMoreText1 = () => string.Empty; - static string tableItemLearnMoreText2() => string.Empty; + string tableItemLearnMoreText2() => string.Empty; - static string tableItemLearnMoreText3() => string.Empty; + string tableItemLearnMoreText3() => string.Empty; - static string tableItemLearnMoreText4() => string.Empty; + string tableItemLearnMoreText4() => string.Empty; - static string tableItemLearnMoreText5() => string.Empty; + string tableItemLearnMoreText5() => string.Empty; - static string tableItemLearnMoreText6() => string.Empty; + string tableItemLearnMoreText6() => string.Empty; - static string tableItemLearnMoreText7() => string.Empty; + string tableItemLearnMoreText7() => string.Empty; var tableItemLearnMoreUrl1 = string.Empty; var tableItemLearnMoreUrl2 = string.Empty; @@ -518,7 +518,7 @@ namespace ASC.Web.Studio.Core.Notify Func greenButtonText = () => string.Empty; - static string blueButtonText() => WebstudioNotifyPatternResource.ButtonRequestCallButton; + string blueButtonText() => WebstudioNotifyPatternResource.ButtonRequestCallButton; var greenButtonUrl = string.Empty; Func tableItemText1 = () => string.Empty; @@ -555,17 +555,17 @@ namespace ASC.Web.Studio.Core.Notify Func tableItemLearnMoreText1 = () => string.Empty; - static string tableItemLearnMoreText2() => string.Empty; + string tableItemLearnMoreText2() => string.Empty; - static string tableItemLearnMoreText3() => string.Empty; + string tableItemLearnMoreText3() => string.Empty; - static string tableItemLearnMoreText4() => string.Empty; + string tableItemLearnMoreText4() => string.Empty; - static string tableItemLearnMoreText5() => string.Empty; + string tableItemLearnMoreText5() => string.Empty; - static string tableItemLearnMoreText6() => string.Empty; + string tableItemLearnMoreText6() => string.Empty; - static string tableItemLearnMoreText7() => string.Empty; + string tableItemLearnMoreText7() => string.Empty; var tableItemLearnMoreUrl1 = string.Empty; var tableItemLearnMoreUrl2 = string.Empty; From d9619e1151a21cdc902edfd988a93403aac48f0d Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Mon, 10 Jan 2022 18:13:54 +0300 Subject: [PATCH 031/167] analizators/U2U1006 --- .../services/ASC.ElasticSearch/Engine/FactoryIndexer.cs | 4 ++-- products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs index f45781ddd4..1f90cd008a 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -546,9 +546,9 @@ namespace ASC.ElasticSearch } } - public async Task SupportAsync(T t) + public Task SupportAsync(T t) { - return await FactoryIndexerCommon.CheckStateAsync(); + return FactoryIndexerCommon.CheckStateAsync(); } } diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index c32b5d1ba7..21c92f37ea 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -354,9 +354,9 @@ namespace ASC.Files.Core.Data { return GetFileStream(file, 0); } - public async Task GetFileStreamAsync(File file) + public Task GetFileStreamAsync(File file) { - return await GlobalStore.GetStore().GetReadStreamAsync(string.Empty, GetUniqFilePath(file), 0); + return GlobalStore.GetStore().GetReadStreamAsync(string.Empty, GetUniqFilePath(file), 0); } public File SaveFile(File file, Stream fileStream) @@ -1157,9 +1157,9 @@ namespace ASC.Files.Core.Data return GlobalStore.GetStore().IsFile(GetUniqFilePath(file)); } - public async Task IsExistOnStorageAsync(File file) + public Task IsExistOnStorageAsync(File file) { - return await GlobalStore.GetStore().IsFileAsync(string.Empty, GetUniqFilePath(file)); + return GlobalStore.GetStore().IsFileAsync(string.Empty, GetUniqFilePath(file)); } private const string DiffTitle = "diff.zip"; From c85c2e6f263cb1dbf8b8ee47d727ce189451f919 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 11 Jan 2022 18:37:10 +0300 Subject: [PATCH 032/167] analizators/U2U1007 --- .../ASC.Common/Threading/DistributedTask.cs | 2 +- common/ASC.Common/Utils/HtmlUtil.cs | 2 +- .../ASC.Core.Common/BaseCommonLinkUtility.cs | 2 +- .../RackspaceCloud/RackspaceCloudStorage.cs | 2 +- common/ASC.Data.Storage/S3/S3Storage.cs | 4 ++-- .../ASC.ApiSystem/Classes/CommonConstants.cs | 4 ++-- .../ASC.AuditTrail/AuditEventsRepository.cs | 2 +- .../services/ASC.TelegramService/Core/Core.cs | 2 +- .../ASC.CRM/Server/Core/Dao/ListItemDao.cs | 2 +- .../Server/Core/Dao/RelationshipEventDao.cs | 2 +- .../ContactPhotoHandlerMiddleware.cs | 2 +- .../Server/BusinessObjects/DataProvider.cs | 22 +++++++++---------- .../Server/Controllers/CalendarController.cs | 6 ++--- .../Server/Models/PublicItemCollection.cs | 4 ++-- .../Core/Core/Dao/TeamlabDao/FileDao.cs | 2 +- .../Core/Core/Dao/TeamlabDao/FolderDao.cs | 4 ++-- .../ASC.Files/Core/Core/FileStorageService.cs | 2 +- .../Core/Thirdparty/Dropbox/DropboxFileDao.cs | 4 ++-- .../Core/Thirdparty/IThirdPartyProviderDao.cs | 2 +- .../Thirdparty/OneDrive/OneDriveFileDao.cs | 4 ++-- .../Core/Thirdparty/ProviderAccountDao.cs | 2 +- .../SharePoint/SharePointFileDao.cs | 2 +- .../ASC.Files/Core/ThirdPartyApp/BoxApp.cs | 8 +++---- .../Core/ThirdPartyApp/GoogleDriveApp.cs | 2 +- products/ASC.Files/Core/Utils/FileMarker.cs | 2 +- .../Server/Controllers/PeopleController.cs | 12 +++++----- web/ASC.Web.Core/WebItemManager.cs | 4 +--- 27 files changed, 53 insertions(+), 55 deletions(-) diff --git a/common/ASC.Common/Threading/DistributedTask.cs b/common/ASC.Common/Threading/DistributedTask.cs index 2365f358c3..83e0bf608a 100644 --- a/common/ASC.Common/Threading/DistributedTask.cs +++ b/common/ASC.Common/Threading/DistributedTask.cs @@ -55,7 +55,7 @@ namespace ASC.Common.Threading } protected set { - DistributedTaskCache.Id = value?.ToString() ?? ""; + DistributedTaskCache.Id = value ?? ""; } } diff --git a/common/ASC.Common/Utils/HtmlUtil.cs b/common/ASC.Common/Utils/HtmlUtil.cs index 631455bf36..c301c43ae4 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -102,7 +102,7 @@ namespace ASC.Common.Utils { if (string.IsNullOrEmpty(searchText) || string.IsNullOrEmpty(htmlText)) return htmlText; - var regexpstr = Worder.Matches(searchText).Cast().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); + var regexpstr = Worder.Matches(searchText).Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); var wordsFinder = new Regex(Regex.Escape(regexpstr), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline); return wordsFinder.Replace(htmlText, m => string.Format("{0}", m.Value, withoutLink ? " bold" : string.Empty)); } diff --git a/common/ASC.Core.Common/BaseCommonLinkUtility.cs b/common/ASC.Core.Common/BaseCommonLinkUtility.cs index f2a63c9f0c..a8e22097da 100644 --- a/common/ASC.Core.Common/BaseCommonLinkUtility.cs +++ b/common/ASC.Core.Common/BaseCommonLinkUtility.cs @@ -217,7 +217,7 @@ namespace ASC.Core.Common if (string.IsNullOrEmpty(lang)) { - url = matches.Cast().Aggregate(url, (current, match) => current.Replace(match.Value, string.Empty)); + url = matches.Aggregate(url, (current, match) => current.Replace(match.Value, string.Empty)); } else { diff --git a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs index 1a13e33710..3df3e451c0 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -566,7 +566,7 @@ namespace ASC.Data.Storage.RackspaceCloud foreach (var obj in objToDel) { client.DeleteObject(_private_container, obj.Name); - QuotaUsedDelete(domain, Convert.ToInt64(obj.Bytes)); + QuotaUsedDelete(domain, obj.Bytes); } } diff --git a/common/ASC.Data.Storage/S3/S3Storage.cs b/common/ASC.Data.Storage/S3/S3Storage.cs index 13d8113eb2..7a688178c9 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -543,7 +543,7 @@ namespace ASC.Data.Storage.S3 client.DeleteObjectAsync(deleteRequest).Wait(); - QuotaUsedDelete(domain, Convert.ToInt64(s3Object.Size)); + QuotaUsedDelete(domain, s3Object.Size); } } @@ -565,7 +565,7 @@ namespace ASC.Data.Storage.S3 client.DeleteObjectAsync(deleteRequest).Wait(); - QuotaUsedDelete(domain, Convert.ToInt64(s3Object.Size)); + QuotaUsedDelete(domain, s3Object.Size); } } diff --git a/common/services/ASC.ApiSystem/Classes/CommonConstants.cs b/common/services/ASC.ApiSystem/Classes/CommonConstants.cs index 66abd3d46a..2ffa9c4f3b 100644 --- a/common/services/ASC.ApiSystem/Classes/CommonConstants.cs +++ b/common/services/ASC.ApiSystem/Classes/CommonConstants.cs @@ -61,9 +61,9 @@ namespace ASC.ApiSystem.Classes MaxAttemptsCount = Convert.ToInt32(configuration["max-attempts-count"] ?? "10"); - MaxAttemptsTimeInterval = TimeSpan.Parse(Convert.ToString(configuration["max-attempts-interval"] ?? "00:05:00")); + MaxAttemptsTimeInterval = TimeSpan.Parse(configuration["max-attempts-interval"] ?? "00:05:00"); - WebApiBaseUrl = Convert.ToString(configuration["api:url"] ?? "/api/2.0/"); + WebApiBaseUrl = configuration["api:url"] ?? "/api/2.0/"; } diff --git a/common/services/ASC.AuditTrail/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/AuditEventsRepository.cs index 16bead0159..00727d4ced 100644 --- a/common/services/ASC.AuditTrail/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/AuditEventsRepository.cs @@ -132,7 +132,7 @@ namespace ASC.AuditTrail if (query.AuditEvent.Description != null) { evt.Description = JsonConvert.DeserializeObject>( - Convert.ToString(query.AuditEvent.Description), + query.AuditEvent.Description, new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); } diff --git a/common/services/ASC.TelegramService/Core/Core.cs b/common/services/ASC.TelegramService/Core/Core.cs index 6e581a8079..1978968edc 100644 --- a/common/services/ASC.TelegramService/Core/Core.cs +++ b/common/services/ASC.TelegramService/Core/Core.cs @@ -107,7 +107,7 @@ namespace ASC.TelegramService.Core var reg = cmdReg.Match(msg.Text); var args = argsReg.Matches(reg.Groups[2].Value); - return new TelegramCommand(msg, reg.Groups[1].Value.ToLowerInvariant(), args.Count > 0 ? args.Cast().Select(a => a.Value).ToArray() : null); + return new TelegramCommand(msg, reg.Groups[1].Value.ToLowerInvariant(), args.Count > 0 ? args.Select(a => a.Value).ToArray() : null); } private object[] ParseParams(MethodInfo cmd, string[] args) diff --git a/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs b/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs index 73f54fa0a2..5e17356c9e 100644 --- a/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs @@ -218,7 +218,7 @@ namespace ASC.CRM.Core.Dao .Where(x => x.ListType == listType) .Select(x => new { x.Id, x.Color }) .ToList() - .ForEach(x => result.Add(x.Id.ToString(), x.Color.ToString())); + .ForEach(x => result.Add(x.Id.ToString(), x.Color)); return result; diff --git a/products/ASC.CRM/Server/Core/Dao/RelationshipEventDao.cs b/products/ASC.CRM/Server/Core/Dao/RelationshipEventDao.cs index d168db971d..15fc763700 100644 --- a/products/ASC.CRM/Server/Core/Dao/RelationshipEventDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/RelationshipEventDao.cs @@ -259,7 +259,7 @@ namespace ASC.CRM.Core.Dao } } - var itemToUpdate = Query(CrmDbContext.Invoices).FirstOrDefault(x => x.FileId == Convert.ToInt32(file.ID)); + var itemToUpdate = Query(CrmDbContext.Invoices).FirstOrDefault(x => x.FileId == file.ID); itemToUpdate.FileId = 0; diff --git a/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs index 5afce5d56c..01ed9567f7 100644 --- a/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs @@ -112,7 +112,7 @@ namespace ASC.Web.CRM.HttpHandlers } var uploadOnly = Convert.ToBoolean(context.Request.Form["uploadOnly"]); - var tmpDirName = Convert.ToString(context.Request.Form["tmpDirName"]); + var tmpDirName = context.Request.Form["tmpDirName"]; try { diff --git a/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs b/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs index a346f49277..8be1a4cc6d 100644 --- a/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs +++ b/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs @@ -124,8 +124,8 @@ namespace ASC.Calendar.BusinessObjects options.Add(new UserViewSettings() { CalendarId = - Convert.ToInt32(r.CalendarId) == 0 - ? Convert.ToString(r.ExtCalendarId) + r.CalendarId == 0 + ? r.ExtCalendarId : Convert.ToString(r.CalendarId), UserId = r.UserId, IsHideEvents = Convert.ToBoolean(r.HideEvents), @@ -751,7 +751,7 @@ namespace ASC.Calendar.BusinessObjects var dataCaldavGuid = CalendarDb.CalendarCalendars.Where(p => p.Id == calendarId).Select(s => s.CaldavGuid).ToArray(); if (dataCaldavGuid[0] != null) - caldavGuid = Guid.Parse(dataCaldavGuid[0].ToString()); + caldavGuid = Guid.Parse(dataCaldavGuid[0]); } catch (Exception ex) { @@ -947,11 +947,11 @@ namespace ASC.Calendar.BusinessObjects var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); todoList = data.ConvertAll(r => new Todo(AuthContext, TimeZoneConverter, icalendar, this) { - Id = r.Id.ToString(), + Id = r.Id, Name = r.Name, Description = r.Description, TenantId = r.TenantId, - CalendarId = r.CalendarId.ToString(), + CalendarId = r.CalendarId, UtcStartDate = r.UtcStartDate ?? DateTime.MinValue, Completed = r.Completed ?? DateTime.MinValue, OwnerId = r.OwnerId, @@ -979,11 +979,11 @@ namespace ASC.Calendar.BusinessObjects var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); todoList = data.ConvertAll(r => new Todo(AuthContext, TimeZoneConverter, icalendar, this) { - Id = r.Id.ToString(), + Id = r.Id, Name = r.Name, Description = r.Description, TenantId = r.TenantId, - CalendarId = r.CalendarId.ToString(), + CalendarId = r.CalendarId, UtcStartDate = r.UtcStartDate ?? DateTime.MinValue, Completed = r.Completed ?? DateTime.MinValue, OwnerId = r.OwnerId, @@ -1703,7 +1703,7 @@ namespace ASC.Calendar.BusinessObjects }; var calendarAlertType = (EventAlertType)calendarData.FirstOrDefault().alertType; - var calendarOwner = Convert.ToString(calendarData.FirstOrDefault().ownerId); + var calendarOwner = calendarData.FirstOrDefault().ownerId; var calendarTimeZone = TimeZoneConverter.GetTimeZone(calendarData.FirstOrDefault().timeZone); var eventUsers = new List(); @@ -1782,7 +1782,7 @@ namespace ASC.Calendar.BusinessObjects u.TimeZone = r.timeZone == null ? calendarTimeZone : TimeZoneConverter.GetTimeZone(Convert.ToString(r.isAccepted)); if (u.AlertType == EventAlertType.Default && u.UserId.Equals(r.userId)) - u.AlertType = (EventAlertType)Convert.ToInt32(r.alertType); + u.AlertType = (EventAlertType)r.alertType; }); } @@ -1837,7 +1837,7 @@ namespace ASC.Calendar.BusinessObjects eventUsers.ForEach(u => { if (u.UserId.Equals(r.userIdCol)) - u.AlertType = (EventAlertType)(Convert.ToInt32(r.alertTypeCol)); + u.AlertType = (EventAlertType)r.alertTypeCol; }); } @@ -1869,7 +1869,7 @@ namespace ASC.Calendar.BusinessObjects u.TimeZone = r.timeZone == null ? calendarTimeZone : TimeZoneConverter.GetTimeZone(r.timeZone); if (u.AlertType == EventAlertType.Default && u.UserId.Equals(r.userId)) - u.AlertType = (EventAlertType)Convert.ToInt32(r.alertType); + u.AlertType = (EventAlertType)r.alertType; }); } diff --git a/products/ASC.Calendar/Server/Controllers/CalendarController.cs b/products/ASC.Calendar/Server/Controllers/CalendarController.cs index e5f7941219..ef175ed13b 100644 --- a/products/ASC.Calendar/Server/Controllers/CalendarController.cs +++ b/products/ASC.Calendar/Server/Controllers/CalendarController.cs @@ -521,7 +521,7 @@ namespace ASC.Calendar.Controllers Description = "", TextColor = BusinessObjects.Calendar.DefaultTextColor, BackgroundColor = BusinessObjects.Calendar.DefaultTodoBackgroundColor, - TimeZone = userTimeZone.ToString(), + TimeZone = userTimeZone, AlertType = EventAlertType.FifteenMinutes, SharingOptions = null, ICalUrl = null, @@ -586,7 +586,7 @@ namespace ASC.Calendar.Controllers "Todo_calendar", "", BusinessObjects.Calendar.DefaultTodoBackgroundColor, - todoCalendars[0].calDavGuid.ToString(), + todoCalendars[0].calDavGuid, myUri, curCaldavUserName, userName @@ -2694,7 +2694,7 @@ namespace ASC.Calendar.Controllers Description = "", TextColor = BusinessObjects.Calendar.DefaultTextColor, BackgroundColor = BusinessObjects.Calendar.DefaultTodoBackgroundColor, - TimeZone = userTimeZone.ToString(), + TimeZone = userTimeZone, AlertType = EventAlertType.FifteenMinutes, SharingOptions = null, ICalUrl = null, diff --git a/products/ASC.Calendar/Server/Models/PublicItemCollection.cs b/products/ASC.Calendar/Server/Models/PublicItemCollection.cs index 3d04903da2..94dc39872f 100644 --- a/products/ASC.Calendar/Server/Models/PublicItemCollection.cs +++ b/products/ASC.Calendar/Server/Models/PublicItemCollection.cs @@ -86,10 +86,10 @@ namespace ASC.Calendar.Models Id = calendar.OwnerId, IsGroup = false }, - calendar.Id.ToString(), calendar.OwnerId)); + calendar.Id, calendar.OwnerId)); foreach (var item in calendar.SharingOptions.PublicItems) - sharingOptions.Items.Add(PublicItemWrapperHelper.Get(item, calendar.Id.ToString(), calendar.OwnerId)); + sharingOptions.Items.Add(PublicItemWrapperHelper.Get(item, calendar.Id, calendar.OwnerId)); return sharingOptions; } diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index 21c92f37ea..6e98f63dbf 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -947,7 +947,7 @@ namespace ASC.Files.Core.Data public string GetUniqFileDirectory(int fileId) { if (fileId == 0) throw new ArgumentNullException("fileIdObject"); - return string.Format("folder_{0}/file_{1}", (Convert.ToInt32(fileId) / 1000 + 1) * 1000, fileId); + return string.Format("folder_{0}/file_{1}", (fileId / 1000 + 1) * 1000, fileId); } public string GetUniqFilePath(File file) diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs index 8c123aa474..a58c56714b 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs @@ -929,7 +929,7 @@ namespace ASC.Files.Core.Data case my: folder.FolderType = FolderType.USER; folder.Title = my; - folder.CreateBy = new Guid(data.ToString()); + folder.CreateBy = new Guid(data); break; case common: folder.FolderType = FolderType.COMMON; @@ -938,7 +938,7 @@ namespace ASC.Files.Core.Data case trash: folder.FolderType = FolderType.TRASH; folder.Title = trash; - folder.CreateBy = new Guid(data.ToString()); + folder.CreateBy = new Guid(data); break; case share: folder.FolderType = FolderType.SHARE; diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index b540cfaaf3..d332c3e4af 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -1319,7 +1319,7 @@ namespace ASC.Web.Files.Services.WCFService } providerDao.RemoveProviderInfo(folder.ProviderId); - FilesMessageService.Send(folder, GetHttpHeaders(), MessageAction.ThirdPartyDeleted, folder.ID.ToString(), providerInfo.ProviderKey); + FilesMessageService.Send(folder, GetHttpHeaders(), MessageAction.ThirdPartyDeleted, folder.ID, providerInfo.ProviderKey); return folder.ID; } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs index d129bb3941..5a7c652ed6 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs @@ -486,10 +486,10 @@ namespace ASC.Files.Thirdparty.Dropbox if (file == null) return null; if (file.ID != null) - file.ID = MakeId(file.ID.ToString()); + file.ID = MakeId(file.ID); if (file.FolderID != null) - file.FolderID = MakeId(file.FolderID.ToString()); + file.FolderID = MakeId(file.FolderID); return file; } diff --git a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs index 971a6246fc..f420f61908 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs @@ -270,7 +270,7 @@ namespace ASC.Files.Thirdparty string result; if (id.StartsWith(Id)) { - result = Regex.Replace(BitConverter.ToString(Hasher.Hash(id.ToString(), HashAlg.MD5)), "-", "").ToLower(); + result = Regex.Replace(BitConverter.ToString(Hasher.Hash(id, HashAlg.MD5)), "-", "").ToLower(); } else { diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs index 0c5f3b9ed3..f60c9a7c97 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs @@ -480,10 +480,10 @@ namespace ASC.Files.Thirdparty.OneDrive if (file == null) return null; if (file.ID != null) - file.ID = MakeId(file.ID.ToString()); + file.ID = MakeId(file.ID); if (file.FolderID != null) - file.FolderID = MakeId(file.FolderID.ToString()); + file.FolderID = MakeId(file.FolderID); return file; } diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs index f1cdd5ba5e..43b626445a 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs @@ -318,7 +318,7 @@ namespace ASC.Files.Thirdparty public virtual void RemoveProviderInfo(int linkId) { using var tx = FilesDbContext.Database.BeginTransaction(); - var folderId = GetProviderInfo(linkId).RootFolderId.ToString(); + var folderId = GetProviderInfo(linkId).RootFolderId; var entryIDs = FilesDbContext.ThirdpartyIdMapping .Where(r => r.TenantId == TenantID) diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs index 393e6f4a3c..86c68236cc 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs @@ -267,7 +267,7 @@ namespace ASC.Files.Thirdparty.SharePoint var folder = ProviderInfo.GetFolderById(file.FolderID); file.Title = GetAvailableTitle(file.Title, folder, IsExist); - var id = ProviderInfo.RenameFile(DaoSelector.ConvertId(resultFile.ID).ToString(), file.Title); + var id = ProviderInfo.RenameFile(DaoSelector.ConvertId(resultFile.ID), file.Title); return GetFile(DaoSelector.ConvertId(id)); } return resultFile; diff --git a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs index 5f4209567c..7c9df95b32 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -197,11 +197,11 @@ namespace ASC.Web.Files.ThirdPartyApp public File GetFile(string fileId, out bool editable) { Logger.Debug("BoxApp: get file " + fileId); - fileId = ThirdPartySelector.GetFileId(fileId.ToString()); + fileId = ThirdPartySelector.GetFileId(fileId); var token = TokenHelper.GetToken(AppAttr); - var boxFile = GetBoxFile(fileId.ToString(), token); + var boxFile = GetBoxFile(fileId, token); editable = true; if (boxFile == null) return null; @@ -274,11 +274,11 @@ namespace ASC.Web.Files.ThirdPartyApp (stream == null ? " from - " + downloadUrl : " from stream")); - fileId = ThirdPartySelector.GetFileId(fileId.ToString()); + fileId = ThirdPartySelector.GetFileId(fileId); var token = TokenHelper.GetToken(AppAttr); - var boxFile = GetBoxFile(fileId.ToString(), token); + var boxFile = GetBoxFile(fileId, token); if (boxFile == null) { Logger.Error("BoxApp: file is null"); diff --git a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs index 63461d7b7e..c56d3da218 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -251,7 +251,7 @@ namespace ASC.Web.Files.ThirdPartyApp { if (file == null) return string.Empty; - var fileId = ThirdPartySelector.GetFileId(file.ID.ToString()); + var fileId = ThirdPartySelector.GetFileId(file.ID); return GetFileStreamUrl(fileId); } diff --git a/products/ASC.Files/Core/Utils/FileMarker.cs b/products/ASC.Files/Core/Utils/FileMarker.cs index facfb661f5..1de062bcdf 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -126,7 +126,7 @@ namespace ASC.Web.Files.Utils internal void ExecMarkFileAsNew(AsyncTaskData obj) { - TenantManager.SetCurrentTenant(Convert.ToInt32(obj.TenantID)); + TenantManager.SetCurrentTenant(obj.TenantID); var folderDao = DaoFactory.GetFolderDao(); T parentFolderId; diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index 06143f600a..29ffb63296 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -562,8 +562,8 @@ namespace ASC.Employee.Core.Controllers ? true : ("female".Equals(memberModel.Sex, StringComparison.OrdinalIgnoreCase) ? (bool?)false : null); - user.BirthDate = memberModel.Birthday != null && memberModel.Birthday != DateTime.MinValue ? TenantUtil.DateTimeFromUtc(Convert.ToDateTime(memberModel.Birthday)) : null; - user.WorkFromDate = memberModel.Worksfrom != null && memberModel.Worksfrom != DateTime.MinValue ? TenantUtil.DateTimeFromUtc(Convert.ToDateTime(memberModel.Worksfrom)) : DateTime.UtcNow.Date; + user.BirthDate = memberModel.Birthday != null && memberModel.Birthday != DateTime.MinValue ? TenantUtil.DateTimeFromUtc(memberModel.Birthday) : null; + user.WorkFromDate = memberModel.Worksfrom != null && memberModel.Worksfrom != DateTime.MinValue ? TenantUtil.DateTimeFromUtc(memberModel.Worksfrom) : DateTime.UtcNow.Date; UpdateContacts(memberModel.Contacts, user); @@ -631,8 +631,8 @@ namespace ASC.Employee.Core.Controllers ? true : ("female".Equals(memberModel.Sex, StringComparison.OrdinalIgnoreCase) ? (bool?)false : null); - user.BirthDate = memberModel.Birthday != null ? TenantUtil.DateTimeFromUtc(Convert.ToDateTime(memberModel.Birthday)) : null; - user.WorkFromDate = memberModel.Worksfrom != null ? TenantUtil.DateTimeFromUtc(Convert.ToDateTime(memberModel.Worksfrom)) : DateTime.UtcNow.Date; + user.BirthDate = memberModel.Birthday != null ? TenantUtil.DateTimeFromUtc(memberModel.Birthday) : null; + user.WorkFromDate = memberModel.Worksfrom != null ? TenantUtil.DateTimeFromUtc(memberModel.Worksfrom) : DateTime.UtcNow.Date; UpdateContacts(memberModel.Contacts, user); @@ -751,14 +751,14 @@ namespace ASC.Employee.Core.Controllers ? true : ("female".Equals(memberModel.Sex, StringComparison.OrdinalIgnoreCase) ? (bool?)false : null)) ?? user.Sex; - user.BirthDate = memberModel.Birthday != null ? TenantUtil.DateTimeFromUtc(Convert.ToDateTime(memberModel.Birthday)) : user.BirthDate; + user.BirthDate = memberModel.Birthday != null ? TenantUtil.DateTimeFromUtc(memberModel.Birthday) : user.BirthDate; if (user.BirthDate == resetDate) { user.BirthDate = null; } - user.WorkFromDate = memberModel.Worksfrom != null ? TenantUtil.DateTimeFromUtc(Convert.ToDateTime(memberModel.Worksfrom)) : user.WorkFromDate; + user.WorkFromDate = memberModel.Worksfrom != null ? TenantUtil.DateTimeFromUtc(memberModel.Worksfrom) : user.WorkFromDate; if (user.WorkFromDate == resetDate) { diff --git a/web/ASC.Web.Core/WebItemManager.cs b/web/ASC.Web.Core/WebItemManager.cs index 1388b56f57..cd8af9da70 100644 --- a/web/ASC.Web.Core/WebItemManager.cs +++ b/web/ASC.Web.Core/WebItemManager.cs @@ -261,9 +261,7 @@ namespace ASC.Web.Core public List GetSubItems(Guid parentItemID, ItemAvailableState avaliableState) { - return GetItems(WebZoneType.All, avaliableState).OfType() - .Where(p => p.ProjectId == parentItemID) - .Cast() + return GetItems(WebZoneType.All, avaliableState).Where(p => ((IModule)p).ProjectId == parentItemID) .ToList(); } } From 50c0596efffadb42e69a36af6ebb9dd5a650dd15 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Tue, 11 Jan 2022 18:37:19 +0300 Subject: [PATCH 033/167] analizators/U2U1009 --- .../ASC.Core.Common/Billing/CouponManager.cs | 14 ++- .../EF/Context/BaseDbContext.cs | 12 +- .../Tasks/PortalTaskBase.cs | 8 +- common/ASC.Data.Storage/StorageHandler.cs | 37 +++--- .../Engine/FactoryIndexer.cs | 26 ++-- .../ContactPhotoHandlerMiddleware.cs | 17 ++- .../ImportFileHandlerMiddleware.cs | 11 +- .../OrganisationLogoHandlerMiddleware.cs | 12 +- .../Core/Core/Dao/TeamlabDao/FileDao.cs | 9 +- .../Core/HttpHandlers/FileHandler.ashx.cs | 115 +++++++++++------- 10 files changed, 179 insertions(+), 82 deletions(-) diff --git a/common/ASC.Core.Common/Billing/CouponManager.cs b/common/ASC.Core.Common/Billing/CouponManager.cs index fc8bcd932c..eb1c9c4180 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -112,19 +112,23 @@ namespace ASC.Core.Common.Billing Log.Error(ex.Message, ex); throw; } + } + + internal Task> GetProducts() + { + if (Products != null) return Task.FromResult(Products); + return InternalGetProducts(); } - internal async Task> GetProducts() - { - if (Products != null) return Products; - + private async Task> InternalGetProducts() + { await SemaphoreSlim.WaitAsync(); if (Products != null) { SemaphoreSlim.Release(); return Products; - } + } try { diff --git a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs index 771201928c..e61b9536c2 100644 --- a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs @@ -133,10 +133,16 @@ namespace ASC.Core.Common.EF } } } - public async ValueTask DisposeAsync() - { - if (Context == null) return; + public ValueTask DisposeAsync() + { + if (Context == null) return ValueTask.CompletedTask; + + return InternalDisposeAsync(); + } + + private async ValueTask InternalDisposeAsync() + { foreach (var c in Context) { if (c != null) diff --git a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs index 079bcdba69..d5de8af201 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -280,11 +280,15 @@ namespace ASC.Data.Backup.Tasks Logger.DebugFormat("complete mysql file {0}", file); } - protected async Task RunMysqlFile(Stream stream, string delimiter = ";") + protected Task RunMysqlFile(Stream stream, string delimiter = ";") { + if (stream == null) return Task.CompletedTask; - if (stream == null) return; + return InternalRunMysqlFile(stream, delimiter); + } + private async Task InternalRunMysqlFile(Stream stream, string delimiter) + { using var reader = new StreamReader(stream, Encoding.UTF8); string commandText; diff --git a/common/ASC.Data.Storage/StorageHandler.cs b/common/ASC.Data.Storage/StorageHandler.cs index b36f22aba8..6a26f7c3e8 100644 --- a/common/ASC.Data.Storage/StorageHandler.cs +++ b/common/ASC.Data.Storage/StorageHandler.cs @@ -63,9 +63,9 @@ namespace ASC.Data.Storage.DiscStorage } private IServiceProvider ServiceProvider { get; } - - public async Task Invoke(HttpContext context) - { + + public Task Invoke(HttpContext context) + { using var scope = ServiceProvider.CreateScope(); var scopeClass = scope.ServiceProvider.GetService(); var (tenantManager, securityContext, storageFactory, emailValidationKeyProvider) = scopeClass; @@ -73,11 +73,11 @@ namespace ASC.Data.Storage.DiscStorage if (_checkAuth && !securityContext.IsAuthenticated) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; - return; + return Task.CompletedTask; } var storage = storageFactory.GetStorage(tenantManager.GetCurrentTenant().TenantId.ToString(CultureInfo.InvariantCulture), _module); - var path = CrossPlatform.PathCombine(_path, GetRouteValue("pathInfo").Replace('/', Path.DirectorySeparatorChar)); + var path = CrossPlatform.PathCombine(_path, GetRouteValue("pathInfo", context).Replace('/', Path.DirectorySeparatorChar)); var header = context.Request.Query[Constants.QUERY_HEADER].FirstOrDefault() ?? ""; var auth = context.Request.Query[Constants.QUERY_AUTH].FirstOrDefault() ?? ""; @@ -92,14 +92,14 @@ namespace ASC.Data.Storage.DiscStorage if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; - return; + return Task.CompletedTask; } } if (!storage.IsFile(_domain, path)) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; - return; + return Task.CompletedTask; } var headers = header.Length > 0 ? header.Split('&').Select(HttpUtility.UrlDecode) : new string[] { }; @@ -113,9 +113,9 @@ namespace ASC.Data.Storage.DiscStorage //context.Response.Cache.SetCacheability(HttpCacheability.NoCache); context.Response.Redirect(uri.ToString()); - return; - } - + return Task.CompletedTask; + } + string encoding = null; if (storage is DiscDataStore && storage.IsFile(_domain, path + ".gz")) { @@ -143,18 +143,23 @@ namespace ASC.Data.Storage.DiscStorage if (encoding != null) context.Response.Headers["Content-Encoding"] = encoding; + return InternalInvoke(context, storage, path); + } + + private async Task InternalInvoke(HttpContext context, IDataStore storage, string path) + { using (var stream = storage.GetReadStream(_domain, path)) { await stream.CopyToAsync(context.Response.Body); } await context.Response.Body.FlushAsync(); - await context.Response.CompleteAsync(); - - string GetRouteValue(string name) - { - return (context.GetRouteValue(name) ?? "").ToString(); - } + await context.Response.CompleteAsync(); + } + + private string GetRouteValue(string name, HttpContext context) + { + return (context.GetRouteValue(name) ?? "").ToString(); } } diff --git a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs index 1f90cd008a..4c23f20347 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -271,13 +271,18 @@ namespace ASC.ElasticSearch throw; } } - } + } - public async Task IndexAsync(List data, bool immediately = true, int retry = 0) + public Task IndexAsync(List data, bool immediately = true, int retry = 0) { var t = ServiceProvider.GetService(); - if (!Support(t) || !data.Any()) return; + if (!Support(t) || !data.Any()) return Task.CompletedTask; + return InternalIndexAsync(data, immediately, retry); + } + + private async Task InternalIndexAsync(List data, bool immediately, int retry) + { try { await Indexer.IndexAsync(data, immediately).ConfigureAwait(false); @@ -627,9 +632,9 @@ namespace ASC.ElasticSearch return false; } } - - public async Task CheckStateAsync(bool cacheState = true) - { + + public Task CheckStateAsync(bool cacheState = true) + { const string key = "elasticsearch"; if (cacheState) @@ -637,10 +642,15 @@ namespace ASC.ElasticSearch var cacheValue = cache.Get(key); if (!string.IsNullOrEmpty(cacheValue)) { - return Convert.ToBoolean(cacheValue); + return Task.FromResult(Convert.ToBoolean(cacheValue)); } - } + } + + return InternalCheckStateAsync(cacheState, key); + } + private async Task InternalCheckStateAsync(bool cacheState, string key) + { var cacheTime = DateTime.UtcNow.AddMinutes(15); try diff --git a/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs index 01ed9567f7..450e5b2316 100644 --- a/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs @@ -54,7 +54,7 @@ namespace ASC.Web.CRM.HttpHandlers private readonly RequestDelegate _next; - public async System.Threading.Tasks.Task Invoke(HttpContext context, + public System.Threading.Tasks.Task Invoke(HttpContext context, SetupInfo setupInfo, CrmSecurity crmSecurity, FileSizeComment fileSizeComment, @@ -62,8 +62,7 @@ namespace ASC.Web.CRM.HttpHandlers MessageTarget messageTarget, MessageService messageService, DaoFactory daoFactory, - ContactPhotoManager contactPhotoManager) - { + ContactPhotoManager contactPhotoManager){ if (!webItemSecurity.IsAvailableForMe(ProductEntryPoint.ID)) throw crmSecurity.CreateSecurityException(); @@ -82,6 +81,18 @@ namespace ASC.Web.CRM.HttpHandlers throw crmSecurity.CreateSecurityException(); } + return InternalInvoke(context, setupInfo, fileSizeComment, messageTarget, messageService, contactPhotoManager, contact, contactId); + } + + private async System.Threading.Tasks.Task InternalInvoke(HttpContext context, + SetupInfo setupInfo, + FileSizeComment fileSizeComment, + MessageTarget messageTarget, + MessageService messageService, + ContactPhotoManager contactPhotoManager, + Contact contact, + int contactId) + { var fileUploadResult = new FileUploadResult(); if (context.Request.Form.Files.Count == 0) diff --git a/products/ASC.CRM/Server/Middlewares/ImportFileHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/ImportFileHandlerMiddleware.cs index 1e495a831b..cdc1d25219 100644 --- a/products/ASC.CRM/Server/Middlewares/ImportFileHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/ImportFileHandlerMiddleware.cs @@ -50,7 +50,7 @@ namespace ASC.Web.CRM.HttpHandlers _next = next; } - public async Task Invoke(HttpContext context, + public Task Invoke(HttpContext context, WebItemSecurity webItemSecurity, CrmSecurity crmSecurity, Global global, @@ -59,6 +59,15 @@ namespace ASC.Web.CRM.HttpHandlers if (!webItemSecurity.IsAvailableForMe(ProductEntryPoint.ID)) throw crmSecurity.CreateSecurityException(); + return InternalInvoke(context, webItemSecurity, crmSecurity, global, importFromCSV); + } + + private async Task InternalInvoke(HttpContext context, + WebItemSecurity webItemSecurity, + CrmSecurity crmSecurity, + Global global, + ImportFromCSV importFromCSV) + { var fileUploadResult = new FileUploadResult(); if (context.Request.Form.Files.Count == 0) diff --git a/products/ASC.CRM/Server/Middlewares/OrganisationLogoHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/OrganisationLogoHandlerMiddleware.cs index 7891665425..8e8a1e8d75 100644 --- a/products/ASC.CRM/Server/Middlewares/OrganisationLogoHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/OrganisationLogoHandlerMiddleware.cs @@ -50,7 +50,7 @@ namespace ASC.Web.CRM.HttpHandlers _next = next; } - public async System.Threading.Tasks.Task Invoke(HttpContext context, + public System.Threading.Tasks.Task Invoke(HttpContext context, CrmSecurity crmSecurity, SetupInfo setupInfo, FileSizeComment fileSizeComment, @@ -62,6 +62,16 @@ namespace ASC.Web.CRM.HttpHandlers if (!crmSecurity.IsAdmin) throw crmSecurity.CreateSecurityException(); + return InternalInvoke(context, crmSecurity, setupInfo, fileSizeComment, contactPhotoManager, organisationLogoManager); + } + + private async System.Threading.Tasks.Task InternalInvoke(HttpContext context, + CrmSecurity crmSecurity, + SetupInfo setupInfo, + FileSizeComment fileSizeComment, + ContactPhotoManager contactPhotoManager, + OrganisationLogoManager organisationLogoManager) + { var fileUploadResult = new FileUploadResult(); if (context.Request.Form.Files.Count == 0) diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index 6e98f63dbf..b636462f6e 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -1507,7 +1507,7 @@ namespace ASC.Files.Core.Data return dbFile; } - internal protected async Task InitDocumentAsync(DbFile dbFile) + internal protected Task InitDocumentAsync(DbFile dbFile) { if (!FactoryIndexer.CanIndexByContent(dbFile)) { @@ -1515,9 +1515,14 @@ namespace ASC.Files.Core.Data { Data = Convert.ToBase64String(Encoding.UTF8.GetBytes("")) }; - return dbFile; + return Task.FromResult(dbFile); } + return InernalInitDocumentAsync(dbFile); + } + + private async Task InernalInitDocumentAsync(DbFile dbFile) + { var file = ServiceProvider.GetService>(); file.ID = dbFile.Id; file.Title = dbFile.Title; diff --git a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs index 7575a48260..4ed9f1b5f8 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -41,6 +41,7 @@ using ASC.Common.Logging; using ASC.Common.Utils; using ASC.Common.Web; using ASC.Core; +using ASC.Data.Storage; using ASC.Files.Core; using ASC.Files.Core.Resources; using ASC.Files.Core.Security; @@ -172,17 +173,22 @@ namespace ASC.Web.Files TempStream = tempStream; UserManager = userManager; Logger = optionsMonitor.CurrentValue; - } - - public async Task Invoke(HttpContext context) - { + } + + public Task Invoke(HttpContext context) + { if (TenantExtra.IsNotPaid()) { context.Response.StatusCode = (int)HttpStatusCode.PaymentRequired; //context.Response.StatusDescription = "Payment Required."; - return; - } + return Task.CompletedTask; + } + + return InternalInvoke(context); + } + private async Task InternalInvoke(HttpContext context) + { try { switch ((context.Request.Query[FilesLinkUtility.Action].FirstOrDefault() ?? "").ToLower()) @@ -228,13 +234,13 @@ namespace ASC.Web.Files throw new HttpException((int)HttpStatusCode.InternalServerError, FilesCommonResource.ErrorMassage_BadRequest, e); } } - - private async Task BulkDownloadFile(HttpContext context) - { + + private Task BulkDownloadFile(HttpContext context) + { if (!SecurityContext.IsAuthenticated) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; - return; + return Task.CompletedTask; } var ext = CompressToArchive.GetExt(ServiceProvider, context.Request.Query["ext"]); @@ -245,18 +251,22 @@ namespace ASC.Web.Files { Logger.ErrorFormat("BulkDownload file error. File is not exist on storage. UserId: {0}.", AuthContext.CurrentAccount.ID); context.Response.StatusCode = (int)HttpStatusCode.NotFound; - return; + return Task.CompletedTask; } if (store.IsSupportedPreSignedUri) { var url = store.GetPreSignedUri(FileConstant.StorageDomainTmp, path, TimeSpan.FromHours(1), null).ToString(); context.Response.Redirect(url); - return; - } - - context.Response.Clear(); + return Task.CompletedTask; + } + + context.Response.Clear(); + return InternalBulkDownloadFile(context, store, path, ext); + } + private async Task InternalBulkDownloadFile(HttpContext context, IDataStore store, string path, string ext) + { try { var flushed = false; @@ -1041,9 +1051,9 @@ namespace ASC.Web.Files { return file.ID + ":" + file.Version + ":" + file.Title.GetHashCode() + ":" + file.ContentLength; } - - private async Task CreateFile(HttpContext context) - { + + private Task CreateFile(HttpContext context) + { if (!SecurityContext.IsAuthenticated) { //var refererURL = context.Request.GetUrlRewriter().AbsoluteUri; @@ -1051,9 +1061,14 @@ namespace ASC.Web.Files //context.Session["refererURL"] = refererURL; var authUrl = "~/Auth.aspx"; context.Response.Redirect(authUrl, true); - return; - } + return Task.CompletedTask; + } + + return InternalCreateFile(context); + } + private async Task InternalCreateFile(HttpContext context) + { var folderId = context.Request.Query[FilesLinkUtility.FolderId].FirstOrDefault(); if (string.IsNullOrEmpty(folderId)) { @@ -1070,11 +1085,12 @@ namespace ASC.Web.Files await CreateFile(context, folderId); } } - } - - private async Task CreateFile(HttpContext context, T folderId) - { - var responseMessage = context.Request.Query["response"] == "message"; + } + + private Task CreateFile(HttpContext context, T folderId) + { + var responseMessage = context.Request.Query["response"] == "message"; + Folder folder; var folderDao = DaoFactory.GetFolderDao(); @@ -1100,28 +1116,40 @@ namespace ASC.Web.Files } catch (Exception ex) { - Logger.Error(ex); - if (responseMessage) - { - await context.Response.WriteAsync("error: " + ex.Message); - return; - } - context.Response.Redirect(PathProvider.StartURL + "#error/" + HttpUtility.UrlEncode(ex.Message), true); - return; + return InternalWriteError(context, ex, responseMessage); } FileMarker.MarkAsNew(file); if (responseMessage) { - await context.Response.WriteAsync("ok: " + string.Format(FilesCommonResource.MessageFileCreated, folder.Title)); - return; + return InternalWriteOk(context, folder); } context.Response.Redirect( (context.Request.Query["openfolder"].FirstOrDefault() ?? "").Equals("true") ? PathProvider.GetFolderUrlById(file.FolderID) - : (FilesLinkUtility.GetFileWebEditorUrl(file.ID) + "#message/" + HttpUtility.UrlEncode(string.Format(FilesCommonResource.MessageFileCreated, folder.Title)))); + : (FilesLinkUtility.GetFileWebEditorUrl(file.ID) + "#message/" + HttpUtility.UrlEncode(string.Format(FilesCommonResource.MessageFileCreated, folder.Title)))); + + return Task.CompletedTask; + } + + private async Task InternalWriteError(HttpContext context, Exception ex, bool responseMessage) + { + Logger.Error(ex); + + if (responseMessage) + { + await context.Response.WriteAsync("error: " + ex.Message); + return; + } + context.Response.Redirect(PathProvider.StartURL + "#error/" + HttpUtility.UrlEncode(ex.Message), true); + return; + } + + private async Task InternalWriteOk(HttpContext context, Folder folder) + { + await context.Response.WriteAsync("ok: " + string.Format(FilesCommonResource.MessageFileCreated, folder.Title)); } private File CreateFileFromTemplate(Folder folder, string fileTitle, string docType) @@ -1264,10 +1292,10 @@ namespace ASC.Web.Files { await TrackFile(context, q.FirstOrDefault() ?? ""); } - } - - private async Task TrackFile(HttpContext context, T fileId) - { + } + + private Task TrackFile(HttpContext context, T fileId) + { var auth = context.Request.Query[FilesLinkUtility.AuthKey].FirstOrDefault(); Logger.Debug("DocService track fileid: " + fileId); @@ -1277,8 +1305,13 @@ namespace ASC.Web.Files { Logger.ErrorFormat("DocService track auth error: {0}, {1}: {2}", validateResult.ToString(), FilesLinkUtility.AuthKey, auth); throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException); - } + } + + return InternalTrackFile(context, fileId); + } + private async Task InternalTrackFile(HttpContext context, T fileId) + { DocumentServiceTracker.TrackerData fileData; try { From 610c45fed36a67356d87e33d594a708c0ac8d83a Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Wed, 12 Jan 2022 12:56:00 +0300 Subject: [PATCH 034/167] analizators/U2U1009 --- .../Commands/UserCommands.cs | 13 +++++++---- .../ASC.TelegramService/TelegramHandler.cs | 22 ++++++++++++++----- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/common/services/ASC.TelegramService/Commands/UserCommands.cs b/common/services/ASC.TelegramService/Commands/UserCommands.cs index c1ee72a456..1cd072b2f6 100644 --- a/common/services/ASC.TelegramService/Commands/UserCommands.cs +++ b/common/services/ASC.TelegramService/Commands/UserCommands.cs @@ -45,11 +45,16 @@ namespace ASC.TelegramService.Commands CachedTelegramDao = cachedTelegramDao.Value; } - [Command("start")] - public async Task StartCommand(string token) - { - if (string.IsNullOrEmpty(token)) return; + [Command("start")] + public Task StartCommand(string token) + { + if (string.IsNullOrEmpty(token)) return Task.CompletedTask; + + return InternalStartCommand(token); + } + private async Task InternalStartCommand(string token) + { var user = MemoryCache.Default.Get(token); if (user != null) { diff --git a/common/services/ASC.TelegramService/TelegramHandler.cs b/common/services/ASC.TelegramService/TelegramHandler.cs index 0bddd8cf86..6237cc91c7 100644 --- a/common/services/ASC.TelegramService/TelegramHandler.cs +++ b/common/services/ASC.TelegramService/TelegramHandler.cs @@ -61,13 +61,19 @@ namespace ASC.TelegramService Clients = new Dictionary(); ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; } + + public Task SendMessage(NotifyMessage msg) + { + if (string.IsNullOrEmpty(msg.To)) return Task.CompletedTask; + if (!Clients.ContainsKey(msg.Tenant)) return Task.CompletedTask; + + return InternalSendMessage(msg); + } - public async Task SendMessage(NotifyMessage msg) + private async Task InternalSendMessage(NotifyMessage msg) { var scope = ServiceProvider.CreateScope(); - var cachedTelegramDao = scope.ServiceProvider.GetService>().Value; - if (string.IsNullOrEmpty(msg.To)) return; - if (!Clients.ContainsKey(msg.Tenant)) return; + var cachedTelegramDao = scope.ServiceProvider.GetService>().Value; var client = Clients[msg.Tenant].Client; @@ -156,10 +162,14 @@ namespace ASC.TelegramService MemoryCache.Default.Set(token, userKey, dateExpires); } + private Task OnMessage(object sender, MessageEventArgs e, TelegramBotClient client, int tenantId) + { + if (string.IsNullOrEmpty(e.Message.Text) || e.Message.Text[0] != '/') return Task.CompletedTask; + return InternalOnMessage(sender, e, client, tenantId); + } - private async Task OnMessage(object sender, MessageEventArgs e, TelegramBotClient client, int tenantId) + private async Task InternalOnMessage(object sender, MessageEventArgs e, TelegramBotClient client, int tenantId) { - if (string.IsNullOrEmpty(e.Message.Text) || e.Message.Text[0] != '/') return; await Command.HandleCommand(e.Message, client, tenantId); } From 3ff7aeca3bfeb7ff16880f40dd10215e7fc6330e Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Wed, 12 Jan 2022 13:27:06 +0300 Subject: [PATCH 035/167] analizators/U2U1015 --- .../Security/Authorizing/AuthorizingException.cs | 14 +++++++++----- .../ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs | 5 +++-- common/ASC.IPSecurity/IPAddressRange.cs | 11 ++++++++--- common/ASC.Notify.Textile/JabberStyler.cs | 13 ++++++++----- .../ASC.ElasticSearch/Engine/BaseIndexer.cs | 7 ++++--- products/ASC.Calendar/Server/iCalParser/Token.cs | 8 +++++--- 6 files changed, 37 insertions(+), 21 deletions(-) diff --git a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs index e1ab1be442..def62d1821 100644 --- a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs +++ b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs @@ -98,15 +98,19 @@ namespace ASC.Common.Security.Authorizing var reasons = ""; for (var i = 0; i < actions.Length; i++) { + var action = actions[i]; + var denyAction = denyActions[i]; + var denySubject = denySubjects[i]; + var reason = ""; - if (denySubjects[i] != null && denyActions[i] != null) + if (denySubject != null && denyAction != null) reason = string.Format("{0}:{1} access denied {2}.", - actions[i].Name, - (denySubjects[i] is IRole ? "role:" : "") + denySubjects[i].Name, - denyActions[i].Name + action.Name, + (denySubject is IRole ? "role:" : "") + denySubject.Name, + denyAction.Name ); else - reason = string.Format("{0}: access denied.", actions[i].Name); + reason = string.Format("{0}: access denied.", action.Name); if (i != actions.Length - 1) reason += ", "; reasons += reason; diff --git a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs index 2d89d272a1..4fec7e0177 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -410,7 +410,8 @@ namespace ASC.Data.Backup.Tasks for (var i = 0; i < obj.Length; i++) { - if (obj[i] is byte[] byteArray) + var value = obj[i]; + if (value is byte[] byteArray) { sw.Write("0x"); foreach (var b in byteArray) @@ -419,7 +420,7 @@ namespace ASC.Data.Backup.Tasks else { var ser = new JsonSerializer(); - ser.Serialize(writer, obj[i]); + ser.Serialize(writer, value); } if (i != obj.Length - 1) { diff --git a/common/ASC.IPSecurity/IPAddressRange.cs b/common/ASC.IPSecurity/IPAddressRange.cs index a9fa0caf1a..8052978b4f 100644 --- a/common/ASC.IPSecurity/IPAddressRange.cs +++ b/common/ASC.IPSecurity/IPAddressRange.cs @@ -56,13 +56,18 @@ namespace ASC.IPSecurity for (var i = 0; i < lowerBytes.Length && (lowerBoundary || upperBoundary); i++) { - if ((lowerBoundary && addressBytes[i] < lowerBytes[i]) || (upperBoundary && addressBytes[i] > upperBytes[i])) + var addressByte = addressBytes[i]; + var upperByte = upperBytes[i]; + var lowerByte = lowerBytes[i]; + + + if ((lowerBoundary && addressByte < lowerByte) || (upperBoundary && addressByte > upperByte)) { return false; } - lowerBoundary &= (addressBytes[i] == lowerBytes[i]); - upperBoundary &= (addressBytes[i] == upperBytes[i]); + lowerBoundary &= (addressByte == lowerByte); + upperBoundary &= (addressByte == upperByte); } return true; diff --git a/common/ASC.Notify.Textile/JabberStyler.cs b/common/ASC.Notify.Textile/JabberStyler.cs index 690defa0db..3848314906 100644 --- a/common/ASC.Notify.Textile/JabberStyler.cs +++ b/common/ASC.Notify.Textile/JabberStyler.cs @@ -58,12 +58,15 @@ namespace ASC.Notify.Textile var lines = message.Body.Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.None); for (var i = 0; i < lines.Length - 1; i++) { - if (string.IsNullOrEmpty(lines[i])) { body += Environment.NewLine; continue; } - lines[i] = VelocityArguments.Replace(lines[i], ArgMatchReplace); - body += LinkReplacer.Replace(lines[i], EvalLink) + Environment.NewLine; + ref var line = ref lines[i]; + if (string.IsNullOrEmpty(line)) { body += Environment.NewLine; continue; } + line = VelocityArguments.Replace(line, ArgMatchReplace); + body += LinkReplacer.Replace(line, EvalLink) + Environment.NewLine; } - lines[^1] = VelocityArguments.Replace(lines[^1], ArgMatchReplace); - body += LinkReplacer.Replace(lines[^1], EvalLink); + + ref var lastLine = ref lines[^1]; + lastLine = VelocityArguments.Replace(lastLine, ArgMatchReplace); + body += LinkReplacer.Replace(lastLine, EvalLink); body = TextileReplacer.Replace(HttpUtility.HtmlDecode(body), ""); //Kill textile markup body = BrReplacer.Replace(body, Environment.NewLine); body = ClosedTagsReplacer.Replace(body, Environment.NewLine); diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index 900beb4513..b5589c2b0b 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -518,12 +518,13 @@ namespace ASC.ElasticSearch var parameters = new Dictionary(); for (var i = 0; i < fields.Length; i++) - { - var func = fields[i].Compile(); + { + var field = fields[i]; + var func = field.Compile(); var newValue = func(data); string name; - var expression = fields[i].Body; + var expression = field.Body; var isList = expression.Type.IsGenericType && expression.Type.GetGenericTypeDefinition() == typeof(List<>); diff --git a/products/ASC.Calendar/Server/iCalParser/Token.cs b/products/ASC.Calendar/Server/iCalParser/Token.cs index d448f30de3..2ab517eca9 100644 --- a/products/ASC.Calendar/Server/iCalParser/Token.cs +++ b/products/ASC.Calendar/Server/iCalParser/Token.cs @@ -139,7 +139,9 @@ namespace ASC.Calendar.iCalParser for (int i = 0; i < lstr.Length; ++i) { - if (lstr[i] == '-') + var c = lstr[i]; + + if (c == '-') { upper = true; } @@ -147,12 +149,12 @@ namespace ASC.Calendar.iCalParser { if (upper) { - buff.Append(Char.ToUpper(lstr[i])); + buff.Append(Char.ToUpper(c)); upper = false; } else { - buff.Append(lstr[i]); + buff.Append(c); } } } From 6961f38593c081221f0fe05b4232d308dfb6272c Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Wed, 12 Jan 2022 15:34:58 +0300 Subject: [PATCH 036/167] analizators/U2U1023 --- common/ASC.Common/DIHelper.cs | 4 ++-- .../Security/Authorizing/AuthorizingException.cs | 2 +- .../ASC.Core.Common/Encryption/EncryptionSettings.cs | 3 +-- .../Notify/Engine/InterceptorStorage.cs | 2 +- common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs | 2 +- .../ASC.Core.Common/Notify/RecipientProviderImpl.cs | 3 +-- common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs | 2 +- .../Storage/DocumentsBackupStorage.cs | 2 +- .../ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs | 2 +- common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs | 1 - common/ASC.Data.Encryption/Metadata.cs | 12 +++++------- common/ASC.Data.Storage/Extensions.cs | 2 +- .../RackspaceCloud/RackspaceCloudStorage.cs | 4 +--- products/ASC.CRM/Server/Classes/CSVReader.cs | 4 ++-- products/ASC.CRM/Server/Classes/Global.cs | 2 +- .../ASC.CRM/Server/Classes/LocalizedEnumConverter.cs | 6 +++--- products/ASC.CRM/Server/Core/Dao/ContactDao.cs | 4 ++-- products/ASC.CRM/Server/Core/Dao/TaskDao.cs | 2 +- .../Server/Middlewares/FileHandlerMiddleware.cs | 2 +- .../Middlewares/WebToLeadFromHandlerMiddleware.cs | 2 +- .../Server/Services/NotifyService/NotifyClient.cs | 4 ++-- .../ASC.CRM/Server/Utils/Import/CSV/ImportTasks.cs | 3 +-- .../Thirdparty/GoogleDrive/GoogleDriveStorage.cs | 2 +- .../FileOperations/FileDownloadOperation.cs | 2 +- .../Server/Helpers/FilesControllerHelper.cs | 4 ++-- web/ASC.Web.Core/CommonPhotoManager.cs | 4 +--- web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs | 2 +- web/ASC.Web.Core/WebItemSecurity.cs | 2 +- .../WhiteLabel/TenantWhiteLabelSettings.cs | 2 +- 29 files changed, 39 insertions(+), 49 deletions(-) diff --git a/common/ASC.Common/DIHelper.cs b/common/ASC.Common/DIHelper.cs index 4af584677f..dbb8dcee3f 100644 --- a/common/ASC.Common/DIHelper.cs +++ b/common/ASC.Common/DIHelper.cs @@ -233,7 +233,7 @@ namespace ASC.Common } else { - Type c = null; + Type c; var a1 = a.GetGenericTypeDefinition(); var b = a.GetGenericArguments().FirstOrDefault(); @@ -297,7 +297,7 @@ namespace ASC.Common } else { - Type c = null; + Type c; var a1 = a.GetGenericTypeDefinition(); var b = a.GetGenericArguments().FirstOrDefault(); diff --git a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs index def62d1821..952ce41661 100644 --- a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs +++ b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs @@ -102,7 +102,7 @@ namespace ASC.Common.Security.Authorizing var denyAction = denyActions[i]; var denySubject = denySubjects[i]; - var reason = ""; + string reason; if (denySubject != null && denyAction != null) reason = string.Format("{0}:{1} access denied {2}.", action.Name, diff --git a/common/ASC.Core.Common/Encryption/EncryptionSettings.cs b/common/ASC.Core.Common/Encryption/EncryptionSettings.cs index 559a939b45..8494e71c41 100644 --- a/common/ASC.Core.Common/Encryption/EncryptionSettings.cs +++ b/common/ASC.Core.Common/Encryption/EncryptionSettings.cs @@ -139,11 +139,10 @@ namespace ASC.Core.Encryption throw new ArgumentException("min_required_non_alphanumeric_characters_incorrect", "numberOfNonAlphanumericCharacters"); } - var array = new byte[length]; var array2 = new char[length]; var num = 0; - array = RandomNumberGenerator.GetBytes(length); + var array = RandomNumberGenerator.GetBytes(length); for (var i = 0; i < length; i++) { diff --git a/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs b/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs index 41ed08dc5d..a514d10fb8 100644 --- a/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs +++ b/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs @@ -119,7 +119,7 @@ namespace ASC.Notify.Engine private ISendInterceptor GetInternal(string name, Dictionary storage) { - ISendInterceptor interceptor = null; + ISendInterceptor interceptor; lock (syncRoot) { storage.TryGetValue(name, out interceptor); diff --git a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs index 23c6c7fe8d..9e30f75da1 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -254,7 +254,7 @@ namespace ASC.Notify.Engine sendResponces.AddRange(SendGroupNotify(request, serviceScope)); } - NotifyResult result = null; + NotifyResult result; if (sendResponces == null || sendResponces.Count == 0) { result = new NotifyResult(SendResult.OK, sendResponces); diff --git a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs index 4d2f6d4bf6..6d4788ff94 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -57,8 +57,7 @@ namespace ASC.Core.Notify if (group == null) throw new ArgumentNullException("group"); var result = new List(); - var groupID = Guid.Empty; - if (TryParseGuid(group.ID, out groupID)) + if (TryParseGuid(group.ID, out var groupID)) { var coreGroup = UserManager.GetGroupInfo(groupID); if (coreGroup.ID != Constants.LostGroupInfo.ID) diff --git a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs index 8b157647a2..01790c82ae 100644 --- a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs +++ b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs @@ -160,7 +160,7 @@ namespace ASC.Data.Backup } xml.Add(new XElement(table)); - DataTable dataTable = null; + DataTable dataTable; while (true) { try diff --git a/common/ASC.Data.Backup.Core/Storage/DocumentsBackupStorage.cs b/common/ASC.Data.Backup.Core/Storage/DocumentsBackupStorage.cs index 2ff9ef461c..38baee80fb 100644 --- a/common/ASC.Data.Backup.Core/Storage/DocumentsBackupStorage.cs +++ b/common/ASC.Data.Backup.Core/Storage/DocumentsBackupStorage.cs @@ -155,7 +155,7 @@ namespace ASC.Data.Backup.Storage var chunkedUploadSession = fileDao.CreateUploadSession(newFile, source.Length); chunkedUploadSession.CheckQuota = false; - var bytesRead = 0; + int bytesRead; while ((bytesRead = source.Read(buffer, 0, (int)SetupInfo.ChunkUploadSize)) > 0) { diff --git a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs index 4fec7e0177..80c0bb0b60 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -284,7 +284,7 @@ namespace ASC.Data.Backup.Tasks } Logger.DebugFormat("dump table data start {0}", t); - var searchWithPrimary = false; + bool searchWithPrimary; string primaryIndex; var primaryIndexStep = 0; var primaryIndexStart = 0; diff --git a/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs b/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs index 3eacb6f69f..dd54560f00 100644 --- a/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs +++ b/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs @@ -63,7 +63,6 @@ namespace ASC.Data.Backup.Tasks.Data IdColumn = idColumn; IdType = idType; TenantColumn = tenantColumn; - UserIDColumns = new string[0]; DateColumns = new Dictionary(); InsertMethod = InsertMethod.Insert; } diff --git a/common/ASC.Data.Encryption/Metadata.cs b/common/ASC.Data.Encryption/Metadata.cs index 5dfc16e51e..73cc75ac7a 100644 --- a/common/ASC.Data.Encryption/Metadata.cs +++ b/common/ASC.Data.Encryption/Metadata.cs @@ -242,16 +242,14 @@ namespace ASC.Data.Encryption private byte[] GenerateRandom(int length) { - var random = new byte[length]; - - random = RandomNumberGenerator.GetBytes(length); + var random = RandomNumberGenerator.GetBytes(length); return random; } private byte[] GenerateKey() { - var key = new byte[keyLength]; + byte[] key; using (var deriveBytes = new Rfc2898DeriveBytes(Password, Salt, Iterations, HashAlgorithmName.SHA256)) { @@ -263,7 +261,7 @@ namespace ASC.Data.Encryption private byte[] GenerateHmacKey() { - var hmacKey = new byte[hmacKeyLength]; + byte[] hmacKey; using (var sha512 = SHA512.Create()) { @@ -274,8 +272,8 @@ namespace ASC.Data.Encryption } private byte[] ComputeHmacHash(Stream stream) - { - var hmacHash = new byte[hmacHashLength]; + { + byte[] hmacHash; stream.Seek(metadataLength - ivLength, SeekOrigin.Begin); // Move position to (IV + encrypted data) diff --git a/common/ASC.Data.Storage/Extensions.cs b/common/ASC.Data.Storage/Extensions.cs index f038f227a2..b8892a79da 100644 --- a/common/ASC.Data.Storage/Extensions.cs +++ b/common/ASC.Data.Storage/Extensions.cs @@ -59,7 +59,7 @@ namespace ASC.Data.Storage tryCurrent++; using var stream = store.GetReadStream(domain, path, offset); var buffer = new byte[BufferSize]; - var readed = 0; + int readed; while ((readed = stream.Read(buffer, 0, BufferSize)) > 0) { readTo.Write(buffer, 0, readed); diff --git a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs index 3df3e451c0..4c66b702aa 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -527,11 +527,9 @@ namespace ASC.Data.Storage.RackspaceCloud public override string[] ListFilesRelative(string domain, string path, string pattern, bool recursive) { - var paths = new List(); - var client = GetClient(); - paths = client.ListObjects(_private_container, null, null, null, MakePath(domain, path), _region).Select(x => x.Name).ToList(); + var paths = client.ListObjects(_private_container, null, null, null, MakePath(domain, path), _region).Select(x => x.Name); return paths .Where(x => Wildcard.IsMatch(pattern, Path.GetFileName(x))) diff --git a/products/ASC.CRM/Server/Classes/CSVReader.cs b/products/ASC.CRM/Server/Classes/CSVReader.cs index 739d2a14f5..5c39e98b20 100644 --- a/products/ASC.CRM/Server/Classes/CSVReader.cs +++ b/products/ASC.CRM/Server/Classes/CSVReader.cs @@ -177,7 +177,7 @@ namespace ASC.Web.CRM.Classes quoted = true; // Find the end of the next value - string nextObjectString = ""; + string nextObjectString; int i = 0; int len = currentLine.Length; bool foundEnd = false; @@ -231,7 +231,7 @@ namespace ASC.Web.CRM.Classes { // Read the CSV data into rows List> rows = new List>(); - List readRow = null; + List readRow; while ((readRow = ReadRow()) != null) rows.Add(readRow); diff --git a/products/ASC.CRM/Server/Classes/Global.cs b/products/ASC.CRM/Server/Classes/Global.cs index 5bc7022eb3..bc3eea5866 100644 --- a/products/ASC.CRM/Server/Classes/Global.cs +++ b/products/ASC.CRM/Server/Classes/Global.cs @@ -206,7 +206,7 @@ namespace ASC.Web.CRM.Classes { var br = new MemoryStream(); var data = new byte[1024]; - var readed = 0; + int readed; while ((readed = inputStream.Read(data, 0, data.Length)) > 0) { diff --git a/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs b/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs index 24875c55e5..f3b4411474 100644 --- a/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs +++ b/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs @@ -87,7 +87,7 @@ namespace ASC.CRM.Classes /// private LookupTable GetLookupTable(CultureInfo culture) { - LookupTable result = null; + LookupTable result; if (culture == null) culture = CultureInfo.CurrentCulture; @@ -191,7 +191,7 @@ namespace ASC.CRM.Classes private object GetValue(CultureInfo culture, string text) { LookupTable lookupTable = GetLookupTable(culture); - object result = null; + object result; lookupTable.TryGetValue(text, out result); return result; } @@ -203,7 +203,7 @@ namespace ASC.CRM.Classes ulong result = 0; foreach (string textValue in textValues) { - object value = null; + object value; string trimmedTextValue = textValue.Trim(); if (!lookupTable.TryGetValue(trimmedTextValue, out value)) { diff --git a/products/ASC.CRM/Server/Core/Dao/ContactDao.cs b/products/ASC.CRM/Server/Core/Dao/ContactDao.cs index b8b095a5fc..2792add0ee 100644 --- a/products/ASC.CRM/Server/Core/Dao/ContactDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/ContactDao.cs @@ -1138,7 +1138,7 @@ namespace ASC.CRM.Core.Dao String title; int companyID; - var displayName = String.Empty; + string displayName; if (contact is Company) { @@ -1346,7 +1346,7 @@ namespace ASC.CRM.Core.Dao String title; int companyID; - var displayName = String.Empty; + string displayName; if (contact is Company) { diff --git a/products/ASC.CRM/Server/Core/Dao/TaskDao.cs b/products/ASC.CRM/Server/Core/Dao/TaskDao.cs index 65c9a5c1e2..3ef6b6623d 100644 --- a/products/ASC.CRM/Server/Core/Dao/TaskDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/TaskDao.cs @@ -333,7 +333,7 @@ namespace ASC.CRM.Core.Dao int entityId) { - int result = 0; + int result; _logger.DebugFormat("Starting GetTasksCount: {0}", DateTime.Now.ToString()); diff --git a/products/ASC.CRM/Server/Middlewares/FileHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/FileHandlerMiddleware.cs index 23433df7bd..0238032732 100644 --- a/products/ASC.CRM/Server/Middlewares/FileHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/FileHandlerMiddleware.cs @@ -89,7 +89,7 @@ namespace ASC.Web.CRM.HttpHandlers var filePath = String.Format("folder_{0}/message_{1}.html", (messageId / 1000 + 1) * 1000, messageId); - string messageContent = string.Empty; + string messageContent; using (var streamReader = new StreamReader(global.GetStore().GetReadStream("mail_messages", filePath))) { diff --git a/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs index 1da79cc7e0..6f7855824d 100644 --- a/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs @@ -152,7 +152,7 @@ namespace ASC.Web.CRM.HttpHandlers var addressTemplateStr = JsonSerializer.Serialize(addressTemplate); - var isCompany = false; + bool isCompany; var isCompanyString = GetValue("is_company"); var firstName = GetValue("firstName"); diff --git a/products/ASC.CRM/Server/Services/NotifyService/NotifyClient.cs b/products/ASC.CRM/Server/Services/NotifyService/NotifyClient.cs index 7cee5ecc14..bc933ca311 100644 --- a/products/ASC.CRM/Server/Services/NotifyService/NotifyClient.cs +++ b/products/ASC.CRM/Server/Services/NotifyService/NotifyClient.cs @@ -246,8 +246,8 @@ namespace ASC.Web.CRM.Services.NotifyService var recipient = notifySource.GetRecipientsProvider().GetRecipient(recipientID.ToString()); - var entitiyListTitle = ""; - var entitiyListRelativeURL = ""; + string entitiyListTitle; + string entitiyListRelativeURL; switch (entityType) { diff --git a/products/ASC.CRM/Server/Utils/Import/CSV/ImportTasks.cs b/products/ASC.CRM/Server/Utils/Import/CSV/ImportTasks.cs index 524482846b..c839237986 100644 --- a/products/ASC.CRM/Server/Utils/Import/CSV/ImportTasks.cs +++ b/products/ASC.CRM/Server/Utils/Import/CSV/ImportTasks.cs @@ -152,9 +152,8 @@ namespace ASC.Web.CRM.Classes } var alertValue = GetPropertyValue("alertValue"); - int alertIntVal = 0; - if (Int32.TryParse(alertValue, out alertIntVal)) + if (Int32.TryParse(alertValue, out var alertIntVal)) obj.AlertValue = alertIntVal; else obj.AlertValue = 0; diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs index e4e9384062..42968cfb72 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs @@ -403,7 +403,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive googleDriveSession.BytesToTransfer)); request.Content = new StreamContent(stream); using var httpClient = new HttpClient(); - HttpResponseMessage response = null; + HttpResponseMessage response; try { diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs index 61dc933b5b..4c827fbd89 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs @@ -94,7 +94,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations if (stream != null) { - var archiveExtension = ""; + string archiveExtension; using(var zip = scope.ServiceProvider.GetService()) { diff --git a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs index 1ba4b8f40a..580f128df5 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -431,8 +431,8 @@ namespace ASC.Files.Helpers public IEnumerable MoveOrCopyBatchCheck(BatchModel batchModel) { - var checkedFiles = new List(); - var checkedFolders = new List(); + List checkedFiles; + List checkedFolders; if (batchModel.DestFolderId.ValueKind == JsonValueKind.Number) { diff --git a/web/ASC.Web.Core/CommonPhotoManager.cs b/web/ASC.Web.Core/CommonPhotoManager.cs index 6140715abd..073bfa5d9f 100644 --- a/web/ASC.Web.Core/CommonPhotoManager.cs +++ b/web/ASC.Web.Core/CommonPhotoManager.cs @@ -51,9 +51,7 @@ namespace ASC.Web.Core var maxSide = realWidth > realHeight ? realWidth : realHeight; var minSide = realWidth < realHeight ? realWidth : realHeight; - var alignWidth = true; - if (crop) alignWidth = (minSide == realWidth); - else alignWidth = (maxSide == realWidth); + var alignWidth = crop ? (minSide == realWidth) : (maxSide == realWidth); var scaleFactor = (alignWidth) ? (realWidth / (1.0 * width)) : (realHeight / (1.0 * height)); diff --git a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs index e1e8e5ac59..2b36a1479d 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -941,7 +941,7 @@ namespace ASC.Web.Studio.Core.Notify Log.Info("Start SendLettersPersonal..."); - var activeTenants = new List(); + List activeTenants; using (var scope = ServiceProvider.CreateScope()) { diff --git a/web/ASC.Web.Core/WebItemSecurity.cs b/web/ASC.Web.Core/WebItemSecurity.cs index 49c20ae116..f49c21d068 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -140,7 +140,7 @@ namespace ASC.Web.Core public bool IsAvailableForUser(Guid itemId, Guid @for) { var id = itemId.ToString(); - var result = false; + bool result; var tenant = TenantManager.GetCurrentTenant(); var dic = WebItemSecurityCache.GetOrInsert(tenant.TenantId); diff --git a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs index 97a881646d..2b9280f443 100644 --- a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs +++ b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs @@ -385,7 +385,7 @@ namespace ASC.Web.Core.WhiteLabel public void SetLogoFromStream(TenantWhiteLabelSettings tenantWhiteLabelSettings, WhiteLabelLogoTypeEnum type, string fileExt, Stream fileStream, IDataStore storage = null) { - byte[] data = null; + byte[] data; using (var memoryStream = new MemoryStream()) { fileStream.CopyTo(memoryStream); From 66cf28ba29c9062c5243a388b516c1148e545616 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Wed, 12 Jan 2022 18:42:03 +0300 Subject: [PATCH 037/167] analizators/U2U1100 --- .../Logging/SpecialFolderPathConverter.cs | 2 +- .../Context/Impl/CoreConfiguration.cs | 4 ++-- .../Context/Impl/UserManager.cs | 6 ++--- .../Data/DbSubscriptionService.cs | 2 +- common/ASC.Core.Common/EF/LinqExtensions.cs | 2 +- .../Notify/Signalr/SignalrServiceClient.cs | 2 +- .../Notify/Telegram/TelegramHelper.cs | 2 +- .../Security/EmailValidationKeyProvider.cs | 2 +- .../Core/DbBackupProvider.cs | 6 ++--- common/ASC.Data.Backup.Core/Core/DbHelper.cs | 4 ++-- .../ASC.CRM/Server/Api/InvoicesController.cs | 6 ++--- .../Api/RelationshipEventsController.cs | 4 ++-- .../ASC.CRM/Server/Api/TasksController.cs | 18 +++++++------- .../ASC.CRM/Server/Classes/CRMSettings.cs | 2 +- products/ASC.CRM/Server/Classes/CSVReader.cs | 6 ++--- .../ASC.CRM/Server/Core/Dao/CustomFieldDao.cs | 2 +- .../Server/Core/Entities/CurrencyInfo.cs | 2 +- .../WebToLeadFromHandlerMiddleware.cs | 2 +- .../ASC.CRM/Server/Utils/CurrencyProvider.cs | 4 ++-- .../Utils/Import/CSV/ImportDataOperation.cs | 2 +- .../Server/Utils/Import/CSV/ImportDeals.cs | 14 +++++------ .../Server/Utils/Import/CSV/ImportTasks.cs | 6 ++--- products/ASC.CRM/Server/Utils/MailSender.cs | 2 +- .../Server/Controllers/CalendarController.cs | 24 +++++++++---------- .../ASC.Calendar/Server/iCalParser/Parser.cs | 3 ++- .../ASC.Calendar/Server/iCalParser/Token.cs | 4 ++-- .../Server/iCalParser/iCalendarEmitter.cs | 2 +- .../ASC.Files/Core/Core/FileStorageService.cs | 2 +- .../Thirdparty/OneDrive/OneDriveDaoBase.cs | 3 +-- .../SharePoint/SharePointProviderInfo.cs | 2 +- .../HttpHandlers/ThirdPartyAppHandler.ashx.cs | 2 +- products/ASC.Files/Core/Utils/EntryManager.cs | 6 ++--- .../Server/Controllers/FilesController.cs | 2 +- .../Controllers/SettingsController.cs | 2 +- web/ASC.Web.Core/Calendars/RecurrenceRule.cs | 2 +- web/ASC.Web.Core/Helpers/GrammaticalHelper.cs | 4 +--- web/ASC.Web.Core/Utility/CommonLinkUtility.cs | 8 +++---- 37 files changed, 83 insertions(+), 85 deletions(-) diff --git a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs index e96bdfcd35..4d63ed3da6 100644 --- a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs +++ b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs @@ -49,7 +49,7 @@ namespace ASC.Common.Logging var args = Environment.CommandLine.Split(' '); for (var i = 0; i < args.Length - 1; i++) { - if (args[i].Equals(Option.Substring(CMD_LINE.Length), StringComparison.InvariantCultureIgnoreCase)) + if (args[i].Contains(Option, StringComparison.InvariantCultureIgnoreCase)) { result = args[i + 1]; } diff --git a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs index ade6cd21b5..562cfa32cc 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -76,13 +76,13 @@ namespace ASC.Core get { //TODO:if (CustomMode && HttpContext.Current != null && HttpContext.Current.Request.SailfishApp()) return true; - return personal ?? (bool)(personal = string.Compare(Configuration["core:personal"], "true", true) == 0); + return personal ?? (bool)(personal = Configuration["core:personal"].Equals("true", StringComparison.OrdinalIgnoreCase)); } } public bool CustomMode { - get { return customMode ?? (bool)(customMode = string.Compare(Configuration["core:custom-mode"], "true", true) == 0); } + get { return customMode ?? (bool)(customMode = Configuration["core:custom-mode"].Equals("true", StringComparison.OrdinalIgnoreCase)); } } } diff --git a/common/ASC.Core.Common/Context/Impl/UserManager.cs b/common/ASC.Core.Common/Context/Impl/UserManager.cs index 3a2ffe8fff..bec401d493 100644 --- a/common/ASC.Core.Common/Context/Impl/UserManager.cs +++ b/common/ASC.Core.Common/Context/Impl/UserManager.cs @@ -175,13 +175,13 @@ namespace ASC.Core public UserInfo GetUserBySid(string sid) { return GetUsersInternal() - .FirstOrDefault(u => u.Sid != null && string.Compare(u.Sid, sid, StringComparison.CurrentCultureIgnoreCase) == 0) ?? Constants.LostUser; + .FirstOrDefault(u => u.Sid != null && u.Sid.Equals(sid, StringComparison.CurrentCultureIgnoreCase)) ?? Constants.LostUser; } public UserInfo GetSsoUserByNameId(string nameId) { return GetUsersInternal() - .FirstOrDefault(u => !string.IsNullOrEmpty(u.SsoNameId) && string.Compare(u.SsoNameId, nameId, StringComparison.CurrentCultureIgnoreCase) == 0) ?? Constants.LostUser; + .FirstOrDefault(u => !string.IsNullOrEmpty(u.SsoNameId) && u.SsoNameId.Equals(nameId, StringComparison.CurrentCultureIgnoreCase)) ?? Constants.LostUser; } public bool IsUserNameExists(string username) { @@ -239,7 +239,7 @@ namespace ASC.Core public UserInfo[] Search(string text, EmployeeStatus status, Guid groupId) { - if (text == null || text.Trim() == string.Empty) return new UserInfo[0]; + if (text == null || text.Trim().Length == 0) return new UserInfo[0]; var words = text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (words.Length == 0) return new UserInfo[0]; diff --git a/common/ASC.Core.Common/Data/DbSubscriptionService.cs b/common/ASC.Core.Common/Data/DbSubscriptionService.cs index 1420c3a2df..c97f98f197 100644 --- a/common/ASC.Core.Common/Data/DbSubscriptionService.cs +++ b/common/ASC.Core.Common/Data/DbSubscriptionService.cs @@ -195,7 +195,7 @@ namespace ASC.Core.Data .Where(r => r.Source == sourceId) .Where(r => r.Action == actionId); - if (objectId != string.Empty) + if (objectId.Length != 0) { q = q.Where(r => r.Object == (objectId ?? string.Empty)); } diff --git a/common/ASC.Core.Common/EF/LinqExtensions.cs b/common/ASC.Core.Common/EF/LinqExtensions.cs index aebb788ec9..c2959d56b3 100644 --- a/common/ASC.Core.Common/EF/LinqExtensions.cs +++ b/common/ASC.Core.Common/EF/LinqExtensions.cs @@ -31,7 +31,7 @@ namespace ASC.Core.Common.EF private static PropertyInfo GetPropertyInfo(Type objType, string name) { var properties = objType.GetProperties(); - var matchedProperty = properties.FirstOrDefault(p => p.Name.ToLower() == name.ToLower()); + var matchedProperty = properties.FirstOrDefault(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (matchedProperty == null) throw new ArgumentException("name"); diff --git a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs index 0793bde618..d85e051936 100644 --- a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs @@ -136,7 +136,7 @@ namespace ASC.Core.Notify.Signalr var tenant = tenantId == -1 ? TenantManager.GetTenant(domain) : TenantManager.GetTenant(tenantId); - var isTenantUser = callerUserName == string.Empty; + var isTenantUser = callerUserName.Length == 0; var message = new MessageClass { UserName = isTenantUser ? tenant.GetTenantDomain(CoreSettings) : callerUserName, diff --git a/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs b/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs index 4b184ebe98..0dbf3d8069 100644 --- a/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs +++ b/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs @@ -106,7 +106,7 @@ namespace ASC.Core.Common.Notify public string CurrentRegistrationLink(Guid userId, int tenantId) { var token = GetCurrentToken(userId, tenantId); - if (token == null || token == "") return ""; + if (token == null || token.Length == 0) return ""; return GetLink(token); } diff --git a/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs b/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs index 3d62360876..36da33b545 100644 --- a/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs +++ b/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs @@ -134,7 +134,7 @@ namespace ASC.Security.Cryptography var hash = GetMashineHashedData(BitConverter.GetBytes(ms), Encoding.ASCII.GetBytes(email)); var key2 = DoStringFromBytes(hash); - var key2_good = string.Compare(parts[1], key2, StringComparison.InvariantCultureIgnoreCase) == 0; + var key2_good = parts[1].Equals(key2, StringComparison.OrdinalIgnoreCase); if (!key2_good) return ValidationResult.Invalid; var ms_current = (long)(DateTime.UtcNow - _from).TotalMilliseconds; return validInterval >= TimeSpan.FromMilliseconds(ms_current - ms) ? ValidationResult.Ok : ValidationResult.Expired; diff --git a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs index 01790c82ae..e2b17a03a0 100644 --- a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs +++ b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs @@ -106,7 +106,7 @@ namespace ASC.Data.Backup { var map = new ExeConfigurationFileMap { - ExeConfigFilename = string.Compare(Path.GetExtension(config), ".config", true) == 0 ? config : CrossPlatform.PathCombine(config, "Web.config") + ExeConfigFilename = string.Equals(Path.GetExtension(config), ".config", StringComparison.OrdinalIgnoreCase) ? config : CrossPlatform.PathCombine(config, "Web.config") }; return ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); } @@ -194,11 +194,11 @@ namespace ASC.Data.Backup private void RestoreDatabase(ConnectionStringSettings connectionString, IEnumerable elements, IDataReadOperator reader) { var dbName = connectionString.Name; - var dbElement = elements.SingleOrDefault(e => string.Compare(e.Name.LocalName, connectionString.Name, true) == 0); + var dbElement = elements.SingleOrDefault(e => string.Equals(e.Name.LocalName, connectionString.Name, StringComparison.OrdinalIgnoreCase)); if (dbElement != null && dbElement.Attribute("ref") != null) { dbName = dbElement.Attribute("ref").Value; - dbElement = elements.Single(e => string.Compare(e.Name.LocalName, dbElement.Attribute("ref").Value, true) == 0); + dbElement = elements.Single(e => string.Equals(e.Name.LocalName, dbElement.Attribute("ref").Value, StringComparison.OrdinalIgnoreCase)); } if (dbElement == null) return; diff --git a/common/ASC.Data.Backup.Core/Core/DbHelper.cs b/common/ASC.Data.Backup.Core/Core/DbHelper.cs index c7a45cadb3..5149a34742 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -52,7 +52,7 @@ namespace ASC.Data.Backup connect.ConnectionString = connectionString.ConnectionString; connect.Open(); - mysql = connectionString.ProviderName.ToLower().Contains("mysql"); + mysql = connectionString.ProviderName.Contains("mysql", StringComparison.OrdinalIgnoreCase); if (mysql) { CreateCommand("set @@session.sql_mode = concat(@@session.sql_mode, ',NO_AUTO_VALUE_ON_ZERO')").ExecuteNonQuery(); @@ -268,7 +268,7 @@ namespace ASC.Data.Backup { return string.Format(whereExceptions[tableName.ToLower()], tenant); } - var tenantColumn = GetColumnsFrom(tableName).FirstOrDefault(c => c.ToLower().StartsWith("tenant")); + var tenantColumn = GetColumnsFrom(tableName).FirstOrDefault(c => c.StartsWith("tenant", StringComparison.OrdinalIgnoreCase)); return tenantColumn != null ? " where " + Quote(tenantColumn) + " = " + tenant : " where 1 = 0"; diff --git a/products/ASC.CRM/Server/Api/InvoicesController.cs b/products/ASC.CRM/Server/Api/InvoicesController.cs index 801bae651b..80168ce318 100644 --- a/products/ASC.CRM/Server/Api/InvoicesController.cs +++ b/products/ASC.CRM/Server/Api/InvoicesController.cs @@ -192,9 +192,9 @@ namespace ASC.CRM.Api ) { if (!String.IsNullOrEmpty(entityType) && !( - String.Compare(entityType, "contact", true) == 0 || - String.Compare(entityType, "opportunity", true) == 0 || - String.Compare(entityType, "case", true) == 0)) + string.Equals(entityType, "contact", StringComparison.CurrentCultureIgnoreCase) || + string.Equals(entityType, "opportunity", StringComparison.CurrentCultureIgnoreCase) || + string.Equals(entityType, "case", StringComparison.CurrentCultureIgnoreCase))) throw new ArgumentException(); IEnumerable result; diff --git a/products/ASC.CRM/Server/Api/RelationshipEventsController.cs b/products/ASC.CRM/Server/Api/RelationshipEventsController.cs index 945a90d51d..fb115d8da9 100644 --- a/products/ASC.CRM/Server/Api/RelationshipEventsController.cs +++ b/products/ASC.CRM/Server/Api/RelationshipEventsController.cs @@ -387,8 +387,8 @@ namespace ASC.CRM.Api if (!string.IsNullOrEmpty(entityType) && !( - string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 || - string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0) + string.Equals(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) || + string.Equals(entityType, "case", StringComparison.OrdinalIgnoreCase)) ) throw new ArgumentException(); diff --git a/products/ASC.CRM/Server/Api/TasksController.cs b/products/ASC.CRM/Server/Api/TasksController.cs index 7c4775c80d..170ae0720d 100644 --- a/products/ASC.CRM/Server/Api/TasksController.cs +++ b/products/ASC.CRM/Server/Api/TasksController.cs @@ -103,9 +103,9 @@ namespace ASC.CRM.Api if (!string.IsNullOrEmpty(entityType) && !( - string.Compare(entityType, "contact", StringComparison.OrdinalIgnoreCase) == 0 || - string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 || - string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0) + string.Equals(entityType, "contact", StringComparison.OrdinalIgnoreCase)|| + string.Equals(entityType, "opportunity", StringComparison.OrdinalIgnoreCase)|| + string.Equals(entityType, "case", StringComparison.OrdinalIgnoreCase)) ) throw new ArgumentException(); @@ -303,8 +303,8 @@ namespace ASC.CRM.Api if (!string.IsNullOrEmpty(entityType) && !( - string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 || - string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0 + string.Equals(entityType, "opportunity", StringComparison.OrdinalIgnoreCase)|| + string.Equals(entityType, "case", StringComparison.OrdinalIgnoreCase) ) || categoryId <= 0) throw new ArgumentException(); @@ -398,8 +398,8 @@ namespace ASC.CRM.Api if ( !string.IsNullOrEmpty(entityType) && - !(string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 || - string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0) + !(string.Equals(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) || + string.Equals(entityType, "case", StringComparison.OrdinalIgnoreCase)) ) throw new ArgumentException(); @@ -508,8 +508,8 @@ namespace ASC.CRM.Api var isNotify = inDto.isNotify; if (!string.IsNullOrEmpty(entityType) && - !(string.Compare(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) == 0 || - string.Compare(entityType, "case", StringComparison.OrdinalIgnoreCase) == 0 + !(string.Equals(entityType, "opportunity", StringComparison.OrdinalIgnoreCase) || + string.Equals(entityType, "case", StringComparison.OrdinalIgnoreCase) ) || categoryid <= 0) throw new ArgumentException(); diff --git a/products/ASC.CRM/Server/Classes/CRMSettings.cs b/products/ASC.CRM/Server/Classes/CRMSettings.cs index e88f7d54a6..15b2a2ca19 100644 --- a/products/ASC.CRM/Server/Classes/CRMSettings.cs +++ b/products/ASC.CRM/Server/Classes/CRMSettings.cs @@ -162,7 +162,7 @@ namespace ASC.Web.CRM.Classes var languageName = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName; - var findedCurrency = currencyProvider.GetAll().Find(item => String.Compare(item.CultureName, languageName, true) == 0); + var findedCurrency = currencyProvider.GetAll().Find(item => string.Equals(item.CultureName, languageName, StringComparison.OrdinalIgnoreCase)); return new CrmSettings() { diff --git a/products/ASC.CRM/Server/Classes/CSVReader.cs b/products/ASC.CRM/Server/Classes/CSVReader.cs index 5c39e98b20..636a5721c6 100644 --- a/products/ASC.CRM/Server/Classes/CSVReader.cs +++ b/products/ASC.CRM/Server/Classes/CSVReader.cs @@ -157,7 +157,7 @@ namespace ASC.Web.CRM.Classes // Build the list of objects in the line List objects = new List(); - while (currentLine != "") + while (currentLine.Length != 0) objects.Add(ReadNextObject()); return objects; } @@ -185,10 +185,10 @@ namespace ASC.Web.CRM.Classes { // Check if we've hit the end of the string if ((!quoted && i == len) // non-quoted strings end with a comma or end of line - || (!quoted && currentLine.Substring(i, 1) == FieldSep) + || (!quoted && string.CompareOrdinal(currentLine, i, FieldSep, 0, 1) == 0) // quoted strings end with a quote followed by a comma or end of line || (quoted && i == len - 1 && currentLine.EndsWith("\"")) - || (quoted && currentLine.Substring(i, 2) == "\"" + FieldSep)) + || (quoted && string.CompareOrdinal(currentLine, i, "\"" + FieldSep, 0, 2) == 0)) foundEnd = true; else i++; diff --git a/products/ASC.CRM/Server/Core/Dao/CustomFieldDao.cs b/products/ASC.CRM/Server/Core/Dao/CustomFieldDao.cs index 6a75bd75a7..b4bf24a4d6 100644 --- a/products/ASC.CRM/Server/Core/Dao/CustomFieldDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/CustomFieldDao.cs @@ -349,7 +349,7 @@ namespace ASC.CRM.Core.Dao if (fieldType == CustomFieldType.SelectBox) { - if (oldMask == customField.Mask || customField.Mask == "") + if (oldMask == customField.Mask || customField.Mask.Length == 0) { resultMask = oldMask; } diff --git a/products/ASC.CRM/Server/Core/Entities/CurrencyInfo.cs b/products/ASC.CRM/Server/Core/Entities/CurrencyInfo.cs index 6337582852..48a7a9d93a 100644 --- a/products/ASC.CRM/Server/Core/Entities/CurrencyInfo.cs +++ b/products/ASC.CRM/Server/Core/Entities/CurrencyInfo.cs @@ -73,7 +73,7 @@ namespace ASC.CRM.Core public override bool Equals(object obj) { var ci = obj as CurrencyInfo; - return ci != null && string.Compare(Title, ci.Title, true) == 0; + return ci != null && string.Equals(Title, ci.Title, StringComparison.OrdinalIgnoreCase); } public override int GetHashCode() diff --git a/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs index 6f7855824d..593be93500 100644 --- a/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs @@ -313,7 +313,7 @@ namespace ASC.Web.CRM.HttpHandlers IsPrimary = true }); } - else if (String.Compare(key, "tag", true) == 0) + else if (string.Equals(key, "tag", StringComparison.OrdinalIgnoreCase)) { var tags = _context.Request.Form["tag"]; diff --git a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs index a0823e282b..e6fa13f388 100644 --- a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs +++ b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs @@ -142,7 +142,7 @@ namespace ASC.Web.CRM.Classes public bool IsConvertable(String abbreviation) { - var findedItem = _currencies.Keys.ToList().Find(item => String.Compare(abbreviation, item) == 0); + var findedItem = _currencies.Keys.ToList().Find(item => string.Equals(abbreviation, item)); if (findedItem == null) throw new ArgumentException(abbreviation); @@ -152,7 +152,7 @@ namespace ASC.Web.CRM.Classes public Decimal MoneyConvert(decimal amount, string from, string to) { - if (string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to) || string.Compare(from, to, true) == 0) return amount; + if (string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to) || string.Equals(from, to, StringComparison.OrdinalIgnoreCase)) return amount; var rates = GetExchangeRates(); diff --git a/products/ASC.CRM/Server/Utils/Import/CSV/ImportDataOperation.cs b/products/ASC.CRM/Server/Utils/Import/CSV/ImportDataOperation.cs index 9cbf155a79..51a194bc21 100644 --- a/products/ASC.CRM/Server/Utils/Import/CSV/ImportDataOperation.cs +++ b/products/ASC.CRM/Server/Utils/Import/CSV/ImportDataOperation.cs @@ -148,7 +148,7 @@ namespace ASC.Web.CRM.Classes var values = jsonElement.EnumerateArray().Select(x => x.GetInt32()).ToList().ConvertAll(columnIndex => _columns[columnIndex]); - values.RemoveAll(item => item == String.Empty); + values.RemoveAll(item => item.Length == 0); return String.Join(",", values.ToArray()); } diff --git a/products/ASC.CRM/Server/Utils/Import/CSV/ImportDeals.cs b/products/ASC.CRM/Server/Utils/Import/CSV/ImportDeals.cs index 92fe4b6a69..4f21010437 100644 --- a/products/ASC.CRM/Server/Utils/Import/CSV/ImportDeals.cs +++ b/products/ASC.CRM/Server/Utils/Import/CSV/ImportDeals.cs @@ -125,17 +125,17 @@ namespace ASC.Web.CRM.Classes if (!string.IsNullOrEmpty(bidTypeStr)) { - if (String.Compare(CRMDealResource.BidType_FixedBid, bidTypeStr, true) == 0) + if (string.Equals(CRMDealResource.BidType_FixedBid, bidTypeStr, StringComparison.OrdinalIgnoreCase)) bidType = BidType.FixedBid; - else if (String.Compare(CRMDealResource.BidType_PerDay, bidTypeStr, true) == 0) + else if (string.Equals(CRMDealResource.BidType_PerDay, bidTypeStr, StringComparison.OrdinalIgnoreCase)) bidType = BidType.PerDay; - else if (String.Compare(CRMDealResource.BidType_PerHour, bidTypeStr, true) == 0) + else if (string.Equals(CRMDealResource.BidType_PerHour, bidTypeStr, StringComparison.OrdinalIgnoreCase)) bidType = BidType.PerHour; - else if (String.Compare(CRMDealResource.BidType_PerMonth, bidTypeStr, true) == 0) + else if (string.Equals(CRMDealResource.BidType_PerMonth, bidTypeStr, StringComparison.OrdinalIgnoreCase)) bidType = BidType.PerMonth; - else if (String.Compare(CRMDealResource.BidType_PerWeek, bidTypeStr, true) == 0) + else if (string.Equals(CRMDealResource.BidType_PerWeek, bidTypeStr, StringComparison.OrdinalIgnoreCase)) bidType = BidType.PerWeek; - else if (String.Compare(CRMDealResource.BidType_PerYear, bidTypeStr, true) == 0) + else if (string.Equals(CRMDealResource.BidType_PerYear, bidTypeStr, StringComparison.OrdinalIgnoreCase)) bidType = BidType.PerYear; } @@ -176,7 +176,7 @@ namespace ASC.Web.CRM.Classes obj.DealMilestoneID = dealMilestones[0].ID; else { - var dealMilestone = dealMilestones.Find(item => String.Compare(item.Title, dealMilestoneTitle, true) == 0); + var dealMilestone = dealMilestones.Find(item => string.Equals(item.Title, dealMilestoneTitle, StringComparison.OrdinalIgnoreCase)); if (dealMilestone == null) obj.DealMilestoneID = dealMilestones[0].ID; diff --git a/products/ASC.CRM/Server/Utils/Import/CSV/ImportTasks.cs b/products/ASC.CRM/Server/Utils/Import/CSV/ImportTasks.cs index c839237986..bc60a84bbc 100644 --- a/products/ASC.CRM/Server/Utils/Import/CSV/ImportTasks.cs +++ b/products/ASC.CRM/Server/Utils/Import/CSV/ImportTasks.cs @@ -108,7 +108,7 @@ namespace ASC.Web.CRM.Classes if (!String.IsNullOrEmpty(categoryTitle)) { - var findedCategory = taskCategories.Find(item => String.Compare(item.Title, categoryTitle) == 0); + var findedCategory = taskCategories.Find(item => string.Equals(item.Title, categoryTitle)); if (findedCategory == null) { @@ -144,9 +144,9 @@ namespace ASC.Web.CRM.Classes var taskStatus = GetPropertyValue("status"); - if (!String.IsNullOrEmpty(taskStatus)) + if (!string.IsNullOrEmpty(taskStatus)) { - if (String.Compare(taskStatus, CRMTaskResource.TaskStatus_Closed, true) == 0) + if (string.Equals(taskStatus, CRMTaskResource.TaskStatus_Closed, StringComparison.OrdinalIgnoreCase)) obj.IsClosed = true; } diff --git a/products/ASC.CRM/Server/Utils/MailSender.cs b/products/ASC.CRM/Server/Utils/MailSender.cs index b120ca72a3..ae898d1adf 100644 --- a/products/ASC.CRM/Server/Utils/MailSender.cs +++ b/products/ASC.CRM/Server/Utils/MailSender.cs @@ -693,7 +693,7 @@ namespace ASC.Web.CRM.Classes foreach (Match match in _regex.Matches(template)) { - var findedTag = tags.Find(item => String.Compare(item.Name, match.Value) == 0); + var findedTag = tags.Find(item => string.Equals(item.Name, match.Value)); if (findedTag == null) continue; diff --git a/products/ASC.Calendar/Server/Controllers/CalendarController.cs b/products/ASC.Calendar/Server/Controllers/CalendarController.cs index ef175ed13b..547200dd53 100644 --- a/products/ASC.Calendar/Server/Controllers/CalendarController.cs +++ b/products/ASC.Calendar/Server/Controllers/CalendarController.cs @@ -541,7 +541,7 @@ namespace ASC.Calendar.Controllers var sharedCalUrl = new Uri(new Uri(calDavServerUrl), "/caldav/" + curCaldavUserName + "/" + caldavGuid).ToString(); var calendar = GetUserCaldavCalendar(sharedCalUrl, userName); - if (calendar != "") + if (calendar.Length != 0) { if (calendar == "NotFound") { @@ -578,7 +578,7 @@ namespace ASC.Calendar.Controllers { var sharedCalUrl = new Uri(new Uri(calDavServerUrl), "/caldav/" + curCaldavUserName + "/" + todoCalendars[0].calDavGuid).ToString(); var calendar = GetUserCaldavCalendar(sharedCalUrl, userName); - if (calendar != "") + if (calendar.Length != 0) { if (calendar == "NotFound") { @@ -616,7 +616,7 @@ namespace ASC.Calendar.Controllers var calendar = GetUserCaldavCalendar(sharedCalUrl, userName); - if (calendar != "") + if (calendar.Length != 0) { if (calendar == "NotFound") { @@ -631,7 +631,7 @@ namespace ASC.Calendar.Controllers true ); } - if (sharedCalUrl != "") + if (sharedCalUrl.Length != 0) { var calendarIcs = GetCalendariCalString(calendarId, true); @@ -653,7 +653,7 @@ namespace ASC.Calendar.Controllers var isShared = ownerId != SecurityContext.CurrentAccount.ID; var calDavGuid = cal.calDavGuid; - if (calDavGuid == "" || calDavGuid == Guid.Empty.ToString()) + if (calDavGuid.Length == 0 || calDavGuid == Guid.Empty.ToString()) { calDavGuid = Guid.NewGuid().ToString(); DataProvider.UpdateCalendarGuid(Convert.ToInt32(cal.Id), Guid.Parse(calDavGuid)); @@ -665,7 +665,7 @@ namespace ASC.Calendar.Controllers var caldavCalendar = GetUserCaldavCalendar(calUrl, userName); - if (caldavCalendar != "") + if (caldavCalendar.Length != 0) { if (caldavCalendar == "NotFound") { @@ -1746,7 +1746,7 @@ namespace ASC.Calendar.Controllers ÑaldavGuid = calendarId; } - if (ÑaldavGuid != "") + if (ÑaldavGuid.Length != 0) { var calDavServerUrl = myUri.Scheme + "://" + myUri.Host + "/caldav"; @@ -3554,10 +3554,10 @@ namespace ASC.Calendar.Controllers var date = periodList.ToString(); //has time - if (date.ToLowerInvariant().IndexOf('t') >= 0) + if (date.IndexOf('t', StringComparison.OrdinalIgnoreCase) >= 0) { //is utc time - if (date.ToLowerInvariant().IndexOf('z') >= 0) + if (date.IndexOf('z', StringComparison.OrdinalIgnoreCase) >= 0) { rrule += date; } @@ -3581,7 +3581,7 @@ namespace ASC.Calendar.Controllers } } //for yyyyMMdd/P1D date. Bug in the ical.net - else if (date.ToLowerInvariant().IndexOf("/p") >= 0) + else if (date.IndexOf("/p", StringComparison.OrdinalIgnoreCase) >= 0) { try { @@ -3993,7 +3993,7 @@ namespace ASC.Calendar.Controllers { try { - if (guid != null && guid != "") + if (guid != null && guid.Length != 0) { var calDavServerUrl = myUri.Scheme + "://" + myUri.Host + "/caldav"; @@ -4647,7 +4647,7 @@ namespace ASC.Calendar.Controllers TimeZoneInfo calendarTimeZone = null, string calGuid = null) { - if (calGuid != "" && myUri != null && user != null) + if (calGuid.Length != 0 && myUri != null && user != null) { string eventUid = guid, oldEventUid = guid; diff --git a/products/ASC.Calendar/Server/iCalParser/Parser.cs b/products/ASC.Calendar/Server/iCalParser/Parser.cs index 9130e13efc..d8c6b36cb3 100644 --- a/products/ASC.Calendar/Server/iCalParser/Parser.cs +++ b/products/ASC.Calendar/Server/iCalParser/Parser.cs @@ -44,6 +44,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ +using System; using System.Collections; using System.IO; using System.Text; @@ -490,7 +491,7 @@ namespace ASC.Calendar.iCalParser } else if (iprop != null && id.TokenVal != TokenValue.Xtension) { - if (iprop.TokenText.ToLowerInvariant() == "uri") + if (iprop.TokenText.Equals("uri", StringComparison.OrdinalIgnoreCase)) { // special case emitter.doURIResource(val); diff --git a/products/ASC.Calendar/Server/iCalParser/Token.cs b/products/ASC.Calendar/Server/iCalParser/Token.cs index 2ab517eca9..22766b3bf5 100644 --- a/products/ASC.Calendar/Server/iCalParser/Token.cs +++ b/products/ASC.Calendar/Server/iCalParser/Token.cs @@ -181,8 +181,8 @@ namespace ASC.Calendar.iCalParser - isUTC= icalDate.ToLowerInvariant().EndsWith("z"); - isDate = !icalDate.ToLowerInvariant().Contains("t"); + isUTC= icalDate.EndsWith("z", StringComparison.OrdinalIgnoreCase); + isDate = icalDate.IndexOf("t", StringComparison.OrdinalIgnoreCase) == -1; DateTime dateTime ; diff --git a/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs b/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs index b16d11f30b..db7762e05e 100644 --- a/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs +++ b/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs @@ -136,7 +136,7 @@ namespace ASC.Calendar.iCalParser || _curPropToken.TokenVal == TokenValue.Texdate) { - if (iprop != null && iprop.TokenText.ToLowerInvariant() == "date") + if (iprop != null && iprop.TokenText.Equals("date", StringComparison.OrdinalIgnoreCase)) dateTime = Token.ParseDate(t.TokenText); else diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index d332c3e4af..cfd0c2a3d7 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -433,7 +433,7 @@ namespace ASC.Web.Files.Services.WCFService var folderAccess = folder.Access; - if (string.Compare(folder.Title, title, false) != 0) + if (string.Equals(folder.Title, title, StringComparison.OrdinalIgnoreCase)) { var newFolderID = folderDao.RenameFolder(folder, title); folder = folderDao.GetFolder(newFolderID); diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs index 666c1e4f21..2a1f454dc4 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs @@ -85,8 +85,7 @@ namespace ASC.Files.Thirdparty.OneDrive protected override string MakeId(string id = null) { return string.Format("{0}{1}", PathPrefix, - string.IsNullOrEmpty(id) || id == "" - ? "" : ("-|" + id.TrimStart('/'))); + string.IsNullOrEmpty(id) ? "" : ("-|" + id.TrimStart('/'))); } public string MakeOneDrivePath(Item onedriveItem) diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs index 9c57234b6c..9e4b374fee 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs @@ -375,7 +375,7 @@ namespace ASC.Files.Thirdparty.SharePoint private Folder GetFolder(object id) { - if ((string)id == "") id = SpRootFolderId; + if (((string)id).Length == 0) id = SpRootFolderId; var folder = clientContext.Web.GetFolderByServerRelativeUrl((string)id); clientContext.Load(folder); clientContext.Load(folder.Files, collection => collection.IncludeWithDefaultProperties(r => r.ListItemAllFields)); diff --git a/products/ASC.Files/Core/HttpHandlers/ThirdPartyAppHandler.ashx.cs b/products/ASC.Files/Core/HttpHandlers/ThirdPartyAppHandler.ashx.cs index 129d7e1c0e..d16a341629 100644 --- a/products/ASC.Files/Core/HttpHandlers/ThirdPartyAppHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/ThirdPartyAppHandler.ashx.cs @@ -115,7 +115,7 @@ namespace ASC.Web.Files.HttpHandlers if (string.IsNullOrEmpty(message)) { - if ((context.Request.Query["error"].FirstOrDefault() ?? "").ToLower() == "access_denied") + if ((context.Request.Query["error"].FirstOrDefault() ?? "").Equals("access_denied", StringComparison.InvariantCultureIgnoreCase)) { message = context.Request.Query["error_description"].FirstOrDefault() ?? FilesCommonResource.AppAccessDenied; } diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index bc487297c7..d22a9dad78 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -751,7 +751,7 @@ namespace ASC.Web.Files.Utils if ((!searchInContent || filter == FilterType.ByExtension) && !string.IsNullOrEmpty(searchText = (searchText ?? string.Empty).ToLower().Trim())) { - entries = entries.Where(f => f.Title.ToLower().Contains(searchText)).ToList(); + entries = entries.Where(f => f.Title.Contains(searchText, StringComparison.InvariantCultureIgnoreCase)).ToList(); } return entries; } @@ -1219,7 +1219,7 @@ namespace ASC.Web.Files.Utils title = Global.ReplaceInvalidCharsAndTruncate(title); var ext = FileUtility.GetFileExtension(file.Title); - if (string.Compare(ext, FileUtility.GetFileExtension(title), true) != 0) + if (!string.Equals(ext, FileUtility.GetFileExtension(title), StringComparison.InvariantCultureIgnoreCase)) { title += ext; } @@ -1227,7 +1227,7 @@ namespace ASC.Web.Files.Utils var fileAccess = file.Access; var renamed = false; - if (string.Compare(file.Title, title, false) != 0) + if (!string.Equals(file.Title, title)) { var newFileID = fileDao.FileRename(file, title); diff --git a/products/ASC.Files/Server/Controllers/FilesController.cs b/products/ASC.Files/Server/Controllers/FilesController.cs index c3da2caf8b..ec6137f96f 100644 --- a/products/ASC.Files/Server/Controllers/FilesController.cs +++ b/products/ASC.Files/Server/Controllers/FilesController.cs @@ -2343,7 +2343,7 @@ namespace ASC.Api.Documents private object WordpressSave(WordpressSaveModel model) { - if (model.Code == "") + if (model.Code.Length == 0) { return new { diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index 629326660d..f72eb80707 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -2613,7 +2613,7 @@ namespace ASC.Api.Settings public object GetSocketSettings() { var hubUrl = Configuration["web:hub"] ?? string.Empty; - if (hubUrl != string.Empty) + if (hubUrl.Length != 0) { if (!hubUrl.EndsWith("/")) { diff --git a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs index d89a288a28..baacd1b20d 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -963,7 +963,7 @@ namespace ASC.Web.Core.Calendars foreach (var date in val.Split(',')) { if (DateTime.TryParseExact(date.ToUpper(), _dateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var dt)) - rr.ExDates.Add(new ExDate() { Date = dt, IsDateTime = (date.ToLower().IndexOf('t') >= 0) }); + rr.ExDates.Add(new ExDate() { Date = dt, IsDateTime = (date.IndexOf('t', StringComparison.InvariantCultureIgnoreCase) >= 0) }); } break; diff --git a/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs b/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs index 5a590261b0..3ed1a568aa 100644 --- a/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs +++ b/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs @@ -33,9 +33,7 @@ namespace ASC.Web.Core.Helpers public static string ChooseNumeralCase(int number, string nominative, string genitiveSingular, string genitivePlural) { if ( - string.Compare( - System.Threading.Thread.CurrentThread.CurrentUICulture.ThreeLetterISOLanguageName, - "rus", true) == 0) + System.Threading.Thread.CurrentThread.CurrentUICulture.ThreeLetterISOLanguageName.Equals("rus", StringComparison.InvariantCultureIgnoreCase)) { int[] formsTable = { 2, 0, 1, 1, 1, 2, 2, 2, 2, 2 }; diff --git a/web/ASC.Web.Core/Utility/CommonLinkUtility.cs b/web/ASC.Web.Core/Utility/CommonLinkUtility.cs index f0a1d81360..e8bbd64422 100644 --- a/web/ASC.Web.Core/Utility/CommonLinkUtility.cs +++ b/web/ASC.Web.Core/Utility/CommonLinkUtility.cs @@ -282,7 +282,7 @@ namespace ASC.Web.Studio.Utility foreach (var item in WebItemManager.GetItemsAll()) { var _itemName = GetWebItemNameFromUrl(item.StartURL); - if (string.Compare(itemName, _itemName, StringComparison.InvariantCultureIgnoreCase) == 0) + if (itemName.Equals(_itemName, StringComparison.InvariantCultureIgnoreCase)) return item; } } @@ -345,7 +345,7 @@ namespace ASC.Web.Studio.Utility var _productName = GetProductNameFromUrl(product.StartURL); if (!string.IsNullOrEmpty(_productName)) { - if (string.Compare(productName, _productName, StringComparison.InvariantCultureIgnoreCase) == 0) + if (string.Equals(productName, _productName, StringComparison.InvariantCultureIgnoreCase)) { currentProduct = product; @@ -356,7 +356,7 @@ namespace ASC.Web.Studio.Utility var _moduleName = GetModuleNameFromUrl(module.StartURL); if (!string.IsNullOrEmpty(_moduleName)) { - if (string.Compare(moduleName, _moduleName, StringComparison.InvariantCultureIgnoreCase) == 0) + if (string.Equals(moduleName, _moduleName, StringComparison.InvariantCultureIgnoreCase)) { currentModule = module; break; @@ -463,7 +463,7 @@ namespace ASC.Web.Studio.Utility if (!string.IsNullOrEmpty(sysName)) foreach (var product in WebItemManager.GetItemsAll()) { - if (string.CompareOrdinal(sysName, WebItemExtension.GetSysName(product)) == 0) + if (string.Equals(sysName, WebItemExtension.GetSysName(product))) { result = product; break; From 4155f911c085d2336fc4e2c6b2ce1286c0b6f65a Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 13 Jan 2022 14:19:39 +0300 Subject: [PATCH 038/167] analizators/U2U1025 --- common/ASC.Core.Common/ASC.Core.Common.csproj | 1 + .../ASC.Core.Common/Billing/BillingClient.cs | 7 ++-- .../ASC.Core.Common/Billing/CouponManager.cs | 19 ++++++---- .../Configuration/AmiPublicDnsSyncService.cs | 16 +++++---- .../Context/Impl/PaymentManager.cs | 10 +++--- .../Notify/Signalr/SignalrServiceClient.cs | 18 ++++++---- common/ASC.Data.Storage/BaseStorage.cs | 6 +++- .../DiscStorage/DiscDataStore.cs | 6 ++-- .../GoogleCloud/GoogleCloudStorage.cs | 5 +-- .../RackspaceCloud/RackspaceCloudStorage.cs | 6 ++-- common/ASC.Data.Storage/S3/S3Storage.cs | 6 ++-- common/ASC.Data.Storage/WebPath.cs | 12 ++++--- .../Helpers/RequestHelper.cs | 7 ++-- .../ASC.ApiSystem/Classes/CommonMethods.cs | 14 ++++++-- .../Controllers/CalDavController.cs | 3 +- .../Server/Classes/ContactPhotoManager.cs | 13 ++++--- products/ASC.CRM/Server/Startup.cs | 11 ++++++ .../ASC.CRM/Server/Utils/CurrencyProvider.cs | 13 ++++--- products/ASC.CRM/Server/Utils/PdfCreator.cs | 13 ++++--- products/ASC.CRM/Server/Utils/ReportHelper.cs | 7 ++-- .../Server/BusinessObjects/DataProvider.cs | 18 +++++----- .../Server/Controllers/CalendarController.cs | 36 ++++++++++--------- .../Server/Models/EventWrapper.cs | 8 +++-- .../Server/Models/PublicItemWrapper.cs | 10 ++++-- .../Server/iCalParser/iCalendar.cs | 13 ++++--- .../Server/iCalParser/iCalendarCache.cs | 11 ++++-- .../Server/iCalParser/iCalendarEmitter.cs | 8 +++-- .../GoogleDrive/GoogleDriveStorage.cs | 35 +++++++++--------- .../Thirdparty/OneDrive/OneDriveStorage.cs | 22 ++++++------ .../Core/HttpHandlers/FileHandler.ashx.cs | 11 +++--- .../DocumentServiceConnector.cs | 31 +++++++++------- .../Server/Helpers/FilesControllerHelper.cs | 7 ++-- .../ASC.Files/Service/Thumbnail/Builder.cs | 14 +++++--- .../Server/Controllers/PeopleController.cs | 9 +++-- .../Controllers/PortalController.cs | 7 ++-- .../Controllers/SettingsController.cs | 7 ++-- .../Core/FirstTimeTenantSettings.cs | 9 +++-- web/ASC.Web.Core/Files/DocumentService.cs | 13 ++++--- web/ASC.Web.Core/Helpers/ApiSystemHelper.cs | 15 ++++---- web/ASC.Web.Core/Recaptcha.cs | 6 ++-- web/ASC.Web.Core/Sms/SmsProvider.cs | 24 ++++++++----- web/ASC.Web.Core/Utility/UrlShortener.cs | 22 +++++++----- 42 files changed, 340 insertions(+), 189 deletions(-) diff --git a/common/ASC.Core.Common/ASC.Core.Common.csproj b/common/ASC.Core.Common/ASC.Core.Common.csproj index 03472ef3f8..e9884d38c0 100644 --- a/common/ASC.Core.Common/ASC.Core.Common.csproj +++ b/common/ASC.Core.Common/ASC.Core.Common.csproj @@ -56,6 +56,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/common/ASC.Core.Common/Billing/BillingClient.cs b/common/ASC.Core.Common/Billing/BillingClient.cs index 43deeb9523..406b7edbec 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -53,6 +53,8 @@ namespace ASC.Core.Billing private const int AvangatePaymentSystemId = 1; + static readonly HttpClient HttpClient = new HttpClient(); + public BillingClient(IConfiguration configuration) : this(false, configuration) @@ -226,8 +228,7 @@ namespace ASC.Core.Billing request.Headers.Add("Authorization", CreateAuthToken(_billingKey, _billingSecret)); } - using var httpClient = new HttpClient(); - httpClient.Timeout = TimeSpan.FromMilliseconds(60000); + HttpClient.Timeout = TimeSpan.FromMilliseconds(60000); var data = new Dictionary>(); if (!string.IsNullOrEmpty(portalId)) @@ -250,7 +251,7 @@ namespace ASC.Core.Billing request.Content = new StringContent(body, Encoding.UTF8, "application/json"); string result; - using (var response = httpClient.Send(request)) + using (var response = HttpClient.Send(request)) using (var stream = response.Content.ReadAsStream()) { if (stream == null) diff --git a/common/ASC.Core.Common/Billing/CouponManager.cs b/common/ASC.Core.Common/Billing/CouponManager.cs index eb1c9c4180..c5f433355e 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -47,7 +47,8 @@ namespace ASC.Core.Common.Billing [Singletone] public class CouponManager { - private IEnumerable Products { get; set; } + private IEnumerable Products { get; set; } + private IHttpClientFactory ClientFactory { get; } private IEnumerable Groups { get; set; } private readonly int Percent; private readonly int Schedule; @@ -56,12 +57,14 @@ namespace ASC.Core.Common.Billing private readonly Uri BaseAddress; private readonly string ApiVersion; private readonly SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1); - private readonly ILog Log; + private readonly ILog Log; + - public CouponManager(IOptionsMonitor option) + public CouponManager(IOptionsMonitor option, IHttpClientFactory clientFactory) { SemaphoreSlim = new SemaphoreSlim(1, 1); - Log = option.CurrentValue; + Log = option.CurrentValue; + ClientFactory = clientFactory; try { @@ -157,8 +160,12 @@ namespace ASC.Core.Common.Billing private HttpClient PrepaireClient() { - const string applicationJson = "application/json"; - var httpClient = new HttpClient { BaseAddress = BaseAddress, Timeout = TimeSpan.FromMinutes(3) }; + const string applicationJson = "application/json"; + + var httpClient = ClientFactory.CreateClient(); + httpClient.BaseAddress = BaseAddress; + httpClient.Timeout = TimeSpan.FromMinutes(3); + httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", applicationJson); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", applicationJson); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("X-Avangate-Authentication", CreateAuthHeader()); diff --git a/common/ASC.Core.Common/Configuration/AmiPublicDnsSyncService.cs b/common/ASC.Core.Common/Configuration/AmiPublicDnsSyncService.cs index 37f3747262..42909c8c1a 100644 --- a/common/ASC.Core.Common/Configuration/AmiPublicDnsSyncService.cs +++ b/common/ASC.Core.Common/Configuration/AmiPublicDnsSyncService.cs @@ -54,13 +54,13 @@ namespace ASC.Core.Configuration { using var scope = ServiceProvider.CreateScope(); var scopeClass = scope.ServiceProvider.GetService(); - var (tenantManager, coreBaseSettings) = scopeClass; + var (tenantManager, coreBaseSettings, clientFactory) = scopeClass; if (coreBaseSettings.Standalone) { var tenants = tenantManager.GetTenants(false).Where(t => MappedDomainNotSettedByUser(t.MappedDomain)); if (tenants.Any()) { - var dnsname = GetAmiPublicDnsName(); + var dnsname = GetAmiPublicDnsName(clientFactory); foreach (var tenant in tenants.Where(t => !string.IsNullOrEmpty(dnsname) && t.MappedDomain != dnsname)) { tenant.MappedDomain = dnsname; @@ -75,7 +75,7 @@ namespace ASC.Core.Configuration return string.IsNullOrEmpty(domain) || Regex.IsMatch(domain, "^ec2.+\\.compute\\.amazonaws\\.com$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); } - private static string GetAmiPublicDnsName() + private static string GetAmiPublicDnsName(IHttpClientFactory clientFactory) { try { @@ -83,7 +83,7 @@ namespace ASC.Core.Configuration request.RequestUri = new Uri("http://169.254.169.254/latest/meta-data/public-hostname"); request.Method = HttpMethod.Get; - using var httpClient = new HttpClient(); + var httpClient = clientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromMilliseconds(5000); using var responce = httpClient.Send(request); @@ -106,16 +106,18 @@ namespace ASC.Core.Configuration { private TenantManager TenantManager { get; } private CoreBaseSettings CoreBaseSettings { get; } + private IHttpClientFactory ClientFactory { get; } - public AmiPublicDnsSyncServiceScope(TenantManager tenantManager, CoreBaseSettings coreBaseSettings) + public AmiPublicDnsSyncServiceScope(TenantManager tenantManager, CoreBaseSettings coreBaseSettings, IHttpClientFactory clientFactory) { TenantManager = tenantManager; CoreBaseSettings = coreBaseSettings; + ClientFactory = clientFactory; } - public void Deconstruct(out TenantManager tenantManager, out CoreBaseSettings coreBaseSettings) + public void Deconstruct(out TenantManager tenantManager, out CoreBaseSettings coreBaseSettings, out IHttpClientFactory clientFactory) { - (tenantManager, coreBaseSettings) = (TenantManager, CoreBaseSettings); + (tenantManager, coreBaseSettings, clientFactory) = (TenantManager, CoreBaseSettings, ClientFactory); } } } diff --git a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs index 33b679222d..e6f1c09317 100644 --- a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs +++ b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs @@ -50,15 +50,17 @@ namespace ASC.Core private readonly string partnerKey; private TenantManager TenantManager { get; } - private IConfiguration Configuration { get; } + private IConfiguration Configuration { get; } + private IHttpClientFactory ClientFactory { get; } - public PaymentManager(TenantManager tenantManager, ITariffService tariffService, IConfiguration configuration) + public PaymentManager(TenantManager tenantManager, ITariffService tariffService, IConfiguration configuration, IHttpClientFactory clientFactory) { TenantManager = tenantManager; this.tariffService = tariffService; Configuration = configuration; partnerUrl = (Configuration["core:payment:partners"] ?? "https://partners.onlyoffice.com/api").TrimEnd('/'); - partnerKey = (Configuration["core:machinekey"] ?? "C5C1F4E85A3A43F5B3202C24D97351DF"); + partnerKey = (Configuration["core:machinekey"] ?? "C5C1F4E85A3A43F5B3202C24D97351DF"); + ClientFactory = clientFactory; } @@ -112,7 +114,7 @@ namespace ASC.Core request.Headers.Add("Authorization", GetPartnerAuthHeader(actionUrl)); request.RequestUri = new Uri(partnerUrl + actionUrl); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); diff --git a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs index d85e051936..9fcfc9d569 100644 --- a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs @@ -52,20 +52,23 @@ namespace ASC.Core.Notify.Signalr internal CoreSettings CoreSettings { get; } internal MachinePseudoKeys MachinePseudoKeys { get; } internal IConfiguration Configuration { get; } - internal IOptionsMonitor Options { get; } + internal IOptionsMonitor Options { get; } + internal IHttpClientFactory ClientFactory { get; } public ConfigureSignalrServiceClient( TenantManager tenantManager, CoreSettings coreSettings, MachinePseudoKeys machinePseudoKeys, IConfiguration configuration, - IOptionsMonitor options) + IOptionsMonitor options, + IHttpClientFactory clientFactory) { TenantManager = tenantManager; CoreSettings = coreSettings; MachinePseudoKeys = machinePseudoKeys; Configuration = configuration; - Options = options; + Options = options; + ClientFactory = clientFactory; } public void Configure(string name, SignalrServiceClient options) @@ -73,7 +76,8 @@ namespace ASC.Core.Notify.Signalr options.Log = Options.CurrentValue; options.hub = name.Trim('/'); options.TenantManager = TenantManager; - options.CoreSettings = CoreSettings; + options.CoreSettings = CoreSettings; + options.ClientFactory = ClientFactory; options.SKey = MachinePseudoKeys.GetMachineConstant(); options.Url = Configuration["web:hub:internal"]; options.EnableSignalr = !string.IsNullOrEmpty(options.Url); @@ -119,7 +123,8 @@ namespace ASC.Core.Notify.Signalr internal string hub; internal TenantManager TenantManager { get; set; } - internal CoreSettings CoreSettings { get; set; } + internal CoreSettings CoreSettings { get; set; } + internal IHttpClientFactory ClientFactory { get; set; } public SignalrServiceClient() { @@ -369,7 +374,8 @@ namespace ASC.Core.Notify.Signalr request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json"); - using (var httpClient = new HttpClient()) + var httpClient = ClientFactory.CreateClient(); + using (var response = httpClient.Send(request)) using (var stream = response.Content.ReadAsStream()) using (var streamReader = new StreamReader(stream)) diff --git a/common/ASC.Data.Storage/BaseStorage.cs b/common/ASC.Data.Storage/BaseStorage.cs index 15049ae5d8..d3a0ade525 100644 --- a/common/ASC.Data.Storage/BaseStorage.cs +++ b/common/ASC.Data.Storage/BaseStorage.cs @@ -29,6 +29,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net.Http; using System.Threading.Tasks; using System.Web; @@ -53,6 +54,7 @@ namespace ASC.Data.Storage protected EmailValidationKeyProvider EmailValidationKeyProvider { get; } protected IHttpContextAccessor HttpContextAccessor { get; } protected IOptionsMonitor Options { get; } + protected IHttpClientFactory ClientFactory { get; } public BaseStorage( TempStream tempStream, @@ -60,7 +62,8 @@ namespace ASC.Data.Storage PathUtils pathUtils, EmailValidationKeyProvider emailValidationKeyProvider, IHttpContextAccessor httpContextAccessor, - IOptionsMonitor options) + IOptionsMonitor options, + IHttpClientFactory clientFactory) { TempStream = tempStream; @@ -70,6 +73,7 @@ namespace ASC.Data.Storage Options = options; Log = options.CurrentValue; HttpContextAccessor = httpContextAccessor; + ClientFactory = clientFactory; } #region IDataStore Members diff --git a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs index 249551c695..8774b9170d 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net.Http; using System.Threading.Tasks; using ASC.Common; @@ -85,8 +86,9 @@ namespace ASC.Data.Storage.DiscStorage IHttpContextAccessor httpContextAccessor, IOptionsMonitor options, EncryptionSettingsHelper encryptionSettingsHelper, - EncryptionFactory encryptionFactory) - : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options) + EncryptionFactory encryptionFactory, + IHttpClientFactory clientFactory) + : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options, clientFactory) { EncryptionSettingsHelper = encryptionSettingsHelper; EncryptionFactory = encryptionFactory; diff --git a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs index e2ebfb5ff0..178e7f4320 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -78,7 +78,8 @@ namespace ASC.Data.Storage.GoogleCloud PathUtils pathUtils, EmailValidationKeyProvider emailValidationKeyProvider, IHttpContextAccessor httpContextAccessor, - IOptionsMonitor options) : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options) + IOptionsMonitor options, + IHttpClientFactory clientFactory) : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options, clientFactory) { } @@ -781,7 +782,7 @@ namespace ASC.Data.Storage.GoogleCloud try { - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); var status = response.StatusCode; diff --git a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs index 4c66b702aa..da7516dafd 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net.Http; using System.Threading.Tasks; using System.Web; @@ -72,8 +73,9 @@ namespace ASC.Data.Storage.RackspaceCloud PathUtils pathUtils, EmailValidationKeyProvider emailValidationKeyProvider, IHttpContextAccessor httpContextAccessor, - IOptionsMonitor options) - : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options) + IOptionsMonitor options, + IHttpClientFactory httpClient) + : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options, httpClient) { _logger = options.Get("ASC.Data.Storage.Rackspace.RackspaceCloudStorage"); TempPath = tempPath; diff --git a/common/ASC.Data.Storage/S3/S3Storage.cs b/common/ASC.Data.Storage/S3/S3Storage.cs index 7a688178c9..78565501aa 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -29,6 +29,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; @@ -84,8 +85,9 @@ namespace ASC.Data.Storage.S3 PathUtils pathUtils, EmailValidationKeyProvider emailValidationKeyProvider, IHttpContextAccessor httpContextAccessor, - IOptionsMonitor options) - : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options) + IOptionsMonitor options, + IHttpClientFactory clientFactory) + : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options, clientFactory) { } diff --git a/common/ASC.Data.Storage/WebPath.cs b/common/ASC.Data.Storage/WebPath.cs index 4c89ff377f..0e5f4e321f 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -158,6 +158,7 @@ namespace ASC.Data.Storage public IHostEnvironment HostEnvironment { get; } private CoreBaseSettings CoreBaseSettings { get; } private IOptionsMonitor Options { get; } + private IHttpClientFactory ClientFactory { get; } public WebPath( WebPathSettings webPathSettings, @@ -166,7 +167,8 @@ namespace ASC.Data.Storage StorageSettingsHelper storageSettingsHelper, IHostEnvironment hostEnvironment, CoreBaseSettings coreBaseSettings, - IOptionsMonitor options) + IOptionsMonitor options, + IHttpClientFactory clientFactory) { WebPathSettings = webPathSettings; ServiceProvider = serviceProvider; @@ -175,6 +177,7 @@ namespace ASC.Data.Storage HostEnvironment = hostEnvironment; CoreBaseSettings = coreBaseSettings; Options = options; + ClientFactory = clientFactory; } public WebPath( @@ -186,8 +189,9 @@ namespace ASC.Data.Storage IHttpContextAccessor httpContextAccessor, IHostEnvironment hostEnvironment, CoreBaseSettings coreBaseSettings, - IOptionsMonitor options) - : this(webPathSettings, serviceProvider, settingsManager, storageSettingsHelper, hostEnvironment, coreBaseSettings, options) + IOptionsMonitor options, + IHttpClientFactory clientFactory) + : this(webPathSettings, serviceProvider, settingsManager, storageSettingsHelper, hostEnvironment, coreBaseSettings, options, clientFactory) { HttpContextAccessor = httpContextAccessor; } @@ -241,7 +245,7 @@ namespace ASC.Data.Storage var request = new HttpRequestMessage(); request.RequestUri = new Uri(path); request.Method = HttpMethod.Head; - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); return response.StatusCode == HttpStatusCode.OK; diff --git a/common/ASC.FederatedLogin/Helpers/RequestHelper.cs b/common/ASC.FederatedLogin/Helpers/RequestHelper.cs index 395b2ceb00..8758502162 100644 --- a/common/ASC.FederatedLogin/Helpers/RequestHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/RequestHelper.cs @@ -34,6 +34,8 @@ namespace ASC.FederatedLogin.Helpers { public class RequestHelper { + private static HttpClient HttpClient { get; } = new HttpClient(); + public static string PerformRequest(string uri, string contentType = "", string method = "GET", string body = "", Dictionary headers = null, int timeout = 30000) { if (string.IsNullOrEmpty(uri)) throw new ArgumentNullException("uri"); @@ -42,8 +44,7 @@ namespace ASC.FederatedLogin.Helpers request.RequestUri = new Uri(uri); request.Method = new HttpMethod(method); - using var httpClient = new HttpClient(); - httpClient.Timeout = TimeSpan.FromMilliseconds(timeout); + HttpClient.Timeout = TimeSpan.FromMilliseconds(timeout); if (headers != null) { @@ -63,7 +64,7 @@ namespace ASC.FederatedLogin.Helpers } } - using var response = httpClient.Send(request); + using var response = HttpClient.Send(request); using var stream = response.Content.ReadAsStream(); if (stream == null) return null; using var readStream = new StreamReader(stream); diff --git a/common/services/ASC.ApiSystem/Classes/CommonMethods.cs b/common/services/ASC.ApiSystem/Classes/CommonMethods.cs index e5d5eea92a..df56cbd911 100644 --- a/common/services/ASC.ApiSystem/Classes/CommonMethods.cs +++ b/common/services/ASC.ApiSystem/Classes/CommonMethods.cs @@ -81,6 +81,8 @@ namespace ASC.ApiSystem.Controllers private TenantManager TenantManager { get; } + private IHttpClientFactory ClientFactory { get; } + public CommonMethods( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, @@ -92,7 +94,8 @@ namespace ASC.ApiSystem.Controllers IMemoryCache memoryCache, IOptionsSnapshot hostedSolutionOptions, CoreBaseSettings coreBaseSettings, - TenantManager tenantManager) + TenantManager tenantManager, + IHttpClientFactory clientFactory) { HttpContextAccessor = httpContextAccessor; @@ -111,8 +114,13 @@ namespace ASC.ApiSystem.Controllers CommonConstants = commonConstants; MemoryCache = memoryCache; + CoreBaseSettings = coreBaseSettings; + TenantManager = tenantManager; + + ClientFactory = clientFactory; + HostedSolution = hostedSolutionOptions.Get(CommonConstants.BaseDbConnKeyString); } @@ -176,7 +184,7 @@ namespace ASC.ApiSystem.Controllers try { - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var stream = response.Content.ReadAsStream(); using var reader = new StreamReader(stream, Encoding.UTF8); @@ -310,7 +318,7 @@ namespace ASC.ApiSystem.Controllers request.Method = HttpMethod.Post; request.Content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded"); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var httpClientResponse = httpClient.Send(request); using var stream = httpClientResponse.Content.ReadAsStream(); using var reader = new StreamReader(stream); diff --git a/common/services/ASC.ApiSystem/Controllers/CalDavController.cs b/common/services/ASC.ApiSystem/Controllers/CalDavController.cs index 0bd087230b..a4fe0e4849 100644 --- a/common/services/ASC.ApiSystem/Controllers/CalDavController.cs +++ b/common/services/ASC.ApiSystem/Controllers/CalDavController.cs @@ -60,6 +60,7 @@ namespace ASC.ApiSystem.Controllers private CommonConstants CommonConstants { get; } public InstanceCrypto InstanceCrypto { get; } private ILog Log { get; } + private IHttpClientFactory ClientFactory { get; } public CalDavController( CommonMethods commonMethods, @@ -344,7 +345,7 @@ namespace ASC.ApiSystem.Controllers request.Method = new HttpMethod(httpMethod); request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); if (data != null) { diff --git a/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs b/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs index e0eb541fe1..1e5f55a955 100644 --- a/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs +++ b/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs @@ -84,7 +84,8 @@ namespace ASC.Web.CRM.Classes public readonly WebImageSupplier _webImageSupplier; private readonly DistributedTaskQueue _resizeQueue; private readonly ICacheNotify _cacheNotify; - private readonly ICache _cache; + private readonly ICache _cache; + private readonly IHttpClientFactory _clientFactory; private const string PhotosBaseDirName = "photos"; private const string PhotosDefaultTmpDirName = "temp"; @@ -103,14 +104,16 @@ namespace ASC.Web.CRM.Classes IOptionsMonitor logger, ICache cache, ICacheNotify cacheNotify, - DistributedTaskQueueOptionsManager optionsQueue) + DistributedTaskQueueOptionsManager optionsQueue, + IHttpClientFactory clientFactory) { _global = global; _webImageSupplier = webImageSupplier; _cacheNotify = cacheNotify; _cache = cache; _resizeQueue = optionsQueue.Get(); - _logger = logger.Get("ASC.CRM"); + _logger = logger.Get("ASC.CRM"); + _clientFactory = clientFactory; _cacheNotify.Subscribe((x) => { @@ -541,7 +544,7 @@ namespace ASC.Web.CRM.Classes var request = new HttpRequestMessage(); request.RequestUri = new Uri(imageUrl); - using var httpClient = new HttpClient(); + var httpClient = _clientFactory.CreateClient(); using var response = httpClient.Send(request); using (var inputStream = response.Content.ReadAsStream()) { @@ -577,7 +580,7 @@ namespace ASC.Web.CRM.Classes var request = new HttpRequestMessage(); request.RequestUri = new Uri(imageUrl); - using var httpClient = new HttpClient(); + var httpClient = _clientFactory.CreateClient(); using var response = httpClient.Send(request); using (var inputStream = response.Content.ReadAsStream()) { diff --git a/products/ASC.CRM/Server/Startup.cs b/products/ASC.CRM/Server/Startup.cs index e38fad6353..4867f36f21 100644 --- a/products/ASC.CRM/Server/Startup.cs +++ b/products/ASC.CRM/Server/Startup.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Net.Http; using System.Text; using System.Text.Json.Serialization; @@ -33,6 +34,16 @@ namespace ASC.CRM base.ConfigureServices(services); + services.AddHttpClient("DownloadCurrencyPage").ConfigurePrimaryHttpMessageHandler(() => + { + return new HttpClientHandler() + { + AllowAutoRedirect = true, + MaxAutomaticRedirections = 2, + UseDefaultCredentials = true + }; + }); + DIHelper.TryAdd(); DIHelper.TryAdd(); DIHelper.TryAdd(); diff --git a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs index e6fa13f388..a75ffe5485 100644 --- a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs +++ b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs @@ -46,7 +46,8 @@ namespace ASC.Web.CRM.Classes [Scope] public class CurrencyProvider { - private readonly ILog _log; + private readonly ILog _log; + private readonly IHttpClientFactory _clientFactory; private readonly object _syncRoot = new object(); private readonly Dictionary _currencies; private Dictionary _exchangeRates; @@ -56,7 +57,8 @@ namespace ASC.Web.CRM.Classes public CurrencyProvider(IOptionsMonitor logger, IConfiguration configuration, SettingsManager settingsManager, - DaoFactory daoFactory) + DaoFactory daoFactory, + IHttpClientFactory clientFactory) { _log = logger.Get("ASC"); Configuration = configuration; @@ -73,8 +75,8 @@ namespace ASC.Web.CRM.Classes }; } - _currencies = currencies.ToDictionary(c => c.Abbreviation); - + _currencies = currencies.ToDictionary(c => c.Abbreviation); + _clientFactory = clientFactory; } public IConfiguration Configuration { get; } @@ -339,7 +341,8 @@ namespace ASC.Web.CRM.Classes handler.MaxAutomaticRedirections = 2; handler.UseDefaultCredentials = true; - var httpClient = new HttpClient(handler); + var httpClient = _clientFactory.CreateClient("DownloadCurrencyPage"); + _clientFactory.CreateClient(); using var response = httpClient.Send(request); using (var responseStream = new StreamReader(response.Content.ReadAsStream())) { diff --git a/products/ASC.CRM/Server/Utils/PdfCreator.cs b/products/ASC.CRM/Server/Utils/PdfCreator.cs index d45abb0c69..cdec421bb0 100644 --- a/products/ASC.CRM/Server/Utils/PdfCreator.cs +++ b/products/ASC.CRM/Server/Utils/PdfCreator.cs @@ -57,7 +57,8 @@ namespace ASC.Web.CRM.Classes private DocumentServiceConnector _documentServiceConnector; private OrganisationLogoManager _organisationLogoManager; private Files.Classes.PathProvider _filesPathProvider; - private ILog _logger; + private ILog _logger; + private IHttpClientFactory _clientFactory; public PdfCreator(IOptionsMonitor logger, @@ -66,7 +67,8 @@ namespace ASC.Web.CRM.Classes IServiceProvider serviceProvider, OrganisationLogoManager organisationLogoManager, DaoFactory daoFactory, - InvoiceFormattedData invoiceFormattedData) + InvoiceFormattedData invoiceFormattedData, + IHttpClientFactory clientFactory) { _filesPathProvider = filesPathProvider; @@ -76,7 +78,8 @@ namespace ASC.Web.CRM.Classes _serviceProvider = serviceProvider; _organisationLogoManager = organisationLogoManager; _daoFactory = daoFactory; - _invoiceFormattedData = invoiceFormattedData; + _invoiceFormattedData = invoiceFormattedData; + _clientFactory = clientFactory; } @@ -130,7 +133,7 @@ namespace ASC.Web.CRM.Classes var request = new HttpRequestMessage(); request.RequestUri = new Uri(urlToFile); - using (var httpClient = new HttpClient()) + var httpClient = _clientFactory.CreateClient(); using (var response = httpClient.Send(request)) using (var stream = response.Content.ReadAsStream()) { @@ -249,7 +252,7 @@ namespace ASC.Web.CRM.Classes var request = new HttpRequestMessage(); request.RequestUri = new Uri(url); - using var httpClient = new HttpClient(); + var httpClient = _clientFactory.CreateClient(); using (var stream = httpClient.Send(request).Content.ReadAsStream()) { diff --git a/products/ASC.CRM/Server/Utils/ReportHelper.cs b/products/ASC.CRM/Server/Utils/ReportHelper.cs index 198f1f7e0c..f50bda6094 100644 --- a/products/ASC.CRM/Server/Utils/ReportHelper.cs +++ b/products/ASC.CRM/Server/Utils/ReportHelper.cs @@ -58,6 +58,7 @@ namespace ASC.Web.CRM.Classes private SettingsManager _settingsManager; private TenantUtil _tenantUtil; private TenantManager _tenantManager; + private IHttpClientFactory _clientFactory; public ReportHelper(TenantManager tenantManager, TenantUtil tenantUtil, @@ -68,7 +69,8 @@ namespace ASC.Web.CRM.Classes SecurityContext securityContext, IServiceProvider serviceProvider, IHttpContextAccessor httpContextAccessor, - CurrencyProvider currencyProvider + CurrencyProvider currencyProvider, + IHttpClientFactory clientFactory ) { _tenantManager = tenantManager; @@ -81,6 +83,7 @@ namespace ASC.Web.CRM.Classes _securityContext = securityContext; _httpContext = httpContextAccessor; _currencyProvider = currencyProvider; + _clientFactory = clientFactory; } private string GetFileName(ReportType reportType) @@ -224,7 +227,7 @@ namespace ASC.Web.CRM.Classes private async Task SaveReportFile(ReportState state, string url) { - using var httpClient = new HttpClient(); + var httpClient = _clientFactory.CreateClient(); var responseData = await httpClient.GetByteArrayAsync(url); using (var stream = new System.IO.MemoryStream(responseData)) diff --git a/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs b/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs index 8be1a4cc6d..dde3267985 100644 --- a/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs +++ b/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs @@ -81,6 +81,7 @@ namespace ASC.Calendar.BusinessObjects protected DDayICalParser DDayICalParser { get; } public ILog Log { get; } public InstanceCrypto InstanceCrypto { get; } + public IHttpClientFactory ClientFactory { get; } public DataProvider(DbContextManager calendarDbContext, AuthManager authentication, @@ -93,7 +94,8 @@ namespace ASC.Calendar.BusinessObjects UserManager userManager, DDayICalParser dDayICalParser, IOptionsMonitor option, - InstanceCrypto instanceCrypto) + InstanceCrypto instanceCrypto, + IHttpClientFactory clientFactory) { Authentication = authentication; CalendarDb = calendarDbContext.Get("calendar"); @@ -107,7 +109,7 @@ namespace ASC.Calendar.BusinessObjects DDayICalParser = dDayICalParser; Log = option.Get("ASC.CalendarDataProvider"); InstanceCrypto = instanceCrypto; - + ClientFactory = clientFactory; } public List GetUserViewSettings(Guid userId, List calendarIds) @@ -335,7 +337,7 @@ namespace ASC.Calendar.BusinessObjects string.Equals(c.Id, r.calId.ToString(), StringComparison.InvariantCultureIgnoreCase)); if (calendar == null) { - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); calendar = new Calendar(AuthContext, TimeZoneConverter, icalendar, this) { Id = r.calId.ToString(), @@ -808,7 +810,7 @@ namespace ASC.Calendar.BusinessObjects request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(authorization))); request.Headers.Add("Content-Type", "text/xml; charset=utf-8"); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); httpClient.Send(request); } catch (Exception ex) @@ -944,7 +946,7 @@ namespace ASC.Calendar.BusinessObjects Uid = s.Uid }) .ToList(); - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); todoList = data.ConvertAll(r => new Todo(AuthContext, TimeZoneConverter, icalendar, this) { Id = r.Id, @@ -976,7 +978,7 @@ namespace ASC.Calendar.BusinessObjects Uid = s.Uid }) .ToList(); - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); todoList = data.ConvertAll(r => new Todo(AuthContext, TimeZoneConverter, icalendar, this) { Id = r.Id, @@ -1128,7 +1130,7 @@ namespace ASC.Calendar.BusinessObjects e => String.Equals(e.Id, r.Id, StringComparison.InvariantCultureIgnoreCase)); if (ev == null) { - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); ev = new Event(AuthContext, TimeZoneConverter, icalendar, this) { Id = r.Id, @@ -1194,7 +1196,7 @@ namespace ASC.Calendar.BusinessObjects e => String.Equals(e.Id, r.Id, StringComparison.InvariantCultureIgnoreCase)); if (ev == null) { - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); ev = new Event(AuthContext, TimeZoneConverter, icalendar, this) { Id = r.Id, diff --git a/products/ASC.Calendar/Server/Controllers/CalendarController.cs b/products/ASC.Calendar/Server/Controllers/CalendarController.cs index 547200dd53..478b020906 100644 --- a/products/ASC.Calendar/Server/Controllers/CalendarController.cs +++ b/products/ASC.Calendar/Server/Controllers/CalendarController.cs @@ -111,7 +111,8 @@ namespace ASC.Calendar.Controllers private EmailValidationKeyProvider EmailValidationKeyProvider { get; } private SetupInfo SetupInfo { get; } private InstanceCrypto InstanceCrypto { get; } - private CalendarManager CalendarManager { get; } + private CalendarManager CalendarManager { get; } + private IHttpClientFactory ClientFactory { get; } public CalendarController( @@ -143,7 +144,8 @@ namespace ASC.Calendar.Controllers SetupInfo setupInfo, InstanceCrypto instanceCrypto, CalendarManager calendarManager, - ProductEntryPoint productEntryPoint) + ProductEntryPoint productEntryPoint, + IHttpClientFactory clientFactory) { AuthContext = authContext; Authentication = authentication; @@ -172,7 +174,8 @@ namespace ASC.Calendar.Controllers SetupInfo = setupInfo; InstanceCrypto = instanceCrypto; CalendarManager = calendarManager; - ProductEntryPoint = productEntryPoint; + ProductEntryPoint = productEntryPoint; + ClientFactory = clientFactory; CalendarManager.RegistryCalendar(new SharedEventsCalendar(AuthContext, TimeZoneConverter, TenantManager, DataProvider)); var birthdayReminderCalendar = new BirthdayReminderCalendar(AuthContext, TimeZoneConverter, UserManager, DisplayUserSettingsHelper); @@ -509,7 +512,7 @@ namespace ASC.Calendar.Controllers var todoCalendars = DataProvider.LoadTodoCalendarsForUser(SecurityContext.CurrentAccount.ID); var userTimeZone = TenantManager.GetCurrentTenant().TimeZone; - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); var newCalendar = new BusinessObjects.Calendar(AuthContext, TimeZoneConverter, icalendar, DataProvider); var todoCal = CalendarWrapperHelper.Get(newCalendar); @@ -1035,7 +1038,7 @@ namespace ASC.Calendar.Controllers try { - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using (var reader = new StreamReader(response.Content.ReadAsStream())) { @@ -1096,7 +1099,7 @@ namespace ASC.Calendar.Controllers request.Content = new StringContent(data, Encoding.UTF8, "text/xml"); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using (var reader = new StreamReader(response.Content.ReadAsStream())) @@ -1267,7 +1270,7 @@ namespace ASC.Calendar.Controllers { var request = new HttpRequestMessage(); request.RequestUri = new Uri(calendar.ICalUrl); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using (var stream = response.Content.ReadAsStream()) @@ -1333,7 +1336,7 @@ namespace ASC.Calendar.Controllers var request = new HttpRequestMessage(); request.RequestUri = new Uri(iCalUrl); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using (var stream = response.Content.ReadAsStream()) { @@ -1765,7 +1768,7 @@ namespace ASC.Calendar.Controllers var authorization = isShared ? DataProvider.GetSystemAuthorization() : DataProvider.GetUserAuthorization(email); request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(authorization))); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); httpClient.Send(request); } catch (HttpRequestException ex) @@ -2682,7 +2685,7 @@ namespace ASC.Calendar.Controllers var todoCalendars = DataProvider.LoadTodoCalendarsForUser(AuthContext.CurrentAccount.ID); var userTimeZone = TenantManager.GetCurrentTenant().TimeZone; - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); var newCalendar = new BusinessObjects.Calendar(AuthContext, TimeZoneConverter, icalendar, DataProvider); var todoCal = CalendarWrapperHelper.Get(newCalendar); @@ -3158,7 +3161,7 @@ namespace ASC.Calendar.Controllers var textColor = ÑalendarUrl.TextColor; var backgroundColor = ÑalendarUrl.BackgroundColor; - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); var cal = icalendar.GetFromUrl(iCalUrl); if (cal.isEmptyName) cal.Name = iCalUrl; @@ -4068,7 +4071,7 @@ namespace ASC.Calendar.Controllers request.Content = new StringContent(ics, Encoding.UTF8, "text/calendar"); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); httpClient.Send(request); } catch (HttpRequestException ex) @@ -4194,7 +4197,8 @@ namespace ASC.Calendar.Controllers string ics = ""; - using (var httpClient = new HttpClient()) + var httpClient = ClientFactory.CreateClient(); + using (var response = httpClient.Send(request)) using (var reader = new StreamReader(response.Content.ReadAsStream())) { @@ -4549,7 +4553,7 @@ namespace ASC.Calendar.Controllers request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(authorization))); request.Content = new StringContent(data, Encoding.UTF8, "text/calendar"); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); var response = httpClient.Send(request); using (var reader = new StreamReader(response.Content.ReadAsStream())) @@ -4685,7 +4689,7 @@ namespace ASC.Calendar.Controllers request.Method = HttpMethod.Delete; request.Headers.Add("Authorization", "Basic " + encoded); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); httpClient.Send(request); } catch (HttpRequestException ex) @@ -4750,7 +4754,7 @@ namespace ASC.Calendar.Controllers request.Method = HttpMethod.Delete; request.Headers.Add("Authorization", "Basic " + encoded); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); httpClient.Send(request); } catch (HttpRequestException ex) diff --git a/products/ASC.Calendar/Server/Models/EventWrapper.cs b/products/ASC.Calendar/Server/Models/EventWrapper.cs index 96a942a087..2be4acbead 100644 --- a/products/ASC.Calendar/Server/Models/EventWrapper.cs +++ b/products/ASC.Calendar/Server/Models/EventWrapper.cs @@ -38,6 +38,7 @@ using ASC.Common.Utils; using ASC.Common; using ASC.Calendar.iCalParser; using ASC.Calendar.BusinessObjects; +using System.Net.Http; namespace ASC.Calendar.Models { @@ -140,6 +141,7 @@ namespace ASC.Calendar.Models private AuthContext AuthContext { get; } private TimeZoneConverter TimeZoneConverter { get; } private DataProvider DataProvider { get; } + private IHttpClientFactory ClientFactory { get; } public EventWrapperHelper( UserManager userManager, @@ -150,7 +152,8 @@ namespace ASC.Calendar.Models PublicItemCollectionHelper publicItemCollectionHelper, AuthContext context, TimeZoneConverter timeZoneConverter, - DataProvider dataProvider) + DataProvider dataProvider, + IHttpClientFactory clientFactory) { Authentication = authentication; TenantManager = tenantManager; @@ -161,6 +164,7 @@ namespace ASC.Calendar.Models AuthContext = context; TimeZoneConverter = timeZoneConverter; DataProvider = dataProvider; + ClientFactory = clientFactory; } public EventWrapper Get(IEvent baseEvent, Guid userId, TimeZoneInfo timeZone, DateTime utcStartDate, DateTime utcEndDate, DateTime utcUpdateDate) { @@ -184,7 +188,7 @@ namespace ASC.Calendar.Models eventWraper.Description = _baseEvent.Description; eventWraper.AllDayLong = _baseEvent.AllDayLong; ; - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); //--- var startD = _utcStartDate != DateTime.MinValue ? _utcStartDate : _baseEvent.UtcStartDate; startD = new DateTime(startD.Ticks, DateTimeKind.Utc); diff --git a/products/ASC.Calendar/Server/Models/PublicItemWrapper.cs b/products/ASC.Calendar/Server/Models/PublicItemWrapper.cs index 7da6fef1a6..c0744159c1 100644 --- a/products/ASC.Calendar/Server/Models/PublicItemWrapper.cs +++ b/products/ASC.Calendar/Server/Models/PublicItemWrapper.cs @@ -35,6 +35,7 @@ using ASC.Common; using ASC.Calendar.iCalParser; using ASC.Calendar.BusinessObjects; using System.Text.Json.Serialization; +using System.Net.Http; namespace ASC.Calendar.Models { @@ -84,6 +85,7 @@ namespace ASC.Calendar.Models private TenantManager TenantManager { get; } private TimeZoneConverter TimeZoneConverter { get; } private PermissionContext PermissionContext { get; } + private IHttpClientFactory ClientFactory { get; } public DisplayUserSettingsHelper DisplayUserSettingsHelper { get; } public DataProvider DataProvider { get; } @@ -96,7 +98,8 @@ namespace ASC.Calendar.Models TimeZoneConverter timeZoneConverter, PermissionContext permissionContext, DisplayUserSettingsHelper displayUserSettingsHelper, - DataProvider dataProvider) + DataProvider dataProvider, + IHttpClientFactory clientFactory) { UserManager = userManager; Authentication = authentication; @@ -106,6 +109,7 @@ namespace ASC.Calendar.Models PermissionContext = permissionContext; DisplayUserSettingsHelper = displayUserSettingsHelper; DataProvider = dataProvider; + ClientFactory = clientFactory; } public PublicItemWrapper Get(ASC.Web.Core.Calendars.SharingOptions.PublicItem publicItem, string calendartId, Guid owner) @@ -164,7 +168,7 @@ namespace ASC.Calendar.Models int calId; if (_isCalendar && int.TryParse(_calendarId, out calId)) { - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); var obj = new BusinessObjects.Calendar(AuthContext, TimeZoneConverter, icalendar, DataProvider) { Id = _calendarId }; if (PermissionContext.PermissionResolver.Check(subject, obj, null, CalendarAccessRights.FullAccessAction)) result.SharingOption = AccessOption.FullAccessOption; @@ -173,7 +177,7 @@ namespace ASC.Calendar.Models } else if (!_isCalendar) { - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); var obj = new BusinessObjects.Event(AuthContext, TimeZoneConverter, icalendar, DataProvider) { Id = _eventId, CalendarId = _calendarId }; if (PermissionContext.PermissionResolver.Check(subject, obj, null, CalendarAccessRights.FullAccessAction)) result.SharingOption = AccessOption.FullAccessOption; diff --git a/products/ASC.Calendar/Server/iCalParser/iCalendar.cs b/products/ASC.Calendar/Server/iCalParser/iCalendar.cs index d15296ce43..c2e429b103 100644 --- a/products/ASC.Calendar/Server/iCalParser/iCalendar.cs +++ b/products/ASC.Calendar/Server/iCalParser/iCalendar.cs @@ -41,10 +41,11 @@ namespace ASC.Calendar.iCalParser public class iCalendar : BaseCalendar { private TenantManager TenantManager { get; } + private IHttpClientFactory ClientFactory { get; } public iCalendar GetFromStream(TextReader reader) { - var emitter = new iCalendarEmitter(AuthContext, TimeZoneConverter, TenantManager); + var emitter = new iCalendarEmitter(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); var parser = new Parser(reader, emitter); parser.Parse(); return emitter.GetCalendar(); @@ -57,7 +58,7 @@ namespace ASC.Calendar.iCalParser public iCalendar GetFromUrl(string url, string calendarId) { - var cache = new iCalendarCache(AuthContext, TimeZoneConverter, TenantManager); + var cache = new iCalendarCache(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); iCalendar calendar = null; if (calendarId != null) calendar = cache.GetCalendarFromCache(calendarId); @@ -72,7 +73,7 @@ namespace ASC.Calendar.iCalParser var request = new HttpRequestMessage(); request.RequestUri = new Uri(url); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using (var response = httpClient.Send(request)) using (var stream = response.Content.ReadAsStream()) { @@ -107,10 +108,12 @@ namespace ASC.Calendar.iCalParser public iCalendar( AuthContext authContext, TimeZoneConverter timeZoneConverter, - TenantManager tenantManager) + TenantManager tenantManager, + IHttpClientFactory clientFactory) : base(authContext, timeZoneConverter) { - TenantManager = tenantManager; + TenantManager = tenantManager; + ClientFactory = clientFactory; this.Context.CanChangeAlertType = false; this.Context.CanChangeTimeZone = false; this.Context.GetGroupMethod = delegate () { return Resources.CalendarApiResource.iCalCalendarsGroup; }; diff --git a/products/ASC.Calendar/Server/iCalParser/iCalendarCache.cs b/products/ASC.Calendar/Server/iCalParser/iCalendarCache.cs index 94f8b9bbc3..9e1bbd389c 100644 --- a/products/ASC.Calendar/Server/iCalParser/iCalendarCache.cs +++ b/products/ASC.Calendar/Server/iCalParser/iCalendarCache.cs @@ -28,6 +28,7 @@ using System; using System.IO; using ASC.Core; using ASC.Common.Utils; +using System.Net.Http; namespace ASC.Calendar.iCalParser { @@ -58,21 +59,25 @@ namespace ASC.Calendar.iCalParser public AuthContext AuthContext { get; } public TimeZoneConverter TimeZoneConverter { get; } public TenantManager TenantManager { get; } + public IHttpClientFactory ClientFactory { get; } public iCalendarCache( AuthContext authContext, TimeZoneConverter timeZoneConverter, - TenantManager tenantManager - ) : this(authContext, timeZoneConverter, tenantManager, iCalendarCacheParams.Default){} + TenantManager tenantManager, + IHttpClientFactory clientFactory + ) : this(authContext, timeZoneConverter, tenantManager, clientFactory, iCalendarCacheParams.Default){} public iCalendarCache( AuthContext authContext, TimeZoneConverter timeZoneConverter, TenantManager tenantManager, + IHttpClientFactory clientFactory, iCalendarCacheParams cacheParams) { AuthContext = authContext; TimeZoneConverter = timeZoneConverter; TenantManager = tenantManager; + ClientFactory = clientFactory; _cacheParams = cacheParams; } @@ -120,7 +125,7 @@ namespace ASC.Calendar.iCalParser using (var tr = new StreamReader(File.OpenRead(filePath))) { - var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); return icalendar.GetFromStream(tr); } } diff --git a/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs b/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs index db7762e05e..a22ab26dec 100644 --- a/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs +++ b/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs @@ -30,6 +30,7 @@ using System.Linq; using ASC.Common.Utils; using ASC.Web.Core.Calendars; using ASC.Core; +using System.Net.Http; namespace ASC.Calendar.iCalParser { @@ -46,14 +47,17 @@ namespace ASC.Calendar.iCalParser private AuthContext AuthContext { get; } private TimeZoneConverter TimeZoneConverter { get; } private TenantManager TenantManager { get; } + private IHttpClientFactory ClientFactory { get; } public iCalendarEmitter( AuthContext authContext, TimeZoneConverter timeZoneConverter, - TenantManager tenantManager) + TenantManager tenantManager, + IHttpClientFactory clientFactory) { AuthContext = authContext; TimeZoneConverter = timeZoneConverter; TenantManager = tenantManager; + ClientFactory = clientFactory; } public iCalendar GetCalendar() { @@ -96,7 +100,7 @@ namespace ASC.Calendar.iCalParser switch (t.TokenVal) { case TokenValue.Tvcalendar: - _curCalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager); + _curCalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); break; case TokenValue.Tvevent: diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs index 42968cfb72..f16d6dabcc 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs @@ -62,19 +62,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive { [Scope] internal class GoogleDriveStorage : IDisposable - { - public GoogleDriveStorage( - ConsumerFactory consumerFactory, - FileUtility fileUtility, - IOptionsMonitor monitor, - TempStream tempStream) - { - ConsumerFactory = consumerFactory; - FileUtility = fileUtility; - Log = monitor.Get("ASC.Files"); - TempStream = tempStream; - } - + { private OAuth20Token _token; private string AccessToken @@ -94,9 +82,24 @@ namespace ASC.Files.Thirdparty.GoogleDrive private FileUtility FileUtility { get; } public ILog Log { get; } private TempStream TempStream { get; } + private IHttpClientFactory ClientFactory { get; } public const long MaxChunkedUploadFileSize = 2L * 1024L * 1024L * 1024L; + public GoogleDriveStorage( + ConsumerFactory consumerFactory, + FileUtility fileUtility, + IOptionsMonitor monitor, + TempStream tempStream, + IHttpClientFactory clientFactory) + { + ConsumerFactory = consumerFactory; + FileUtility = fileUtility; + Log = monitor.Get("ASC.Files"); + TempStream = tempStream; + ClientFactory = clientFactory; + } + public void Open(OAuth20Token token) { if (IsOpened) @@ -222,7 +225,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive request.Method = HttpMethod.Get; request.Headers.Add("Authorization", "Bearer " + AccessToken); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); if (offset == 0 && file.Size.HasValue && file.Size > 0) @@ -374,7 +377,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive request.Headers.Add("Authorization", "Bearer " + AccessToken); request.Content = new StringContent(body, Encoding.UTF8, "application/json"); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); var uploadSession = new ResumableUploadSession(driveFile.Id, folderId, contentLength); @@ -402,7 +405,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive googleDriveSession.BytesTransfered + chunkLength - 1, googleDriveSession.BytesToTransfer)); request.Content = new StreamContent(stream); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); HttpResponseMessage response; try diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs index 4eea2afd8d..4ac0611721 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs @@ -49,11 +49,6 @@ namespace ASC.Files.Thirdparty.OneDrive [Scope] internal class OneDriveStorage { - public OneDriveStorage(ConsumerFactory consumerFactory) - { - ConsumerFactory = consumerFactory; - } - private OAuth20Token _token; private string AccessToken @@ -78,9 +73,16 @@ namespace ASC.Files.Thirdparty.OneDrive } public bool IsOpened { get; private set; } - private ConsumerFactory ConsumerFactory { get; } + private ConsumerFactory ConsumerFactory { get; } + private IHttpClientFactory ClientFactory { get; } - public long MaxChunkedUploadFileSize = 10L * 1024L * 1024L * 1024L; + public long MaxChunkedUploadFileSize = 10L * 1024L * 1024L * 1024L; + + public OneDriveStorage(ConsumerFactory consumerFactory, IHttpClientFactory clientFactory) + { + ConsumerFactory = consumerFactory; + ClientFactory = clientFactory; + } public void Open(OAuth20Token token) { @@ -266,7 +268,7 @@ namespace ASC.Files.Thirdparty.OneDrive var uploadSession = new ResumableUploadSession(onedriveFile.Id, folderId, contentLength); - using (var httpClient = new HttpClient()) + var httpClient = ClientFactory.CreateClient(); using (var response = httpClient.Send(request)) using (var responseStream = response.Content.ReadAsStream()) { @@ -302,7 +304,7 @@ namespace ASC.Files.Thirdparty.OneDrive oneDriveSession.BytesToTransfer)); request.Content = new StreamContent(stream); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); if (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK) @@ -329,7 +331,7 @@ namespace ASC.Files.Thirdparty.OneDrive request.RequestUri = new Uri(oneDriveSession.Location); request.Method = HttpMethod.Delete; - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); } } diff --git a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs index 4ed9f1b5f8..75ba36c129 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -120,7 +120,8 @@ namespace ASC.Web.Files private IServiceProvider ServiceProvider { get; } public TempStream TempStream { get; } private UserManager UserManager { get; } - private ILog Logger { get; } + private ILog Logger { get; } + private IHttpClientFactory ClientFactory { get; } public FileHandlerService( FilesLinkUtility filesLinkUtility, @@ -147,7 +148,8 @@ namespace ASC.Web.Files FileConverter fileConverter, FFmpegService fFmpegService, IServiceProvider serviceProvider, - TempStream tempStream) + TempStream tempStream, + IHttpClientFactory clientFactory) { FilesLinkUtility = filesLinkUtility; TenantExtra = tenantExtra; @@ -172,7 +174,8 @@ namespace ASC.Web.Files ServiceProvider = serviceProvider; TempStream = tempStream; UserManager = userManager; - Logger = optionsMonitor.CurrentValue; + Logger = optionsMonitor.CurrentValue; + ClientFactory = clientFactory; } public Task Invoke(HttpContext context) @@ -1208,7 +1211,7 @@ namespace ASC.Web.Files request.RequestUri = new Uri(fileUri); var fileDao = DaoFactory.GetFileDao(); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var fileStream = httpClient.Send(request).Content.ReadAsStream(); diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs index 6f09cae6b8..157805d761 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs @@ -55,7 +55,8 @@ namespace ASC.Web.Files.Services.DocumentService { public ILog Logger { get; } private FilesLinkUtility FilesLinkUtility { get; } - private FileUtility FileUtility { get; } + private FileUtility FileUtility { get; } + private IHttpClientFactory ClientFactory { get; } private GlobalStore GlobalStore { get; } private BaseCommonLinkUtility BaseCommonLinkUtility { get; } private TenantManager TenantManager { get; } @@ -72,7 +73,8 @@ namespace ASC.Web.Files.Services.DocumentService BaseCommonLinkUtility baseCommonLinkUtility, TenantManager tenantManager, TenantExtra tenantExtra, - CoreSettings coreSettings) + CoreSettings coreSettings, + IHttpClientFactory clientFactory) { Logger = optionsMonitor.CurrentValue; FilesLinkUtility = filesLinkUtility; @@ -82,7 +84,8 @@ namespace ASC.Web.Files.Services.DocumentService TenantManager = tenantManager; TenantExtra = tenantExtra; CoreSettings = coreSettings; - PathProvider = pathProvider; + PathProvider = pathProvider; + ClientFactory = clientFactory; } public static string GenerateRevisionId(string expectedKey) @@ -114,7 +117,8 @@ namespace ASC.Web.Files.Services.DocumentService thumbnail, spreadsheetLayout, isAsync, - FileUtility.SignatureSecret, + FileUtility.SignatureSecret, + ClientFactory, out convertedDocumentUri); } catch (Exception ex) @@ -141,7 +145,8 @@ namespace ASC.Web.Files.Services.DocumentService callbackUrl, users, meta, - FileUtility.SignatureSecret, + FileUtility.SignatureSecret, + ClientFactory, out var version); if (result == Web.Core.Files.DocumentService.CommandResultTypes.NoError) @@ -187,7 +192,8 @@ namespace ASC.Web.Files.Services.DocumentService GenerateRevisionId(requestKey), scriptUrl, isAsync, - FileUtility.SignatureSecret, + FileUtility.SignatureSecret, + ClientFactory, out urls); } catch (Exception ex) @@ -209,7 +215,8 @@ namespace ASC.Web.Files.Services.DocumentService null, null, null, - FileUtility.SignatureSecret, + FileUtility.SignatureSecret, + ClientFactory, out var version); if (result == Web.Core.Files.DocumentService.CommandResultTypes.NoError) @@ -232,7 +239,7 @@ namespace ASC.Web.Files.Services.DocumentService { try { - if (!Web.Core.Files.DocumentService.HealthcheckRequest(FilesLinkUtility.DocServiceHealthcheckUrl)) + if (!Web.Core.Files.DocumentService.HealthcheckRequest(FilesLinkUtility.DocServiceHealthcheckUrl, ClientFactory)) { throw new Exception("bad status"); } @@ -256,7 +263,7 @@ namespace ASC.Web.Files.Services.DocumentService var fileUri = ReplaceCommunityAdress(url); var key = GenerateRevisionId(Guid.NewGuid().ToString()); - Web.Core.Files.DocumentService.GetConvertedUri(FileUtility, FilesLinkUtility.DocServiceConverterUrl, fileUri, fileExtension, toExtension, key, null, null, null, false, FileUtility.SignatureSecret, out convertedFileUri); + Web.Core.Files.DocumentService.GetConvertedUri(FileUtility, FilesLinkUtility.DocServiceConverterUrl, fileUri, fileExtension, toExtension, key, null, null, null, false, FileUtility.SignatureSecret, ClientFactory, out convertedFileUri); } catch (Exception ex) { @@ -269,7 +276,7 @@ namespace ASC.Web.Files.Services.DocumentService var request1 = new HttpRequestMessage(); request1.RequestUri = new Uri(convertedFileUri); - using var httpClient = new HttpClient(); + using var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request1); if (response.StatusCode != HttpStatusCode.OK) @@ -289,7 +296,7 @@ namespace ASC.Web.Files.Services.DocumentService try { var key = GenerateRevisionId(Guid.NewGuid().ToString()); - Web.Core.Files.DocumentService.CommandRequest(FileUtility, FilesLinkUtility.DocServiceCommandUrl, CommandMethod.Version, key, null, null, null, FileUtility.SignatureSecret, out var version); + Web.Core.Files.DocumentService.CommandRequest(FileUtility, FilesLinkUtility.DocServiceCommandUrl, CommandMethod.Version, key, null, null, null, FileUtility.SignatureSecret, ClientFactory, out var version); } catch (Exception ex) { @@ -307,7 +314,7 @@ namespace ASC.Web.Files.Services.DocumentService var scriptUrl = BaseCommonLinkUtility.GetFullAbsolutePath(scriptUri.ToString()); scriptUrl = ReplaceCommunityAdress(scriptUrl); - Web.Core.Files.DocumentService.DocbuilderRequest(FileUtility, FilesLinkUtility.DocServiceDocbuilderUrl, null, scriptUrl, false, FileUtility.SignatureSecret, out var urls); + Web.Core.Files.DocumentService.DocbuilderRequest(FileUtility, FilesLinkUtility.DocServiceDocbuilderUrl, null, scriptUrl, false, FileUtility.SignatureSecret, ClientFactory, out var urls); } catch (Exception ex) { diff --git a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs index 580f128df5..dfde169ca7 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -67,6 +67,7 @@ namespace ASC.Files.Helpers private EncryptionKeyPairHelper EncryptionKeyPairHelper { get; } private IHttpContextAccessor HttpContextAccessor { get; } private ILog Logger { get; set; } + private IHttpClientFactory ClientFactory { get; set; } /// /// @@ -93,7 +94,8 @@ namespace ASC.Files.Helpers IOptionsMonitor optionMonitor, SettingsManager settingsManager, EncryptionKeyPairHelper encryptionKeyPairHelper, - IHttpContextAccessor httpContextAccessor) + IHttpContextAccessor httpContextAccessor, + IHttpClientFactory clientFactory) { ApiContext = context; FileStorageService = fileStorageService; @@ -116,6 +118,7 @@ namespace ASC.Files.Helpers EncryptionKeyPairHelper = encryptionKeyPairHelper; HttpContextAccessor = httpContextAccessor; Logger = optionMonitor.Get("ASC.Files"); + ClientFactory = clientFactory; } public FolderContentWrapper GetFolder(T folderId, Guid userIdOrGroupId, FilterType filterType, bool withSubFolders) @@ -257,7 +260,7 @@ namespace ASC.Files.Helpers var createSessionUrl = FilesLinkUtility.GetInitiateUploadSessionUrl(TenantManager.GetCurrentTenant().TenantId, file.FolderID, file.ID, file.Title, file.ContentLength, encrypted, SecurityContext); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); var request = new HttpRequestMessage(); request.RequestUri = new Uri(createSessionUrl); diff --git a/products/ASC.Files/Service/Thumbnail/Builder.cs b/products/ASC.Files/Service/Thumbnail/Builder.cs index 653aea5908..c24fb691ea 100644 --- a/products/ASC.Files/Service/Thumbnail/Builder.cs +++ b/products/ASC.Files/Service/Thumbnail/Builder.cs @@ -48,9 +48,12 @@ namespace ASC.Files.ThumbnailBuilder { private readonly ThumbnailSettings config; private readonly ILog logger; + private readonly IHttpClientFactory clientFactory; private IServiceProvider ServiceProvider { get; } - public BuilderQueue(IServiceProvider serviceProvider, IOptionsMonitor log, ASC.Common.Utils.ConfigurationExtension configurationExtension) + public BuilderQueue(IServiceProvider serviceProvider, + IOptionsMonitor log, + Common.Utils.ConfigurationExtension configurationExtension) { logger = log.Get("ASC.Files.ThumbnailBuilder"); ServiceProvider = serviceProvider; @@ -94,6 +97,7 @@ namespace ASC.Files.ThumbnailBuilder private DocumentServiceHelper DocumentServiceHelper { get; } private Global Global { get; } private PathProvider PathProvider { get; } + private IHttpClientFactory ClientFactory { get; } public Builder( Common.Utils.ConfigurationExtension configurationExtension, @@ -103,7 +107,8 @@ namespace ASC.Files.ThumbnailBuilder DocumentServiceHelper documentServiceHelper, Global global, PathProvider pathProvider, - IOptionsMonitor log) + IOptionsMonitor log, + IHttpClientFactory clientFactory) { this.config = ThumbnailSettings.GetInstance(configurationExtension); TenantManager = tenantManager; @@ -112,7 +117,8 @@ namespace ASC.Files.ThumbnailBuilder DocumentServiceHelper = documentServiceHelper; Global = global; PathProvider = pathProvider; - logger = log.Get("ASC.Files.ThumbnailBuilder"); + logger = log.Get("ASC.Files.ThumbnailBuilder"); + ClientFactory = clientFactory; } internal void BuildThumbnail(FileData fileData) @@ -289,7 +295,7 @@ namespace ASC.Files.ThumbnailBuilder var request = new HttpRequestMessage(); request.RequestUri = new Uri(thumbnailUrl); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using (var stream = new ResponseStream(response)) { diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index 29ffb63296..b48b26f846 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -99,6 +99,7 @@ namespace ASC.Employee.Core.Controllers private Constants Constants { get; } private Recaptcha Recaptcha { get; } private ILog Log { get; } + private IHttpClientFactory ClientFactory { get; } public PeopleController( MessageService messageService, @@ -140,7 +141,8 @@ namespace ASC.Employee.Core.Controllers MobileDetector mobileDetector, ProviderManager providerManager, Constants constants, - Recaptcha recaptcha + Recaptcha recaptcha, + IHttpClientFactory clientFactory ) { Log = option.Get("ASC.Api"); @@ -183,6 +185,7 @@ namespace ASC.Employee.Core.Controllers ProviderManager = providerManager; Constants = constants; Recaptcha = recaptcha; + ClientFactory = clientFactory; } [Read("info")] @@ -1851,7 +1854,7 @@ namespace ASC.Employee.Core.Controllers var request = new HttpRequestMessage(); request.RequestUri = new Uri(url); - using (var httpClient = new HttpClient()) + var httpClient = ClientFactory.CreateClient(); using (var response = httpClient.Send(request)) using (var stream = response.Content.ReadAsStream()) { @@ -2101,7 +2104,7 @@ namespace ASC.Employee.Core.Controllers var request = new HttpRequestMessage(); request.RequestUri = new Uri(files); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var inputStream = response.Content.ReadAsStream(); using var br = new BinaryReader(inputStream); diff --git a/web/ASC.Web.Api/Controllers/PortalController.cs b/web/ASC.Web.Api/Controllers/PortalController.cs index 7b4e13337e..d4262ac59b 100644 --- a/web/ASC.Web.Api/Controllers/PortalController.cs +++ b/web/ASC.Web.Api/Controllers/PortalController.cs @@ -55,6 +55,7 @@ namespace ASC.Web.Api.Controllers public SetupInfo SetupInfo { get; } private TenantExtra TenantExtra { get; set; } public ILog Log { get; } + public IHttpClientFactory ClientFactory { get; } public PortalController( @@ -74,7 +75,8 @@ namespace ASC.Web.Api.Controllers IConfiguration configuration, CoreBaseSettings coreBaseSettings, LicenseReader licenseReader, - SetupInfo setupInfo + SetupInfo setupInfo, + IHttpClientFactory clientFactory ) { Log = options.CurrentValue; @@ -94,6 +96,7 @@ namespace ASC.Web.Api.Controllers LicenseReader = licenseReader; SetupInfo = setupInfo; TenantExtra = tenantExtra; + ClientFactory = clientFactory; } [Read("")] @@ -216,7 +219,7 @@ namespace ASC.Web.Api.Controllers var request = new HttpRequestMessage(); request.RequestUri = new Uri(string.Format(Configuration["bookmarking:thumbnail-url"], url)); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var stream = response.Content.ReadAsStream(); var bytes = new byte[stream.Length]; diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index f72eb80707..4d3ea3fe80 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -172,6 +172,7 @@ namespace ASC.Api.Settings private PaymentManager PaymentManager { get; } private DbWorker WebhookDbWorker { get; } public Constants Constants { get; } + public IHttpClientFactory ClientFactory { get; } public SettingsController( IOptionsMonitor option, @@ -234,7 +235,8 @@ namespace ASC.Api.Settings PasswordHasher passwordHasher, PaymentManager paymentManager, DbWorker dbWorker, - Constants constants) + Constants constants, + IHttpClientFactory clientFactory) { Log = option.Get("ASC.Api"); WebHostEnvironment = webHostEnvironment; @@ -297,6 +299,7 @@ namespace ASC.Api.Settings PaymentManager = paymentManager; WebhookDbWorker = dbWorker; Constants = constants; + ClientFactory = clientFactory; } [Read("", Check = false)] @@ -1377,7 +1380,7 @@ namespace ASC.Api.Settings var body = JsonSerializer.Serialize(data);//todo check request.Content = new StringContent(body); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); } diff --git a/web/ASC.Web.Api/Core/FirstTimeTenantSettings.cs b/web/ASC.Web.Api/Core/FirstTimeTenantSettings.cs index 24cc65fec9..8027e62eec 100644 --- a/web/ASC.Web.Api/Core/FirstTimeTenantSettings.cs +++ b/web/ASC.Web.Api/Core/FirstTimeTenantSettings.cs @@ -70,6 +70,7 @@ namespace ASC.Web.Studio.UserControls.FirstTime private StudioNotifyService StudioNotifyService { get; } private TimeZoneConverter TimeZoneConverter { get; } public CoreBaseSettings CoreBaseSettings { get; } + public IHttpClientFactory ClientFactory { get; } public FirstTimeTenantSettings( IOptionsMonitor options, @@ -84,7 +85,8 @@ namespace ASC.Web.Studio.UserControls.FirstTime LicenseReader licenseReader, StudioNotifyService studioNotifyService, TimeZoneConverter timeZoneConverter, - CoreBaseSettings coreBaseSettings) + CoreBaseSettings coreBaseSettings, + IHttpClientFactory clientFactory) { Log = options.CurrentValue; TenantManager = tenantManager; @@ -99,6 +101,7 @@ namespace ASC.Web.Studio.UserControls.FirstTime StudioNotifyService = studioNotifyService; TimeZoneConverter = timeZoneConverter; CoreBaseSettings = coreBaseSettings; + ClientFactory = clientFactory; } public WizardSettings SaveData(WizardModel wizardModel) @@ -247,7 +250,7 @@ namespace ASC.Web.Studio.UserControls.FirstTime try { - using (var httpClient = new HttpClient()) + var httpClient = ClientFactory.CreateClient(); using (var response = httpClient.Send(request)) using (var responseStream = response.Content.ReadAsStream()) using (var reader = new StreamReader(responseStream)) @@ -286,7 +289,7 @@ namespace ASC.Web.Studio.UserControls.FirstTime var data = JsonSerializer.Serialize(values); request.Content = new StringContent(data); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); Log.Debug("Subscribe response: " + response);//toto write diff --git a/web/ASC.Web.Core/Files/DocumentService.cs b/web/ASC.Web.Core/Files/DocumentService.cs index 9ca0b2ef15..1650337130 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -110,6 +110,7 @@ namespace ASC.Web.Core.Files SpreadsheetLayout spreadsheetLayout, bool isAsync, string signatureSecret, + IHttpClientFactory clientFactory, out string convertedDocumentUri) { fromExtension = string.IsNullOrEmpty(fromExtension) ? Path.GetExtension(documentUri) : fromExtension; @@ -129,7 +130,7 @@ namespace ASC.Web.Core.Files request.Method = HttpMethod.Post; request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json")); - using var httpClient = new HttpClient(); + var httpClient = clientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout); var body = new ConvertionBody @@ -231,13 +232,14 @@ namespace ASC.Web.Core.Files string[] users, MetaData meta, string signatureSecret, + IHttpClientFactory clientFactory, out string version) { var request = new HttpRequestMessage(); request.RequestUri = new Uri(documentTrackerUrl); request.Method = HttpMethod.Post; - using var httpClient = new HttpClient(); + var httpClient = clientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout); var body = new CommandBody @@ -304,6 +306,7 @@ namespace ASC.Web.Core.Files string scriptUrl, bool isAsync, string signatureSecret, + IHttpClientFactory clientFactory, out Dictionary urls) { if (string.IsNullOrEmpty(docbuilderUrl)) @@ -316,7 +319,7 @@ namespace ASC.Web.Core.Files request.RequestUri = new Uri(docbuilderUrl); request.Method = HttpMethod.Post; - using var httpClient = new HttpClient(); + var httpClient = clientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout); var body = new BuilderBody @@ -385,7 +388,7 @@ namespace ASC.Web.Core.Files return responseFromService.Value("key"); } - public static bool HealthcheckRequest(string healthcheckUrl) + public static bool HealthcheckRequest(string healthcheckUrl, IHttpClientFactory clientFactory) { if (string.IsNullOrEmpty(healthcheckUrl)) throw new ArgumentNullException("healthcheckUrl"); @@ -393,7 +396,7 @@ namespace ASC.Web.Core.Files var request = new HttpRequestMessage(); request.RequestUri = new Uri(healthcheckUrl); - using var httpClient = new HttpClient(); + var httpClient = clientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout); using var response = httpClient.Send(request); diff --git a/web/ASC.Web.Core/Helpers/ApiSystemHelper.cs b/web/ASC.Web.Core/Helpers/ApiSystemHelper.cs index ebb370dea2..713972fa7f 100644 --- a/web/ASC.Web.Core/Helpers/ApiSystemHelper.cs +++ b/web/ASC.Web.Core/Helpers/ApiSystemHelper.cs @@ -51,18 +51,21 @@ namespace ASC.Web.Core.Helpers public class ApiSystemHelper { public string ApiSystemUrl { get; private set; } - public string ApiCacheUrl { get; private set; } - private static byte[] Skey { get; set; } - private CommonLinkUtility CommonLinkUtility { get; } + private CommonLinkUtility CommonLinkUtility { get; } + private IHttpClientFactory ClientFactory { get; } - public ApiSystemHelper(IConfiguration configuration, CommonLinkUtility commonLinkUtility, MachinePseudoKeys machinePseudoKeys) + public ApiSystemHelper(IConfiguration configuration, + CommonLinkUtility commonLinkUtility, + MachinePseudoKeys machinePseudoKeys, + IHttpClientFactory clientFactory) { ApiSystemUrl = configuration["web:api-system"]; ApiCacheUrl = configuration["web:api-cache"]; CommonLinkUtility = commonLinkUtility; - Skey = machinePseudoKeys.GetMachineConstant(); + Skey = machinePseudoKeys.GetMachineConstant(); + ClientFactory = clientFactory; } @@ -163,7 +166,7 @@ namespace ASC.Web.Core.Helpers request.Content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded"); } - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var stream = response.Content.ReadAsStream(); using var reader = new StreamReader(stream, Encoding.UTF8); diff --git a/web/ASC.Web.Core/Recaptcha.cs b/web/ASC.Web.Core/Recaptcha.cs index 6e017f9be7..cccc9dd80f 100644 --- a/web/ASC.Web.Core/Recaptcha.cs +++ b/web/ASC.Web.Core/Recaptcha.cs @@ -27,10 +27,12 @@ namespace ASC.Web.Core public class Recaptcha { private SetupInfo SetupInfo { get; } + private IHttpClientFactory ClientFactory { get; } - public Recaptcha(SetupInfo setupInfo) + public Recaptcha(SetupInfo setupInfo, IHttpClientFactory clientFactory) { SetupInfo = setupInfo; + ClientFactory = clientFactory; } @@ -45,7 +47,7 @@ namespace ASC.Web.Core request.Method = HttpMethod.Post; request.Content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded"); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var httpClientResponse = httpClient.Send(request); using (var reader = new StreamReader(httpClientResponse.Content.ReadAsStream())) { diff --git a/web/ASC.Web.Core/Sms/SmsProvider.cs b/web/ASC.Web.Core/Sms/SmsProvider.cs index 18d93d0272..aaf04b470b 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -118,7 +118,8 @@ namespace ASC.Web.Core.Sms public abstract class SmsProvider : Consumer { - protected readonly ILog Log; + protected ILog Log { get; } + protected IHttpClientFactory ClientFactory { get; } protected ICache MemoryCache { get; set; } protected virtual string SendMessageUrlFormat { get; set; } @@ -139,12 +140,14 @@ namespace ASC.Web.Core.Sms ICacheNotify cache, ConsumerFactory consumerFactory, IOptionsMonitor options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order, Dictionary props, Dictionary additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) { MemoryCache = memCache; Log = options.CurrentValue; + ClientFactory = clientFactory; } public virtual bool Enable() @@ -171,7 +174,7 @@ namespace ASC.Web.Core.Sms request.RequestUri = new Uri(url); request.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromMilliseconds(15000); using var response = httpClient.Send(request); @@ -206,9 +209,10 @@ namespace ASC.Web.Core.Sms ICacheNotify cache, ConsumerFactory consumerFactory, IOptionsMonitor options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order, Dictionary props, Dictionary additional = null) - : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, options, memCache, name, order, props, additional) + : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, options, clientFactory, memCache, name, order, props, additional) { } @@ -265,7 +269,7 @@ namespace ASC.Web.Core.Sms request.RequestUri = new Uri(url); request.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); httpClient.Timeout = TimeSpan.FromMilliseconds(1000); using var response = httpClient.Send(request); @@ -347,9 +351,10 @@ namespace ASC.Web.Core.Sms ICacheNotify cache, ConsumerFactory consumerFactory, IOptionsMonitor options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order, Dictionary props, Dictionary additional = null) - : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, options, memCache, name, order, props, additional) + : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, options, clientFactory, memCache, name, order, props, additional) { } } @@ -368,9 +373,10 @@ namespace ASC.Web.Core.Sms ICacheNotify cache, ConsumerFactory consumerFactory, IOptionsMonitor options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order, Dictionary additional = null) - : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, options, memCache, name, order, null, additional) + : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, options, clientFactory, memCache, name, order, null, additional) { } } @@ -450,9 +456,10 @@ namespace ASC.Web.Core.Sms ICacheNotify cache, ConsumerFactory consumerFactory, IOptionsMonitor options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order, Dictionary props) - : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, options, memCache, name, order, props) + : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, options, clientFactory, memCache, name, order, props) { AuthContext = authContext; TenantUtil = tenantUtil; @@ -501,9 +508,10 @@ namespace ASC.Web.Core.Sms ICacheNotify cache, ConsumerFactory consumerFactory, IOptionsMonitor options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order) - : base(authContext, tenantUtil, securityContext, baseCommonLinkUtility, twilioProviderCleaner, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, options, memCache, name, order, null) + : base(authContext, tenantUtil, securityContext, baseCommonLinkUtility, twilioProviderCleaner, tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, options, clientFactory, memCache, name, order, null) { } } diff --git a/web/ASC.Web.Core/Utility/UrlShortener.cs b/web/ASC.Web.Core/Utility/UrlShortener.cs index ac8f8ecd05..32f94f8eec 100644 --- a/web/ASC.Web.Core/Utility/UrlShortener.cs +++ b/web/ASC.Web.Core/Utility/UrlShortener.cs @@ -38,7 +38,7 @@ namespace ASC.Web.Core.Utility } else if (!string.IsNullOrEmpty(Configuration["web:url-shortener:value"])) { - _instance = new OnlyoShortener(Configuration, CommonLinkUtility, MachinePseudoKeys); + _instance = new OnlyoShortener(Configuration, CommonLinkUtility, MachinePseudoKeys, ClientFactory); } else { @@ -58,17 +58,20 @@ namespace ASC.Web.Core.Utility private ConsumerFactory ConsumerFactory { get; } private CommonLinkUtility CommonLinkUtility { get; } private MachinePseudoKeys MachinePseudoKeys { get; } + private IHttpClientFactory ClientFactory { get; } public UrlShortener( IConfiguration configuration, ConsumerFactory consumerFactory, CommonLinkUtility commonLinkUtility, - MachinePseudoKeys machinePseudoKeys) + MachinePseudoKeys machinePseudoKeys, + IHttpClientFactory clientFactory) { Configuration = configuration; ConsumerFactory = consumerFactory; CommonLinkUtility = commonLinkUtility; MachinePseudoKeys = machinePseudoKeys; + ClientFactory = clientFactory; } } @@ -91,12 +94,16 @@ namespace ASC.Web.Core.Utility { private readonly string url; private readonly string internalUrl; - private readonly byte[] sKey; + private readonly byte[] sKey; + + private CommonLinkUtility CommonLinkUtility { get; } + private IHttpClientFactory ClientFactory { get; } public OnlyoShortener( IConfiguration configuration, CommonLinkUtility commonLinkUtility, - MachinePseudoKeys machinePseudoKeys) + MachinePseudoKeys machinePseudoKeys, + IHttpClientFactory clientFactory) { url = configuration["web:url-shortener:value"]; internalUrl = configuration["web:url-shortener:internal"]; @@ -104,11 +111,10 @@ namespace ASC.Web.Core.Utility if (!url.EndsWith("/")) url += '/'; - CommonLinkUtility = commonLinkUtility; + CommonLinkUtility = commonLinkUtility; + ClientFactory = clientFactory; } - private CommonLinkUtility CommonLinkUtility { get; } - public string GetShortenLink(string shareLink) { var request = new HttpRequestMessage(); @@ -116,7 +122,7 @@ namespace ASC.Web.Core.Utility request.Headers.Add("Authorization", CreateAuthToken()); request.Headers.Add("Encoding", Encoding.UTF8.ToString());//todo check - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var stream = response.Content.ReadAsStream(); using var rs = new StreamReader(stream); From d1ce4c5ed67447d65d964a8363d766355f3ef00c Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 13 Jan 2022 14:30:40 +0300 Subject: [PATCH 039/167] analizators/U2U1025 --- .../DocumentService/DocumentServiceTracker.cs | 17 ++++++++++------- .../ASC.Files/Core/ThirdPartyApp/BoxApp.cs | 13 ++++++++----- .../Core/ThirdPartyApp/GoogleDriveApp.cs | 19 +++++++++++-------- products/ASC.Files/Core/Utils/EntryManager.cs | 9 ++++++--- .../ASC.Files/Core/Utils/FileConverter.cs | 18 +++++++++++------- .../ASC.Files/Core/Utils/MailMergeTask.cs | 8 ++++---- 6 files changed, 50 insertions(+), 34 deletions(-) diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs index 7278d24d28..572c7bf97a 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -184,7 +184,8 @@ namespace ASC.Web.Files.Services.DocumentService private NotifyClient NotifyClient { get; } private MailMergeTaskRunner MailMergeTaskRunner { get; } private FileTrackerHelper FileTracker { get; } - public ILog Logger { get; } + public ILog Logger { get; } + public IHttpClientFactory ClientFactory { get; } public DocumentServiceTrackerHelper( SecurityContext securityContext, @@ -205,7 +206,8 @@ namespace ASC.Web.Files.Services.DocumentService DocumentServiceConnector documentServiceConnector, NotifyClient notifyClient, MailMergeTaskRunner mailMergeTaskRunner, - FileTrackerHelper fileTracker) + FileTrackerHelper fileTracker, + IHttpClientFactory clientFactory) { SecurityContext = securityContext; UserManager = userManager; @@ -225,7 +227,8 @@ namespace ASC.Web.Files.Services.DocumentService NotifyClient = notifyClient; MailMergeTaskRunner = mailMergeTaskRunner; FileTracker = fileTracker; - Logger = options.CurrentValue; + Logger = options.CurrentValue; + ClientFactory = clientFactory; } public string GetCallbackUrl(T fileId) @@ -491,7 +494,7 @@ namespace ASC.Web.Files.Services.DocumentService var message = fileData.MailMerge.Message; Stream attach = null; - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); switch (fileData.MailMerge.Type) { case MailMergeType.AttachDocx: @@ -553,7 +556,7 @@ namespace ASC.Web.Files.Services.DocumentService Attach = attach }) { - var response = MailMergeTaskRunner.Run(mailMergeTask); + var response = MailMergeTaskRunner.Run(mailMergeTask, ClientFactory); Logger.InfoFormat("DocService mailMerge {0}/{1} send: {2}", fileData.MailMerge.RecordIndex + 1, fileData.MailMerge.RecordCount, response); } @@ -598,7 +601,7 @@ namespace ASC.Web.Files.Services.DocumentService var request = new HttpRequestMessage(); request.RequestUri = new Uri(downloadUri); - using (var httpClient = new HttpClient()) + var httpClient = ClientFactory.CreateClient(); using (var response = httpClient.Send(request)) using (var stream = response.Content.ReadAsStream()) using (var fileStream = new ResponseStream(stream, stream.Length)) @@ -625,7 +628,7 @@ namespace ASC.Web.Files.Services.DocumentService var request = new HttpRequestMessage(); request.RequestUri = new Uri(differenceUrl); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var stream = response.Content.ReadAsStream(); diff --git a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs index 7c9df95b32..2532231761 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -112,7 +112,8 @@ namespace ASC.Web.Files.ThirdPartyApp private DocumentServiceConnector DocumentServiceConnector { get; } private ThirdPartyAppHandlerService ThirdPartyAppHandlerService { get; } private IServiceProvider ServiceProvider { get; } - public ILog Logger { get; } + public ILog Logger { get; } + public IHttpClientFactory ClientFactory { get; } public BoxApp() { @@ -145,7 +146,8 @@ namespace ASC.Web.Files.ThirdPartyApp CoreSettings coreSettings, IConfiguration configuration, ICacheNotify cache, - ConsumerFactory consumerFactory, + ConsumerFactory consumerFactory, + IHttpClientFactory clientFactory, string name, int order, Dictionary additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) { @@ -169,7 +171,8 @@ namespace ASC.Web.Files.ThirdPartyApp DocumentServiceConnector = documentServiceConnector; ThirdPartyAppHandlerService = thirdPartyAppHandlerService; ServiceProvider = serviceProvider; - Logger = option.CurrentValue; + Logger = option.CurrentValue; + ClientFactory = clientFactory; } public bool Request(HttpContext context) @@ -310,7 +313,7 @@ namespace ASC.Web.Files.ThirdPartyApp } } - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); var request = new HttpRequestMessage(); request.RequestUri = new Uri(BoxUrlUpload.Replace("{fileId}", fileId)); @@ -471,7 +474,7 @@ namespace ASC.Web.Files.ThirdPartyApp request.Method = HttpMethod.Get; request.Headers.Add("Authorization", "Bearer " + token); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var stream = new ResponseStream(response); stream.CopyTo(context.Response.Body); diff --git a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs index c56d3da218..88fc5610b7 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -118,7 +118,8 @@ namespace ASC.Web.Files.ThirdPartyApp private TokenHelper TokenHelper { get; } private DocumentServiceConnector DocumentServiceConnector { get; } private ThirdPartyAppHandlerService ThirdPartyAppHandlerService { get; } - private IServiceProvider ServiceProvider { get; } + private IServiceProvider ServiceProvider { get; } + private IHttpClientFactory ClientFactory { get; } public GoogleDriveApp() { @@ -155,7 +156,8 @@ namespace ASC.Web.Files.ThirdPartyApp CoreSettings coreSettings, IConfiguration configuration, ICacheNotify cache, - ConsumerFactory consumerFactory, + ConsumerFactory consumerFactory, + IHttpClientFactory clientFactory, string name, int order, Dictionary additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) { @@ -183,7 +185,8 @@ namespace ASC.Web.Files.ThirdPartyApp TokenHelper = tokenHelper; DocumentServiceConnector = documentServiceConnector; ThirdPartyAppHandlerService = thirdPartyAppHandlerService; - ServiceProvider = serviceProvider; + ServiceProvider = serviceProvider; + ClientFactory = clientFactory; } public bool Request(HttpContext context) @@ -315,7 +318,7 @@ namespace ASC.Web.Files.ThirdPartyApp } } - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); var request = new HttpRequestMessage(); request.RequestUri = new Uri(GoogleLoginProvider.GoogleUrlFileUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId)); @@ -522,7 +525,7 @@ namespace ASC.Web.Files.ThirdPartyApp request.Method = HttpMethod.Get; request.Headers.Add("Authorization", "Bearer " + token); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var stream = new ResponseStream(response); stream.CopyTo(context.Response.Body); @@ -732,7 +735,7 @@ namespace ASC.Web.Files.ThirdPartyApp var request = new HttpRequestMessage(); request.RequestUri = new Uri(contentUrl); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var content = new ResponseStream(response); return CreateFile(content, fileName, folderId, token); @@ -742,7 +745,7 @@ namespace ASC.Web.Files.ThirdPartyApp { Logger.Debug("GoogleDriveApp: create file"); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); var request = new HttpRequestMessage(); request.RequestUri = new Uri(GoogleLoginProvider.GoogleUrlFileUpload + "?uploadType=multipart"); @@ -847,7 +850,7 @@ namespace ASC.Web.Files.ThirdPartyApp fileId, HttpUtility.UrlEncode(requiredMimeType)); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); var request = new HttpRequestMessage(); request.RequestUri = new Uri(downloadUrl); diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index d22a9dad78..87e1fa8a71 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -267,7 +267,8 @@ namespace ASC.Web.Files.Utils private TenantManager TenantManager { get; } private SettingsManager SettingsManager { get; } private IServiceProvider ServiceProvider { get; } - private ILog Logger { get; } + private ILog Logger { get; } + private IHttpClientFactory ClientFactory { get; } public EntryManager( IDaoFactory daoFactory, @@ -295,7 +296,8 @@ namespace ASC.Web.Files.Utils IServiceProvider serviceProvider, ICache cache, FileTrackerHelper fileTracker, - EntryStatusManager entryStatusManager) + EntryStatusManager entryStatusManager, + IHttpClientFactory clientFactory) { DaoFactory = daoFactory; FileSecurity = fileSecurity; @@ -323,6 +325,7 @@ namespace ASC.Web.Files.Utils Cache = cache; FileTracker = fileTracker; EntryStatusManager = entryStatusManager; + ClientFactory = clientFactory; } public IEnumerable GetEntries(Folder parent, int from, int count, FilterType filter, bool subjectGroup, Guid subjectId, string searchText, bool searchInContent, bool withSubfolders, OrderBy orderBy, out int total) @@ -1007,7 +1010,7 @@ namespace ASC.Web.Files.Utils var request = new HttpRequestMessage(); request.RequestUri = new Uri(downloadUri); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); using var editedFileStream = new ResponseStream(response); editedFileStream.CopyTo(tmpStream); diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index 92746740ab..3c2d3f9e7c 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -542,7 +542,8 @@ namespace ASC.Web.Files.Utils private BaseCommonLinkUtility BaseCommonLinkUtility { get; } private EntryStatusManager EntryStatusManager { get; } private IServiceProvider ServiceProvider { get; } - private IHttpContextAccessor HttpContextAccesor { get; } + private IHttpContextAccessor HttpContextAccesor { get; } + private IHttpClientFactory ClientFactory { get; } public FileConverter( FileUtility fileUtility, @@ -564,7 +565,8 @@ namespace ASC.Web.Files.Utils FileTrackerHelper fileTracker, BaseCommonLinkUtility baseCommonLinkUtility, EntryStatusManager entryStatusManager, - IServiceProvider serviceProvider) + IServiceProvider serviceProvider, + IHttpClientFactory clientFactory) { FileUtility = fileUtility; FilesLinkUtility = filesLinkUtility; @@ -585,7 +587,8 @@ namespace ASC.Web.Files.Utils FileTracker = fileTracker; BaseCommonLinkUtility = baseCommonLinkUtility; EntryStatusManager = entryStatusManager; - ServiceProvider = serviceProvider; + ServiceProvider = serviceProvider; + ClientFactory = clientFactory; } public FileConverter( FileUtility fileUtility, @@ -608,11 +611,12 @@ namespace ASC.Web.Files.Utils BaseCommonLinkUtility baseCommonLinkUtility, EntryStatusManager entryStatusManager, IServiceProvider serviceProvider, - IHttpContextAccessor httpContextAccesor) + IHttpContextAccessor httpContextAccesor, + IHttpClientFactory clientFactory) : this(fileUtility, filesLinkUtility, daoFactory, setupInfo, pathProvider, fileSecurity, fileMarker, tenantManager, authContext, entryManager, filesSettingsHelper, globalFolderHelper, filesMessageService, fileShareLink, documentServiceHelper, documentServiceConnector, fileTracker, - baseCommonLinkUtility, entryStatusManager, serviceProvider) + baseCommonLinkUtility, entryStatusManager, serviceProvider, clientFactory) { HttpContextAccesor = httpContextAccesor; } @@ -683,7 +687,7 @@ namespace ASC.Web.Files.Utils var request = new HttpRequestMessage(); request.RequestUri = new Uri(convertUri); - using var httpClient = new HttpClient(); + using var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); return new ResponseStream(response); } @@ -851,7 +855,7 @@ namespace ASC.Web.Files.Utils var request = new HttpRequestMessage(); request.RequestUri = new Uri(convertedFileUrl); - using var httpClient = new HttpClient(); + var httpClient = ClientFactory.CreateClient(); try { diff --git a/products/ASC.Files/Core/Utils/MailMergeTask.cs b/products/ASC.Files/Core/Utils/MailMergeTask.cs index b08b2c9c93..c1e34a1964 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -86,14 +86,14 @@ namespace ASC.Web.Files.Utils BaseCommonLinkUtility = baseCommonLinkUtility; } - public string Run(MailMergeTask mailMergeTask) + public string Run(MailMergeTask mailMergeTask, IHttpClientFactory clientFactory) { if (string.IsNullOrEmpty(mailMergeTask.From)) throw new ArgumentException("From is null"); if (string.IsNullOrEmpty(mailMergeTask.To)) throw new ArgumentException("To is null"); CreateDraftMail(mailMergeTask); - var bodySendAttach = AttachToMail(mailMergeTask); + var bodySendAttach = AttachToMail(mailMergeTask, clientFactory); return SendMail(mailMergeTask, bodySendAttach); } @@ -122,7 +122,7 @@ namespace ASC.Web.Files.Utils mailMergeTask.StreamId = responseCreate["response"]["streamId"].Value(); } - private string AttachToMail(MailMergeTask mailMergeTask) + private string AttachToMail(MailMergeTask mailMergeTask, IHttpClientFactory clientFactory) { if (mailMergeTask.Attach == null) return string.Empty; @@ -141,7 +141,7 @@ namespace ASC.Web.Files.Utils request.Content = new StreamContent(mailMergeTask.Attach); string responseAttachString; - using var httpClient = new HttpClient(); + var httpClient = clientFactory.CreateClient(); using var response = httpClient.Send(request); using (var stream = response.Content.ReadAsStream()) { From cacb889ee2910a47350cf04de56d42594ebcd3d7 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 13 Jan 2022 15:04:28 +0300 Subject: [PATCH 040/167] analizators/U2U1100 --- common/ASC.Api.Core/Core/CustomHealthCheck.cs | 4 ++-- common/ASC.Common/Web/MimeMapping.cs | 2 +- .../LoginProviders/TelegramLoginProvider.cs | 2 +- common/ASC.Notify.Textile/TextileStyler.cs | 4 ++-- products/ASC.People/Server/Controllers/PeopleController.cs | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/common/ASC.Api.Core/Core/CustomHealthCheck.cs b/common/ASC.Api.Core/Core/CustomHealthCheck.cs index 57a8990396..29b56aa66d 100644 --- a/common/ASC.Api.Core/Core/CustomHealthCheck.cs +++ b/common/ASC.Api.Core/Core/CustomHealthCheck.cs @@ -24,7 +24,7 @@ namespace ASC.Api.Core.Core var connectionString = configurationExtension.GetConnectionStrings("default"); - if (String.Compare(connectionString.ProviderName, "MySql.Data.MySqlClient") == 0) + if (string.Equals(connectionString.ProviderName, "MySql.Data.MySqlClient")) { hcBuilder.AddMySql(connectionString.ConnectionString, name: "mysqldb", @@ -32,7 +32,7 @@ namespace ASC.Api.Core.Core ); } - if (String.Compare(connectionString.ProviderName, "Npgsql") == 0) + if (string.Equals(connectionString.ProviderName, "Npgsql")) { hcBuilder.AddNpgSql(connectionString.ConnectionString, name: "postgredb", diff --git a/common/ASC.Common/Web/MimeMapping.cs b/common/ASC.Common/Web/MimeMapping.cs index e3cdf33aa0..5831431b2f 100644 --- a/common/ASC.Common/Web/MimeMapping.cs +++ b/common/ASC.Common/Web/MimeMapping.cs @@ -852,7 +852,7 @@ namespace ASC.Common.Web foreach (DictionaryEntry entry in extensionToMimeMappingTable) { var mime = (string)entry.Value; - if (mime == mimeMapping.ToLowerInvariant()) return (string)entry.Key; + if (mime.Equals(mimeMapping, StringComparison.OrdinalIgnoreCase)) return (string)entry.Key; if (!mimeSynonyms.ContainsKey(mime)) continue; if (mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; } diff --git a/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs index 3a86305340..a918e26014 100644 --- a/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs @@ -83,7 +83,7 @@ namespace ASC.FederatedLogin.LoginProviders public bool ValidateKeys() { - if (TelegramBotToken == "") + if (TelegramBotToken.Length == 0) { TelegramHelper.DisableClient(TenantManager.GetCurrentTenant().TenantId); return true; diff --git a/common/ASC.Notify.Textile/TextileStyler.cs b/common/ASC.Notify.Textile/TextileStyler.cs index 1ba89b2610..795f119e5a 100644 --- a/common/ASC.Notify.Textile/TextileStyler.cs +++ b/common/ASC.Notify.Textile/TextileStyler.cs @@ -152,7 +152,7 @@ namespace ASC.Notify.Textile if (string.IsNullOrEmpty(logoImg)) { var logo = message.GetArgument("LetterLogo"); - if (logo != null && (string)logo.Value != "") + if (logo != null && ((string)logo.Value).Length != 0) { logoImg = (string)logo.Value; } @@ -173,7 +173,7 @@ namespace ASC.Notify.Textile if (string.IsNullOrEmpty(logoText)) { var llt = message.GetArgument("LetterLogoText"); - if (llt != null && (string)llt.Value != "") + if (llt != null && ((string)llt.Value).Length != 0) { logoText = (string)llt.Value; } diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index b48b26f846..fb56fa28a6 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -1594,7 +1594,7 @@ namespace ASC.Employee.Core.Controllers foreach (var provider in ProviderManager.AuthProviders.Where(provider => string.IsNullOrEmpty(fromOnly) || fromOnly == provider || (provider == "google" && fromOnly == "openid"))) { - if (inviteView && provider.ToLower() == "twitter") continue; + if (inviteView && provider.Equals("twitter", StringComparison.OrdinalIgnoreCase)) continue; var loginProvider = ProviderManager.GetLoginProvider(provider); if (loginProvider != null && loginProvider.IsEnabled) From 9bc8584184e1dfd3d58656d841ee6c44e45128c6 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Thu, 13 Jan 2022 15:53:57 +0300 Subject: [PATCH 041/167] analizators/U2U1103 --- common/ASC.Api.Core/Core/ApiDateTime.cs | 2 +- common/ASC.Common/DependencyInjection/AutofacExtension.cs | 2 +- common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs | 2 +- common/ASC.Core.Common/Core/DBResourceManager.cs | 2 +- common/ASC.Core.Common/Notify/Cron/CronExpression.cs | 4 ++-- .../ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs | 2 +- common/ASC.Data.Storage/BaseStorage.cs | 4 ++-- common/ASC.Notify.Textile/TextileStyler.cs | 2 +- common/ASC.Textile/Blocks/NoTextileEncoder.cs | 2 +- common/ASC.Textile/Blocks/PhraseBlockModifier.cs | 2 +- common/ASC.VoipService/Dao/AbstractDao.cs | 2 +- common/services/ASC.ElasticSearch/Core/Selector.cs | 6 +++--- products/ASC.CRM/Server/Classes/CSVReader.cs | 2 +- products/ASC.CRM/Server/Core/Dao/AbstractDao.cs | 4 ++-- products/ASC.Calendar/Server/iCalParser/Token.cs | 2 +- products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs | 4 ++-- .../Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs | 4 ++-- .../Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs | 4 ++-- .../Core/Core/Thirdparty/SharePoint/SharePointDaoBase.cs | 4 ++-- .../Core/Thirdparty/SharePoint/SharePointProviderInfo.cs | 2 +- .../Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs | 4 ++-- web/ASC.Web.Api/Controllers/ThirdPartyController.cs | 2 +- web/ASC.Web.Core/Extensions/StringExtension.cs | 2 +- web/ASC.Web.Core/Files/DocumentService.cs | 2 +- web/ASC.Web.Core/Users/UserManagerWrapper.cs | 2 +- web/ASC.Web.Core/Utility/Skins/WebImageSupplier.cs | 4 ++-- 26 files changed, 37 insertions(+), 37 deletions(-) diff --git a/common/ASC.Api.Core/Core/ApiDateTime.cs b/common/ASC.Api.Core/Core/ApiDateTime.cs index 125aead66e..7e83a7d834 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -97,7 +97,7 @@ namespace ASC.Api.Core { //Parse time var tzOffset = TimeSpan.Zero; - if (offsetPart.Contains(":") && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset)) + if (offsetPart.Contains(':') && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset)) { return new ApiDateTime(dateTime, tzOffset); } diff --git a/common/ASC.Common/DependencyInjection/AutofacExtension.cs b/common/ASC.Common/DependencyInjection/AutofacExtension.cs index 8dec7cb508..70cb4b7530 100644 --- a/common/ASC.Common/DependencyInjection/AutofacExtension.cs +++ b/common/ASC.Common/DependencyInjection/AutofacExtension.cs @@ -120,7 +120,7 @@ namespace ASC.Common.DependencyInjection void LoadAssembly(string type) { - var dll = type.Substring(type.IndexOf(",") + 1).Trim(); + var dll = type.Substring(type.IndexOf(',') + 1).Trim(); var path = GetFullPath(dll); if (!string.IsNullOrEmpty(path)) diff --git a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs index 562cfa32cc..dc54200cae 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -167,7 +167,7 @@ namespace ASC.Core { var baseHost = BaseDomain; - if (string.IsNullOrEmpty(hostedRegion) || string.IsNullOrEmpty(baseHost) || !baseHost.Contains(".")) + if (string.IsNullOrEmpty(hostedRegion) || string.IsNullOrEmpty(baseHost) || baseHost.IndexOf('.') < 0) { return baseHost; } diff --git a/common/ASC.Core.Common/Core/DBResourceManager.cs b/common/ASC.Core.Common/Core/DBResourceManager.cs index 0a0395a6a0..88f41aa727 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -341,7 +341,7 @@ namespace TMResourceData { var newTextReplacement = newText; - if (resourceValue.Contains("<") && resourceValue.Contains(">") || resourceName.StartsWith("pattern_")) + if (resourceValue.IndexOf('<') >= 0 && resourceValue.IndexOf('>') >= 0 || resourceName.StartsWith("pattern_")) { newTextReplacement = HttpUtility.HtmlEncode(newTextReplacement); } diff --git a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs index 555266d412..8d887eebc0 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -277,13 +277,13 @@ namespace ASC.Notify.Cron break; } - if (exprOn == DayOfMonth && expr.IndexOf('L') != -1 && expr.Length > 1 && expr.IndexOf(",") >= 0) + if (exprOn == DayOfMonth && expr.IndexOf('L') != -1 && expr.Length > 1 && expr.IndexOf(',') >= 0) { 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.IndexOf('L') != -1 && expr.Length > 1 && expr.IndexOf(',') >= 0) { throw new FormatException( "Support for specifying 'L' with other days of the week is not implemented"); diff --git a/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs b/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs index 5ab25c5837..985cc18bbc 100644 --- a/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs +++ b/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs @@ -161,7 +161,7 @@ namespace ASC.Notify.Patterns static string ToUpper(string name) { - return name.Substring(0, 1).ToUpper() + name.Substring(1); + return name[0].ToString().ToUpper() + name.Substring(1); } } } diff --git a/common/ASC.Data.Storage/BaseStorage.cs b/common/ASC.Data.Storage/BaseStorage.cs index d3a0ade525..823a845089 100644 --- a/common/ASC.Data.Storage/BaseStorage.cs +++ b/common/ASC.Data.Storage/BaseStorage.cs @@ -141,7 +141,7 @@ namespace ASC.Data.Storage var auth = EmailValidationKeyProvider.GetEmailKey(currentTenantId, path.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar) + "." + headerAttr + "." + expireString); query = string.Format("{0}{1}={2}&{3}={4}", - path.Contains("?") ? "&" : "?", + path.IndexOf('?') >= 0 ? "&" : "?", Constants.QUERY_EXPIRE, expireString, Constants.QUERY_AUTH, @@ -151,7 +151,7 @@ namespace ASC.Data.Storage if (!string.IsNullOrEmpty(headerAttr)) { query += string.Format("{0}{1}={2}", - query.Contains("?") ? "&" : "?", + query.IndexOf('?') >= 0 ? "&" : "?", Constants.QUERY_HEADER, HttpUtility.UrlEncode(headerAttr)); } diff --git a/common/ASC.Notify.Textile/TextileStyler.cs b/common/ASC.Notify.Textile/TextileStyler.cs index 795f119e5a..baefd5ea3a 100644 --- a/common/ASC.Notify.Textile/TextileStyler.cs +++ b/common/ASC.Notify.Textile/TextileStyler.cs @@ -299,7 +299,7 @@ namespace ASC.Notify.Textile private string GetSiteUnsubscribeLink(NoticeMessage message, MailWhiteLabelSettings settings) { - var mail = message.Recipient.Addresses.FirstOrDefault(r => r.Contains("@")); + var mail = message.Recipient.Addresses.FirstOrDefault(r => r.Contains('@')); if (string.IsNullOrEmpty(mail)) return string.Empty; diff --git a/common/ASC.Textile/Blocks/NoTextileEncoder.cs b/common/ASC.Textile/Blocks/NoTextileEncoder.cs index 0da996cb69..e679ccd55d 100644 --- a/common/ASC.Textile/Blocks/NoTextileEncoder.cs +++ b/common/ASC.Textile/Blocks/NoTextileEncoder.cs @@ -39,7 +39,7 @@ namespace Textile.Blocks string evaluator(Match m) { var toEncode = m.Groups["notex"].Value; - if (toEncode == string.Empty) + if (toEncode.Length == 0) { return string.Empty; } diff --git a/common/ASC.Textile/Blocks/PhraseBlockModifier.cs b/common/ASC.Textile/Blocks/PhraseBlockModifier.cs index b789f9fb30..985c506815 100644 --- a/common/ASC.Textile/Blocks/PhraseBlockModifier.cs +++ b/common/ASC.Textile/Blocks/PhraseBlockModifier.cs @@ -35,7 +35,7 @@ namespace Textile.Blocks else if (modifier.Length == 2) { if (modifier[0] != '\\') - compressedModifier = modifier.Substring(0, 1); + compressedModifier = modifier[0].ToString(); //else: compressedModifier = modifier; } //else: compressedModifier = modifier; diff --git a/common/ASC.VoipService/Dao/AbstractDao.cs b/common/ASC.VoipService/Dao/AbstractDao.cs index 61b3602ff4..a051f4fb6a 100644 --- a/common/ASC.VoipService/Dao/AbstractDao.cs +++ b/common/ASC.VoipService/Dao/AbstractDao.cs @@ -54,7 +54,7 @@ namespace ASC.VoipService.Dao protected string GetTenantColumnName(string table) { const string tenant = "tenant_id"; - if (!table.Contains(" ")) return tenant; + if (!table.Contains(' ')) return tenant; return table.Substring(table.IndexOf(" ", StringComparison.Ordinal)).Trim() + "." + tenant; } diff --git a/common/services/ASC.ElasticSearch/Core/Selector.cs b/common/services/ASC.ElasticSearch/Core/Selector.cs index bdd8d0f133..72eabc0e72 100644 --- a/common/services/ASC.ElasticSearch/Core/Selector.cs +++ b/common/services/ASC.ElasticSearch/Core/Selector.cs @@ -341,7 +341,7 @@ namespace ASC.ElasticSearch if (string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(fieldSelector.Name) && - fieldSelector.Name.IndexOf(".", StringComparison.InvariantCulture) > 0) + fieldSelector.Name.IndexOf('.') > 0) { var splitted = fieldSelector.Name.Split(':')[1]; path = splitted.Split('.')[0]; @@ -372,7 +372,7 @@ namespace ASC.ElasticSearch private bool IsPhrase(string searchText) { - return searchText.Contains(" ") || searchText.Contains("\r\n") || searchText.Contains("\n"); + return searchText.Contains(' ') || searchText.Contains("\r\n") || searchText.Contains('\n'); } private bool IsExactlyPhrase(string searchText) @@ -440,7 +440,7 @@ namespace ASC.ElasticSearch { var result = value; - if (!value.Contains("*") && !value.Contains("?")) + if (!value.Contains('*') && !value.Contains('?')) { result = "*" + result + "*"; } diff --git a/products/ASC.CRM/Server/Classes/CSVReader.cs b/products/ASC.CRM/Server/Classes/CSVReader.cs index 636a5721c6..f1e71f2a0a 100644 --- a/products/ASC.CRM/Server/Classes/CSVReader.cs +++ b/products/ASC.CRM/Server/Classes/CSVReader.cs @@ -195,7 +195,7 @@ namespace ASC.Web.CRM.Classes } if (quoted) { - if (i > len || !currentLine.Substring(i, 1).StartsWith("\"")) + if (i > len || currentLine[i] != '\"') throw new FormatException("Invalid CSV format: " + currentLine.Substring(0, i)); i++; } diff --git a/products/ASC.CRM/Server/Core/Dao/AbstractDao.cs b/products/ASC.CRM/Server/Core/Dao/AbstractDao.cs index bf183d36be..13914a7b15 100644 --- a/products/ASC.CRM/Server/Core/Dao/AbstractDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/AbstractDao.cs @@ -300,9 +300,9 @@ namespace ASC.CRM.Core.Dao { var tenant = "tenant_id"; - if (!table.Contains(" ")) return tenant; + if (!table.Contains(' ')) return tenant; - return table.Substring(table.IndexOf(" ")).Trim() + "." + tenant; + return table.Substring(table.IndexOf(' ')).Trim() + "." + tenant; } protected static Guid ToGuid(object guid) diff --git a/products/ASC.Calendar/Server/iCalParser/Token.cs b/products/ASC.Calendar/Server/iCalParser/Token.cs index 22766b3bf5..4c09103c10 100644 --- a/products/ASC.Calendar/Server/iCalParser/Token.cs +++ b/products/ASC.Calendar/Server/iCalParser/Token.cs @@ -123,7 +123,7 @@ namespace ASC.Calendar.iCalParser { if (str.Length > 0) { - return CamelCase(str.Substring(0, 1).ToUpper() + str.Substring(1)); + return CamelCase(str[0].ToString().ToUpper() + str.Substring(1)); } else { diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs index 33ca8c75f7..7370d3b956 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs @@ -297,9 +297,9 @@ namespace ASC.Files.Thirdparty.Box if (!match.Success) { var insertIndex = requestTitle.Length; - if (requestTitle.LastIndexOf(".", StringComparison.InvariantCulture) != -1) + if (requestTitle.LastIndexOf('.') != -1) { - insertIndex = requestTitle.LastIndexOf(".", StringComparison.InvariantCulture); + insertIndex = requestTitle.LastIndexOf('.'); } requestTitle = requestTitle.Insert(insertIndex, " (1)"); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs index f94366f4b4..83329eaae8 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs @@ -289,9 +289,9 @@ namespace ASC.Files.Thirdparty.Dropbox if (!match.Success) { var insertIndex = requestTitle.Length; - if (requestTitle.LastIndexOf(".", StringComparison.InvariantCulture) != -1) + if (requestTitle.LastIndexOf('.') != -1) { - insertIndex = requestTitle.LastIndexOf(".", StringComparison.InvariantCulture); + insertIndex = requestTitle.LastIndexOf('.'); } requestTitle = requestTitle.Insert(insertIndex, " (1)"); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs index 2a1f454dc4..a905fbf23c 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs @@ -253,9 +253,9 @@ namespace ASC.Files.Thirdparty.OneDrive if (!match.Success) { var insertIndex = requestTitle.Length; - if (requestTitle.LastIndexOf(".", StringComparison.InvariantCulture) != -1) + if (requestTitle.LastIndexOf('.') != -1) { - insertIndex = requestTitle.LastIndexOf(".", StringComparison.InvariantCulture); + insertIndex = requestTitle.LastIndexOf('.'); } requestTitle = requestTitle.Insert(insertIndex, " (1)"); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoBase.cs index c193facc12..002d6bedba 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoBase.cs @@ -63,9 +63,9 @@ namespace ASC.Files.Thirdparty.SharePoint if (!match.Success) { var insertIndex = requestTitle.Length; - if (requestTitle.LastIndexOf(".", StringComparison.Ordinal) != -1) + if (requestTitle.LastIndexOf('.') != -1) { - insertIndex = requestTitle.LastIndexOf(".", StringComparison.Ordinal); + insertIndex = requestTitle.LastIndexOf('.'); } requestTitle = requestTitle.Insert(insertIndex, " (1)"); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs index 9e4b374fee..8fd12c9e2f 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs @@ -114,7 +114,7 @@ namespace ASC.Files.Thirdparty.SharePoint if (authData.Login.EndsWith("onmicrosoft.com")) { - var personalPath = string.Concat("/personal/", authData.Login.Replace("@", "_").Replace(".", "_").ToLower()); + var personalPath = string.Concat("/personal/", authData.Login.Replace('@', '_').Replace('.', '_').ToLower()); SpRootFolderId = string.Concat(personalPath, "/Documents"); var ss = new SecureString(); diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs index 2216330cea..1d8f659a00 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs @@ -446,9 +446,9 @@ namespace ASC.Files.Thirdparty.Sharpbox if (!match.Success) { var insertIndex = requestTitle.Length; - if (requestTitle.LastIndexOf(".", StringComparison.InvariantCulture) != -1) + if (requestTitle.LastIndexOf('.') != -1) { - insertIndex = requestTitle.LastIndexOf(".", StringComparison.InvariantCulture); + insertIndex = requestTitle.LastIndexOf('.'); } requestTitle = requestTitle.Insert(insertIndex, " (1)"); } diff --git a/web/ASC.Web.Api/Controllers/ThirdPartyController.cs b/web/ASC.Web.Api/Controllers/ThirdPartyController.cs index 65c975614c..5808c024bf 100644 --- a/web/ASC.Web.Api/Controllers/ThirdPartyController.cs +++ b/web/ASC.Web.Api/Controllers/ThirdPartyController.cs @@ -140,7 +140,7 @@ namespace ASC.Web.Api.Controllers private static string AppendCode(string url, string code = null, string error = null) { - url += (url.Contains("#") ? "&" : "#") + url += (url.Contains('#') ? "&" : "#") + (string.IsNullOrEmpty(error) ? (string.IsNullOrEmpty(code) ? string.Empty diff --git a/web/ASC.Web.Core/Extensions/StringExtension.cs b/web/ASC.Web.Core/Extensions/StringExtension.cs index 126cc5569f..fdee36c266 100644 --- a/web/ASC.Web.Core/Extensions/StringExtension.cs +++ b/web/ASC.Web.Core/Extensions/StringExtension.cs @@ -52,7 +52,7 @@ namespace System /// public static string ReplaceSingleQuote(this string str) { - return str?.Replace("'", "′"); + return str?.Replace('\'', '′'); } public static bool TestEmailRegex(this string emailAddress) diff --git a/web/ASC.Web.Core/Files/DocumentService.cs b/web/ASC.Web.Core/Files/DocumentService.cs index 1650337130..73f1bbee1b 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -118,7 +118,7 @@ namespace ASC.Web.Core.Files if (string.IsNullOrEmpty(toExtension)) throw new ArgumentNullException("toExtension", "Extension for conversion is not known"); var title = Path.GetFileName(documentUri ?? ""); - title = string.IsNullOrEmpty(title) || title.Contains("?") ? Guid.NewGuid().ToString() : title; + title = string.IsNullOrEmpty(title) || title.Contains('?') ? Guid.NewGuid().ToString() : title; documentRevisionId = string.IsNullOrEmpty(documentRevisionId) ? documentUri diff --git a/web/ASC.Web.Core/Users/UserManagerWrapper.cs b/web/ASC.Web.Core/Users/UserManagerWrapper.cs index 0b058d1ffc..234745d495 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -302,7 +302,7 @@ namespace ASC.Web.Core.Users var pwd = string.Empty; while (length-- > 0) { - pwd += noise.Substring(RandomNumberGenerator.GetInt32(noise.Length - 1), 1); + pwd += noise[RandomNumberGenerator.GetInt32(noise.Length - 1)]; } return pwd; } diff --git a/web/ASC.Web.Core/Utility/Skins/WebImageSupplier.cs b/web/ASC.Web.Core/Utility/Skins/WebImageSupplier.cs index 8bffe180c5..40036983ee 100644 --- a/web/ASC.Web.Core/Utility/Skins/WebImageSupplier.cs +++ b/web/ASC.Web.Core/Utility/Skins/WebImageSupplier.cs @@ -111,8 +111,8 @@ namespace ASC.Web.Core.Utility.Skins return string.Empty; } - var dir = webitem.StartURL.Contains(".") ? - webitem.StartURL.Substring(0, webitem.StartURL.LastIndexOf("/")) : + var dir = webitem.StartURL.Contains('.') ? + webitem.StartURL.Substring(0, webitem.StartURL.LastIndexOf('/')) : webitem.StartURL.TrimEnd('/'); return dir + "/App_Themes"; } From 4bf841581f44795102dd8a19119e2e72660cbd3d Mon Sep 17 00:00:00 2001 From: SuhorukovAnton Date: Fri, 14 Jan 2022 16:12:37 +0300 Subject: [PATCH 042/167] Analizators/U2U1104 --- .../Collections/CachedDictionaryBase.cs | 2 +- .../ASC.Common/Logging/SelfCleaningTarget.cs | 2 +- .../Authorizing/AuthorizingException.cs | 15 +-- .../Security/Authorizing/Domain/Role.cs | 2 +- common/ASC.Common/Utils/HtmlUtil.cs | 2 +- common/ASC.Common/Utils/MailAddressUtils.cs | 2 +- .../TimeZoneConverter/TimeZoneConverter.cs | 4 +- .../ASC.Core.Common/Billing/BillingClient.cs | 4 +- .../ASC.Core.Common/Billing/CouponManager.cs | 10 +- .../ASC.Core.Common/Billing/TariffService.cs | 4 +- .../Context/Impl/PaymentManager.cs | 2 +- .../ASC.Core.Common/Core/DBResourceManager.cs | 2 +- common/ASC.Core.Common/Core/UserInfo.cs | 4 +- .../Notify/Channels/SenderChannel.cs | 2 +- common/ASC.Core.Common/Notify/Context.cs | 2 +- .../Notify/Cron/CronExpression.cs | 15 +-- .../Notify/Engine/NotifyEngine.cs | 4 +- .../Notify/Engine/NotifyRequest.cs | 2 +- .../Notify/Model/NotifyAction.cs | 2 +- common/ASC.Core.Common/Notify/NotifySource.cs | 4 +- .../Patterns/NVelocityPatternFormatter.cs | 4 +- .../Notify/Patterns/XmlPatternProvider2.cs | 2 +- .../Notify/Recipients/DirectRecipient.cs | 2 +- .../Notify/Recipients/RecipientsGroup.cs | 2 +- .../Notify/ReplyToTagProvider.cs | 2 +- .../Notify/Senders/SmtpSender.cs | 16 ++-- .../Notify/Signalr/SignalrServiceClient.cs | 4 +- .../Notify/Telegram/TelegramHelper.cs | 2 +- common/ASC.Core.Common/Tenants/Tenant.cs | 2 +- .../Core/DbBackupProvider.cs | 4 +- common/ASC.Data.Backup.Core/Core/DbHelper.cs | 6 +- .../Core/FileBackupProvider.cs | 2 +- .../Exceptions/ThrowHelper.cs | 12 +-- .../Tasks/BackupPortalTask.cs | 16 ++-- .../Tasks/ColumnMapper.cs | 2 +- .../Tasks/Data/DataRowInfo.cs | 2 +- .../ASC.Data.Backup.Core/Tasks/KeyHelper.cs | 12 +-- .../Tasks/Modules/ModuleSpecificsBase.cs | 12 +-- .../Tasks/PortalTaskBase.cs | 10 +- .../Tasks/RestoreDbModuleTask.cs | 2 +- .../Tasks/TransferPortalTask.cs | 17 ++-- common/ASC.Data.Encryption/Crypt.cs | 4 +- common/ASC.Data.Storage/BaseStorage.cs | 12 +-- .../DiscStorage/DiscDataStore.cs | 4 +- .../Encryption/EncryptionOperation.cs | 4 +- .../GoogleCloud/GoogleCloudStorage.cs | 20 ++-- common/ASC.Data.Storage/PathUtils.cs | 4 +- .../RackspaceCloud/RackspaceCloudStorage.cs | 18 ++-- common/ASC.Data.Storage/S3/S3Storage.cs | 96 +++++++++---------- .../ASC.Data.Storage/TenantQuotaController.cs | 2 +- common/ASC.Data.Storage/WebPath.cs | 12 +-- .../Helpers/OAuth20TokenHelper.cs | 10 +- .../ASC.FederatedLogin/Helpers/XrdsHelper.cs | 13 ++- .../LoginProviders/DocuSignLoginProvider.cs | 6 +- .../LoginProviders/FacebookLoginProvider.cs | 2 +- .../MultiRegionAccountLinker.cs | 2 +- .../Profile/LoginProfile.cs | 5 +- common/ASC.Feed/Core/Feed.cs | 2 +- .../DbSender/MessagesRepository.cs | 4 +- common/ASC.Notify.Textile/JabberStyler.cs | 2 +- .../Blocks/HyperLinkBlockModifier.cs | 2 +- common/ASC.Textile/Blocks/NoTextileEncoder.cs | 4 +- .../States/HeaderFormatterState.cs | 6 +- .../ASC.Textile/States/ListFormatterState.cs | 2 +- .../States/TableRowFormatterState.cs | 2 +- common/ASC.VoipService/Dao/VoipDao.cs | 2 +- .../ASC.ApiSystem/Classes/CommonMethods.cs | 16 +--- .../Controllers/CalDavController.cs | 21 ++-- .../Controllers/PortalController.cs | 2 +- .../Mappers/AuditActionMapper.cs | 2 +- .../ASC.ElasticSearch/Engine/BaseIndexer.cs | 10 +- .../SocketServiceLauncher.cs | 4 +- common/services/ASC.SsoAuth.Svc/Launcher.cs | 2 +- .../services/ASC.TelegramService/Core/Core.cs | 2 +- .../ThumbnailsServiceLauncher.cs | 2 +- .../UrlShortenerService.cs | 2 +- .../Api/RelationshipEventsController.cs | 4 +- .../Server/Classes/InvoiceFormattedData.cs | 8 +- .../Server/Classes/LocalizedEnumConverter.cs | 4 +- .../Server/Core/Dao/DealMilestoneDao.cs | 4 +- .../ASC.CRM/Server/Core/Dao/ListItemDao.cs | 16 ++-- products/ASC.CRM/Server/Core/Dao/ReportDao.cs | 9 +- products/ASC.CRM/Server/Core/Dao/SearchDao.cs | 2 +- .../ASC.CRM/Server/Core/Entities/Contact.cs | 2 +- .../WebToLeadFromHandlerMiddleware.cs | 6 +- .../ASC.CRM/Server/Utils/CurrencyProvider.cs | 9 +- products/ASC.CRM/Server/Utils/ExportToCSV.cs | 12 +-- products/ASC.CRM/Server/Utils/MailSender.cs | 4 +- products/ASC.CRM/Server/Utils/PdfCreator.cs | 4 +- products/ASC.CRM/Server/Utils/ReportHelper.cs | 5 +- .../Server/BusinessObjects/DataProvider.cs | 2 +- .../Server/Controllers/CalendarController.cs | 30 +++--- .../Core/Core/Dao/TeamlabDao/FileDao.cs | 2 +- .../Core/Core/Dao/TeamlabDao/FolderDao.cs | 4 +- .../Core/Core/Thirdparty/Box/BoxDaoBase.cs | 5 +- .../Core/Thirdparty/Dropbox/DropboxDaoBase.cs | 5 +- .../GoogleDrive/GoogleDriveDaoBase.cs | 5 +- .../GoogleDrive/GoogleDriveStorage.cs | 12 +-- .../Thirdparty/OneDrive/OneDriveDaoBase.cs | 6 +- .../SharePoint/SharePointProviderInfo.cs | 5 +- .../Thirdparty/Sharpbox/SharpBoxDaoBase.cs | 6 +- .../DocumentServiceConnector.cs | 2 +- .../DocumentService/DocumentServiceHelper.cs | 4 +- .../DocumentService/DocumentServiceTracker.cs | 5 +- .../FileOperations/FileDownloadOperation.cs | 2 +- .../ASC.Files/Core/ThirdPartyApp/BoxApp.cs | 8 +- .../Core/ThirdPartyApp/GoogleDriveApp.cs | 19 ++-- .../ASC.Files/Core/Utils/FileConverter.cs | 4 +- .../ASC.Files/Core/Utils/MailMergeTask.cs | 4 +- .../ASC.Files/Service/Core/FilesModule.cs | 4 +- .../ASC.Files/Service/Core/FoldersModule.cs | 4 +- .../Server/Controllers/PeopleController.cs | 2 +- .../Controllers/CapabilitiesController.cs | 3 +- .../Controllers/SettingsController.cs | 4 +- web/ASC.Web.Core/Calendars/BaseCalendar.cs | 6 +- web/ASC.Web.Core/Calendars/BaseEvent.cs | 29 ++++-- web/ASC.Web.Core/Calendars/BaseTodo.cs | 26 +++-- web/ASC.Web.Core/Calendars/RecurrenceRule.cs | 14 +-- .../Extensions/UserInfoExtension.cs | 6 +- web/ASC.Web.Core/FileSizeComment.cs | 4 +- web/ASC.Web.Core/Helpers/ApiSystemHelper.cs | 10 +- .../Helpers/ResourceEnumConverter.cs | 4 +- .../Notify/NotifyConfiguration.cs | 2 +- .../Notify/StudioNotifyService.cs | 3 +- .../Notify/StudioPeriodicNotify.cs | 8 +- web/ASC.Web.Core/Notify/TagValues.cs | 43 +++------ web/ASC.Web.Core/Recaptcha.cs | 2 +- web/ASC.Web.Core/Users/UserManagerWrapper.cs | 18 ++-- web/ASC.Web.Core/Utility/UrlShortener.cs | 2 +- web/ASC.Web.Core/WebItemManager.cs | 2 +- .../WhiteLabel/TenantWhiteLabelSettings.cs | 2 +- 131 files changed, 423 insertions(+), 516 deletions(-) diff --git a/common/ASC.Common/Collections/CachedDictionaryBase.cs b/common/ASC.Common/Collections/CachedDictionaryBase.cs index 6ffa5009ce..68de00e0df 100644 --- a/common/ASC.Common/Collections/CachedDictionaryBase.cs +++ b/common/ASC.Common/Collections/CachedDictionaryBase.cs @@ -89,7 +89,7 @@ namespace ASC.Collections protected string BuildKey(string key, string rootkey) { - return string.Format("{0}-{1}-{2}", baseKey, rootkey, key); + return $"{baseKey}-{rootkey}-{key}"; } protected abstract object GetObjectFromCache(string fullKey); diff --git a/common/ASC.Common/Logging/SelfCleaningTarget.cs b/common/ASC.Common/Logging/SelfCleaningTarget.cs index bcf43b3c17..613c1dd405 100644 --- a/common/ASC.Common/Logging/SelfCleaningTarget.cs +++ b/common/ASC.Common/Logging/SelfCleaningTarget.cs @@ -111,7 +111,7 @@ namespace ASC.Common.Logging { Exception = err, Level = LogLevel.Error, - Message = string.Format("file: {0}, dir: {1}, mess: {2}", filePath, dirPath, err.Message), + Message = $"file: {filePath}, dir: {dirPath}, mess: {err.Message}", LoggerName = "SelfCleaningTarget" }); } diff --git a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs index 952ce41661..3f980fb994 100644 --- a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs +++ b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs @@ -104,25 +104,16 @@ namespace ASC.Common.Security.Authorizing string reason; if (denySubject != null && denyAction != null) - reason = string.Format("{0}:{1} access denied {2}.", - action.Name, - (denySubject is IRole ? "role:" : "") + denySubject.Name, - denyAction.Name - ); + reason = $"{action.Name}:{(denySubject is IRole ? "role:" : "") + denySubject.Name} access denied {denyAction.Name}."; else - reason = string.Format("{0}: access denied.", action.Name); + reason = $"{action.Name}: access denied."; if (i != actions.Length - 1) reason += ", "; reasons += reason; } var sactions = ""; Array.ForEach(actions, action => { sactions += action.ToString() + ", "; }); - var message = string.Format( - "\"{0}\" access denied \"{1}\". Cause: {2}.", - (subject is IRole ? "role:" : "") + subject.Name, - sactions, - reasons - ); + var message = $"\"{(subject is IRole ? "role:" : "") + subject.Name}\" access denied \"{sactions}\". Cause: {reasons}."; return message; } } diff --git a/common/ASC.Common/Security/Authorizing/Domain/Role.cs b/common/ASC.Common/Security/Authorizing/Domain/Role.cs index df93ff3b94..3099de7f86 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Role.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Role.cs @@ -75,7 +75,7 @@ namespace ASC.Common.Security.Authorizing public override string ToString() { - return string.Format("Role: {0}", Name); + return $"Role: {Name}"; } } } \ No newline at end of file diff --git a/common/ASC.Common/Utils/HtmlUtil.cs b/common/ASC.Common/Utils/HtmlUtil.cs index c301c43ae4..ff90d5e5bb 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -104,7 +104,7 @@ namespace ASC.Common.Utils var regexpstr = Worder.Matches(searchText).Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); var wordsFinder = new Regex(Regex.Escape(regexpstr), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline); - return wordsFinder.Replace(htmlText, m => string.Format("{0}", m.Value, withoutLink ? " bold" : string.Empty)); + return wordsFinder.Replace(htmlText, m => "{0}"); } } } \ No newline at end of file diff --git a/common/ASC.Common/Utils/MailAddressUtils.cs b/common/ASC.Common/Utils/MailAddressUtils.cs index 96ef7ea071..a8c08b9c07 100644 --- a/common/ASC.Common/Utils/MailAddressUtils.cs +++ b/common/ASC.Common/Utils/MailAddressUtils.cs @@ -66,7 +66,7 @@ namespace ASC.Common.Utils private static string ToSmtpAddress(string address, string displayName) { - return string.Format("\"{0}\" <{1}>", displayName, address); + return $"\"{displayName}\" <{address}>"; } } } diff --git a/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs b/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs index 6a3ab2d8dd..28be6abef0 100644 --- a/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs +++ b/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs @@ -122,7 +122,7 @@ namespace ASC.Common.Utils if (mapZone != null) return mapZone.WindowsTimeZoneId; - Log.Error(string.Format("OlsonTimeZone {0} not found", olsonTimeZoneId)); + Log.Error("OlsonTimeZone " + olsonTimeZoneId + " not found"); return defaultIfNoMatch ? "UTC" : null; } @@ -139,7 +139,7 @@ namespace ASC.Common.Utils if (mapZone != null) return mapZone.OlsonTimeZoneId; - Log.Error(string.Format("WindowsTimeZone {0} not found", windowsTimeZoneId)); + Log.Error("WindowsTimeZone " + windowsTimeZoneId + " not found"); return defaultIfNoMatch ? "Etc/GMT" : null; } diff --git a/common/ASC.Core.Common/Billing/BillingClient.cs b/common/ASC.Core.Common/Billing/BillingClient.cs index 406b7edbec..dd07b0f168 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -212,7 +212,7 @@ namespace ASC.Core.Billing { var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss"); var hash = WebEncoders.Base64UrlEncode(hasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("\n", now, pkey)))); - return string.Format("ASC {0}:{1}:{2}", pkey, now, hash); + return "ASC " + pkey + ":" + now + ":" + hash; } } @@ -273,7 +273,7 @@ namespace ASC.Core.Billing return result; } - var @params = parameters.Select(p => string.Format("{0}: {1}", p.Item1, p.Item2)); + var @params = parameters.Select(p => p.Item1 + ": " + p.Item2); var info = new { Method = method, PortalId = portalId, Params = string.Join(", ", @params) }; if (result.Contains("{\"Message\":\"error: cannot find ")) { diff --git a/common/ASC.Core.Common/Billing/CouponManager.cs b/common/ASC.Core.Common/Billing/CouponManager.cs index c5f433355e..9fd7056160 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -101,7 +101,7 @@ namespace ASC.Core.Common.Billing { using var httpClient = PrepaireClient(); using var content = new StringContent(await Promotion.GeneratePromotion(Log, this, tenantManager, Percent, Schedule), Encoding.Default, "application/json"); - using var response = await httpClient.PostAsync(string.Format("{0}/promotions/", ApiVersion), content); + using var response = await httpClient.PostAsync($"{ApiVersion}/promotions/", content); if (!response.IsSuccessStatusCode) throw new Exception(response.ReasonPhrase); @@ -136,7 +136,7 @@ namespace ASC.Core.Common.Billing try { using var httpClient = PrepaireClient(); - using var response = await httpClient.GetAsync(string.Format("{0}/products/?Limit=1000&Enabled=true", ApiVersion)); + using var response = await httpClient.GetAsync($"{ApiVersion}/products/?Limit=1000&Enabled=true"); if (!response.IsSuccessStatusCode) throw new Exception(response.ReasonPhrase); @@ -186,9 +186,9 @@ namespace ASC.Core.Common.Billing } var stringBuilder = new StringBuilder(); - stringBuilder.AppendFormat("code='{0}' ", VendorCode); - stringBuilder.AppendFormat("date='{0}' ", date); - stringBuilder.AppendFormat("hash='{0}'", sBuilder); + stringBuilder.Append($"code='{VendorCode}' "); + stringBuilder.Append($"date='{date}' "); + stringBuilder.Append($"hash='{sBuilder}'"); return stringBuilder.ToString(); } } diff --git a/common/ASC.Core.Common/Billing/TariffService.cs b/common/ASC.Core.Common/Billing/TariffService.cs index 5deee5f5c1..8bfd0c5d51 100644 --- a/common/ASC.Core.Common/Billing/TariffService.cs +++ b/common/ASC.Core.Common/Billing/TariffService.cs @@ -239,7 +239,7 @@ namespace ASC.Core.Billing var quota = QuotaService.GetTenantQuotas().SingleOrDefault(q => q.AvangateId == lastPayment.ProductId); if (quota == null) { - throw new InvalidOperationException(string.Format("Quota with id {0} not found for portal {1}.", lastPayment.ProductId, GetPortalId(tenantId))); + throw new InvalidOperationException($"Quota with id {lastPayment.ProductId} not found for portal {GetPortalId(tenantId)}."); } var asynctariff = Tariff.CreateDefault(); @@ -362,7 +362,7 @@ namespace ASC.Core.Billing var key = tenant.HasValue ? GetBillingUrlCacheKey(tenant.Value) - : string.Format("notenant{0}", !string.IsNullOrEmpty(affiliateId) ? "_" + affiliateId : ""); + : string.Format($"notenant{(!string.IsNullOrEmpty(affiliateId) ? "_" + affiliateId : "")}"); key += quota.Visible ? "" : "0"; if (!(Cache.Get>>(key) is IDictionary> urls)) { diff --git a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs index e6f1c09317..12dcf9a966 100644 --- a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs +++ b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs @@ -135,7 +135,7 @@ namespace ASC.Core var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture); var data = string.Join("\n", now, "/api/" + url.TrimStart('/')); //data: UTC DateTime (yyyy:MM:dd HH:mm:ss) + \n + url var hash = WebEncoders.Base64UrlEncode(hasher.ComputeHash(Encoding.UTF8.GetBytes(data))); - return string.Format("ASC :{0}:{1}", now, hash); + return $"ASC :{now}:{hash}"; } } diff --git a/common/ASC.Core.Common/Core/DBResourceManager.cs b/common/ASC.Core.Common/Core/DBResourceManager.cs index 88f41aa727..b14ad1bba9 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -248,7 +248,7 @@ namespace TMResourceData private Dictionary GetResources() { - var key = string.Format("{0}/{1}", filename, culture); + var key = $"{filename}/{culture}"; if (!(cache.Get(key) is Dictionary dic)) { lock (locker) diff --git a/common/ASC.Core.Common/Core/UserInfo.cs b/common/ASC.Core.Common/Core/UserInfo.cs index 4bd972457d..d13357cdf6 100644 --- a/common/ASC.Core.Common/Core/UserInfo.cs +++ b/common/ASC.Core.Common/Core/UserInfo.cs @@ -112,7 +112,7 @@ namespace ASC.Core.Users public override string ToString() { - return string.Format("{0} {1}", FirstName, LastName).Trim(); + return $"{FirstName} {LastName}".Trim(); } public override int GetHashCode() @@ -168,7 +168,7 @@ namespace ASC.Core.Users var sBuilder = new StringBuilder(); foreach (var contact in ContactsList) { - sBuilder.AppendFormat("{0}|", contact); + sBuilder.Append($"{contact}|"); } return sBuilder.ToString(); } diff --git a/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs b/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs index 5f83c54ac8..ead6ec0a20 100644 --- a/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs +++ b/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs @@ -50,7 +50,7 @@ namespace ASC.Notify.Channels this.context = context ?? throw new ArgumentNullException("context"); this.SenderName = senderName ?? throw new ArgumentNullException("senderName"); this.firstSink = decorateSink; - this.senderSink = senderSink ?? throw new ApplicationException(string.Format("channel with tag {0} not created sender sink", senderName)); + this.senderSink = senderSink ?? throw new ApplicationException($"channel with tag {senderName} not created sender sink"); var dispatcherSink = new DispatchSink(SenderName, this.context.DispatchEngine); this.firstSink = AddSink(firstSink, dispatcherSink); diff --git a/common/ASC.Core.Common/Notify/Context.cs b/common/ASC.Core.Common/Notify/Context.cs index c99517a4b5..f158e3035f 100644 --- a/common/ASC.Core.Common/Notify/Context.cs +++ b/common/ASC.Core.Common/Notify/Context.cs @@ -131,7 +131,7 @@ namespace ASC.Notify var pattern = source.GetPatternProvider().GetPattern(a, s); if (pattern == null) { - throw new NotifyException(string.Format("In notify source {0} pattern not found for action {1} and sender {2}", source.ID, a.ID, s)); + throw new NotifyException($"In notify source {source.ID} pattern not found for action {a.ID} and sender {s}"); } } catch (Exception error) diff --git a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs index 8d887eebc0..93111a8164 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -350,8 +350,7 @@ namespace ASC.Notify.Cron sval = GetMonthNumber(sub) + 1; if (sval <= 0) { - throw new FormatException(string.Format(CultureInfo.InvariantCulture, - "Invalid Month value: '{0}'", sub)); + throw new FormatException($"Invalid Month value: '{sub}'"); } if (s.Length > i + 3) { @@ -363,8 +362,7 @@ namespace ASC.Notify.Cron eval = GetMonthNumber(sub) + 1; if (eval <= 0) { - throw new FormatException( - string.Format(CultureInfo.InvariantCulture, "Invalid Month value: '{0}'", sub)); + throw new FormatException($"Invalid Month value: '{sub}'"); } } } @@ -374,8 +372,7 @@ namespace ASC.Notify.Cron sval = GetDayOfWeekNumber(sub); if (sval < 0) { - throw new FormatException(string.Format(CultureInfo.InvariantCulture, - "Invalid Day-of-Week value: '{0}'", sub)); + throw new FormatException($"Invalid Day-of-Week value: '{sub}'"); } if (s.Length > i + 3) { @@ -387,8 +384,7 @@ namespace ASC.Notify.Cron eval = GetDayOfWeekNumber(sub); if (eval < 0) { - throw new FormatException( - string.Format(CultureInfo.InvariantCulture, "Invalid Day-of-Week value: '{0}'", sub)); + throw new FormatException($"Invalid Day-of-Week value: '{sub}'"); } } else if (c == '#') @@ -417,8 +413,7 @@ namespace ASC.Notify.Cron } else { - throw new FormatException( - string.Format(CultureInfo.InvariantCulture, "Illegal characters for this position: '{0}'", sub)); + throw new FormatException($"Illegal characters for this position: '{sub}'"); } if (eval != -1) { diff --git a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs index 9e30f75da1..f031c7b886 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -386,7 +386,7 @@ namespace ASC.Notify.Engine } else { - response = new SendResponse(request.NotifyAction, sendertag, request.Recipient, new NotifyException(string.Format("Not registered sender \"{0}\".", sendertag))); + response = new SendResponse(request.NotifyAction, sendertag, request.Recipient, new NotifyException($"Not registered sender \"{sendertag}\".")); } responses.Add(response); } @@ -535,7 +535,7 @@ namespace ASC.Notify.Engine pattern = apProvider.GetPattern(request.NotifyAction, senderName); } - request.Patterns[i] = pattern ?? throw new NotifyException(string.Format("For action \"{0}\" by sender \"{1}\" no one patterns getted.", request.NotifyAction.ID, senderName)); + request.Patterns[i] = pattern ?? throw new NotifyException($"For action \"{request.NotifyAction.ID}\" by sender \"{senderName}\" no one patterns getted."); } } } diff --git a/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs b/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs index 12ae7ef5c3..1e34ce40cf 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs @@ -118,7 +118,7 @@ namespace ASC.Notify.Engine var index = Array.IndexOf(SenderNames, senderName); if (index < 0) { - throw new ApplicationException(string.Format("Sender with tag {0} dnot found", senderName)); + throw new ApplicationException($"Sender with tag {senderName} dnot found"); } return Patterns[index]; } diff --git a/common/ASC.Core.Common/Notify/Model/NotifyAction.cs b/common/ASC.Core.Common/Notify/Model/NotifyAction.cs index 58318c2f44..ec0a449c6c 100644 --- a/common/ASC.Core.Common/Notify/Model/NotifyAction.cs +++ b/common/ASC.Core.Common/Notify/Model/NotifyAction.cs @@ -69,7 +69,7 @@ namespace ASC.Notify.Model public override string ToString() { - return string.Format("action: {0}", ID); + return $"action: {ID}"; } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Notify/NotifySource.cs b/common/ASC.Core.Common/Notify/NotifySource.cs index 4a15992042..76917bcb21 100644 --- a/common/ASC.Core.Common/Notify/NotifySource.cs +++ b/common/ASC.Core.Common/Notify/NotifySource.cs @@ -132,12 +132,12 @@ namespace ASC.Core.Notify { var subscriptionProvider = new DirectSubscriptionProvider(ID, SubscriptionManager, RecipientsProvider); return new TopSubscriptionProvider(RecipientsProvider, subscriptionProvider, WorkContext.DefaultClientSenders) ?? - throw new NotifyException(string.Format("Provider {0} not instanced.", "ISubscriprionProvider")); + throw new NotifyException("Provider ISubscriprionProvider not instanced."); } protected virtual IRecipientProvider CreateRecipientsProvider() { - return new RecipientProviderImpl(UserManager) ?? throw new NotifyException(string.Format("Provider {0} not instanced.", "IRecipientsProvider")); + return new RecipientProviderImpl(UserManager) ?? throw new NotifyException("Provider IRecipientsProvider not instanced."); } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs b/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs index 486fbf9e3f..1224a50232 100644 --- a/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs +++ b/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs @@ -79,9 +79,9 @@ namespace ASC.Notify.Patterns e.NewValue = string.Empty; for (var i = 0; i < lines.Length - 1; i++) { - e.NewValue += string.Format("{0}{1}{2}\n", NoStylePreffix, lines[i], NoStyleSuffix); + e.NewValue += $"{NoStylePreffix}{lines[i]}{NoStyleSuffix}\n"; } - e.NewValue += string.Format("{0}{1}{2}", NoStylePreffix, lines[^1], NoStyleSuffix); + e.NewValue += $"{NoStylePreffix}{lines[^1]}{NoStyleSuffix}"; } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs b/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs index 985cc18bbc..d15a021e9f 100644 --- a/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs +++ b/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs @@ -155,7 +155,7 @@ namespace ASC.Notify.Patterns resourceManagerType.GetProperty(ToUpper(array[0]), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); if (property == null) { - throw new NotifyException(string.Format("Resource {0} not found in resourceManager {1}", array[0], array[1])); + throw new NotifyException($"Resource {array[0]} not found in resourceManager {array[1]}"); } return property.GetValue(resourceManagerType, null) as string; diff --git a/common/ASC.Core.Common/Notify/Recipients/DirectRecipient.cs b/common/ASC.Core.Common/Notify/Recipients/DirectRecipient.cs index 17c8447f0e..39020b3bc7 100644 --- a/common/ASC.Core.Common/Notify/Recipients/DirectRecipient.cs +++ b/common/ASC.Core.Common/Notify/Recipients/DirectRecipient.cs @@ -88,7 +88,7 @@ namespace ASC.Notify.Recipients public override string ToString() { - return string.Format("{0}({1})", Name, string.Join(";", _Addresses.ToArray())); + return $"{Name}({string.Join(";", _Addresses.ToArray())})"; } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Notify/Recipients/RecipientsGroup.cs b/common/ASC.Core.Common/Notify/Recipients/RecipientsGroup.cs index bef149944a..5baddc025e 100644 --- a/common/ASC.Core.Common/Notify/Recipients/RecipientsGroup.cs +++ b/common/ASC.Core.Common/Notify/Recipients/RecipientsGroup.cs @@ -59,7 +59,7 @@ namespace ASC.Notify.Recipients public override string ToString() { - return string.Format("{0}", Name); + return Name; } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Notify/ReplyToTagProvider.cs b/common/ASC.Core.Common/Notify/ReplyToTagProvider.cs index 8a2f746cc1..f213453691 100644 --- a/common/ASC.Core.Common/Notify/ReplyToTagProvider.cs +++ b/common/ASC.Core.Common/Notify/ReplyToTagProvider.cs @@ -71,7 +71,7 @@ namespace ASC.Core.Common.Notify if (string.IsNullOrEmpty(entityId)) throw new ArgumentException(@"Entity Id is null or empty", entityId); var pId = parentId != Guid.Empty.ToString() && parentId != null ? parentId : string.Empty; - return new TagValue(TagName, string.Format("reply_{0}_{1}_{2}@{3}", entity, entityId, pId, AutoreplyDomain)); + return new TagValue(TagName, $"reply_{entity}_{entityId}_{pId}@{AutoreplyDomain}"); } /// diff --git a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs index 059a69b4da..370e579f66 100644 --- a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs @@ -48,14 +48,6 @@ namespace ASC.Core.Notify.Senders [Singletone(Additional = typeof(SmtpSenderExtension))] public class SmtpSender : INotifySender { - private const string HTML_FORMAT = - @" - - - - -{0} -"; protected ILog Log { get; set; } protected IConfiguration Configuration { get; } @@ -276,7 +268,13 @@ namespace ASC.Core.Notify.Senders protected string GetHtmlView(string body) { - return string.Format(HTML_FORMAT, body); + return $@" + + + + +{body} +"; } private MailKit.Net.Smtp.SmtpClient GetSmtpClient() diff --git a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs index 9fcfc9d569..558fd6a282 100644 --- a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs @@ -397,7 +397,7 @@ namespace ASC.Core.Notify.Signalr private string GetMethod(string method) { - return string.Format("{0}/controller/{1}/{2}", Url.TrimEnd('/'), hub, method); + return $"{Url.TrimEnd('/')}/controller/{hub}/{method}"; } public string CreateAuthToken(string pkey = "socketio") @@ -405,7 +405,7 @@ namespace ASC.Core.Notify.Signalr using var hasher = new HMACSHA1(SKey); var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss"); var hash = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("\n", now, pkey)))); - return string.Format("ASC {0}:{1}:{2}", pkey, now, hash); + return $"ASC {pkey}:{now}:{hash}"; } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs b/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs index 0dbf3d8069..295aa0f391 100644 --- a/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs +++ b/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs @@ -149,7 +149,7 @@ namespace ASC.Core.Common.Notify var botname = tgProvider == null ? default : tgProvider.TelegramBotName; if (string.IsNullOrEmpty(botname)) return null; - return string.Format("t.me/{0}?start={1}", botname, token); + return $"t.me/{botname}?start={token}"; } public bool TestingClient(TelegramBotClient telegramBotClient) diff --git a/common/ASC.Core.Common/Tenants/Tenant.cs b/common/ASC.Core.Common/Tenants/Tenant.cs index b074f96120..df277d6afd 100644 --- a/common/ASC.Core.Common/Tenants/Tenant.cs +++ b/common/ASC.Core.Common/Tenants/Tenant.cs @@ -181,7 +181,7 @@ namespace ASC.Core.Tenants } else { - result = string.Format("{0}.{1}", TenantAlias, baseHost).TrimEnd('.').ToLowerInvariant(); + result = $"{TenantAlias}.{baseHost}".TrimEnd('.').ToLowerInvariant(); } if (!string.IsNullOrEmpty(MappedDomain) && allowMappedDomain) { diff --git a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs index e2b17a03a0..9c67a8c3ff 100644 --- a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs +++ b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs @@ -183,7 +183,7 @@ namespace ASC.Data.Backup using (var file = tempStream.Create()) { dataTable.WriteXml(file, XmlWriteMode.WriteSchema); - writer.WriteEntry(string.Format("{0}\\{1}\\{2}", Name, connectionString.Name, table).ToLower(), file); + writer.WriteEntry($"{Name}\\{connectionString.Name}\\{table}".ToLower(), file); } processedTables.Add(table); @@ -215,7 +215,7 @@ namespace ASC.Data.Backup if (dbElement.Element(table) != null) { - using (var stream = reader.GetEntry(string.Format("{0}\\{1}\\{2}", Name, dbName, table).ToLower())) + using (var stream = reader.GetEntry($"{Name}\\{dbName}\\{table}".ToLower())) { var data = new DataTable(); data.ReadXml(stream); diff --git a/common/ASC.Data.Backup.Core/Core/DbHelper.cs b/common/ASC.Data.Backup.Core/Core/DbHelper.cs index 5149a34742..f4637094d8 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -185,13 +185,13 @@ namespace ASC.Data.Backup .Intersect(table.Columns.Cast().Select(c => c.ColumnName), StringComparer.InvariantCultureIgnoreCase) .ToList(); - tableColumns.ForEach(column => sql.AppendFormat("{0}, ", Quote(column))); + tableColumns.ForEach(column => sql.Append($"{Quote(column)}, ")); sql.Replace(", ", ") values (", sql.Length - 2, 2); var insert = connect.CreateCommand(); tableColumns.ForEach(column => { - sql.AppendFormat("@{0}, ", column); + sql.Append($"@{column}, "); var p = insert.CreateParameter(); p.ParameterName = "@" + column; insert.Parameters.Add(p); @@ -255,7 +255,7 @@ namespace ASC.Data.Backup } else { - return columns.Select(string.Format("TABLE_NAME = '{0}'", table)) + return columns.Select($"TABLE_NAME = '{table}'") .Select(r => r["COLUMN_NAME"].ToString()); } } diff --git a/common/ASC.Data.Backup.Core/Core/FileBackupProvider.cs b/common/ASC.Data.Backup.Core/Core/FileBackupProvider.cs index 5494183ad2..200731a094 100644 --- a/common/ASC.Data.Backup.Core/Core/FileBackupProvider.cs +++ b/common/ASC.Data.Backup.Core/Core/FileBackupProvider.cs @@ -132,7 +132,7 @@ namespace ASC.Data.Backup files.AddRange(store .ListFilesRelative(string.Empty, "\\", "*.*", true) - .Where(x => domainList.All(domain => x.IndexOf(string.Format("{0}/", domain)) == -1)) + .Where(x => domainList.All(domain => x.IndexOf($"{domain}/") == -1)) .Select(x => new FileBackupInfo(string.Empty, module, x))); } } diff --git a/common/ASC.Data.Backup.Core/Exceptions/ThrowHelper.cs b/common/ASC.Data.Backup.Core/Exceptions/ThrowHelper.cs index 94dccdcb2c..d88631c5ff 100644 --- a/common/ASC.Data.Backup.Core/Exceptions/ThrowHelper.cs +++ b/common/ASC.Data.Backup.Core/Exceptions/ThrowHelper.cs @@ -34,32 +34,32 @@ namespace ASC.Data.Backup.Exceptions { public static DbBackupException CantDetectTenant(string tableName) { - return new DbBackupException(string.Format("Can't detect tenant column for table {0}.", tableName)); + return new DbBackupException($"Can't detect tenant column for table {tableName}."); } public static DbBackupException CantOrderTables(IEnumerable conflictingTables) { - return new DbBackupException(string.Format("Can't order tables [\"{0}\"].", string.Join("\", \"", conflictingTables.ToArray()))); + return new DbBackupException($"Can't order tables [\"{string.Join("\", \"", conflictingTables.ToArray())}\"]."); } public static DbBackupException CantOrderModules(IEnumerable conflictingTypes) { - return new DbBackupException(string.Format("Can't order modules [\"{0}\"].", string.Join("\", \"", conflictingTypes.Select(x => x.Name).ToArray()))); + return new DbBackupException($"Can't order modules [\"{string.Join("\", \"", conflictingTypes.Select(x => x.Name).ToArray())}\"]."); } public static DbBackupException CantRestoreTable(string tableName, Exception reason) { - return new DbBackupException(string.Format("Can't restore table {0}.", tableName), reason); + return new DbBackupException($"Can't restore table {tableName}.", reason); } public static DbBackupException CantBackupTable(string tableName, Exception reason) { - return new DbBackupException(string.Format("Can't backup table {0}.", tableName), reason); + return new DbBackupException($"Can't backup table {tableName}.", reason); } public static DbBackupException CantDeleteTable(string tableName, Exception reason) { - return new DbBackupException(string.Format("Can't delete table {0}.", tableName), reason); + return new DbBackupException($"Can't delete table {tableName}.", reason); } } } diff --git a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs index 80c0bb0b60..a858385af6 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -209,7 +209,7 @@ namespace ASC.Data.Backup.Tasks { var files = GetFilesToProcess(tenantId).ToList(); var exclude = BackupRecordContext.Backups.Where(b => b.TenantId == tenantId && b.StorageType == 0 && b.StoragePath != null).ToList(); - files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains(string.Format("/file_{0}/", e.StoragePath)))).ToList(); + files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains($"/file_{e.StoragePath}/"))).ToList(); return files; } @@ -222,10 +222,10 @@ namespace ASC.Data.Backup.Tasks using (var connection = DbFactory.OpenConnection()) { var command = connection.CreateCommand(); - command.CommandText = string.Format("SHOW CREATE TABLE `{0}`", t); + command.CommandText = $"SHOW CREATE TABLE `{t}`"; var createScheme = ExecuteList(command); var creates = new StringBuilder(); - creates.AppendFormat("DROP TABLE IF EXISTS `{0}`;", t); + creates.Append($"DROP TABLE IF EXISTS `{t}`;"); creates.AppendLine(); creates.Append(createScheme .Select(r => Convert.ToString(r[1])) @@ -293,7 +293,7 @@ namespace ASC.Data.Backup.Tasks using (var connection = DbFactory.OpenConnection()) { var command = connection.CreateCommand(); - command.CommandText = string.Format("SHOW COLUMNS FROM `{0}`", t); + command.CommandText = string.Format($"SHOW COLUMNS FROM `{t}`"); columns = ExecuteList(command).Select(r => "`" + Convert.ToString(r[0]) + "`").ToList(); if (command.CommandText.Contains("tenants_quota") || command.CommandText.Contains("webstudio_settings")) { @@ -304,14 +304,14 @@ namespace ASC.Data.Backup.Tasks using (var connection = DbFactory.OpenConnection()) { var command = connection.CreateCommand(); - command.CommandText = string.Format("select COLUMN_NAME from information_schema.`COLUMNS` where TABLE_SCHEMA = '{0}' and TABLE_NAME = '{1}' and COLUMN_KEY = 'PRI' and DATA_TYPE = 'int'", connection.Database, t); + command.CommandText = $"select COLUMN_NAME from information_schema.`COLUMNS` where TABLE_SCHEMA = '{connection.Database}' and TABLE_NAME = '{t}' and COLUMN_KEY = 'PRI' and DATA_TYPE = 'int'"; primaryIndex = ExecuteList(command).ConvertAll(r => Convert.ToString(r[0])).FirstOrDefault(); } using (var connection = DbFactory.OpenConnection()) { var command = connection.CreateCommand(); - command.CommandText = string.Format("SHOW INDEXES FROM {0} WHERE COLUMN_NAME='{1}' AND seq_in_index=1", t, primaryIndex); + command.CommandText = $"SHOW INDEXES FROM {t} WHERE COLUMN_NAME='{primaryIndex}' AND seq_in_index=1"; var isLeft = ExecuteList(command); searchWithPrimary = isLeft.Count == 1; } @@ -320,7 +320,7 @@ namespace ASC.Data.Backup.Tasks { using var connection = DbFactory.OpenConnection(); var command = connection.CreateCommand(); - command.CommandText = string.Format("select max({1}), min({1}) from {0}", t, primaryIndex); + command.CommandText = $"select max({primaryIndex}), min({primaryIndex}) from {t}"; var minMax = ExecuteList(command).ConvertAll(r => new Tuple(Convert.ToInt32(r[0]), Convert.ToInt32(r[1]))).FirstOrDefault(); primaryIndexStart = minMax.Item2; primaryIndexStep = (minMax.Item1 - minMax.Item2) / count; @@ -543,7 +543,7 @@ namespace ASC.Data.Backup.Tasks var files = GetFilesToProcess(TenantId).ToList(); var exclude = BackupRecordContext.Backups.Where(b => b.TenantId == TenantId && b.StorageType == 0 && b.StoragePath != null).ToList(); - files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains(string.Format("/file_{0}/", e.StoragePath)))).ToList(); + files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains($"/file_{e.StoragePath}/"))).ToList(); return files.GroupBy(file => file.Module).ToList(); } diff --git a/common/ASC.Data.Backup.Core/Tasks/ColumnMapper.cs b/common/ASC.Data.Backup.Core/Tasks/ColumnMapper.cs index e4e8829d77..7e4bb6e171 100644 --- a/common/ASC.Data.Backup.Core/Tasks/ColumnMapper.cs +++ b/common/ASC.Data.Backup.Core/Tasks/ColumnMapper.cs @@ -140,7 +140,7 @@ namespace ASC.Data.Backup.Tasks private static string GetMappingKey(string tableName, string columnName) { - return string.Format("t:{0};c:{1}", tableName, columnName).ToLowerInvariant(); + return $"t:{tableName};c:{columnName}".ToLowerInvariant(); } private static string GetMappingKey(string tableName, string columnName, object oldValue) diff --git a/common/ASC.Data.Backup.Core/Tasks/Data/DataRowInfo.cs b/common/ASC.Data.Backup.Core/Tasks/Data/DataRowInfo.cs index 445e94625f..4a8556aa1d 100644 --- a/common/ASC.Data.Backup.Core/Tasks/Data/DataRowInfo.cs +++ b/common/ASC.Data.Backup.Core/Tasks/Data/DataRowInfo.cs @@ -86,7 +86,7 @@ namespace ASC.Data.Backup.Tasks.Data while (i < _values.Count && sb.Length <= maxStrLength) { var strVal = Convert.ToString(_values[i]); - sb.AppendFormat("\"{0}\", ", strVal); + sb.Append($"\"{strVal}\", "); i++; } diff --git a/common/ASC.Data.Backup.Core/Tasks/KeyHelper.cs b/common/ASC.Data.Backup.Core/Tasks/KeyHelper.cs index e0666604c1..f9246cd14d 100644 --- a/common/ASC.Data.Backup.Core/Tasks/KeyHelper.cs +++ b/common/ASC.Data.Backup.Core/Tasks/KeyHelper.cs @@ -40,27 +40,27 @@ namespace ASC.Data.Backup.Tasks public static string GetDatabaseSchema() { - return string.Format("{0}/{1}", Databases, "scheme"); + return $"{Databases}/scheme"; } public static string GetDatabaseData() { - return string.Format("{0}/{1}", Databases, "data"); + return $"{Databases}/data"; } public static string GetDatabaseSchema(string table) { - return string.Format("{0}/{1}", GetDatabaseSchema(), table); + return $"{GetDatabaseSchema()}/{table}"; } public static string GetDatabaseData(string table) { - return string.Format("{0}/{1}", GetDatabaseData(), table); + return $"{GetDatabaseData()}/{table}"; } public static string GetTableZipKey(IModuleSpecifics module, string tableName) { - return string.Format("{0}/{1}/{2}", Databases, module.ConnectionStringName, tableName); + return $"{Databases}/{module.ConnectionStringName}/{tableName}"; } public static string GetZipKey(this BackupFileInfo file) @@ -74,7 +74,7 @@ namespace ASC.Data.Backup.Tasks } public static string GetStorageRestoreInfoZipKey() { - return string.Format("{0}/restore_info", GetStorage()); + return $"{GetStorage()}/restore_info"; } } } diff --git a/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs b/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs index b4e9165231..d276c1c46f 100644 --- a/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs @@ -99,7 +99,7 @@ namespace ASC.Data.Backup.Tasks.Modules public DbCommand CreateDeleteCommand(DbConnection connection, int tenantId, TableInfo table) { var command = connection.CreateCommand(); - command.CommandText = string.Format("delete t.* from {0} as t {1};", table.Name, GetDeleteCommandConditionText(tenantId, table)); + command.CommandText = $"delete t.* from {table.Name} as t {GetDeleteCommandConditionText(tenantId, table)};"; return command; } @@ -112,14 +112,10 @@ namespace ASC.Data.Backup.Tasks.Modules return null; var columns = valuesForInsert.Keys.Intersect(table.Columns).ToArray(); - - var insertCommantText = string.Format("{0} into {1}({2}) values({3});", - table.InsertMethod != InsertMethod.Ignore + var insert = table.InsertMethod != InsertMethod.Ignore ? table.InsertMethod.ToString().ToLower() - : "insert ignore", - table.Name, - string.Join(",", columns), - string.Join(",", columns.Select(c => "@" + c))); + : "insert ignore"; + var insertCommantText = $"{insert} into {table.Name}({string.Join(",", columns)}) values({string.Join(",", columns.Select(c => "@" + c))});"; var command = connection.CreateCommand(); command.CommandText = insertCommantText; diff --git a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs index d5de8af201..d77348d209 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -243,16 +243,16 @@ namespace ASC.Data.Backup.Tasks { var connectionString = ParseConnectionString(DbFactory.ConnectionStringSettings.ConnectionString); var args = new StringBuilder() - .AppendFormat("-h {0} ", connectionString["server"]) - .AppendFormat("-u {0} ", connectionString["user id"]) - .AppendFormat("-p{0} ", connectionString["password"]); + .Append($"-h {connectionString["server"]} ") + .Append($"-u {connectionString["user id"]} ") + .Append($"-p{connectionString["password"]} "); if (db) { - args.AppendFormat("-D {0} ", connectionString["database"]); + args.Append($"-D {connectionString["database"]} "); } - args.AppendFormat("-e \" source {0}\"", file); + args.Append($"-e \" source {file}\""); Logger.DebugFormat("run mysql file {0} {1}", file, args.ToString()); var startInfo = new ProcessStartInfo diff --git a/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs b/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs index 419689d3cf..06f36cbb43 100644 --- a/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs @@ -139,7 +139,7 @@ namespace ASC.Data.Backup.Tasks else if (tableInfo.IdType == IdType.Integer) { var command = connection.CreateCommand(); - command.CommandText = string.Format("select max({0}) from {1};", tableInfo.IdColumn, tableInfo.Name); + command.CommandText = $"select max({tableInfo.IdColumn}) from {tableInfo.Name};"; newIdValue = (int)command.WithTimeout(120).ExecuteScalar() + 1; } } diff --git a/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs index bb1b900760..7ff38c2187 100644 --- a/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs @@ -221,18 +221,13 @@ namespace ASC.Data.Backup.Tasks newAlias = GetUniqAlias(connection, newAlias); } - var commandText = string.Format( - "update tenants_tenants " + + var commandText = "update tenants_tenants " + "set " + - " status={0}, " + - " alias = '{1}', " + - " last_modified='{2}', " + - " statuschanged='{2}' " + - "where alias = '{3}'", - status.ToString("d"), - newAlias, - DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"), - alias); + $" status={status.ToString("d")}, " + + $" alias = '{newAlias}', " + + $" last_modified='{DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")}', " + + $" statuschanged='{DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")}' " + + $"where alias = '{alias}'"; if (!string.IsNullOrEmpty(whereCondition)) commandText += (" and " + whereCondition); diff --git a/common/ASC.Data.Encryption/Crypt.cs b/common/ASC.Data.Encryption/Crypt.cs index d899667783..254888eb06 100644 --- a/common/ASC.Data.Encryption/Crypt.cs +++ b/common/ASC.Data.Encryption/Crypt.cs @@ -295,12 +295,12 @@ namespace ASC.Data.Encryption { var dir = string.IsNullOrEmpty(TempDir) ? Path.GetDirectoryName(filePath) : TempDir; var name = Path.GetFileNameWithoutExtension(filePath); - var result = CrossPlatform.PathCombine(dir, string.Format("{0}_{1}{2}", Storage, name, ext)); + var result = CrossPlatform.PathCombine(dir, $"{Storage}_{name}{ext}"); var index = 1; while (File.Exists(result)) { - result = CrossPlatform.PathCombine(dir, string.Format("{0}_{1}({2}){3}", Storage, name, index++, ext)); + result = CrossPlatform.PathCombine(dir, $"{Storage}_{name}({index++}){ext}"); } return result; diff --git a/common/ASC.Data.Storage/BaseStorage.cs b/common/ASC.Data.Storage/BaseStorage.cs index 823a845089..b0c8f49873 100644 --- a/common/ASC.Data.Storage/BaseStorage.cs +++ b/common/ASC.Data.Storage/BaseStorage.cs @@ -140,20 +140,12 @@ namespace ASC.Data.Storage } var auth = EmailValidationKeyProvider.GetEmailKey(currentTenantId, path.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar) + "." + headerAttr + "." + expireString); - query = string.Format("{0}{1}={2}&{3}={4}", - path.IndexOf('?') >= 0 ? "&" : "?", - Constants.QUERY_EXPIRE, - expireString, - Constants.QUERY_AUTH, - auth); + query = $"{(path.IndexOf('?') >= 0 ? "&" : "?")}{Constants.QUERY_EXPIRE}={expireString}&{Constants.QUERY_AUTH}={auth}"; } if (!string.IsNullOrEmpty(headerAttr)) { - query += string.Format("{0}{1}={2}", - query.IndexOf('?') >= 0 ? "&" : "?", - Constants.QUERY_HEADER, - HttpUtility.UrlEncode(headerAttr)); + query += $"{(query.IndexOf('?') >= 0 ? "&" : "?")}{Constants.QUERY_HEADER}={HttpUtility.UrlEncode(headerAttr)}"; } var tenant = _tenant.Trim('/'); diff --git a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs index 8774b9170d..c5b86fde9e 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -329,7 +329,7 @@ namespace ASC.Data.Storage.DiscStorage } else { - throw new DirectoryNotFoundException(string.Format("Directory '{0}' not found", targetDir)); + throw new DirectoryNotFoundException($"Directory '{targetDir}' not found"); } } @@ -355,7 +355,7 @@ namespace ASC.Data.Storage.DiscStorage } else { - throw new DirectoryNotFoundException(string.Format("Directory '{0}' not found", targetDir)); + throw new DirectoryNotFoundException($"Directory '{targetDir}' not found"); } } diff --git a/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs b/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs index 1da1837d52..8905fef52f 100644 --- a/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs +++ b/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs @@ -147,7 +147,7 @@ namespace ASC.Data.Storage.Encryption foreach (var domain in domains) { - var logParent = string.Format("Tenant: {0}, Module: {1}, Domain: {2}", tenant.TenantAlias, module, domain); + var logParent = $"Tenant: {tenant.TenantAlias}, Module: {module}, Domain: {domain}"; var files = GetFiles(domains, progress, store, domain); @@ -217,7 +217,7 @@ namespace ASC.Data.Storage.Encryption { foreach (var file in files) { - var logItem = string.Format("{0}, File: {1}", logParent, file); + var logItem = $"{logParent}, File: {file}"; log.Debug(logItem); diff --git a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs index 178e7f4320..78cb2c1fc8 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -113,12 +113,12 @@ namespace ASC.Data.Storage.GoogleCloud _bucketRoot = props.ContainsKey("cname") && Uri.IsWellFormedUriString(props["cname"], UriKind.Absolute) ? new Uri(props["cname"], UriKind.Absolute) - : new Uri(string.Format("https://storage.googleapis.com/{0}/", _bucket), UriKind.Absolute); + : new Uri("https://storage.googleapis.com/" + _bucket + "/", UriKind.Absolute); _bucketSSlRoot = props.ContainsKey("cnamessl") && Uri.IsWellFormedUriString(props["cnamessl"], UriKind.Absolute) ? new Uri(props["cnamessl"], UriKind.Absolute) - : new Uri(string.Format("https://storage.googleapis.com/{0}/", _bucket), UriKind.Absolute); + : new Uri("https://storage.googleapis.com/" + _bucket + "/", UriKind.Absolute); if (props.ContainsKey("lower")) { @@ -153,14 +153,10 @@ namespace ASC.Data.Storage.GoogleCloud if (_subDir.Length == 1 && (_subDir[0] == '/' || _subDir[0] == '\\')) result = path; else - result = string.Format("{0}/{1}", _subDir, path); // Ignory all, if _subDir is not null + result = $"{_subDir}/{path}"; // Ignory all, if _subDir is not null } else//Key combined from module+domain+filename - result = string.Format("{0}/{1}/{2}/{3}", - _tenant, - _modulename, - domain, - path); + result = $"{_tenant}/{_modulename}/{domain}/{path}"; result = result.Replace("//", "/").TrimStart('/'); if (_lowerCasing) @@ -260,12 +256,10 @@ namespace ASC.Data.Storage.GoogleCloud protected override Uri SaveWithAutoAttachment(string domain, string path, System.IO.Stream stream, string attachmentFileName) { - var contentDisposition = string.Format("attachment; filename={0};", - HttpUtility.UrlPathEncode(attachmentFileName)); + var contentDisposition = $"attachment; filename={HttpUtility.UrlPathEncode(attachmentFileName)};"; if (attachmentFileName.Any(c => c >= 0 && c <= 127)) { - contentDisposition = string.Format("attachment; filename*=utf-8''{0};", - HttpUtility.UrlPathEncode(attachmentFileName)); + contentDisposition = $"attachment; filename*=utf-8''{HttpUtility.UrlPathEncode(attachmentFileName)};"; } return Save(domain, path, stream, null, contentDisposition); } @@ -764,7 +758,7 @@ namespace ASC.Data.Storage.GoogleCloud if (chunkLength != defaultChunkSize) totalBytes = Convert.ToString((chunkNumber - 1) * defaultChunkSize + chunkLength); - var contentRangeHeader = string.Format("bytes {0}-{1}/{2}", bytesRangeStart, bytesRangeEnd, totalBytes); + var contentRangeHeader = $"bytes {bytesRangeStart}-{bytesRangeEnd}/{totalBytes}"; var request = new HttpRequestMessage(); request.RequestUri = new Uri(uploadUri); diff --git a/common/ASC.Data.Storage/PathUtils.cs b/common/ASC.Data.Storage/PathUtils.cs index 6291a3e477..7b5683395f 100644 --- a/common/ASC.Data.Storage/PathUtils.cs +++ b/common/ASC.Data.Storage/PathUtils.cs @@ -70,9 +70,7 @@ namespace ASC.Data.Storage public string ResolveVirtualPath(string module, string domain) { - var url = string.Format("~/storage/{0}/{1}/", - module, - string.IsNullOrEmpty(domain) ? "root" : domain); + var url = $"~/storage/{module}/{(string.IsNullOrEmpty(domain) ? "root" : domain)}/"; return ResolveVirtualPath(url); } diff --git a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs index da7516dafd..b76ea13260 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -92,14 +92,10 @@ namespace ASC.Data.Storage.RackspaceCloud if (_subDir.Length == 1 && (_subDir[0] == '/' || _subDir[0] == '\\')) result = path; else - result = string.Format("{0}/{1}", _subDir, path); // Ignory all, if _subDir is not null + result = $"{_subDir}/{path}"; // Ignory all, if _subDir is not null } else//Key combined from module+domain+filename - result = string.Format("{0}/{1}/{2}/{3}", - _tenant, - _modulename, - domain, - path); + result = $"{_tenant}/{_modulename}/{domain}/{path}"; result = result.Replace("//", "/").TrimStart('/'); if (_lowerCasing) @@ -129,7 +125,7 @@ namespace ASC.Data.Storage.RackspaceCloud { _modulename = moduleConfig.Name; _dataList = new DataList(moduleConfig); - _domains.AddRange(moduleConfig.Domain.Select(x => string.Format("{0}/", x.Name))); + _domains.AddRange(moduleConfig.Domain.Select(x => $"{x.Name}/")); _domainsExpires = moduleConfig.Domain.Where(x => x.Expires != TimeSpan.Zero).ToDictionary(x => x.Name, y => y.Expires); _domainsExpires.Add(string.Empty, moduleConfig.Expires); _domainsAcl = moduleConfig.Domain.ToDictionary(x => x.Name, y => y.Acl); @@ -259,12 +255,10 @@ namespace ASC.Data.Storage.RackspaceCloud protected override Uri SaveWithAutoAttachment(string domain, string path, Stream stream, string attachmentFileName) { - var contentDisposition = string.Format("attachment; filename={0};", - HttpUtility.UrlPathEncode(attachmentFileName)); + var contentDisposition = $"attachment; filename={HttpUtility.UrlPathEncode(attachmentFileName)};"; if (attachmentFileName.Any(c => c >= 0 && c <= 127)) { - contentDisposition = string.Format("attachment; filename*=utf-8''{0};", - HttpUtility.UrlPathEncode(attachmentFileName)); + contentDisposition = $"attachment; filename*=utf-8''{HttpUtility.UrlPathEncode(attachmentFileName)};"; } return Save(domain, path, stream, null, contentDisposition); @@ -339,7 +333,7 @@ namespace ASC.Data.Storage.RackspaceCloud var headers = new Dictionary { - { "X-Object-Manifest", string.Format("{0}/{1}", _private_container, MakePath(domain, path)) } + { "X-Object-Manifest", $"{_private_container}/{MakePath(domain, path)}" } }; // create symlink client.CreateObject(_public_container, diff --git a/common/ASC.Data.Storage/S3/S3Storage.cs b/common/ASC.Data.Storage/S3/S3Storage.cs index 78565501aa..7b4489040f 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -157,7 +157,7 @@ namespace ASC.Data.Storage.S3 else if (h.StartsWith("Content-Language")) headersOverrides.ContentLanguage = (h.Substring("Content-Language".Length + 1)); else if (h.StartsWith("Content-Type")) headersOverrides.ContentType = (h.Substring("Content-Type".Length + 1)); else if (h.StartsWith("Expires")) headersOverrides.Expires = (h.Substring("Expires".Length + 1)); - else throw new FormatException(string.Format("Invalid header: {0}", h)); + else throw new FormatException($"Invalid header: {h}"); } pUrlRequest.ResponseHeaderOverrides = headersOverrides; } @@ -232,12 +232,10 @@ namespace ASC.Data.Storage.S3 protected override Uri SaveWithAutoAttachment(string domain, string path, Stream stream, string attachmentFileName) { - var contentDisposition = string.Format("attachment; filename={0};", - HttpUtility.UrlPathEncode(attachmentFileName)); + var contentDisposition = $"attachment; filename={HttpUtility.UrlPathEncode(attachmentFileName)};"; if (attachmentFileName.Any(c => c >= 0 && c <= 127)) { - contentDisposition = string.Format("attachment; filename*=utf-8''{0};", - HttpUtility.UrlPathEncode(attachmentFileName)); + contentDisposition = $"attachment; filename*=utf-8''{HttpUtility.UrlPathEncode(attachmentFileName)};"; } return Save(domain, path, stream, null, contentDisposition); } @@ -730,22 +728,22 @@ namespace ASC.Data.Storage.S3 out var sign); var postBuilder = new StringBuilder(); postBuilder.Append("{"); - postBuilder.AppendFormat("\"key\":\"{0}${{filename}}\",", key); - postBuilder.AppendFormat("\"acl\":\"public-read\","); - postBuilder.AppendFormat("\"key\":\"{0}\",", key); - postBuilder.AppendFormat("\"success_action_status\":\"{0}\",", 201); + postBuilder.Append("\"key\":\"").Append(key).Append("${{filename}}\","); + postBuilder.Append("\"acl\":\"public-read\","); + postBuilder.Append($"\"key\":\"{key}\","); + postBuilder.Append("\"success_action_status\":\"201\","); if (!string.IsNullOrEmpty(contentType)) - postBuilder.AppendFormat("\"Content-Type\":\"{0}\",", contentType); + postBuilder.Append($"\"Content-Type\":\"{contentType}\","); if (!string.IsNullOrEmpty(contentDisposition)) - postBuilder.AppendFormat("\"Content-Disposition\":\"{0}\",", contentDisposition); + postBuilder.Append($"\"Content-Disposition\":\"{contentDisposition}\","); - postBuilder.AppendFormat("\"AWSAccessKeyId\":\"{0}\",", _accessKeyId); - postBuilder.AppendFormat("\"Policy\":\"{0}\",", policyBase64); - postBuilder.AppendFormat("\"Signature\":\"{0}\"", sign); - postBuilder.AppendFormat("\"SignatureVersion\":\"{0}\"", 2); - postBuilder.AppendFormat("\"SignatureMethod\":\"{0}\"", "HmacSHA1"); - postBuilder.Append("}"); + postBuilder.Append($"\"AWSAccessKeyId\":\"{_accessKeyId}\","); + postBuilder.Append($"\"Policy\":\"{policyBase64}\","); + postBuilder.Append($"\"Signature\":\"{sign}\""); + postBuilder.Append("\"SignatureVersion\":\"2\""); + postBuilder.Append("\"SignatureMethod\":\"HmacSHA1\""); + postBuilder.Append('}'); return postBuilder.ToString(); } @@ -759,27 +757,25 @@ namespace ASC.Data.Storage.S3 out var sign); var formBuilder = new StringBuilder(); - formBuilder.AppendFormat("
", destBucket); - formBuilder.AppendFormat("", key); + formBuilder.Append($""); + formBuilder.Append($""); formBuilder.Append(""); if (!string.IsNullOrEmpty(redirectTo)) - formBuilder.AppendFormat("", - redirectTo); + formBuilder.Append($""); formBuilder.AppendFormat("", 201); if (!string.IsNullOrEmpty(contentType)) - formBuilder.AppendFormat("", contentType); + formBuilder.Append($""); if (!string.IsNullOrEmpty(contentDisposition)) - formBuilder.AppendFormat("", - contentDisposition); - formBuilder.AppendFormat("", _accessKeyId); - formBuilder.AppendFormat("", policyBase64); - formBuilder.AppendFormat("", sign); - formBuilder.AppendFormat("", 2); - formBuilder.AppendFormat("", "HmacSHA1"); - formBuilder.AppendFormat(""); - formBuilder.AppendFormat("
", submitLabel); + formBuilder.Append($""); + formBuilder.Append($""); + formBuilder.Append($""); + formBuilder.Append($""); + formBuilder.Append(""); + formBuilder.Append(""); + formBuilder.Append(""); + formBuilder.Append($""); return formBuilder.ToString(); } @@ -787,26 +783,28 @@ namespace ASC.Data.Storage.S3 long maxUploadSize, out string sign) { var policyBuilder = new StringBuilder(); - policyBuilder.AppendFormat("{{\"expiration\": \"{0}\",\"conditions\":[", - DateTime.UtcNow.AddMinutes(15).ToString(AWSSDKUtils.ISO8601DateFormat, - CultureInfo.InvariantCulture)); - policyBuilder.AppendFormat("{{\"bucket\": \"{0}\"}},", _bucket); - policyBuilder.AppendFormat("[\"starts-with\", \"$key\", \"{0}\"],", key); + + var minutes = DateTime.UtcNow.AddMinutes(15).ToString(AWSSDKUtils.ISO8601DateFormat, + CultureInfo.InvariantCulture); + + policyBuilder.Append($"{{\"expiration\": \"{minutes}\",\"conditions\":["); + policyBuilder.Append($"{{\"bucket\": \"{_bucket}\"}},"); + policyBuilder.Append($"[\"starts-with\", \"$key\", \"{key}\"],"); policyBuilder.Append("{\"acl\": \"public-read\"},"); if (!string.IsNullOrEmpty(redirectTo)) { - policyBuilder.AppendFormat("{{\"success_action_redirect\": \"{0}\"}},", redirectTo); + policyBuilder.Append($"{{\"success_action_redirect\": \"{redirectTo}\"}},"); } - policyBuilder.AppendFormat("{{\"success_action_status\": \"{0}\"}},", 201); + policyBuilder.Append("{{\"success_action_status\": \"201\"}},"); if (!string.IsNullOrEmpty(contentType)) { - policyBuilder.AppendFormat("[\"eq\", \"$Content-Type\", \"{0}\"],", contentType); + policyBuilder.Append($"[\"eq\", \"$Content-Type\", \"{contentType}\"],"); } if (!string.IsNullOrEmpty(contentDisposition)) { - policyBuilder.AppendFormat("[\"eq\", \"$Content-Disposition\", \"{0}\"],", contentDisposition); + policyBuilder.Append($"[\"eq\", \"$Content-Disposition\", \"{contentDisposition}\"],"); } - policyBuilder.AppendFormat("[\"content-length-range\", 0, {0}]", maxUploadSize); + policyBuilder.Append($"[\"content-length-range\", 0, {maxUploadSize}]"); policyBuilder.Append("]}"); var policyBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(policyBuilder.ToString())); @@ -1093,7 +1091,7 @@ namespace ASC.Data.Storage.S3 { _modulename = moduleConfig.Name; _dataList = new DataList(moduleConfig); - _domains.AddRange(moduleConfig.Domain.Select(x => string.Format("{0}/", x.Name))); + _domains.AddRange(moduleConfig.Domain.Select(x => $"{x.Name}/")); //Make expires _domainsExpires = moduleConfig.Domain.Where(x => x.Expires != TimeSpan.Zero).ToDictionary(x => x.Name, y => y.Expires); @@ -1162,11 +1160,11 @@ namespace ASC.Data.Storage.S3 _bucketRoot = props.ContainsKey("cname") && Uri.IsWellFormedUriString(props["cname"], UriKind.Absolute) ? new Uri(props["cname"], UriKind.Absolute) - : new Uri(string.Format("http://s3.{1}.amazonaws.com/{0}/", _bucket, _region), UriKind.Absolute); + : new Uri($"http://s3.{_region}.amazonaws.com/{_bucket}/", UriKind.Absolute); _bucketSSlRoot = props.ContainsKey("cnamessl") && Uri.IsWellFormedUriString(props["cnamessl"], UriKind.Absolute) ? new Uri(props["cnamessl"], UriKind.Absolute) - : new Uri(string.Format("https://s3.{1}.amazonaws.com/{0}/", _bucket, _region), UriKind.Absolute); + : new Uri($"https://s3.{_region}.amazonaws.com/{_bucket}/", UriKind.Absolute); if (props.ContainsKey("lower")) { @@ -1200,14 +1198,10 @@ namespace ASC.Data.Storage.S3 if (_subDir.Length == 1 && (_subDir[0] == '/' || _subDir[0] == '\\')) result = path; else - result = string.Format("{0}/{1}", _subDir, path); // Ignory all, if _subDir is not null + result = $"{_subDir}/{path}"; // Ignory all, if _subDir is not null } else//Key combined from module+domain+filename - result = string.Format("{0}/{1}/{2}/{3}", - _tenant, - _modulename, - domain, - path); + result = $"{_tenant}/{_modulename}/{domain}/{path}"; result = result.Replace("//", "/").TrimStart('/').TrimEnd('/'); if (_lowerCasing) @@ -1220,7 +1214,7 @@ namespace ASC.Data.Storage.S3 private string GetRecyclePath(string path) { - return string.IsNullOrEmpty(_recycleDir) ? "" : string.Format("{0}/{1}", _recycleDir, path.TrimStart('/')); + return string.IsNullOrEmpty(_recycleDir) ? "" : $"{_recycleDir}/{path.TrimStart('/')}"; } private void Recycle(IAmazonS3 client, string domain, string key) diff --git a/common/ASC.Data.Storage/TenantQuotaController.cs b/common/ASC.Data.Storage/TenantQuotaController.cs index 0f34fd4843..12d8b43c8f 100644 --- a/common/ASC.Data.Storage/TenantQuotaController.cs +++ b/common/ASC.Data.Storage/TenantQuotaController.cs @@ -129,7 +129,7 @@ namespace ASC.Data.Storage private void SetTenantQuotaRow(string module, string domain, long size, string dataTag, bool exchange) { TenantManager.SetTenantQuotaRow( - new TenantQuotaRow { Tenant = tenant, Path = string.Format("/{0}/{1}", module, domain), Counter = size, Tag = dataTag }, + new TenantQuotaRow { Tenant = tenant, Path = $"/{module}/{domain}", Counter = size, Tag = dataTag }, exchange); } diff --git a/common/ASC.Data.Storage/WebPath.cs b/common/ASC.Data.Storage/WebPath.cs index 0e5f4e321f..9b8c519186 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -65,7 +65,7 @@ namespace ASC.Data.Storage { if (!Uri.IsWellFormedUriString(absolutePath, UriKind.Absolute)) { - throw new ArgumentException(string.Format("bad path format {0} is not absolute", absolutePath)); + throw new ArgumentException($"bad path format {absolutePath} is not absolute"); } var appender = Appenders.FirstOrDefault(x => absolutePath.Contains(x.Append) || (absolutePath.Contains(x.AppendSecure) && !string.IsNullOrEmpty(x.AppendSecure))); @@ -82,7 +82,7 @@ namespace ASC.Data.Storage { if (!string.IsNullOrEmpty(relativePath) && relativePath.IndexOf('~') == 0) { - throw new ArgumentException(string.Format("bad path format {0} remove '~'", relativePath), "relativePath"); + throw new ArgumentException($"bad path format {relativePath} remove '~'", "relativePath"); } var result = relativePath; @@ -123,7 +123,7 @@ namespace ASC.Data.Storage //} //else //{ - result = string.Format("{0}/{1}{2}", appender.Append.TrimEnd('/').TrimStart('~'), relativePath.TrimStart('/'), query); + result = $"{appender.Append.TrimEnd('/').TrimStart('~')}/{relativePath.TrimStart('/')}{query}"; //} } else @@ -131,12 +131,12 @@ namespace ASC.Data.Storage //TODO HostingEnvironment.IsHosted if (SecureHelper.IsSecure(httpContext, options) && !string.IsNullOrEmpty(appender.AppendSecure)) { - result = string.Format("{0}/{1}", appender.AppendSecure.TrimEnd('/'), relativePath.TrimStart('/')); + result = $"{appender.AppendSecure.TrimEnd('/')}/{relativePath.TrimStart('/')}"; } else { //Append directly - result = string.Format("{0}/{1}", appender.Append.TrimEnd('/'), relativePath.TrimStart('/')); + result = $"{appender.Append.TrimEnd('/')}/{relativePath.TrimStart('/')}"; } } } @@ -200,7 +200,7 @@ namespace ASC.Data.Storage { if (!string.IsNullOrEmpty(relativePath) && relativePath.IndexOf('~') == 0) { - throw new ArgumentException(string.Format("bad path format {0} remove '~'", relativePath), "relativePath"); + throw new ArgumentException($"bad path format {relativePath} remove '~'", "relativePath"); } if (CoreBaseSettings.Standalone && ServiceProvider.GetService().CanUpload()) //hack for skip resolve DistributedTaskQueueOptionsManager diff --git a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs index 1f2ec7bfa4..37c1587786 100644 --- a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs @@ -107,10 +107,7 @@ namespace ASC.FederatedLogin.Helpers if (string.IsNullOrEmpty(clientID)) throw new ArgumentNullException("clientID"); if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret"); - var data = string.Format("code={0}&client_id={1}&client_secret={2}", - HttpUtility.UrlEncode(authCode), - HttpUtility.UrlEncode(clientID), - HttpUtility.UrlEncode(clientSecret)); + var data = $"code={HttpUtility.UrlEncode(authCode)}&client_id={HttpUtility.UrlEncode(clientID)}&client_secret={HttpUtility.UrlEncode(clientSecret)}"; if (!string.IsNullOrEmpty(redirectUri)) data += "&redirect_uri=" + HttpUtility.UrlEncode(redirectUri); @@ -147,10 +144,7 @@ namespace ASC.FederatedLogin.Helpers { if (token == null || !CanRefresh(token)) throw new ArgumentException("Can not refresh given token", "token"); - var data = string.Format("client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token", - HttpUtility.UrlEncode(token.ClientID), - HttpUtility.UrlEncode(token.ClientSecret), - HttpUtility.UrlEncode(token.RefreshToken)); + var data = $"client_id={HttpUtility.UrlEncode(token.ClientID)}&client_secret={HttpUtility.UrlEncode(token.ClientSecret)}&refresh_token={HttpUtility.UrlEncode(token.RefreshToken)}&grant_type=refresh_token"; var json = RequestHelper.PerformRequest(requestUrl, "application/x-www-form-urlencoded", "POST", data); if (json != null) diff --git a/common/ASC.FederatedLogin/Helpers/XrdsHelper.cs b/common/ASC.FederatedLogin/Helpers/XrdsHelper.cs index 767691a740..43932ad3f6 100644 --- a/common/ASC.FederatedLogin/Helpers/XrdsHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/XrdsHelper.cs @@ -32,17 +32,16 @@ namespace ASC.FederatedLogin.Helpers { public class XrdsHelper { - private const string Xrds = + internal static async Task RenderXrds(HttpResponse responce, string location, string iconlink) + { + var xrds = @"http://specs.openid.net/auth/2.0/return_to{0}http://specs.openid.net/extensions/ui/icon{1}"; + $@"priority=""1"">{location}http://specs.openid.net/extensions/ui/icon{iconlink}"; - - internal static async Task RenderXrds(HttpResponse responce, string location, string iconlink) - { - await responce.WriteAsync(string.Format(Xrds, location, iconlink)); + await responce.WriteAsync(xrds); } //TODO diff --git a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs index a5822378a3..58400b1b58 100644 --- a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs @@ -79,7 +79,7 @@ namespace ASC.FederatedLogin.LoginProviders { get { - var codeAuth = string.Format("{0}:{1}", ClientID, ClientSecret); + var codeAuth = $"{ClientID}:{ClientSecret}"; var codeAuthBytes = Encoding.UTF8.GetBytes(codeAuth); var codeAuthBase64 = Convert.ToBase64String(codeAuthBytes); return "Basic " + codeAuthBase64; @@ -92,7 +92,7 @@ namespace ASC.FederatedLogin.LoginProviders if (string.IsNullOrEmpty(ClientID)) throw new ArgumentException("clientID"); if (string.IsNullOrEmpty(ClientSecret)) throw new ArgumentException("clientSecret"); - var data = string.Format("grant_type=authorization_code&code={0}", authCode); + var data = $"grant_type=authorization_code&code={authCode}"; var headers = new Dictionary { { "Authorization", AuthHeader } }; var json = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", data, headers); @@ -117,7 +117,7 @@ namespace ASC.FederatedLogin.LoginProviders if (string.IsNullOrEmpty(refreshToken) || string.IsNullOrEmpty(ClientID) || string.IsNullOrEmpty(ClientSecret)) throw new ArgumentException("Can not refresh given token"); - var data = string.Format("grant_type=refresh_token&refresh_token={0}", refreshToken); + var data = $"grant_type=refresh_token&refresh_token={refreshToken}"; var headers = new Dictionary { { "Authorization", AuthHeader } }; var json = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", data, headers); diff --git a/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs index 8586df0b38..30d7d5590f 100644 --- a/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs @@ -100,7 +100,7 @@ namespace ASC.FederatedLogin.LoginProviders TimeZone = jProfile.Value("timezone"), Locale = jProfile.Value("locale"), Provider = ProviderConstants.Facebook, - Avatar = string.Format("http://graph.facebook.com/{0}/picture?type=large", jProfile.Value("id")) + Avatar = "http://graph.facebook.com/" + jProfile.Value("id") + "/picture?type=large" }; return profile; diff --git a/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs b/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs index a689447b59..cfb901392a 100644 --- a/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs +++ b/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs @@ -48,7 +48,7 @@ namespace ASC.FederatedLogin databaseId = string.Join(".", new[] { _baseDatabaseId, hostedRegion.Trim() }); if (!_accountLinkers.ContainsKey(databaseId)) - throw new ArgumentException(string.Format("Region {0} is not defined", databaseId), "hostedRegion"); + throw new ArgumentException($"Region {databaseId} is not defined", "hostedRegion"); return databaseId; } diff --git a/common/ASC.FederatedLogin/Profile/LoginProfile.cs b/common/ASC.FederatedLogin/Profile/LoginProfile.cs index 9a1f6911f8..bbed67d0df 100644 --- a/common/ASC.FederatedLogin/Profile/LoginProfile.cs +++ b/common/ASC.FederatedLogin/Profile/LoginProfile.cs @@ -163,7 +163,7 @@ namespace ASC.FederatedLogin.Profile public string UniqueId { - get { return string.Format("{0}/{1}", Provider, Id); } + get { return $"{Provider}/{Id}"; } } public string HashId @@ -306,8 +306,7 @@ namespace ASC.FederatedLogin.Profile var query = new StringBuilder(); foreach (var key in queryString.AllKeys) { - query.AppendFormat("{0}={1}&", key, - queryString[key]); + query.Append($"{key}={queryString[key]}&"); } var builder = new UriBuilder(uri) { Query = query.ToString().TrimEnd('&') }; return builder.Uri; diff --git a/common/ASC.Feed/Core/Feed.cs b/common/ASC.Feed/Core/Feed.cs index 45e9a5aee2..9ee3ee7af7 100644 --- a/common/ASC.Feed/Core/Feed.cs +++ b/common/ASC.Feed/Core/Feed.cs @@ -53,7 +53,7 @@ namespace ASC.Feed.Aggregator public string Id { - get { return string.Format("{0}_{1}", Item, ItemId); } + get { return $"{Item}_{ItemId}"; } } public Guid AuthorId { get; private set; } diff --git a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs index 32bf2ca09b..d02ee8012a 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -251,14 +251,14 @@ namespace ASC.MessagingSystem.DbSender { return clientInfo == null ? null - : string.Format("{0} {1}", clientInfo.UA.Family, clientInfo.UA.Major); + : $"{clientInfo.UA.Family} {clientInfo.UA.Major}"; } private static string GetPlatform(ClientInfo clientInfo) { return clientInfo == null ? null - : string.Format("{0} {1}", clientInfo.OS.Family, clientInfo.OS.Major); + : $"{clientInfo.OS.Family} {clientInfo.OS.Major}"; } public void Dispose() diff --git a/common/ASC.Notify.Textile/JabberStyler.cs b/common/ASC.Notify.Textile/JabberStyler.cs index 3848314906..3a2f26c493 100644 --- a/common/ASC.Notify.Textile/JabberStyler.cs +++ b/common/ASC.Notify.Textile/JabberStyler.cs @@ -85,7 +85,7 @@ namespace ASC.Notify.Textile { return " " + match.Groups["text"].Value + " "; } - return match.Groups["text"].Value + string.Format(" ( {0} )", match.Groups["link"].Value); + return match.Groups["text"].Value + $" ( {match.Groups["link"].Value} )"; } } return match.Value; diff --git a/common/ASC.Textile/Blocks/HyperLinkBlockModifier.cs b/common/ASC.Textile/Blocks/HyperLinkBlockModifier.cs index a44dbe5d35..dab812c2ac 100644 --- a/common/ASC.Textile/Blocks/HyperLinkBlockModifier.cs +++ b/common/ASC.Textile/Blocks/HyperLinkBlockModifier.cs @@ -33,7 +33,7 @@ namespace Textile.Blocks @"\s?" + @"(?:\((?[^)]+)\)(?=""))?" + // title "\":" + - string.Format(@"""(?<url>\S+[^""]+)""", Regex.Escape(@"a-zA-Z:/.-{}?&_%#+=@")) + // url + @"""(?<url>\S+[^""]+)""" + // url @"(?<slash>\/)?" + // slash @"(?<post>[^\w\/;]*)" + // post @"(?=\s|$)", diff --git a/common/ASC.Textile/Blocks/NoTextileEncoder.cs b/common/ASC.Textile/Blocks/NoTextileEncoder.cs index e679ccd55d..7f717ee980 100644 --- a/common/ASC.Textile/Blocks/NoTextileEncoder.cs +++ b/common/ASC.Textile/Blocks/NoTextileEncoder.cs @@ -52,7 +52,7 @@ namespace Textile.Blocks } return patternPrefix + toEncode + patternSuffix; } - tmp = Regex.Replace(tmp, string.Format("({0}(?<notex>.+?){1})*", patternPrefix, patternSuffix), new MatchEvaluator(evaluator)); + tmp = Regex.Replace(tmp, "("+ patternPrefix + "(?<notex>.+?)" + patternSuffix + ")*", new MatchEvaluator(evaluator)); return tmp; } @@ -75,7 +75,7 @@ namespace Textile.Blocks } return toEncode; } - tmp = Regex.Replace(tmp, string.Format("({0}(?<notex>.+?){1})*", patternPrefix, patternSuffix), new MatchEvaluator(evaluator)); + tmp = Regex.Replace(tmp, "(" + patternPrefix + "(?<notex>.+?)" + patternSuffix + ")*", new MatchEvaluator(evaluator)); return tmp; } } diff --git a/common/ASC.Textile/States/HeaderFormatterState.cs b/common/ASC.Textile/States/HeaderFormatterState.cs index debabe18c7..bd28563a05 100644 --- a/common/ASC.Textile/States/HeaderFormatterState.cs +++ b/common/ASC.Textile/States/HeaderFormatterState.cs @@ -32,7 +32,7 @@ namespace Textile.States { for (var i = 0; i < HeaderLevel; i++) { - Formatter.Output.Write(string.Format("<br {0}/>", FormattedStylesAndAlignment("br"))); + Formatter.Output.Write("<br {0}/>"); } } @@ -77,12 +77,12 @@ namespace Textile.States public override void Enter() { - Formatter.Output.Write(string.Format("<h{0}{1}>", HeaderLevel, FormattedStylesAndAlignment(string.Format("h{0}", HeaderLevel)))); + Formatter.Output.Write("<h"+ HeaderLevel + FormattedStylesAndAlignment("h" + HeaderLevel) + ">"); } public override void Exit() { - Formatter.Output.WriteLine(string.Format("</h{0}>", HeaderLevel.ToString())); + Formatter.Output.WriteLine("</h" + HeaderLevel + ">"); } protected override void OnContextAcquired() diff --git a/common/ASC.Textile/States/ListFormatterState.cs b/common/ASC.Textile/States/ListFormatterState.cs index fba026681b..72b8b5510e 100644 --- a/common/ASC.Textile/States/ListFormatterState.cs +++ b/common/ASC.Textile/States/ListFormatterState.cs @@ -72,7 +72,7 @@ namespace Textile.States { if (!m_firstItem) Formatter.Output.WriteLine("</li>"); - Formatter.Output.Write(string.Format("<li {0}>", FormattedStylesAndAlignment("li"))); + Formatter.Output.Write("<li " + FormattedStylesAndAlignment("li") + ">"); m_firstItemLine = false; } else diff --git a/common/ASC.Textile/States/TableRowFormatterState.cs b/common/ASC.Textile/States/TableRowFormatterState.cs index d2628dddc7..c7d83ae786 100644 --- a/common/ASC.Textile/States/TableRowFormatterState.cs +++ b/common/ASC.Textile/States/TableRowFormatterState.cs @@ -18,7 +18,7 @@ namespace Textile.States { m_alignInfo = m.Groups["align"].Value; m_attsInfo = m.Groups["atts"].Value; - input = string.Format("|{0}|", m.Groups["content"].Value); + input = "|" + m.Groups["content"].Value + "|"; if (!(this.Formatter.CurrentState is TableFormatterState)) { diff --git a/common/ASC.VoipService/Dao/VoipDao.cs b/common/ASC.VoipService/Dao/VoipDao.cs index f28f7792b6..2ef0656245 100644 --- a/common/ASC.VoipService/Dao/VoipDao.cs +++ b/common/ASC.VoipService/Dao/VoipDao.cs @@ -343,7 +343,7 @@ namespace ASC.VoipService.Dao { call.ContactTitle = call.ContactIsCompany ? dbVoipCall.CrmContact.CompanyName - : dbVoipCall.CrmContact.FirstName == null || dbVoipCall.CrmContact.LastName == null ? null : string.Format("{0} {1}", dbVoipCall.CrmContact.FirstName, dbVoipCall.CrmContact.LastName); + : dbVoipCall.CrmContact.FirstName == null || dbVoipCall.CrmContact.LastName == null ? null : $"{dbVoipCall.CrmContact.FirstName} {dbVoipCall.CrmContact.LastName}"; } return call; diff --git a/common/services/ASC.ApiSystem/Classes/CommonMethods.cs b/common/services/ASC.ApiSystem/Classes/CommonMethods.cs index df56cbd911..298e27cc7d 100644 --- a/common/services/ASC.ApiSystem/Classes/CommonMethods.cs +++ b/common/services/ASC.ApiSystem/Classes/CommonMethods.cs @@ -146,17 +146,9 @@ namespace ASC.ApiSystem.Controllers } public string CreateReference(string requestUriScheme, string tenantDomain, string email, bool first = false, string module = "", bool sms = false) - { - return string.Format("{0}{1}{2}/{3}{4}{5}{6}", - requestUriScheme, - Uri.SchemeDelimiter, - tenantDomain, - CommonLinkUtility.GetConfirmationUrlRelative(email, ConfirmType.Auth, (first ? "true" : "") + module + (sms ? "true" : "")), - first ? "&first=true" : "", - string.IsNullOrEmpty(module) ? "" : "&module=" + module, - sms ? "&sms=true" : "" - - ); + { + var url = CommonLinkUtility.GetConfirmationUrlRelative(email, ConfirmType.Auth, (first ? "true" : "") + module + (sms ? "true" : "")); + return $"{requestUriScheme}{Uri.SchemeDelimiter}{tenantDomain}/{url}{(first ? "&first=true" : "")}{(string.IsNullOrEmpty(module) ? "" : "&module=" + module)}{(sms ? "&sms=true" : "")}"; } public bool SendCongratulations(string requestUriScheme, Tenant tenant, bool skipWelcome, out string url) @@ -310,7 +302,7 @@ namespace ASC.ApiSystem.Controllers { try { - var data = string.Format("secret={0}&remoteip={1}&response={2}", Configuration["recaptcha:private-key"], ip, response); + var data = $"secret={Configuration["recaptcha:private-key"]}&remoteip={ip}&response={response}"; var url = Configuration["recaptcha:verify-url"] ?? "https://www.recaptcha.net/recaptcha/api/siteverify"; var request = new HttpRequestMessage(); diff --git a/common/services/ASC.ApiSystem/Controllers/CalDavController.cs b/common/services/ASC.ApiSystem/Controllers/CalDavController.cs index a4fe0e4849..35b1e90784 100644 --- a/common/services/ASC.ApiSystem/Controllers/CalDavController.cs +++ b/common/services/ASC.ApiSystem/Controllers/CalDavController.cs @@ -185,10 +185,7 @@ namespace ASC.ApiSystem.Controllers var validationKey = EmailValidationKeyProvider.GetEmailKey(tenant.TenantId, email + userPassword.Password + ConfirmType.Auth); - var authData = string.Format("userName={0}&password={1}&key={2}", - HttpUtility.UrlEncode(email), - HttpUtility.UrlEncode(userPassword.Password), - HttpUtility.UrlEncode(validationKey)); + var authData = $"userName={HttpUtility.UrlEncode(email)}&password={HttpUtility.UrlEncode(userPassword.Password)}&key={HttpUtility.UrlEncode(validationKey)}"; SendToApi(Request.Scheme, tenant, "authentication/login", null, WebRequestMethods.Http.Post, authData); @@ -231,7 +228,7 @@ namespace ASC.ApiSystem.Controllers return false; } - Log.Info(string.Format("CalDav calendarParam: {0}", calendarParam)); + Log.Info($"CalDav calendarParam: {calendarParam}"); var userParam = calendarParam.Split('/')[0]; return GetUserData(userParam, out _, out tenant, out error); @@ -261,7 +258,7 @@ namespace ASC.ApiSystem.Controllers if (userData.Length < 3) { - Log.Error(string.Format("Error Caldav username: {0}", userParam)); + Log.Error($"Error Caldav username: {userParam}"); error = new { @@ -284,7 +281,7 @@ namespace ASC.ApiSystem.Controllers tenantName = tenantName.Replace("." + baseUrl, ""); } - Log.Info(string.Format("CalDav: user:{0} tenantName:{1}", userParam, tenantName)); + Log.Info($"CalDav: user:{userParam} tenantName:{tenantName}"); var tenantModel = new TenantModel { PortalName = tenantName }; @@ -330,15 +327,9 @@ namespace ASC.ApiSystem.Controllers ? null : string.Join("&", args.Select(arg => HttpUtility.UrlEncode(arg.Key) + "=" + HttpUtility.UrlEncode(arg.Value)).ToArray()); - var url = string.Format("{0}{1}{2}{3}{4}{5}", - requestUriScheme, - Uri.SchemeDelimiter, - tenant.GetTenantDomain(CoreSettings), - CommonConstants.WebApiBaseUrl, - path, - string.IsNullOrEmpty(query) ? "" : "?" + query); + var url = $"{requestUriScheme}{Uri.SchemeDelimiter}{tenant.GetTenantDomain(CoreSettings)}{CommonConstants.WebApiBaseUrl}{path}{(string.IsNullOrEmpty(query) ? "" : "?" + query)}"; - Log.Info(string.Format("CalDav: SendToApi: {0}", url)); + Log.Info($"CalDav: SendToApi: {url}"); var request = new HttpRequestMessage(); request.RequestUri = new Uri(url); diff --git a/common/services/ASC.ApiSystem/Controllers/PortalController.cs b/common/services/ASC.ApiSystem/Controllers/PortalController.cs index 81d95688a1..ce8ecda528 100644 --- a/common/services/ASC.ApiSystem/Controllers/PortalController.cs +++ b/common/services/ASC.ApiSystem/Controllers/PortalController.cs @@ -673,7 +673,7 @@ namespace ASC.ApiSystem.Controllers return true; } - var data = string.Format("{0} {1} {2} {3} {4}", model.PortalName, model.FirstName, model.LastName, model.Email, model.Phone); + var data = $"{model.PortalName} {model.FirstName} {model.LastName} {model.Email} {model.Phone}"; /*** validate recaptcha ***/ if (!CommonMethods.ValidateRecaptcha(model.RecaptchaResponse, clientIP)) diff --git a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs index d6d6be2612..1dc54beeb2 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -142,7 +142,7 @@ namespace ASC.AuditTrail.Mappers private string ToLimitedText(string text) { if (text == null) return null; - return text.Length < 50 ? text : string.Format("{0}...", text.Substring(0, 47)); + return text.Length < 50 ? text : $"{text.Substring(0, 47)}..."; } } } \ No newline at end of file diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index b5589c2b0b..c5df10a50f 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -544,12 +544,12 @@ namespace ASC.ElasticSearch { if (newValue == default(T)) { - source.AppendFormat("ctx._source.remove('{0}');", sourceExprText.Substring(1)); + source.Append($"ctx._source.remove('{sourceExprText.Substring(1)}');"); } else { var pkey = "p" + sourceExprText.Replace(".", ""); - source.AppendFormat("ctx._source{0} = params.{1};", sourceExprText, pkey); + source.Append($"ctx._source{sourceExprText} = params.{pkey};"); parameters.Add(pkey, newValue); } } @@ -606,18 +606,18 @@ namespace ASC.ElasticSearch for (var i = 0; i < newValue.Count; i++) { parameters.Add(paramKey + i, newValue[i]); - source.AppendFormat("if (!ctx._source{0}.contains(params.{1})){{ctx._source{0}.add(params.{1})}}", key, paramKey + i); + source.Append($"if (!ctx._source{key}.contains(params.{paramKey + i})){{ctx._source{key}.add(params.{paramKey + i})}}"); } break; case UpdateAction.Replace: parameters.Add(paramKey, newValue); - source.AppendFormat("ctx._source{0} = params.{1};", key, paramKey); + source.Append($"ctx._source{key} = params.{paramKey};"); break; case UpdateAction.Remove: for (var i = 0; i < newValue.Count; i++) { parameters.Add(paramKey + i, newValue[i]); - source.AppendFormat("ctx._source{0}.removeIf(item -> item.id == params.{1}.id)", key, paramKey + i); + source.Append($"ctx._source{key}.removeIf(item -> item.id == params.{paramKey + i}.id)"); } break; default: diff --git a/common/services/ASC.Socket.IO.Svc/SocketServiceLauncher.cs b/common/services/ASC.Socket.IO.Svc/SocketServiceLauncher.cs index fc2a6bfddb..018fc52e3f 100644 --- a/common/services/ASC.Socket.IO.Svc/SocketServiceLauncher.cs +++ b/common/services/ASC.Socket.IO.Svc/SocketServiceLauncher.cs @@ -90,7 +90,7 @@ namespace ASC.Socket.IO.Svc UseShellExecute = false, FileName = "node", WindowStyle = ProcessWindowStyle.Hidden, - Arguments = string.Format("\"{0}\"", Path.GetFullPath(CrossPlatform.PathCombine(HostEnvironment.ContentRootPath, settings.Path, "app.js"))), + Arguments = $"\"{Path.GetFullPath(CrossPlatform.PathCombine(HostEnvironment.ContentRootPath, settings.Path, "app.js"))}\"", WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory }; StartInfo.EnvironmentVariables.Add("core.machinekey", Configuration["core:machinekey"]); @@ -161,7 +161,7 @@ namespace ASC.Socket.IO.Svc Thread.Sleep(PingInterval); var error = false; - WebSocket = new WebSocket(string.Format("ws://127.0.0.1:{0}/socket.io/?EIO=3&transport=websocket", StartInfo.EnvironmentVariables["port"])); + WebSocket = new WebSocket($"ws://127.0.0.1:{StartInfo.EnvironmentVariables["port"]}/socket.io/?EIO=3&transport=websocket"); WebSocket.SetCookie(new WebSocketSharp.Net.Cookie("authorization", SignalrServiceClient.CreateAuthToken())); WebSocket.EmitOnPing = true; diff --git a/common/services/ASC.SsoAuth.Svc/Launcher.cs b/common/services/ASC.SsoAuth.Svc/Launcher.cs index d195957760..ca8d2e93c9 100644 --- a/common/services/ASC.SsoAuth.Svc/Launcher.cs +++ b/common/services/ASC.SsoAuth.Svc/Launcher.cs @@ -69,7 +69,7 @@ namespace ASC.SsoAuth.Svc UseShellExecute = false, FileName = "node", WindowStyle = ProcessWindowStyle.Hidden, - Arguments = string.Format("\"{0}\"", Path.GetFullPath(CrossPlatform.PathCombine(HostEnvironment.ContentRootPath, cfg.Path, "app.js"))), + Arguments = $"\"{Path.GetFullPath(CrossPlatform.PathCombine(HostEnvironment.ContentRootPath, cfg.Path, "app.js"))}\"", WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory }; diff --git a/common/services/ASC.TelegramService/Core/Core.cs b/common/services/ASC.TelegramService/Core/Core.cs index 1978968edc..091a52f309 100644 --- a/common/services/ASC.TelegramService/Core/Core.cs +++ b/common/services/ASC.TelegramService/Core/Core.cs @@ -141,7 +141,7 @@ namespace ASC.TelegramService.Core { var cmd = ParseCommand(msg); - if (!commands.ContainsKey(cmd.CommandName)) throw new Exception(string.Format("No handler found for command '{0}'", cmd.CommandName)); + if (!commands.ContainsKey(cmd.CommandName)) throw new Exception($"No handler found for command '{cmd.CommandName}'"); var command = commands[cmd.CommandName]; var context = (CommandContext)ServiceProvider.CreateScope().ServiceProvider.GetService(contexts[cmd.CommandName]); diff --git a/common/services/ASC.Thumbnails.Svc/ThumbnailsServiceLauncher.cs b/common/services/ASC.Thumbnails.Svc/ThumbnailsServiceLauncher.cs index 3a2742a4ea..572159d9fd 100644 --- a/common/services/ASC.Thumbnails.Svc/ThumbnailsServiceLauncher.cs +++ b/common/services/ASC.Thumbnails.Svc/ThumbnailsServiceLauncher.cs @@ -67,7 +67,7 @@ namespace ASC.Thumbnails.Svc UseShellExecute = false, FileName = "node", WindowStyle = ProcessWindowStyle.Hidden, - Arguments = string.Format("\"{0}\"", Path.GetFullPath(CrossPlatform.PathCombine(HostEnvironment.ContentRootPath, settings.Path, "index.js"))), + Arguments = $"\"{Path.GetFullPath(CrossPlatform.PathCombine(HostEnvironment.ContentRootPath, settings.Path, "index.js"))}\"", WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory }; diff --git a/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs b/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs index deb3c76561..a343f8dc5b 100644 --- a/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs +++ b/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs @@ -116,7 +116,7 @@ namespace ASC.UrlShortener.Svc UseShellExecute = false, FileName = "node", WindowStyle = ProcessWindowStyle.Hidden, - Arguments = string.Format("\"{0}\"", Path.GetFullPath(CrossPlatform.PathCombine(hostEnvironment.ContentRootPath, path))), + Arguments = $"\"{Path.GetFullPath(CrossPlatform.PathCombine(hostEnvironment.ContentRootPath, path))}\"", WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory }; diff --git a/products/ASC.CRM/Server/Api/RelationshipEventsController.cs b/products/ASC.CRM/Server/Api/RelationshipEventsController.cs index fb115d8da9..0194c26a64 100644 --- a/products/ASC.CRM/Server/Api/RelationshipEventsController.cs +++ b/products/ASC.CRM/Server/Api/RelationshipEventsController.cs @@ -458,14 +458,14 @@ namespace ASC.CRM.Api var extension = Path.GetExtension(file.Title); if (extension == null) continue; - var fileInfo = string.Format("{0} ({1})", file.Title, extension.ToUpper()); + var fileInfo = $"{file.Title} ({extension.ToUpper()})"; if (!fileListInfoHashtable.ContainsKey(fileInfo)) { fileListInfoHashtable.Add(fileInfo, file.DownloadUrl); } else { - fileInfo = string.Format("{0} ({1}, {2})", file.Title, extension.ToUpper(), file.UniqID); + fileInfo = $"{file.Title} ({extension.ToUpper()}, {file.UniqID})"; fileListInfoHashtable.Add(fileInfo, file.DownloadUrl); } } diff --git a/products/ASC.CRM/Server/Classes/InvoiceFormattedData.cs b/products/ASC.CRM/Server/Classes/InvoiceFormattedData.cs index 8fee0d4dc9..be51671ae1 100644 --- a/products/ASC.CRM/Server/Classes/InvoiceFormattedData.cs +++ b/products/ASC.CRM/Server/Classes/InvoiceFormattedData.cs @@ -341,9 +341,7 @@ namespace ASC.Web.CRM.Classes //data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Discount", cultureInfo), "-" + discount.ToString(CultureInfo.InvariantCulture))); data.TableTotalRow = - new Tuple<string, string>( - string.Format("{0} ({1})", CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo), - invoice.Currency), amount.ToString(CultureInfo.InvariantCulture)); + new Tuple<string, string>($"{CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo)} ({invoice.Currency})", amount.ToString(CultureInfo.InvariantCulture)); #endregion @@ -671,9 +669,7 @@ namespace ASC.Web.CRM.Classes //data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Discount", cultureInfo), "-" + discount.ToString(CultureInfo.InvariantCulture))); data.TableTotalRow = - new Tuple<string, string>( - string.Format("{0} ({1})", CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo), - invoice.Currency), amount.ToString(CultureInfo.InvariantCulture)); + new Tuple<string, string>($"{CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo)} ({invoice.Currency})", amount.ToString(CultureInfo.InvariantCulture)); #endregion diff --git a/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs b/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs index f3b4411474..91d5a78297 100644 --- a/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs +++ b/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs @@ -116,7 +116,7 @@ namespace ASC.CRM.Classes private string GetValueText(CultureInfo culture, object value) { Type type = value.GetType(); - string resourceName = string.Format("{0}_{1}", type.Name, value.ToString()); + string resourceName = $"{type.Name}_{value}"; string result = _resourceManager.GetString(resourceName, culture); if (result == null) result = resourceName; @@ -174,7 +174,7 @@ namespace ASC.CRM.Classes } else { - result = string.Format("{0}, {1}", result, valueText); + result = $"{result}, {valueText}"; } } } diff --git a/products/ASC.CRM/Server/Core/Dao/DealMilestoneDao.cs b/products/ASC.CRM/Server/Core/Dao/DealMilestoneDao.cs index d8cf263517..52f9274c9a 100644 --- a/products/ASC.CRM/Server/Core/Dao/DealMilestoneDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/DealMilestoneDao.cs @@ -158,7 +158,7 @@ namespace ASC.CRM.Core.Dao public void Edit(DealMilestone item) { if (HaveContactLink(item.ID)) - throw new ArgumentException(String.Format("{0}. {1}.", CRMErrorsResource.BasicCannotBeEdited, CRMErrorsResource.DealMilestoneHasRelatedDeals)); + throw new ArgumentException($"{CRMErrorsResource.BasicCannotBeEdited}. {CRMErrorsResource.DealMilestoneHasRelatedDeals}."); var dbEntity = CrmDbContext.DealMilestones.Find(item.ID); @@ -183,7 +183,7 @@ namespace ASC.CRM.Core.Dao public void Delete(int id) { if (HaveContactLink(id)) - throw new ArgumentException(String.Format("{0}. {1}.", CRMErrorsResource.BasicCannotBeDeleted, CRMErrorsResource.DealMilestoneHasRelatedDeals)); + throw new ArgumentException($"{CRMErrorsResource.BasicCannotBeDeleted}. {CRMErrorsResource.DealMilestoneHasRelatedDeals}."); var dbEntity = CrmDbContext.DealMilestones.Find(id); diff --git a/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs b/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs index 5e17356c9e..317c9ef1f4 100644 --- a/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs @@ -381,13 +381,13 @@ namespace ASC.CRM.Core.Dao { case ListType.ContactStatus: case ListType.ContactType: - throw new ArgumentException(string.Format("{0}. {1}.", CRMErrorsResource.BasicCannotBeEdited, CRMErrorsResource.HasRelatedContacts)); + throw new ArgumentException($"{CRMErrorsResource.BasicCannotBeEdited}. {CRMErrorsResource.HasRelatedContacts}."); case ListType.TaskCategory: - throw new ArgumentException(string.Format("{0}. {1}.", CRMErrorsResource.BasicCannotBeEdited, CRMErrorsResource.TaskCategoryHasRelatedTasks)); + throw new ArgumentException($"{CRMErrorsResource.BasicCannotBeEdited}. {CRMErrorsResource.TaskCategoryHasRelatedTasks}."); case ListType.HistoryCategory: - throw new ArgumentException(string.Format("{0}. {1}.", CRMErrorsResource.BasicCannotBeEdited, CRMErrorsResource.HistoryCategoryHasRelatedEvents)); + throw new ArgumentException($"{CRMErrorsResource.BasicCannotBeEdited}. {CRMErrorsResource.HistoryCategoryHasRelatedEvents}."); default: - throw new ArgumentException(string.Format("{0}.", CRMErrorsResource.BasicCannotBeEdited)); + throw new ArgumentException($"{CRMErrorsResource.BasicCannotBeEdited}."); } } @@ -498,16 +498,16 @@ namespace ASC.CRM.Core.Dao { case ListType.ContactStatus: case ListType.ContactType: - throw new ArgumentException(string.Format("{0}. {1}.", CRMErrorsResource.BasicCannotBeDeleted, CRMErrorsResource.HasRelatedContacts)); + throw new ArgumentException($"{CRMErrorsResource.BasicCannotBeDeleted}. {CRMErrorsResource.HasRelatedContacts}."); case ListType.TaskCategory: - var exMsg = string.Format("{0}. {1}.", CRMErrorsResource.BasicCannotBeDeleted, CRMErrorsResource.TaskCategoryHasRelatedTasks); + var exMsg = $"{CRMErrorsResource.BasicCannotBeDeleted}. {CRMErrorsResource.TaskCategoryHasRelatedTasks}."; if (itemID == toItemID) throw new ArgumentException(exMsg); ChangeRelativeItemsLink(listType, itemID, toItemID); break; case ListType.HistoryCategory: - throw new ArgumentException(string.Format("{0}. {1}.", CRMErrorsResource.BasicCannotBeDeleted, CRMErrorsResource.HistoryCategoryHasRelatedEvents)); + throw new ArgumentException($"{CRMErrorsResource.BasicCannotBeDeleted}. {CRMErrorsResource.HistoryCategoryHasRelatedEvents}."); default: - throw new ArgumentException(string.Format("{0}.", CRMErrorsResource.BasicCannotBeDeleted)); + throw new ArgumentException($"{CRMErrorsResource.BasicCannotBeDeleted}."); } } diff --git a/products/ASC.CRM/Server/Core/Dao/ReportDao.cs b/products/ASC.CRM/Server/Core/Dao/ReportDao.cs index a0218d701a..32c1c44ec8 100644 --- a/products/ASC.CRM/Server/Core/Dao/ReportDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/ReportDao.cs @@ -241,7 +241,7 @@ namespace ASC.CRM.Core.Dao case ReportTimePeriod.CurrentWeek: case ReportTimePeriod.PreviousWeek: case ReportTimePeriod.NextWeek: - return string.Format("{0}-{1}", fromDate.ToShortDateString(), toDate.ToShortDateString()); + return $"{fromDate.ToShortDateString()}-{toDate.ToShortDateString()}"; case ReportTimePeriod.CurrentMonth: case ReportTimePeriod.PreviousMonth: case ReportTimePeriod.NextMonth: @@ -249,7 +249,7 @@ namespace ASC.CRM.Core.Dao case ReportTimePeriod.CurrentQuarter: case ReportTimePeriod.PreviousQuarter: case ReportTimePeriod.NextQuarter: - return string.Format("{0}-{1}", fromDate.ToString("Y"), toDate.ToString("Y")); + return $"{fromDate.ToString("Y")}-{toDate.ToString("Y")}"; case ReportTimePeriod.CurrentYear: case ReportTimePeriod.PreviousYear: case ReportTimePeriod.NextYear: @@ -1755,10 +1755,7 @@ namespace ASC.CRM.Core.Dao { var timeSpan = TimeSpan.FromSeconds(duration); - return string.Format("{0}:{1}:{2}", - ((timeSpan.TotalHours < 10 ? "0" : "") + (int)timeSpan.TotalHours), - ((timeSpan.Minutes < 10 ? "0" : "") + timeSpan.Minutes), - ((timeSpan.Seconds < 10 ? "0" : "") + timeSpan.Seconds)); + return $"{(timeSpan.TotalHours < 10 ? "0" : "") + (int)timeSpan.TotalHours}:{(timeSpan.Minutes < 10 ? "0" : "") + timeSpan.Minutes}:{(timeSpan.Seconds < 10 ? "0" : "") + timeSpan.Seconds}"; } #endregion diff --git a/products/ASC.CRM/Server/Core/Dao/SearchDao.cs b/products/ASC.CRM/Server/Core/Dao/SearchDao.cs index 85f10363a2..7da8707ce1 100644 --- a/products/ASC.CRM/Server/Core/Dao/SearchDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/SearchDao.cs @@ -345,7 +345,7 @@ namespace ASC.CRM.Core.Dao result.Add(new SearchResultItem { - Name = x.IsCompany ? x.CompanyName : String.Format("{0} {1}", x.FirstName, x.LastName), + Name = x.IsCompany ? x.CompanyName : $"{x.FirstName} {x.LastName}", Description = HtmlUtil.GetText(x.Notes, 120), URL = String.Concat(_pathProvider.BaseAbsolutePath, String.Format("default.aspx?id={0}", x.Id)), Date = _tenantUtil.DateTimeFromUtc(x.CreateOn), diff --git a/products/ASC.CRM/Server/Core/Entities/Contact.cs b/products/ASC.CRM/Server/Core/Entities/Contact.cs index 6f03c0fc4e..7b27ef3b34 100644 --- a/products/ASC.CRM/Server/Core/Entities/Contact.cs +++ b/products/ASC.CRM/Server/Core/Entities/Contact.cs @@ -75,7 +75,7 @@ namespace ASC.CRM.Core.Entities var people = (Person)contact; - return String.Format("{0} {1}", people.FirstName, people.LastName); + return $"{people.FirstName} {people.LastName}"; } //public static String RenderLinkForCard(this Contact contact) diff --git a/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs b/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs index 593be93500..9ae99dabb9 100644 --- a/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs @@ -267,7 +267,7 @@ namespace ASC.Web.CRM.HttpHandlers .Cast<object>() .Any(categoryEnum => (int)categoryEnum == category); if (!categoryIsExists) - throw new ArgumentException(String.Format("Category for {0} not found", nameParts[0])); + throw new ArgumentException($"Category for {nameParts[0]} not found"); if (contactInfoType == ContactInfoType.Address) { @@ -355,8 +355,8 @@ namespace ASC.Web.CRM.HttpHandlers context.Response.Headers.Add("Location", newURL); await context.Response.WriteAsync("<HTML><Head>"); - await context.Response.WriteAsync(String.Format("<META HTTP-EQUIV=Refresh CONTENT=\"0;URL={0}\">", newURL)); - await context.Response.WriteAsync(String.Format("<Script>window.location='{0}';</Script>", newURL)); + await context.Response.WriteAsync($"<META HTTP-EQUIV=Refresh CONTENT=\"0;URL={newURL}\">"); + await context.Response.WriteAsync($"<Script>window.location='{newURL}';</Script>"); await context.Response.WriteAsync("</Head>"); await context.Response.WriteAsync("</HTML>"); } diff --git a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs index a75ffe5485..624b574c5e 100644 --- a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs +++ b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs @@ -131,7 +131,7 @@ namespace ASC.Web.CRM.Classes continue; } - var key = String.Format("{1}/{0}", baseCurrency.Abbreviation, ci.Abbreviation); + var key = $"{ci.Abbreviation}/{baseCurrency.Abbreviation}"; if (!rates.ContainsKey(key)) continue; @@ -160,7 +160,7 @@ namespace ASC.Web.CRM.Classes if (from.Contains('-')) from = new RegionInfo(from).ISOCurrencySymbol; if (to.Contains('-')) to = new RegionInfo(to).ISOCurrencySymbol; - var key = string.Format("{0}/{1}", to, from); + var key = $"{to}/{from}"; return Math.Round(rates[key] * amount, 4, MidpointRounding.AwayFromZero); } @@ -270,8 +270,7 @@ namespace ASC.Web.CRM.Classes { foreach (var curInfo in currencyInfos) { - _exchangeRates.Add( - String.Format("{0}/{1}", (curInfo as Match).Groups["Currency"].Value.Trim(), curCI.Abbreviation), + _exchangeRates.Add($"{(curInfo as Match).Groups["Currency"].Value.Trim()}/{curCI.Abbreviation}", Convert.ToDecimal((curInfo as Match).Groups["Rate"].Value.Trim(), CultureInfo.InvariantCulture.NumberFormat)); success = true; @@ -329,7 +328,7 @@ namespace ASC.Web.CRM.Classes Directory.CreateDirectory(dir); } - var destinationURI = new Uri(String.Format("https://themoneyconverter.com/{0}/{0}.aspx", currency)); + var destinationURI = new Uri("https://themoneyconverter.com/"+ currency + "/" + currency + ".aspx"); var request = new HttpRequestMessage(); request.RequestUri = destinationURI; diff --git a/products/ASC.CRM/Server/Utils/ExportToCSV.cs b/products/ASC.CRM/Server/Utils/ExportToCSV.cs index ad2fd70f9b..0b09d02de0 100644 --- a/products/ASC.CRM/Server/Utils/ExportToCSV.cs +++ b/products/ASC.CRM/Server/Utils/ExportToCSV.cs @@ -473,7 +473,7 @@ namespace ASC.Web.CRM.Classes foreach (ContactInfoType infoTypeEnum in Enum.GetValues(typeof(ContactInfoType))) foreach (Enum categoryEnum in Enum.GetValues(ContactInfo.GetCategory(infoTypeEnum))) { - var localTitle = String.Format("{1} ({0})", categoryEnum.ToLocalizedString().ToLower(), infoTypeEnum.ToLocalizedString()); + var localTitle = $"{infoTypeEnum.ToLocalizedString()} ({categoryEnum.ToLocalizedString().ToLower()})"; if (infoTypeEnum == ContactInfoType.Address) dataTable.Columns.AddRange((from AddressPart addressPartEnum in Enum.GetValues(typeof(AddressPart)) @@ -942,15 +942,13 @@ namespace ASC.Web.CRM.Classes var casesObj = casesDao.GetByID(item.EntityID); if (casesObj != null) - entityTitle = String.Format("{0}: {1}", CRMCasesResource.Case, - casesObj.Title); + entityTitle = $"{CRMCasesResource.Case}: {casesObj.Title}"; break; case EntityType.Opportunity: var dealObj = dealDao.GetByID(item.EntityID); if (dealObj != null) - entityTitle = String.Format("{0}: {1}", CRMDealResource.Deal, - dealObj.Title); + entityTitle = $"{CRMDealResource.Deal}: {dealObj.Title}"; break; } @@ -1069,13 +1067,13 @@ namespace ASC.Web.CRM.Classes var caseObj = casesDao.GetByID(item.EntityID); if (caseObj != null) - entityTitle = String.Format("{0}: {1}", CRMCasesResource.Case, caseObj.Title); + entityTitle = $"{CRMCasesResource.Case}: {caseObj.Title}"; break; case EntityType.Opportunity: var dealObj = dealDao.GetByID(item.EntityID); if (dealObj != null) - entityTitle = String.Format("{0}: {1}", CRMDealResource.Deal, dealObj.Title); + entityTitle = $"{CRMDealResource.Deal}: {dealObj.Title}"; break; } diff --git a/products/ASC.CRM/Server/Utils/MailSender.cs b/products/ASC.CRM/Server/Utils/MailSender.cs index ae898d1adf..70ca2befc7 100644 --- a/products/ASC.CRM/Server/Utils/MailSender.cs +++ b/products/ASC.CRM/Server/Utils/MailSender.cs @@ -827,7 +827,7 @@ namespace ASC.Web.CRM.Classes private String ToTagName(String value, bool isCompany) { - return String.Format("$({0}.{1})", isCompany ? "Company" : "Person", value); + return $"$({(isCompany ? "Company" : "Person")}.{value})"; } private List<MailTemplateTag> GetAllTags() @@ -907,7 +907,7 @@ namespace ASC.Web.CRM.Classes DisplayName = String.Format(localTitle + " {0}", addressPartEnum.ToLocalizedString()), Category = CRMContactResource.GeneralInformation, isCompany = isCompany, - Name = ToTagName(String.Format("{0} {1}", infoTypeEnum.ToString(), addressPartEnum.ToString()), isCompany) + Name = ToTagName($"{infoTypeEnum} {addressPartEnum}", isCompany) }); else result.Add(new MailTemplateTag diff --git a/products/ASC.CRM/Server/Utils/PdfCreator.cs b/products/ASC.CRM/Server/Utils/PdfCreator.cs index cdec421bb0..86ce4a0666 100644 --- a/products/ASC.CRM/Server/Utils/PdfCreator.cs +++ b/products/ASC.CRM/Server/Utils/PdfCreator.cs @@ -127,7 +127,7 @@ namespace ASC.Web.CRM.Classes var file = _serviceProvider.GetService<File<int>>(); - file.Title = string.Format("{0}{1}", invoice.Number, FormatPdf); + file.Title = $"{invoice.Number}{FormatPdf}"; file.FolderID = _daoFactory.GetFileDao().GetRoot(); var request = new HttpRequestMessage(); @@ -260,7 +260,7 @@ namespace ASC.Web.CRM.Classes { var document = _serviceProvider.GetService<File<int>>(); - document.Title = string.Format("{0}{1}", data.Number, FormatPdf); + document.Title = $"{data.Number}{FormatPdf}"; document.FolderID = _daoFactory.GetFileDao().GetRoot(); document.ContentLength = stream.Length; diff --git a/products/ASC.CRM/Server/Utils/ReportHelper.cs b/products/ASC.CRM/Server/Utils/ReportHelper.cs index f50bda6094..a728e7e659 100644 --- a/products/ASC.CRM/Server/Utils/ReportHelper.cs +++ b/products/ASC.CRM/Server/Utils/ReportHelper.cs @@ -127,10 +127,7 @@ namespace ASC.Web.CRM.Classes break; } - return string.Format("{0} ({1} {2}).xlsx", - reportName, - _tenantUtil.DateTimeNow().ToShortDateString(), - _tenantUtil.DateTimeNow().ToShortTimeString()); + return $"{reportName} ({_tenantUtil.DateTimeNow().ToShortDateString()} {_tenantUtil.DateTimeNow().ToShortTimeString()}).xlsx"; } public bool CheckReportData(ReportType reportType, ReportTimePeriod timePeriod, Guid[] managers) diff --git a/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs b/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs index dde3267985..5e022aa5ff 100644 --- a/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs +++ b/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs @@ -1615,7 +1615,7 @@ namespace ASC.Calendar.BusinessObjects if (!string.IsNullOrEmpty(uid)) return uid; - return string.Format("{0}@onlyoffice.com", string.IsNullOrEmpty(id) ? Guid.NewGuid().ToString() : id); + return $"{(string.IsNullOrEmpty(id) ? Guid.NewGuid().ToString() : id)}@onlyoffice.com"; } diff --git a/products/ASC.Calendar/Server/Controllers/CalendarController.cs b/products/ASC.Calendar/Server/Controllers/CalendarController.cs index 478b020906..6cae096572 100644 --- a/products/ASC.Calendar/Server/Controllers/CalendarController.cs +++ b/products/ASC.Calendar/Server/Controllers/CalendarController.cs @@ -747,7 +747,7 @@ namespace ASC.Calendar.Controllers } catch (Exception ex) { - Log.Error(String.Format("Delete project caldav calendar: {0}", ex.Message)); + Log.Error($"Delete project caldav calendar: {ex.Message}"); } } @@ -804,7 +804,7 @@ namespace ASC.Calendar.Controllers } catch (Exception ex) { - Log.Error(String.Format("Delete CRM caldav event: {0}", ex.Message)); + Log.Error($"Delete CRM caldav event: {ex.Message}"); } } @@ -897,7 +897,7 @@ namespace ASC.Calendar.Controllers } catch (Exception ex) { - Log.Error(String.Format("Error: {0}", ex.Message)); + Log.Error($"Error: {ex.Message}"); } finally { @@ -911,7 +911,7 @@ namespace ASC.Calendar.Controllers } catch (Exception ex) { - Log.Error(String.Format("Create/update CRM caldav event: {0}", ex.Message)); + Log.Error($"Create/update CRM caldav event: {ex.Message}"); } } @@ -1289,7 +1289,7 @@ namespace ASC.Calendar.Controllers } catch (Exception ex) { - Log.Info(String.Format("Error import events to new calendar by ical url: {0}", ex.Message)); + Log.Info($"Error import events to new calendar by ical url: {ex.Message}"); } } @@ -1354,7 +1354,7 @@ namespace ASC.Calendar.Controllers } catch (Exception ex) { - Log.Info(String.Format("Error import events to calendar by ical url: {0}", ex.Message)); + Log.Info($"Error import events to calendar by ical url: {ex.Message}"); } } @@ -1859,7 +1859,7 @@ namespace ASC.Calendar.Controllers return AddEvent(calendarId, eventModel); } - throw new Exception(string.Format("Can't parse {0} to int", calendar.Id)); + throw new Exception($"Can't parse {calendar.Id} to int"); } /// <summary> @@ -1943,7 +1943,7 @@ namespace ASC.Calendar.Controllers { var defaultCalendar = LoadInternalCalendars().First(x => (!x.IsSubscription && x.IsTodo != 1)); if (!int.TryParse(defaultCalendar.Id, out calId)) - throw new Exception(string.Format("Can't parse {0} to int", defaultCalendar.Id)); + throw new Exception($"Can't parse {defaultCalendar.Id} to int"); } var calendars = DDayICalParser.DeserializeCalendar(ics); @@ -1972,7 +1972,7 @@ namespace ASC.Calendar.Controllers if (eventObj.IsAllDay && utcStartDate.Date < utcEndDate.Date) utcEndDate = utcEndDate.AddDays(-1); - eventUid = eventUid == null ? null : string.Format("{0}@onlyoffice.com", eventUid); + eventUid = eventUid == null ? null : $"{eventUid}@onlyoffice.com"; var result = CreateEvent(calId, eventObj.Summary, @@ -2711,7 +2711,7 @@ namespace ASC.Calendar.Controllers { var defaultCalendar = LoadInternalCalendars().First(x => (!x.IsSubscription && x.IsTodo != 1)); if (!int.TryParse(defaultCalendar.Id, out calendarId)) - throw new Exception(string.Format("Can't parse {0} to int", defaultCalendar.Id)); + throw new Exception($"Can't parse {defaultCalendar.Id} to int"); } var calendars = DDayICalParser.DeserializeCalendar(ics); @@ -2734,7 +2734,7 @@ namespace ASC.Calendar.Controllers var utcStartDate = todoObj.Start != null ? DDayICalParser.ToUtc(todoObj.Start) : DateTime.MinValue; - todoUid = todoUid == null ? null : string.Format("{0}@onlyoffice.com", todoUid); + todoUid = todoUid == null ? null : $"{todoUid}@onlyoffice.com"; var result = CreateTodo(calendarId, @@ -3069,7 +3069,7 @@ namespace ASC.Calendar.Controllers if (int.TryParse(calendar.Id, out calendarId)) return ImportEvents(calendarId, uploadModel); - throw new Exception(string.Format("Can't parse {0} to int", calendar.Id)); + throw new Exception($"Can't parse {calendar.Id} to int"); } /// <summary> @@ -3139,7 +3139,7 @@ namespace ASC.Calendar.Controllers } - throw new Exception(string.Format("Can't parse {0} to int", calendar.Id)); + throw new Exception($"Can't parse {calendar.Id} to int"); } /// <summary> @@ -4193,7 +4193,7 @@ namespace ASC.Calendar.Controllers request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(authorization))); request.Headers.Add("Content-Type", "text/calendar; charset=utf-8"); - Log.Info(String.Format("UpdateCalDavEvent eventURl: {0}", eventURl)); + Log.Info($"UpdateCalDavEvent eventURl: {eventURl}"); string ics = ""; @@ -4204,7 +4204,7 @@ namespace ASC.Calendar.Controllers { ics = reader.ReadToEnd(); } - Log.Info(String.Format("UpdateCalDavEvent: {0}", ics)); + Log.Info($"UpdateCalDavEvent: {ics}"); var existEvent = DataProvider.GetEventIdByUid(eventGuid + "%", calendarId); var existCalendar = DataProvider.GetCalendarById(calendarId); diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index b636462f6e..399b54d6f2 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -960,7 +960,7 @@ namespace ASC.Files.Core.Data public string GetUniqFilePath(File<int> file, string fileTitle) { return file != null - ? string.Format("{0}/{1}", GetUniqFileVersionPath(file.ID, file.Version), fileTitle) + ? $"{GetUniqFileVersionPath(file.ID, file.Version)}/{fileTitle}" : null; } diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs index a58c56714b..816ebd24bb 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs @@ -824,7 +824,7 @@ namespace ASC.Files.Core.Data if (string.IsNullOrEmpty(module)) throw new ArgumentNullException("module"); if (string.IsNullOrEmpty(bunch)) throw new ArgumentNullException("bunch"); - var keys = data.Select(id => string.Format("{0}/{1}/{2}", module, bunch, id)).ToArray(); + var keys = data.Select(id => $"{module}/{bunch}/{id}").ToArray(); var folderIdsDictionary = Query(FilesDbContext.BunchObjects) .AsNoTracking() @@ -908,7 +908,7 @@ namespace ASC.Files.Core.Data if (string.IsNullOrEmpty(module)) throw new ArgumentNullException("module"); if (string.IsNullOrEmpty(bunch)) throw new ArgumentNullException("bunch"); - var key = string.Format("{0}/{1}/{2}", module, bunch, data); + var key = $"{module}/{bunch}/{data}"; var folderId = Query(FilesDbContext.BunchObjects) .Where(r => r.RightNode == key) .Select(r => r.LeftNode) diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs index 7370d3b956..59d16f94b4 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs @@ -92,8 +92,9 @@ namespace ASC.Files.Thirdparty.Box } protected override string MakeId(string path = null) - { - return string.Format("{0}{1}", PathPrefix, string.IsNullOrEmpty(path) || path == "0" ? "" : ("-|" + path.TrimStart('/'))); + { + var p = string.IsNullOrEmpty(path) || path == "0" ? "" : ("-|" + path.TrimStart('/')); + return $"{PathPrefix}{p}"; } protected string MakeFolderTitle(BoxFolder boxFolder) diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs index 83329eaae8..6f0bb68169 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs @@ -87,8 +87,9 @@ namespace ASC.Files.Thirdparty.Dropbox } protected override string MakeId(string path = null) - { - return string.Format("{0}{1}", PathPrefix, string.IsNullOrEmpty(path) || path == "/" ? "" : ("-" + path.Replace('/', '|'))); + { + var p = string.IsNullOrEmpty(path) || path == "/" ? "" : ("-" + path.Replace('/', '|')); + return $"{PathPrefix}{p}"; } protected string MakeFolderTitle(FolderMetadata dropboxFolder) diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoBase.cs index c1a4d7235e..16e833a95d 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoBase.cs @@ -84,8 +84,9 @@ namespace ASC.Files.Thirdparty.GoogleDrive } protected override string MakeId(string path = null) - { - return string.Format("{0}{1}", PathPrefix, string.IsNullOrEmpty(path) || path == "root" || path == ProviderInfo.DriveRootId ? "" : ("-|" + path.TrimStart('/'))); + { + var p = string.IsNullOrEmpty(path) || path == "root" || path == ProviderInfo.DriveRootId ? "" : ("-|" + path.TrimStart('/')); + return $"{PathPrefix}{p}"; } protected string MakeFolderTitle(DriveFile driveFolder) diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs index f16d6dabcc..8930f5d4c9 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs @@ -207,7 +207,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive { if (file == null) throw new ArgumentNullException("file"); - var downloadArg = string.Format("{0}?alt=media", file.Id); + var downloadArg = $"{file.Id}?alt=media"; var ext = MimeMapping.GetExtention(file.MimeType); if (GoogleLoginProvider.GoogleDriveExt.Contains(ext)) @@ -215,9 +215,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive var internalExt = FileUtility.GetGoogleDownloadableExtension(ext); var requiredMimeType = MimeMapping.GetMimeMapping(internalExt); - downloadArg = string.Format("{0}/export?mimeType={1}", - file.Id, - HttpUtility.UrlEncode(requiredMimeType)); + downloadArg = $"{file.Id}/export?mimeType={HttpUtility.UrlEncode(requiredMimeType)}"; } var request = new HttpRequestMessage(); @@ -363,10 +361,10 @@ namespace ASC.Files.Thirdparty.GoogleDrive } else { - var titleData = !string.IsNullOrEmpty(driveFile.Name) ? string.Format("\"name\":\"{0}\"", driveFile.Name) : ""; - var parentData = !string.IsNullOrEmpty(folderId) ? string.Format(",\"parents\":[\"{0}\"]", folderId) : ""; + var titleData = !string.IsNullOrEmpty(driveFile.Name) ? $"\"name\":\"{driveFile.Name}\"" : ""; + var parentData = !string.IsNullOrEmpty(folderId) ? $",\"parents\":[\"{folderId}\"]" : ""; - body = !string.IsNullOrEmpty(titleData + parentData) ? string.Format("{{{0}{1}}}", titleData, parentData) : ""; + body = !string.IsNullOrEmpty(titleData + parentData) ? "{{" + titleData + parentData + "}}" : ""; } var request = new HttpRequestMessage(); diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs index a905fbf23c..1cd4f28b60 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs @@ -83,9 +83,9 @@ namespace ASC.Files.Thirdparty.OneDrive } protected override string MakeId(string id = null) - { - return string.Format("{0}{1}", PathPrefix, - string.IsNullOrEmpty(id) ? "" : ("-|" + id.TrimStart('/'))); + { + var i = string.IsNullOrEmpty(id) ? "" : ("-|" + id.TrimStart('/')); + return $"{PathPrefix}{i}"; } public string MakeOneDrivePath(Item onedriveItem) diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs index 8fd12c9e2f..94e9b54d2a 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs @@ -548,8 +548,9 @@ namespace ASC.Files.Thirdparty.SharePoint public string MakeId(string path = "") { - path = path.Replace(SpRootFolderId, ""); - return string.Format("{0}{1}", "spoint-" + ID, string.IsNullOrEmpty(path) || path == "/" || path == SpRootFolderId ? "" : ("-" + path.Replace('/', '|'))); + path = path.Replace(SpRootFolderId, ""); + var p = string.IsNullOrEmpty(path) || path == "/" || path == SpRootFolderId ? "" : ("-" + path.Replace('/', '|')); + return $"{ID}{p}"; } private string MakeId(object path) diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs index 1d8f659a00..a2cb4e3b16 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs @@ -214,7 +214,7 @@ namespace ASC.Files.Thirdparty.Sharpbox protected string MakePath(object entryId) { - return string.Format("/{0}", Convert.ToString(entryId, CultureInfo.InvariantCulture).Trim('/')); + return $"/{Convert.ToString(entryId, CultureInfo.InvariantCulture).Trim('/')}"; } protected override string MakeId(string path = null) @@ -240,8 +240,8 @@ namespace ASC.Files.Thirdparty.Sharpbox { path = entry.Id; } - - return string.Format("{0}{1}", PathPrefix, string.IsNullOrEmpty(path) || path == "/" ? "" : ("-" + path.Replace('/', '|'))); + var p = string.IsNullOrEmpty(path) || path == "/" ? "" : ("-" + path.Replace('/', '|')); + return $"{PathPrefix}{p}"; } protected string MakeTitle(ICloudFileSystemEntry fsEntry) diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs index 157805d761..04829daa84 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs @@ -389,7 +389,7 @@ namespace ASC.Web.Files.Services.DocumentService { var error = FilesCommonResource.ErrorMassage_DocServiceException; if (!string.IsNullOrEmpty(ex.Message)) - error += string.Format(" ({0})", ex.Message); + error += $" ({ex.Message})"; Logger.Error("DocService error", ex); return new Exception(error, ex); diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs index 9948023f53..0d6a4a0993 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs @@ -225,7 +225,7 @@ namespace ASC.Web.Files.Services.DocumentService } - if (!editPossible && !FileUtility.CanWebView(file.Title)) throw new Exception(string.Format("{0} ({1})", FilesCommonResource.ErrorMassage_NotSupportedFormat, FileUtility.GetFileExtension(file.Title))); + if (!editPossible && !FileUtility.CanWebView(file.Title)) throw new Exception($"{FilesCommonResource.ErrorMassage_NotSupportedFormat} ({FileUtility.GetFileExtension(file.Title)})"); if (reviewPossible && !FileUtility.CanWebReview(file.Title)) @@ -308,7 +308,7 @@ namespace ASC.Web.Files.Services.DocumentService if (!lastVersion) { - configuration.Document.Title += string.Format(" ({0})", file.CreateOnString); + configuration.Document.Title += $" ({file.CreateOnString})"; } return file; diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs index 572c7bf97a..f8acf8736e 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -592,10 +592,7 @@ namespace ASC.Web.Files.Services.DocumentService try { var fileName = Global.ReplaceInvalidCharsAndTruncate(fileId + FileUtility.GetFileExtension(downloadUri)); - var path = string.Format(@"save_crash\{0}\{1}_{2}", - DateTime.UtcNow.ToString("yyyy_MM_dd"), - userId, - fileName); + var path = $@"save_crash\{DateTime.UtcNow.ToString("yyyy_MM_dd")}\{userId}_{fileName}"; var store = GlobalStore.GetStore(); var request = new HttpRequestMessage(); diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs index 4c827fbd89..9ef7231d52 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs @@ -117,7 +117,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations stream, MimeMapping.GetMimeMapping(path), "attachment; filename=\"" + fileName + "\""); - Result = string.Format("{0}?{1}=bulk&ext={2}", filesLinkUtility.FileHandlerPath, FilesLinkUtility.Action, archiveExtension); + Result = $"{filesLinkUtility.FileHandlerPath}?{FilesLinkUtility.Action}=bulk&ext={archiveExtension}"; TaskInfo.SetProperty(PROGRESS, 100); TaskInfo.SetProperty(RESULT, Result); diff --git a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs index 2532231761..e992d64771 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -322,8 +322,8 @@ namespace ASC.Web.Files.ThirdPartyApp { var boundary = DateTime.UtcNow.Ticks.ToString("x"); - var metadata = string.Format("Content-Disposition: form-data; name=\"filename\"; filename=\"{0}\"\r\nContent-Type: application/octet-stream\r\n\r\n", title); - var metadataPart = string.Format("--{0}\r\n{1}", boundary, metadata); + var metadata = $"Content-Disposition: form-data; name=\"filename\"; filename=\"{title}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; + var metadataPart = $"--{boundary}\r\n{metadata}"; var bytes = Encoding.UTF8.GetBytes(metadataPart); tmpStream.Write(bytes, 0, bytes.Length); @@ -340,7 +340,7 @@ namespace ASC.Web.Files.ThirdPartyApp downloadStream.CopyTo(tmpStream); } - var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary); + var mediaPartEnd = $"\r\n--{boundary}--\r\n"; bytes = Encoding.UTF8.GetBytes(mediaPartEnd); tmpStream.Write(bytes, 0, bytes.Length); @@ -502,7 +502,7 @@ namespace ASC.Web.Files.ThirdPartyApp private bool CurrentUser(string boxUserId) { var linkedProfiles = Snapshot.Get("webstudio") - .GetLinkedObjectsByHashId(HashHelper.MD5(string.Format("{0}/{1}", ProviderConstants.Box, boxUserId))); + .GetLinkedObjectsByHashId(HashHelper.MD5($"{ProviderConstants.Box}/{boxUserId}")); return linkedProfiles.Any(profileId => Guid.TryParse(profileId, out var tmp) && tmp == AuthContext.CurrentAccount.ID); } diff --git a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs index 88fc5610b7..39ba1eba9d 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -627,8 +627,8 @@ namespace ASC.Web.Files.ThirdPartyApp private bool CurrentUser(string googleId) { var linker = Snapshot.Get("webstudio"); - var linkedProfiles = linker.GetLinkedObjectsByHashId(HashHelper.MD5(string.Format("{0}/{1}", ProviderConstants.Google, googleId))); - linkedProfiles = linkedProfiles.Concat(linker.GetLinkedObjectsByHashId(HashHelper.MD5(string.Format("{0}/{1}", ProviderConstants.OpenId, googleId)))); + var linkedProfiles = linker.GetLinkedObjectsByHashId(HashHelper.MD5($"{ProviderConstants.Google}/{googleId}")); + linkedProfiles = linkedProfiles.Concat(linker.GetLinkedObjectsByHashId(HashHelper.MD5($"{ProviderConstants.OpenId}/{googleId}"))); return linkedProfiles.Any(profileId => Guid.TryParse(profileId, out var tmp) && tmp == AuthContext.CurrentAccount.ID); } @@ -754,19 +754,19 @@ namespace ASC.Web.Files.ThirdPartyApp { var boundary = DateTime.UtcNow.Ticks.ToString("x"); - var folderdata = string.IsNullOrEmpty(folderId) ? "" : string.Format(",\"parents\":[\"{0}\"]", folderId); - var metadata = string.Format("{{\"name\":\"{0}\"{1}}}", fileName, folderdata); - var metadataPart = string.Format("\r\n--{0}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{1}", boundary, metadata); + var folderdata = string.IsNullOrEmpty(folderId) ? "" : $",\"parents\":[\"{folderId}\"]"; + var metadata = "{{\"name\":\"" + fileName + "\"" + folderdata + "}}"; + var metadataPart = $"\r\n--{boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{metadata}"; var bytes = Encoding.UTF8.GetBytes(metadataPart); tmpStream.Write(bytes, 0, bytes.Length); - var mediaPartStart = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n", boundary, MimeMapping.GetMimeMapping(fileName)); + var mediaPartStart = $"\r\n--{boundary}\r\nContent-Type: {MimeMapping.GetMimeMapping(fileName)}\r\n\r\n"; bytes = Encoding.UTF8.GetBytes(mediaPartStart); tmpStream.Write(bytes, 0, bytes.Length); content.CopyTo(tmpStream); - var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary); + var mediaPartEnd = $"\r\n--{boundary}--\r\n"; bytes = Encoding.UTF8.GetBytes(mediaPartEnd); tmpStream.Write(bytes, 0, bytes.Length); @@ -845,10 +845,7 @@ namespace ASC.Web.Files.ThirdPartyApp fileName = FileUtility.ReplaceFileExtension(fileName, internalExt); var requiredMimeType = MimeMapping.GetMimeMapping(internalExt); - var downloadUrl = GoogleLoginProvider.GoogleUrlFile - + string.Format("{0}/export?mimeType={1}", - fileId, - HttpUtility.UrlEncode(requiredMimeType)); + var downloadUrl = GoogleLoginProvider.GoogleUrlFile + $"{fileId}/export?mimeType={HttpUtility.UrlEncode(requiredMimeType)}"; var httpClient = ClientFactory.CreateClient(); diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index 3c2d3f9e7c..9b9dd24499 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -866,13 +866,13 @@ namespace ASC.Web.Files.Utils } catch (HttpRequestException e) { - var errorString = string.Format("HttpRequestException: {0}", e.StatusCode); + var errorString = $"HttpRequestException: {e.StatusCode}"; if (e.StatusCode != HttpStatusCode.NotFound) { if (e.Message != null) { - errorString += string.Format(" Error message: {0}", e.Message); + errorString += $" Error message: {e.Message}"; } } diff --git a/products/ASC.Files/Core/Utils/MailMergeTask.cs b/products/ASC.Files/Core/Utils/MailMergeTask.cs index c1e34a1964..f23c194e37 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -100,7 +100,7 @@ namespace ASC.Web.Files.Utils private void CreateDraftMail(MailMergeTask mailMergeTask) { - var apiUrlCreate = string.Format("{0}mail/drafts/save.json", SetupInfo.WebApiBaseUrl); + var apiUrlCreate = $"{SetupInfo.WebApiBaseUrl}mail/drafts/save.json"; var bodyCreate = string.Format( MailMergeTask.MessageBodyFormat, @@ -172,7 +172,7 @@ namespace ASC.Web.Files.Utils private string SendMail(MailMergeTask mailMergeTask, string bodySendAttach) { - var apiUrlSend = string.Format("{0}mail/messages/send.json", SetupInfo.WebApiBaseUrl); + var apiUrlSend = $"{SetupInfo.WebApiBaseUrl}mail/messages/send.json"; var bodySend = string.Format( diff --git a/products/ASC.Files/Service/Core/FilesModule.cs b/products/ASC.Files/Service/Core/FilesModule.cs index f3bd00f7dc..a9b2ec8139 100644 --- a/products/ASC.Files/Service/Core/FilesModule.cs +++ b/products/ASC.Files/Service/Core/FilesModule.cs @@ -147,7 +147,7 @@ namespace ASC.Files.Service.Core ExtraLocation = rootFolder.FolderType == FolderType.DEFAULT ? rootFolder.Title : string.Empty, ExtraLocationUrl = rootFolder.FolderType == FolderType.DEFAULT ? FilesLinkUtility.GetFileRedirectPreviewUrl(file.FolderID, false) : string.Empty, AdditionalInfo = file.ContentLengthString, - Keywords = string.Format("{0}", file.Title), + Keywords = file.Title, HasPreview = false, CanComment = false, Target = shareRecord.ShareTo, @@ -170,7 +170,7 @@ namespace ASC.Files.Service.Core ExtraLocation = rootFolder.FolderType == FolderType.DEFAULT ? rootFolder.Title : string.Empty, ExtraLocationUrl = rootFolder.FolderType == FolderType.DEFAULT ? FilesLinkUtility.GetFileRedirectPreviewUrl(file.FolderID, false) : string.Empty, AdditionalInfo = file.ContentLengthString, - Keywords = string.Format("{0}", file.Title), + Keywords = file.Title, HasPreview = false, CanComment = false, Target = null, diff --git a/products/ASC.Files/Service/Core/FoldersModule.cs b/products/ASC.Files/Service/Core/FoldersModule.cs index f22db52a5e..949a499c40 100644 --- a/products/ASC.Files/Service/Core/FoldersModule.cs +++ b/products/ASC.Files/Service/Core/FoldersModule.cs @@ -110,7 +110,7 @@ namespace ASC.Files.Service.Core Title = folder.Title, ExtraLocation = rootFolder.FolderType == FolderType.DEFAULT ? rootFolder.Title : string.Empty, ExtraLocationUrl = rootFolder.FolderType == FolderType.DEFAULT ? FilesLinkUtility.GetFileRedirectPreviewUrl(folder.FolderID, false) : string.Empty, - Keywords = string.Format("{0}", folder.Title), + Keywords = folder.Title, HasPreview = false, CanComment = false, Target = shareRecord.ShareTo, @@ -130,7 +130,7 @@ namespace ASC.Files.Service.Core Title = folder.Title, ExtraLocation = rootFolder.FolderType == FolderType.DEFAULT ? rootFolder.Title : string.Empty, ExtraLocationUrl = rootFolder.FolderType == FolderType.DEFAULT ? FilesLinkUtility.GetFileRedirectPreviewUrl(folder.FolderID, false) : string.Empty, - Keywords = string.Format("{0}", folder.Title), + Keywords = folder.Title, HasPreview = false, CanComment = false, Target = null, diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index fb56fa28a6..2c42145526 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -499,7 +499,7 @@ namespace ASC.Employee.Core.Controllers } catch (Exception ex) { - Log.Debug(String.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, model.Email.ToLowerInvariant())); + Log.Debug($"ERROR write to template_unsubscribe {ex.Message}, email:{model.Email.ToLowerInvariant()}"); } } diff --git a/web/ASC.Web.Api/Controllers/CapabilitiesController.cs b/web/ASC.Web.Api/Controllers/CapabilitiesController.cs index 7c83de70a3..20550e58e1 100644 --- a/web/ASC.Web.Api/Controllers/CapabilitiesController.cs +++ b/web/ASC.Web.Api/Controllers/CapabilitiesController.cs @@ -119,8 +119,7 @@ namespace ASC.Web.Api.Controllers var configUrl = Configuration["web:sso:saml:login:url"] ?? ""; - result.SsoUrl = string.Format("{0}://{1}{2}{3}", uri.Scheme, uri.Host, - (uri.Port == 80 || uri.Port == 443) ? "" : ":" + uri.Port, configUrl); + result.SsoUrl = $"{uri.Scheme}://{uri.Host}{((uri.Port == 80 || uri.Port == 443) ? "" : ":" + uri.Port)}{configUrl}"; result.SsoLabel = string.Empty; // result.SsoLabel = settings.SpLoginLabel; //} diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index 4d3ea3fe80..f563dd5e99 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1370,7 +1370,7 @@ namespace ASC.Api.Settings try { var request = new HttpRequestMessage(); - request.RequestUri = new Uri(string.Format("{0}/tips/deletereaded", SetupInfo.TipsAddress)); + request.RequestUri = new Uri($"{SetupInfo.TipsAddress}/tips/deletereaded"); var data = new NameValueCollection { @@ -1795,7 +1795,7 @@ namespace ASC.Api.Settings MessageService.Send(MessageAction.OwnerSentChangeOwnerInstructions, MessageTarget.Create(owner.ID), owner.DisplayUserName(false, DisplayUserSettingsHelper)); - var emailLink = string.Format("<a href=\"mailto:{0}\">{0}</a>", owner.Email); + var emailLink = $"<a href=\"mailto:{owner.Email}\">{owner.Email}</a>"; return new { Status = 1, Message = Resource.ChangePortalOwnerMsg.Replace(":email", emailLink) }; } diff --git a/web/ASC.Web.Core/Calendars/BaseCalendar.cs b/web/ASC.Web.Core/Calendars/BaseCalendar.cs index d67a7a0b42..fed61d0588 100644 --- a/web/ASC.Web.Core/Calendars/BaseCalendar.cs +++ b/web/ASC.Web.Core/Calendars/BaseCalendar.cs @@ -92,11 +92,11 @@ namespace ASC.Web.Core.Calendars sb.AppendLine("METHOD:PUBLISH"); sb.AppendLine("CALSCALE:GREGORIAN"); - sb.AppendLine(string.Format("X-WR-CALNAME:{0}", Name)); - sb.AppendLine(string.Format("X-WR-TIMEZONE:{0}", TimeZoneConverter.WindowsTzId2OlsonTzId(TimeZone.Id))); + sb.AppendLine($"X-WR-CALNAME:{Name}"); + sb.AppendLine($"X-WR-TIMEZONE:{TimeZoneConverter.WindowsTzId2OlsonTzId(TimeZone.Id)}"); //tz sb.AppendLine("BEGIN:VTIMEZONE"); - sb.AppendLine(string.Format("TZID:{0}", TimeZoneConverter.WindowsTzId2OlsonTzId(TimeZone.Id))); + sb.AppendLine($"TZID:{TimeZoneConverter.WindowsTzId2OlsonTzId(TimeZone.Id)}"); sb.AppendLine("END:VTIMEZONE"); //events diff --git a/web/ASC.Web.Core/Calendars/BaseEvent.cs b/web/ASC.Web.Core/Calendars/BaseEvent.cs index 80d0ba2165..17a4a895ff 100644 --- a/web/ASC.Web.Core/Calendars/BaseEvent.cs +++ b/web/ASC.Web.Core/Calendars/BaseEvent.cs @@ -96,11 +96,14 @@ namespace ASC.Web.Core.Calendars var sb = new StringBuilder(); sb.AppendLine("BEGIN:VEVENT"); - sb.AppendLine(string.Format("UID:{0}", string.IsNullOrEmpty(this.Uid) ? this.Id : this.Uid)); - sb.AppendLine(string.Format("SUMMARY:{0}", this.Name)); + + var id = string.IsNullOrEmpty(Uid) ? Id : Uid; + + sb.AppendLine($"UID:{id}"); + sb.AppendLine($"SUMMARY:{Name}"); if (!string.IsNullOrEmpty(this.Description)) - sb.AppendLine(string.Format("DESCRIPTION:{0}", this.Description.Replace("\n", "\\n"))); + sb.AppendLine($"DESCRIPTION:{Description.Replace("\n", "\\n")}"); if (this.AllDayLong) { @@ -115,18 +118,30 @@ namespace ASC.Web.Core.Calendars } if (this.UtcStartDate != DateTime.MinValue) - sb.AppendLine(string.Format("DTSTART;VALUE=DATE:{0}", startDate.ToString("yyyyMMdd"))); + { + var start = startDate.ToString("yyyyMMdd"); + sb.AppendLine($"DTSTART;VALUE=DATE:{start}"); + } if (this.UtcEndDate != DateTime.MinValue) - sb.AppendLine(string.Format("DTEND;VALUE=DATE:{0}", endDate.AddDays(1).ToString("yyyyMMdd"))); + { + var end = endDate.AddDays(1).ToString("yyyyMMdd"); + sb.AppendLine($"DTEND;VALUE=DATE:{end}"); + } } else { if (this.UtcStartDate != DateTime.MinValue) - sb.AppendLine(string.Format("DTSTART:{0}", this.UtcStartDate.ToString("yyyyMMdd'T'HHmmss'Z'"))); + { + var utcStart = UtcStartDate.ToString("yyyyMMdd'T'HHmmss'Z'"); + sb.AppendLine($"DTSTART:{utcStart}"); + } if (this.UtcEndDate != DateTime.MinValue) - sb.AppendLine(string.Format("DTEND:{0}", this.UtcEndDate.ToString("yyyyMMdd'T'HHmmss'Z'"))); + { + var utcEnd = UtcEndDate.ToString("yyyyMMdd'T'HHmmss'Z'"); + sb.AppendLine($"DTEND:{utcEnd}"); + } } diff --git a/web/ASC.Web.Core/Calendars/BaseTodo.cs b/web/ASC.Web.Core/Calendars/BaseTodo.cs index 4b30e3e07a..6dce6fff94 100644 --- a/web/ASC.Web.Core/Calendars/BaseTodo.cs +++ b/web/ASC.Web.Core/Calendars/BaseTodo.cs @@ -80,19 +80,27 @@ namespace ASC.Web.Core.Calendars { var sb = new StringBuilder(); - sb.AppendLine("BEGIN:TODO"); - sb.AppendLine(string.Format("UID:{0}", string.IsNullOrEmpty(this.Uid) ? this.Id : this.Uid)); - sb.AppendLine(string.Format("SUMMARY:{0}", this.Name)); + sb.AppendLine("BEGIN:TODO"); + + var id = string.IsNullOrEmpty(this.Uid) ? this.Id : this.Uid; + + sb.AppendLine($"UID:{id}"); + sb.AppendLine($"SUMMARY:{Name}"); if (!string.IsNullOrEmpty(this.Description)) - sb.AppendLine(string.Format("DESCRIPTION:{0}", this.Description.Replace("\n", "\\n"))); + sb.AppendLine($"DESCRIPTION:{Description.Replace("\n", "\\n")}"); - if (this.UtcStartDate != DateTime.MinValue) - sb.AppendLine(string.Format("DTSTART:{0}", this.UtcStartDate.ToString("yyyyMMdd'T'HHmmss'Z'"))); - - if (this.Completed != DateTime.MinValue) - sb.AppendLine(string.Format("COMPLETED:{0}", this.Completed.ToString("yyyyMMdd'T'HHmmss'Z'"))); + if (this.UtcStartDate != DateTime.MinValue) + { + var utcStart = UtcStartDate.ToString("yyyyMMdd'T'HHmmss'Z'"); + sb.AppendLine($"DTSTART:{utcStart}"); + } + if (this.Completed != DateTime.MinValue) + { + var completed = Completed.ToString("yyyyMMdd'T'HHmmss'Z'"); + sb.AppendLine($"COMPLETED:{completed}"); + } sb.Append("END:TODO"); return sb.ToString(); diff --git a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs index baacd1b20d..898e889757 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -76,7 +76,7 @@ namespace ASC.Web.Core.Calendars public static string ToShortString(this DateTime targetDateTime) { - return String.Format("{0} {1}", targetDateTime.ToShortDateString(), targetDateTime.ToShortTimeString()); + return $"{targetDateTime.ToShortDateString()} {targetDateTime.ToShortTimeString()}"; } } @@ -738,23 +738,23 @@ namespace ASC.Web.Core.Calendars if (Until != DateTime.MinValue) { - sb.AppendFormat(";until={0}", Until.ToString("yyyyMMdd'T'HHmmss'Z'")); + sb.Append($";until={Until.ToString("yyyyMMdd'T'HHmmss'Z'")}"); } else if (Count >= 0) { - sb.AppendFormat(";count={0}", Count); + sb.Append($";count={Count}"); } if (Interval > 1) { - sb.AppendFormat(";interval={0}", Interval); + sb.Append($";interval={Interval}"); } if (BySecond != null && BySecond.Length > 0) { sb.Append(";bysecond="); foreach (var s in BySecond) - sb.AppendFormat("{0},", s); + sb.Append($"{s},"); sb.Remove(sb.Length - 1, 1); } @@ -833,11 +833,11 @@ namespace ASC.Web.Core.Calendars } if (WKST.DayOfWeek != DayOfWeek.Monday) - sb.AppendFormat(";wkst={0}", WKST.Id); + sb.Append($";wkst={WKST.Id}"); if (!iCal && ExDates != null && ExDates.Count > 0) { - sb.AppendFormat(";exdates="); + sb.Append(";exdates="); foreach (var d in this.ExDates) { if (d.IsDateTime) diff --git a/web/ASC.Web.Core/Extensions/UserInfoExtension.cs b/web/ASC.Web.Core/Extensions/UserInfoExtension.cs index 603170b1e1..a65d7e6a93 100644 --- a/web/ASC.Web.Core/Extensions/UserInfoExtension.cs +++ b/web/ASC.Web.Core/Extensions/UserInfoExtension.cs @@ -103,13 +103,13 @@ namespace ASC.Core.Users //check for removed users if (userInfo.ID == Constants.LostUser.ID) { - sb.AppendFormat("<span class='userLink text-medium-describe' style='white-space:nowrap;'>{0}</span>", userInfo.DisplayUserName(displayUserSettingsHelper)); + sb.Append($"<span class='userLink text-medium-describe' style='white-space:nowrap;'>{userInfo.DisplayUserName(displayUserSettingsHelper)}</span>"); } else { var popupID = Guid.NewGuid(); - sb.AppendFormat("<span class=\"userLink\" style='white-space:nowrap;' id='{0}' data-uid='{1}'>", popupID, userInfo.ID); - sb.AppendFormat("<a class='linkDescribe' href=\"{0}\">{1}</a>", userInfo.GetUserProfilePageURLGeneral(commonLinkUtility), userInfo.DisplayUserName(displayUserSettingsHelper)); + sb.Append($"<span class=\"userLink\" style='white-space:nowrap;' id='{popupID}' data-uid='{userInfo.ID}'>"); + sb.Append($"<a class='linkDescribe' href=\"{userInfo.GetUserProfilePageURLGeneral(commonLinkUtility)}\">{userInfo.DisplayUserName(displayUserSettingsHelper)}</a>"); sb.Append("</span>"); sb.AppendFormat("<script language='javascript'> StudioUserProfileInfo.RegistryElement('{0}','\"{1}\"); </script>", popupID, userInfo.ID); diff --git a/web/ASC.Web.Core/FileSizeComment.cs b/web/ASC.Web.Core/FileSizeComment.cs index c5a3e77ff7..10823dfc6a 100644 --- a/web/ASC.Web.Core/FileSizeComment.cs +++ b/web/ASC.Web.Core/FileSizeComment.cs @@ -57,12 +57,12 @@ namespace ASC.Web.Studio.Core public static string GetFileSizeExceptionString(long size) { - return string.Format("{0} ({1}).", Resource.FileSizeMaxExceed, FilesSizeToString(size)); + return $"{Resource.FileSizeMaxExceed} ({FilesSizeToString(size)})."; } public static string GetPersonalFreeSpaceExceptionString(long size) { - return string.Format("{0} ({1}).", Resource.PersonalFreeSpaceException, FilesSizeToString(size)); + return $"{Resource.PersonalFreeSpaceException} ({FilesSizeToString(size)})."; } /// <summary> diff --git a/web/ASC.Web.Core/Helpers/ApiSystemHelper.cs b/web/ASC.Web.Core/Helpers/ApiSystemHelper.cs index 713972fa7f..55678c7b92 100644 --- a/web/ASC.Web.Core/Helpers/ApiSystemHelper.cs +++ b/web/ASC.Web.Core/Helpers/ApiSystemHelper.cs @@ -74,7 +74,7 @@ namespace ASC.Web.Core.Helpers using var hasher = new HMACSHA1(Skey); var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss"); var hash = WebEncoders.Base64UrlEncode(hasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("\n", now, pkey)))); - return string.Format("ASC {0}:{1}:{2}", pkey, now, hash); + return $"ASC {pkey}:{now}:{hash}"; } #region system @@ -83,7 +83,7 @@ namespace ASC.Web.Core.Helpers { try { - var data = string.Format("portalName={0}", HttpUtility.UrlEncode(domain)); + var data = $"portalName={HttpUtility.UrlEncode(domain)}"; SendToApi(ApiSystemUrl, "portal/validateportalname", WebRequestMethods.Http.Post, userId, data); } catch (WebException exception) @@ -125,7 +125,7 @@ namespace ASC.Web.Core.Helpers public void AddTenantToCache(string domain, Guid userId) { - var data = string.Format("portalName={0}", HttpUtility.UrlEncode(domain)); + var data = $"portalName={HttpUtility.UrlEncode(domain)}"; SendToApi(ApiCacheUrl, "portal/add", WebRequestMethods.Http.Post, userId, data); } @@ -150,10 +150,10 @@ namespace ASC.Web.Core.Helpers if (!Uri.TryCreate(absoluteApiUrl, UriKind.Absolute, out var uri)) { var appUrl = CommonLinkUtility.GetFullAbsolutePath("/"); - absoluteApiUrl = string.Format("{0}/{1}", appUrl.TrimEnd('/'), absoluteApiUrl.TrimStart('/')).TrimEnd('/'); + absoluteApiUrl = $"{appUrl.TrimEnd('/')}/{absoluteApiUrl.TrimStart('/')}".TrimEnd('/'); } - var url = string.Format("{0}/{1}", absoluteApiUrl, apiPath); + var url = $"{absoluteApiUrl}/{apiPath}"; var request = new HttpRequestMessage(); request.RequestUri = new Uri(url); diff --git a/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs b/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs index 13378990f9..c83aa94c5e 100644 --- a/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs +++ b/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs @@ -88,7 +88,7 @@ namespace ASC.Web.Core.Helpers private string GetValueText(CultureInfo culture, object value) { var type = value.GetType(); - var resourceName = string.Format("{0}_{1}", type.Name, value.ToString()); + var resourceName = $"{type.Name}_{value}"; var result = _resourceManager.GetString(resourceName, culture); if (result == null) result = resourceName; @@ -144,7 +144,7 @@ namespace ASC.Web.Core.Helpers } else { - result = string.Format("{0}, {1}", result, valueText); + result = $"{result}, {valueText}"; } } } diff --git a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs index ed9ba6e6a4..8726484552 100644 --- a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs +++ b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs @@ -236,7 +236,7 @@ namespace ASC.Web.Studio.Core.Notify if (!string.IsNullOrEmpty(logoText)) { r.CurrentMessage.Body = r.CurrentMessage.Body - .Replace(string.Format("${{{0}}}", CommonTags.LetterLogoText), logoText); + .Replace("${{"+ CommonTags.LetterLogoText + "}}", logoText); } } catch (Exception error) diff --git a/web/ASC.Web.Core/Notify/StudioNotifyService.cs b/web/ASC.Web.Core/Notify/StudioNotifyService.cs index fe30c0aa20..6039ff24a6 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyService.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyService.cs @@ -253,8 +253,7 @@ namespace ASC.Web.Studio.Core.Notify if (!skipSettings) { - var link = string.Format("{0}/addons/mail/#accounts/changepwd={1}", - CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/'), address); + var link = $"{CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')}/addons/mail/#accounts/changepwd={address}"; tags.Add(new TagValue(Tags.MyStaffLink, link)); tags.Add(new TagValue(Tags.Server, server)); diff --git a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs index 2b36a1479d..e11e034ee1 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -205,7 +205,7 @@ namespace ASC.Web.Studio.Core.Notify toadmins = true; greenButtonText = () => WebstudioNotifyPatternResource.ButtonAccessYouWebOffice; - greenButtonUrl = String.Format("{0}/", commonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')); + greenButtonUrl = $"{commonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')}/"; } #endregion @@ -268,7 +268,7 @@ namespace ASC.Web.Studio.Core.Notify tableItemComment7 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_differences; greenButtonText = () => WebstudioNotifyPatternResource.ButtonAccessYouWebOffice; - greenButtonUrl = string.Format("{0}/products/files/", commonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')); + greenButtonUrl = $"{commonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')}/products/files/"; } #endregion @@ -623,7 +623,7 @@ namespace ASC.Web.Studio.Core.Notify toadmins = true; greenButtonText = () => WebstudioNotifyPatternResource.ButtonInviteRightNow; - greenButtonUrl = string.Format("{0}/products/people/", commonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')); + greenButtonUrl = $"{commonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')}/products/people/"; } #endregion @@ -696,7 +696,7 @@ namespace ASC.Web.Studio.Core.Notify tableItemComment7 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_apps; greenButtonText = () => WebstudioNotifyPatternResource.ButtonAccessYouWebOffice; - greenButtonUrl = string.Format("{0}/products/files/", commonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')); + greenButtonUrl = $"{commonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')}/products/files/"; } #endregion diff --git a/web/ASC.Web.Core/Notify/TagValues.cs b/web/ASC.Web.Core/Notify/TagValues.cs index d37196f810..06b09bb682 100644 --- a/web/ASC.Web.Core/Notify/TagValues.cs +++ b/web/ASC.Web.Core/Notify/TagValues.cs @@ -53,14 +53,10 @@ namespace ASC.Web.Studio.Core.Notify string action() { var btnText = btnTextFunc != null ? btnTextFunc() ?? string.Empty : string.Empty; - - return - string.Format( - @"<table style=""height: 48px; width: 540px; border-collapse: collapse; empty-cells: show; vertical-align: middle; text-align: center; margin: 30px auto; padding: 0;""><tbody><tr cellpadding=""0"" cellspacing=""0"" border=""0"">{2}<td style=""height: 48px; width: 380px; margin:0; padding:0; background-color: #66b76d; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px;""><a style=""{3}"" target=""_blank"" href=""{0}"">{1}</a></td>{2}</tr></tbody></table>", - btnUrl, - btnText, - "<td style=\"height: 48px; width: 80px; margin:0; padding:0;\"> </td>", - "color: #fff; font-family: Helvetica, Arial, Tahoma; font-size: 18px; font-weight: 600; vertical-align: middle; display: block; padding: 12px 0; text-align: center; text-decoration: none; background-color: #66b76d;"); + var td = "<td style=\"height: 48px; width: 80px; margin:0; padding:0;\"> </td>"; + var color = "color: #fff; font-family: Helvetica, Arial, Tahoma; font-size: 18px; font-weight: 600; vertical-align: middle; display: block; padding: 12px 0; text-align: center; text-decoration: none; background-color: #66b76d;"; + + return $@"<table style=""height: 48px; width: 540px; border-collapse: collapse; empty-cells: show; vertical-align: middle; text-align: center; margin: 30px auto; padding: 0;""><tbody><tr cellpadding=""0"" cellspacing=""0"" border=""0"">{td}<td style=""height: 48px; width: 380px; margin:0; padding:0; background-color: #66b76d; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px;""><a style=""{color}"" target=""_blank"" href=""{btnUrl}"">{btnText}</a></td>{td}</tr></tbody></table>"; } return new ASC.Notify.Patterns.TagActionValue("BlueButton", action); @@ -71,14 +67,10 @@ namespace ASC.Web.Studio.Core.Notify string action() { var btnText = btnTextFunc != null ? btnTextFunc() ?? string.Empty : string.Empty; + var td = "<td style=\"height: 48px; width: 80px; margin:0; padding:0;\"> </td>"; + var color = "color: #fff; font-family: Helvetica, Arial, Tahoma; font-size: 18px; font-weight: 600; vertical-align: middle; display: block; padding: 12px 0; text-align: center; text-decoration: none; background-color: #66b76d;"; - return - string.Format( - @"<table style=""height: 48px; width: 540px; border-collapse: collapse; empty-cells: show; vertical-align: middle; text-align: center; margin: 30px auto; padding: 0;""><tbody><tr cellpadding=""0"" cellspacing=""0"" border=""0"">{2}<td style=""height: 48px; width: 380px; margin:0; padding:0; background-color: #66b76d; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px;""><a style=""{3}"" target=""_blank"" href=""{0}"">{1}</a></td>{2}</tr></tbody></table>", - btnUrl, - btnText, - "<td style=\"height: 48px; width: 80px; margin:0; padding:0;\"> </td>", - "color: #fff; font-family: Helvetica, Arial, Tahoma; font-size: 18px; font-weight: 600; vertical-align: middle; display: block; padding: 12px 0; text-align: center; text-decoration: none; background-color: #66b76d;"); + return $@"<table style=""height: 48px; width: 540px; border-collapse: collapse; empty-cells: show; vertical-align: middle; text-align: center; margin: 30px auto; padding: 0;""><tbody><tr cellpadding=""0"" cellspacing=""0"" border=""0"">{td}<td style=""height: 48px; width: 380px; margin:0; padding:0; background-color: #66b76d; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px;""><a style=""{3}"" target=""_blank"" href=""{btnUrl}"">{btnText}</a></td>{td}</tr></tbody></table>"; } return new TagActionValue("GreenButton", action); @@ -112,10 +104,7 @@ namespace ASC.Web.Studio.Core.Notify ? bottomlinkTextFunc() ?? string.Empty : string.Empty; - var imgHtml = string.Format( - "<img style=\"border: 0; padding: 0 15px 0 5px; width: auto; height: auto;\" alt=\"{1}\" src=\"{0}\"/>", - imgSrc ?? string.Empty, - linkText); + var imgHtml = $"<img style=\"border: 0; padding: 0 15px 0 5px; width: auto; height: auto;\" alt=\"{linkText}\" src=\"{imgSrc ?? string.Empty}\"/>"; var linkHtml = string.Empty; @@ -123,22 +112,14 @@ namespace ASC.Web.Studio.Core.Notify { linkHtml = !string.IsNullOrEmpty(linkUrl) - ? string.Format( - "<a target=\"_blank\" style=\"color:#0078bd; font-family: Arial; font-size: 14px; font-weight: bold;\" href=\"{0}\">{1}</a><br/>", - linkUrl, - linkText) - : string.Format( - "<div style=\"display:block; color:#333333; font-family: Arial; font-size: 14px; font-weight: bold;margin-bottom: 10px;\">{0}</div>", - linkText); + ? $"<a target=\"_blank\" style=\"color:#0078bd; font-family: Arial; font-size: 14px; font-weight: bold;\" href=\"{linkUrl}\">{linkText}</a><br/>" + : $"<div style=\"display:block; color:#333333; font-family: Arial; font-size: 14px; font-weight: bold;margin-bottom: 10px;\">{linkText}</div>"; } var underCommentLinkHtml = string.IsNullOrEmpty(bottomlinkUrl) ? string.Empty - : string.Format( - "<br/><a target=\"_blank\" style=\"color: #0078bd; font-family: Arial; font-size: 14px;\" href=\"{0}\">{1}</a>", - bottomlinkUrl, - bottomlinkText); + : $"<br/><a target=\"_blank\" style=\"color: #0078bd; font-family: Arial; font-size: 14px;\" href=\"{bottomlinkUrl}\">{bottomlinkText}</a>"; var html = "<tr><td style=\"vertical-align: top; padding: 5px 10px; width: 70px;\">" + @@ -159,7 +140,7 @@ namespace ASC.Web.Studio.Core.Notify { var imgSrc = studioNotifyHelper.GetNotificationImageUrl(imageFileName); - var imgHtml = string.Format("<img style=\"border: 0; padding: 0; width: auto; height: auto;\" alt=\"\" src=\"{0}\"/>", imgSrc); + var imgHtml = $"<img style=\"border: 0; padding: 0; width: auto; height: auto;\" alt=\"\" src=\"{imgSrc}\"/>"; var tagName = "Image" + (id > 0 ? id.ToString() : string.Empty); diff --git a/web/ASC.Web.Core/Recaptcha.cs b/web/ASC.Web.Core/Recaptcha.cs index cccc9dd80f..1b4207a7c1 100644 --- a/web/ASC.Web.Core/Recaptcha.cs +++ b/web/ASC.Web.Core/Recaptcha.cs @@ -40,7 +40,7 @@ namespace ASC.Web.Core { try { - var data = string.Format("secret={0}&remoteip={1}&response={2}", SetupInfo.RecaptchaPrivateKey, ip, response); + var data = $"secret={SetupInfo.RecaptchaPrivateKey}&remoteip={ip}&response={response}"; var request = new HttpRequestMessage(); request.RequestUri = new Uri(SetupInfo.RecaptchaVerifyUrl); diff --git a/web/ASC.Web.Core/Users/UserManagerWrapper.cs b/web/ASC.Web.Core/Users/UserManagerWrapper.cs index 234745d495..e015bde108 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -105,7 +105,7 @@ namespace ASC.Web.Core.Users var i = 0; while (!TestUniqueUserName(uniqueName)) { - uniqueName = string.Format("{0}{1}", startUniqueName, (++i).ToString(CultureInfo.InvariantCulture)); + uniqueName = $"{startUniqueName}{(++i).ToString(CultureInfo.InvariantCulture)}"; } return uniqueName; } @@ -311,14 +311,14 @@ namespace ASC.Web.Core.Users { var error = new StringBuilder(); - error.AppendFormat("{0} ", Resource.ErrorPasswordMessage); + error.Append($"{Resource.ErrorPasswordMessage} "); error.AppendFormat(Resource.ErrorPasswordLength, passwordSettings.MinLength, PasswordSettings.MaxLength); if (passwordSettings.UpperCase) - error.AppendFormat(", {0}", Resource.ErrorPasswordNoUpperCase); + error.AppendFormat($", {Resource.ErrorPasswordNoUpperCase}"); if (passwordSettings.Digits) - error.AppendFormat(", {0}", Resource.ErrorPasswordNoDigits); + error.Append($", {Resource.ErrorPasswordNoDigits}"); if (passwordSettings.SpecSymbols) - error.AppendFormat(", {0}", Resource.ErrorPasswordNoSpecialSymbols); + error.Append($", {Resource.ErrorPasswordNoSpecialSymbols}"); return error.ToString(); } @@ -327,14 +327,14 @@ namespace ASC.Web.Core.Users { var info = new StringBuilder(); var passwordSettings = SettingsManager.Load<PasswordSettings>(); - info.AppendFormat("{0} ", Resource.ErrorPasswordMessageStart); + info.Append($"{Resource.ErrorPasswordMessageStart} "); info.AppendFormat(Resource.ErrorPasswordLength, passwordSettings.MinLength, PasswordSettings.MaxLength); if (passwordSettings.UpperCase) - info.AppendFormat(", {0}", Resource.ErrorPasswordNoUpperCase); + info.Append($", {Resource.ErrorPasswordNoUpperCase}"); if (passwordSettings.Digits) - info.AppendFormat(", {0}", Resource.ErrorPasswordNoDigits); + info.Append($", {Resource.ErrorPasswordNoDigits}"); if (passwordSettings.SpecSymbols) - info.AppendFormat(", {0}", Resource.ErrorPasswordNoSpecialSymbols); + info.Append($", {Resource.ErrorPasswordNoSpecialSymbols}"); return info.ToString(); } diff --git a/web/ASC.Web.Core/Utility/UrlShortener.cs b/web/ASC.Web.Core/Utility/UrlShortener.cs index 32f94f8eec..2bdac1c3aa 100644 --- a/web/ASC.Web.Core/Utility/UrlShortener.cs +++ b/web/ASC.Web.Core/Utility/UrlShortener.cs @@ -134,7 +134,7 @@ namespace ASC.Web.Core.Utility using var hasher = new HMACSHA1(sKey); var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss"); var hash = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("\n", now, pkey)))); - return string.Format("ASC {0}:{1}:{2}", pkey, now, hash); + return $"ASC {pkey}:{now}:{hash}"; } } diff --git a/web/ASC.Web.Core/WebItemManager.cs b/web/ASC.Web.Core/WebItemManager.cs index cd8af9da70..fd15c79ec0 100644 --- a/web/ASC.Web.Core/WebItemManager.cs +++ b/web/ASC.Web.Core/WebItemManager.cs @@ -156,7 +156,7 @@ namespace ASC.Web.Core } catch (Exception exc) { - log.Error(string.Format("Couldn't load web item {0}", file), exc); + log.Error($"Couldn't load web item {file}", exc); } } diff --git a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs index 2b9280f443..5c049aca8b 100644 --- a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs +++ b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs @@ -500,7 +500,7 @@ namespace ASC.Web.Core.WhiteLabel public static string BuildLogoFileName(WhiteLabelLogoTypeEnum type, string fileExt, bool general) { - return string.Format("logo_{0}{2}.{1}", type.ToString().ToLowerInvariant(), fileExt, general ? "_general" : ""); + return $"logo_{type.ToString().ToLowerInvariant()}{(general ? "_general" : "")}.{fileExt}"; } public static Size GetSize(WhiteLabelLogoTypeEnum type, bool general) From b9884e6b814083722198d224582affb013c5275d Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 14 Jan 2022 16:32:06 +0300 Subject: [PATCH 043/167] Analizators/U2U1107 --- .../Notify/Cron/CronExpression.cs | 28 +++++++++---------- .../Tasks/BackupPortalTask.cs | 2 +- common/ASC.Data.Storage/S3/S3Storage.cs | 2 +- web/ASC.Web.Core/Calendars/RecurrenceRule.cs | 4 +-- web/ASC.Web.Core/Sms/SmsSender.cs | 4 +-- web/ASC.Web.Core/Users/UserManagerWrapper.cs | 6 ++-- 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs index 93111a8164..17ac36d4c7 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -737,43 +737,43 @@ namespace ASC.Notify.Cron var buf = new StringBuilder(); buf.Append("seconds: "); buf.Append(GetExpressionSetSummary(seconds)); - buf.Append("\n"); + buf.Append('\n'); buf.Append("minutes: "); buf.Append(GetExpressionSetSummary(minutes)); - buf.Append("\n"); + buf.Append('\n'); buf.Append("hours: "); buf.Append(GetExpressionSetSummary(hours)); - buf.Append("\n"); + buf.Append('\n'); buf.Append("daysOfMonth: "); buf.Append(GetExpressionSetSummary(daysOfMonth)); - buf.Append("\n"); + buf.Append('\n'); buf.Append("months: "); buf.Append(GetExpressionSetSummary(months)); - buf.Append("\n"); + buf.Append('\n'); buf.Append("daysOfWeek: "); buf.Append(GetExpressionSetSummary(daysOfWeek)); - buf.Append("\n"); + buf.Append('\n'); buf.Append("lastdayOfWeek: "); buf.Append(lastdayOfWeek); - buf.Append("\n"); + buf.Append('\n'); buf.Append("nearestWeekday: "); buf.Append(nearestWeekday); - buf.Append("\n"); + buf.Append('\n'); buf.Append("NthDayOfWeek: "); buf.Append(nthdayOfWeek); - buf.Append("\n"); + buf.Append('\n'); buf.Append("lastdayOfMonth: "); buf.Append(lastdayOfMonth); - buf.Append("\n"); + buf.Append('\n'); buf.Append("calendardayOfWeek: "); buf.Append(calendardayOfWeek); - buf.Append("\n"); + buf.Append('\n'); buf.Append("calendardayOfMonth: "); buf.Append(calendardayOfMonth); - buf.Append("\n"); + buf.Append('\n'); buf.Append("years: "); buf.Append(GetExpressionSetSummary(years)); - buf.Append("\n"); + buf.Append('\n'); return buf.ToString(); } @@ -794,7 +794,7 @@ namespace ASC.Notify.Cron var val = iVal.ToString(CultureInfo.InvariantCulture); if (!first) { - buf.Append(","); + buf.Append(','); } buf.Append(val); first = false; diff --git a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs index a858385af6..4b7c73cd98 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -230,7 +230,7 @@ namespace ASC.Data.Backup.Tasks creates.Append(createScheme .Select(r => Convert.ToString(r[1])) .FirstOrDefault()); - creates.Append(";"); + creates.Append(';'); var path = CrossPlatform.PathCombine(dir, t); using (var stream = File.OpenWrite(path)) diff --git a/common/ASC.Data.Storage/S3/S3Storage.cs b/common/ASC.Data.Storage/S3/S3Storage.cs index 7b4489040f..139a2a92a9 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -727,7 +727,7 @@ namespace ASC.Data.Storage.S3 var policyBase64 = GetPolicyBase64(key, string.Empty, contentType, contentDisposition, maxUploadSize, out var sign); var postBuilder = new StringBuilder(); - postBuilder.Append("{"); + postBuilder.Append('{'); postBuilder.Append("\"key\":\"").Append(key).Append("${{filename}}\","); postBuilder.Append("\"acl\":\"public-read\","); postBuilder.Append($"\"key\":\"{key}\","); diff --git a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs index 898e889757..314920d7bb 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -989,7 +989,7 @@ namespace ASC.Web.Core.Calendars if (!this.ExDates[0].IsDateTime) sb.Append(";VALUE=DATE"); - sb.Append(":"); + sb.Append(':'); foreach (var d in this.ExDates) { if (d.IsDateTime) @@ -997,7 +997,7 @@ namespace ASC.Web.Core.Calendars else sb.Append(d.Date.ToString("yyyyMMdd")); - sb.Append(","); + sb.Append(','); } sb.Remove(sb.Length - 1, 1); } diff --git a/web/ASC.Web.Core/Sms/SmsSender.cs b/web/ASC.Web.Core/Sms/SmsSender.cs index ba3afbfe63..634b65d881 100644 --- a/web/ASC.Web.Core/Sms/SmsSender.cs +++ b/web/ASC.Web.Core/Sms/SmsSender.cs @@ -106,11 +106,11 @@ namespace ASC.Web.Core.Sms return mobilePhone; var sb = new StringBuilder(); - sb.Append("+"); + sb.Append('+'); sb.Append(mobilePhone.Substring(0, startLen)); for (var i = startLen; i < mobilePhone.Length - endLen; i++) { - sb.Append("*"); + sb.Append('*'); } sb.Append(mobilePhone.Substring(mobilePhone.Length - endLen)); return sb.ToString(); diff --git a/web/ASC.Web.Core/Users/UserManagerWrapper.cs b/web/ASC.Web.Core/Users/UserManagerWrapper.cs index e015bde108..032e7cb6f7 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -235,12 +235,12 @@ namespace ASC.Web.Core.Users if (passwordSettings.SpecSymbols) pwdBuilder.Append(@"(?=.*[\W])"); - pwdBuilder.Append(@"."); + pwdBuilder.Append('.'); } - pwdBuilder.Append(@"{"); + pwdBuilder.Append('{'); pwdBuilder.Append(passwordSettings.MinLength); - pwdBuilder.Append(@","); + pwdBuilder.Append(','); pwdBuilder.Append(PasswordSettings.MaxLength); pwdBuilder.Append(@"}$"); From 516cd2fd8035ec65be3db4e44d11957050ceca91 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 14 Jan 2022 16:44:02 +0300 Subject: [PATCH 044/167] analizators/U2U1111 --- web/ASC.Web.Core/Sms/SmsSender.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/ASC.Web.Core/Sms/SmsSender.cs b/web/ASC.Web.Core/Sms/SmsSender.cs index 634b65d881..e903983ab9 100644 --- a/web/ASC.Web.Core/Sms/SmsSender.cs +++ b/web/ASC.Web.Core/Sms/SmsSender.cs @@ -107,12 +107,12 @@ namespace ASC.Web.Core.Sms var sb = new StringBuilder(); sb.Append('+'); - sb.Append(mobilePhone.Substring(0, startLen)); + sb.Append(mobilePhone, 0, startLen); for (var i = startLen; i < mobilePhone.Length - endLen; i++) { sb.Append('*'); } - sb.Append(mobilePhone.Substring(mobilePhone.Length - endLen)); + sb.Append(mobilePhone, mobilePhone.Length - endLen, mobilePhone.Length - (endLen +1)); return sb.ToString(); } } From 0ee1a354248cf0abcf250116dc7332e85488a337 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 17 Jan 2022 11:22:52 +0300 Subject: [PATCH 045/167] analizators/U2U1115 --- common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs | 4 ++-- common/ASC.Api.Core/Auth/CookieAuthHandler.cs | 2 +- common/ASC.Data.Backup.Core/BackupAjaxHandler.cs | 4 ++-- .../services/ASC.ApiSystem/Classes/AuthHandler.cs | 12 ++++++------ .../ASC.ElasticSearch/Engine/BaseIndexer.cs | 14 +++++++------- products/ASC.CRM/Server/Api/UtilsController.cs | 2 +- products/ASC.CRM/Server/Api/VoipController.cs | 2 +- .../Server/Controllers/CalendarController.cs | 4 ++-- products/ASC.Files/Core/Helpers/DocuSignHelper.cs | 6 +++--- .../Controllers/CapabilitiesController.cs | 4 ++-- web/ASC.Web.Api/Controllers/SecurityController.cs | 12 ++++++------ web/ASC.Web.Api/Controllers/SettingsController.cs | 10 +++++----- .../Controllers/SmtpSettingsController.cs | 2 +- web/ASC.Web.Core/PrivacyRoomSettings.cs | 2 +- 14 files changed, 40 insertions(+), 40 deletions(-) diff --git a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs index 9b4d611e27..4b3bf08b28 100644 --- a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs @@ -53,7 +53,7 @@ namespace ASC.Api.Core.Auth { return SecurityContext.IsAuthenticated ? Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name))) - : Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString()))); + : Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Unauthorized)))); } EmailValidationKeyProvider.ValidationResult checkKeyResult; @@ -105,7 +105,7 @@ namespace ASC.Api.Core.Auth var result = checkKeyResult switch { EmailValidationKeyProvider.ValidationResult.Ok => AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)), - _ => AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString())) + _ => AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Unauthorized))) }; return Task.FromResult(result); diff --git a/common/ASC.Api.Core/Auth/CookieAuthHandler.cs b/common/ASC.Api.Core/Auth/CookieAuthHandler.cs index 1316ab3185..13590079a6 100644 --- a/common/ASC.Api.Core/Auth/CookieAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/CookieAuthHandler.cs @@ -50,7 +50,7 @@ namespace ASC.Api.Core.Auth return Task.FromResult( result ? AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)) : - AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString())) + AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Unauthorized))) ); } } diff --git a/common/ASC.Data.Backup.Core/BackupAjaxHandler.cs b/common/ASC.Data.Backup.Core/BackupAjaxHandler.cs index 694fd05bf9..831849fcb5 100644 --- a/common/ASC.Data.Backup.Core/BackupAjaxHandler.cs +++ b/common/ASC.Data.Backup.Core/BackupAjaxHandler.cs @@ -233,7 +233,7 @@ namespace ASC.Data.Backup { PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings); - if (!SetupInfo.IsVisibleSettings(ManagementType.Backup.ToString())) + if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.Backup))) throw new BillingException(Resource.ErrorNotAllowedOption, "Backup"); } @@ -319,7 +319,7 @@ namespace ASC.Data.Backup PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var currentUser = UserManager.GetUsers(SecurityContext.CurrentAccount.ID); - if (!SetupInfo.IsVisibleSettings(ManagementType.Migration.ToString()) + if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.Migration)) || !currentUser.IsOwner(TenantManager.GetCurrentTenant()) || !SetupInfo.IsSecretEmail(currentUser.Email) && !TenantExtra.GetTenantQuota().HasMigration) throw new InvalidOperationException(Resource.ErrorNotAllowedOption); diff --git a/common/services/ASC.ApiSystem/Classes/AuthHandler.cs b/common/services/ASC.ApiSystem/Classes/AuthHandler.cs index d3119f2701..607ea5d446 100644 --- a/common/services/ASC.ApiSystem/Classes/AuthHandler.cs +++ b/common/services/ASC.ApiSystem/Classes/AuthHandler.cs @@ -105,7 +105,7 @@ namespace ASC.ApiSystem.Classes { Log.Debug("Auth header is NULL"); - return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString()))); + return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Unauthorized)))); } var substring = "ASC"; @@ -118,7 +118,7 @@ namespace ASC.ApiSystem.Classes { Log.DebugFormat("Auth failed: invalid token {0}.", header); - return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString()))); + return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Unauthorizednameof()))); } var pkey = splitted[0]; @@ -137,7 +137,7 @@ namespace ASC.ApiSystem.Classes { Log.DebugFormat("Auth failed: invalid timesatmp {0}, now {1}.", timestamp, DateTime.UtcNow); - return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Forbidden.ToString()))); + return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Forbidden)))); } } @@ -150,21 +150,21 @@ namespace ASC.ApiSystem.Classes { Log.DebugFormat("Auth failed: invalid token {0}, expect {1} or {2}.", orighash, WebEncoders.Base64UrlEncode(hash), Convert.ToBase64String(hash)); - return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Forbidden.ToString()))); + return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Forbidden)))); } } else { Log.DebugFormat("Auth failed: invalid auth header. Sheme: {0}, parameter: {1}.", Scheme.Name, header); - return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Forbidden.ToString()))); + return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Forbidden)))); } } catch (Exception ex) { Log.Error(ex); - return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.InternalServerError.ToString()))); + return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.InternalServerError)))); } var identity = new ClaimsIdentity( Scheme.Name); diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index c5df10a50f..59ce729c99 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -426,21 +426,21 @@ namespace ASC.ElasticSearch foreach (var c in Enum.GetNames(typeof(Analyzer))) { var c1 = c; - b.Custom(c1 + "custom", ca => ca.Tokenizer(c1).Filters(Filter.lowercase.ToString()).CharFilters(CharFilter.io.ToString())); + b.Custom(c1 + "custom", ca => ca.Tokenizer(c1).Filters(nameof(Filter.lowercase)).CharFilters(nameof(CharFilter.io))); } foreach (var c in Enum.GetNames(typeof(CharFilter))) { - if (c == CharFilter.io.ToString()) continue; + if (c == nameof(CharFilter.io)) continue; - var charFilters = new List<string>() { CharFilter.io.ToString(), c }; + var charFilters = new List<string>() { nameof(CharFilter.io), c }; var c1 = c; - b.Custom(c1 + "custom", ca => ca.Tokenizer(Analyzer.whitespace.ToString()).Filters(Filter.lowercase.ToString()).CharFilters(charFilters)); + b.Custom(c1 + "custom", ca => ca.Tokenizer(nameof(Analyzer.whitespace)).Filters(nameof(Filter.lowercase)).CharFilters(charFilters)); } if (data is ISearchItemDocument) { - b.Custom("document", ca => ca.Tokenizer(Analyzer.whitespace.ToString()).Filters(Filter.lowercase.ToString()).CharFilters(CharFilter.io.ToString())); + b.Custom("document", ca => ca.Tokenizer(nameof(Analyzer.whitespace)).Filters(nameof(Filter.lowercase)).CharFilters(nameof(CharFilter.io))); } return b; @@ -451,8 +451,8 @@ namespace ASC.ElasticSearch c.Map<T>(m => m.AutoMap()) .Settings(r => r.Analysis(a => a.Analyzers(analyzers) - .CharFilters(d => d.HtmlStrip(CharFilter.html.ToString()) - .Mapping(CharFilter.io.ToString(), m => m.Mappings("Ñ‘ => е", "Ð => Е")))))); + .CharFilters(d => d.HtmlStrip(nameof(CharFilter.html)) + .Mapping(nameof(CharFilter.io), m => m.Mappings("Ñ‘ => е", "Ð => Е")))))); IsExist = true; } diff --git a/products/ASC.CRM/Server/Api/UtilsController.cs b/products/ASC.CRM/Server/Api/UtilsController.cs index cb8a780de1..63027453bd 100644 --- a/products/ASC.CRM/Server/Api/UtilsController.cs +++ b/products/ASC.CRM/Server/Api/UtilsController.cs @@ -304,7 +304,7 @@ namespace ASC.CRM.Api var companyAddress = JsonSerializer.Serialize(new { - type = AddressCategory.Billing.ToString(), + type = nameof(AddressCategory.Billing), street, city, state, diff --git a/products/ASC.CRM/Server/Api/VoipController.cs b/products/ASC.CRM/Server/Api/VoipController.cs index 0e2dd31590..8272fb092f 100644 --- a/products/ASC.CRM/Server/Api/VoipController.cs +++ b/products/ASC.CRM/Server/Api/VoipController.cs @@ -390,7 +390,7 @@ namespace ASC.CRM.Api return new { queue = number.Settings.Queue, pause = number.Settings.Pause }; } - var files = _storageFactory.GetStorage("", "crm").ListFiles("voip", "default/" + AudioType.Queue.ToString().ToLower(), "*.*", true); + var files = _storageFactory.GetStorage("", "crm").ListFiles("voip", "default/" + nameof(AudioType.Queue).ToLower(), "*.*", true); var file = files.FirstOrDefault(); return new { queue = new Queue(null, "Default", 5, file != null ? _commonLinkUtility.GetFullAbsolutePath(file.ToString()) : "", 5), pause = false }; } diff --git a/products/ASC.Calendar/Server/Controllers/CalendarController.cs b/products/ASC.Calendar/Server/Controllers/CalendarController.cs index 6cae096572..cc16401996 100644 --- a/products/ASC.Calendar/Server/Controllers/CalendarController.cs +++ b/products/ASC.Calendar/Server/Controllers/CalendarController.cs @@ -926,7 +926,7 @@ namespace ASC.Calendar.Controllers { evt.End = new CalDateTime(evt.End.AddDays(1)); } - evt.Status = EventStatus.Confirmed.ToString(); + evt.Status = nameof(EventStatus.Confirmed); if (alert > 0) { evt.Alarms.Add( @@ -3958,7 +3958,7 @@ namespace ASC.Calendar.Controllers else if (calendarId == "crm_calendar" || calendarId.Contains("Project_")) { e.Created = null; - e.Status = EventStatus.Confirmed.ToString(); + e.Status = nameof(EventStatus.Confirmed); } calendar.Events.Clear(); diff --git a/products/ASC.Files/Core/Helpers/DocuSignHelper.cs b/products/ASC.Files/Core/Helpers/DocuSignHelper.cs index 2246221241..13f24d05a9 100644 --- a/products/ASC.Files/Core/Helpers/DocuSignHelper.cs +++ b/products/ASC.Files/Core/Helpers/DocuSignHelper.cs @@ -302,9 +302,9 @@ namespace ASC.Web.Files.Helpers { //new EnvelopeEvent {EnvelopeEventStatusCode = DocuSignStatus.Sent.ToString()}, //new EnvelopeEvent {EnvelopeEventStatusCode = DocuSignStatus.Delivered.ToString()}, - new EnvelopeEvent {EnvelopeEventStatusCode = DocuSignStatus.Completed.ToString()}, - new EnvelopeEvent {EnvelopeEventStatusCode = DocuSignStatus.Declined.ToString()}, - new EnvelopeEvent {EnvelopeEventStatusCode = DocuSignStatus.Voided.ToString()}, + new EnvelopeEvent {EnvelopeEventStatusCode = nameof(DocuSignStatus.Completed)}, + new EnvelopeEvent {EnvelopeEventStatusCode = nameof(DocuSignStatus.Declined)}, + new EnvelopeEvent {EnvelopeEventStatusCode = nameof(DocuSignStatus.Voided)}, }, IncludeDocumentFields = "true", //RecipientEvents = new List<RecipientEvent> diff --git a/web/ASC.Web.Api/Controllers/CapabilitiesController.cs b/web/ASC.Web.Api/Controllers/CapabilitiesController.cs index 20550e58e1..9a4f50d326 100644 --- a/web/ASC.Web.Api/Controllers/CapabilitiesController.cs +++ b/web/ASC.Web.Api/Controllers/CapabilitiesController.cs @@ -77,7 +77,7 @@ namespace ASC.Web.Api.Controllers try { - if (SetupInfo.IsVisibleSettings(ManagementType.LdapSettings.ToString()) + if (SetupInfo.IsVisibleSettings(nameof(ManagementType.LdapSettings)) && (!CoreBaseSettings.Standalone || TenantManager.GetTenantQuota(TenantManager.GetCurrentTenant().TenantId).Ldap)) { @@ -108,7 +108,7 @@ namespace ASC.Web.Api.Controllers try { - if (SetupInfo.IsVisibleSettings(ManagementType.SingleSignOnSettings.ToString()) + if (SetupInfo.IsVisibleSettings(nameof(ManagementType.SingleSignOnSettings)) && TenantManager.GetTenantQuota(TenantManager.GetCurrentTenant().TenantId).Sso) { //var settings = SettingsManager.Load<SsoSettingsV2>(); diff --git a/web/ASC.Web.Api/Controllers/SecurityController.cs b/web/ASC.Web.Api/Controllers/SecurityController.cs index 0b9a81ca5c..b8d0f40bd5 100644 --- a/web/ASC.Web.Api/Controllers/SecurityController.cs +++ b/web/ASC.Web.Api/Controllers/SecurityController.cs @@ -60,7 +60,7 @@ namespace ASC.Web.Api.Controllers [Read("audit/login/last")] public IEnumerable<EventWrapper> GetLastLoginEvents() { - if (!SetupInfo.IsVisibleSettings(ManagementType.LoginHistory.ToString())) + if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory))) { throw new BillingException(Resource.ErrorNotAllowedOption, "Audit"); } @@ -73,7 +73,7 @@ namespace ASC.Web.Api.Controllers [Read("audit/events/last")] public IEnumerable<EventWrapper> GetLastAuditEvents() { - if (!SetupInfo.IsVisibleSettings(ManagementType.AuditTrail.ToString())) + if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.AuditTrail))) { throw new BillingException(Resource.ErrorNotAllowedOption, "Audit"); } @@ -90,7 +90,7 @@ namespace ASC.Web.Api.Controllers var tenantId = TenantManager.GetCurrentTenant().TenantId; - if (!TenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(ManagementType.LoginHistory.ToString())) + if (!TenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory))) throw new BillingException(Resource.ErrorNotAllowedOption, "Audit"); var settings = SettingsManager.LoadForTenant<TenantAuditSettings>(TenantManager.GetCurrentTenant().TenantId); @@ -113,7 +113,7 @@ namespace ASC.Web.Api.Controllers var tenantId = TenantManager.GetCurrentTenant().TenantId; - if (!TenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(ManagementType.AuditTrail.ToString())) + if (!TenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(nameof(ManagementType.AuditTrail))) throw new BillingException(Resource.ErrorNotAllowedOption, "Audit"); var settings = SettingsManager.LoadForTenant<TenantAuditSettings>(TenantManager.GetCurrentTenant().TenantId); @@ -133,7 +133,7 @@ namespace ASC.Web.Api.Controllers [Read("audit/settings/lifetime")] public TenantAuditSettings GetAuditSettings() { - if (!SetupInfo.IsVisibleSettings(ManagementType.LoginHistory.ToString())) + if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory))) { throw new BillingException(Resource.ErrorNotAllowedOption, "Audit"); } @@ -158,7 +158,7 @@ namespace ASC.Web.Api.Controllers private TenantAuditSettings SetAuditSettings(TenantAuditSettingsWrapper wrapper) { - if (!TenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(ManagementType.LoginHistory.ToString())) + if (!TenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory))) throw new BillingException(Resource.ErrorNotAllowedOption, "Audit"); PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings); diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index f563dd5e99..a1c50594de 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1188,10 +1188,10 @@ namespace ASC.Api.Settings return new[] { - new {type = (int)WhiteLabelLogoTypeEnum.LightSmall, name = WhiteLabelLogoTypeEnum.LightSmall.ToString(), height = TenantWhiteLabelSettings.logoLightSmallSize.Height, width = TenantWhiteLabelSettings.logoLightSmallSize.Width}, - new {type = (int)WhiteLabelLogoTypeEnum.Dark, name = WhiteLabelLogoTypeEnum.Dark.ToString(), height = TenantWhiteLabelSettings.logoDarkSize.Height, width = TenantWhiteLabelSettings.logoDarkSize.Width}, - new {type = (int)WhiteLabelLogoTypeEnum.Favicon, name = WhiteLabelLogoTypeEnum.Favicon.ToString(), height = TenantWhiteLabelSettings.logoFaviconSize.Height, width = TenantWhiteLabelSettings.logoFaviconSize.Width}, - new {type = (int)WhiteLabelLogoTypeEnum.DocsEditor, name = WhiteLabelLogoTypeEnum.DocsEditor.ToString(), height = TenantWhiteLabelSettings.logoDocsEditorSize.Height, width = TenantWhiteLabelSettings.logoDocsEditorSize.Width} + new {type = (int)WhiteLabelLogoTypeEnum.LightSmall, name = nameof(WhiteLabelLogoTypeEnum.LightSmall), height = TenantWhiteLabelSettings.logoLightSmallSize.Height, width = TenantWhiteLabelSettings.logoLightSmallSize.Width}, + new {type = (int)WhiteLabelLogoTypeEnum.Dark, name = nameof(WhiteLabelLogoTypeEnum.Dark), height = TenantWhiteLabelSettings.logoDarkSize.Height, width = TenantWhiteLabelSettings.logoDarkSize.Width}, + new {type = (int)WhiteLabelLogoTypeEnum.Favicon, name = nameof(WhiteLabelLogoTypeEnum.Favicon), height = TenantWhiteLabelSettings.logoFaviconSize.Height, width = TenantWhiteLabelSettings.logoFaviconSize.Width}, + new {type = (int)WhiteLabelLogoTypeEnum.DocsEditor, name = nameof(WhiteLabelLogoTypeEnum.DocsEditor), height = TenantWhiteLabelSettings.logoDocsEditorSize.Height, width = TenantWhiteLabelSettings.logoDocsEditorSize.Width} }; } @@ -2838,7 +2838,7 @@ namespace ASC.Api.Settings PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings); var saveAvailable = CoreBaseSettings.Standalone || TenantManager.GetTenantQuota(TenantManager.GetCurrentTenant().TenantId).ThirdParty; - if (!SetupInfo.IsVisibleSettings(ManagementType.ThirdPartyAuthorization.ToString()) + if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.ThirdPartyAuthorization)) || !saveAvailable) throw new BillingException(Resource.ErrorNotAllowedOption, "ThirdPartyAuthorization"); diff --git a/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs b/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs index 6b040484b6..1476025ca0 100644 --- a/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs @@ -231,7 +231,7 @@ namespace ASC.Api.Settings private static void CheckSmtpPermissions() { - if (!SetupInfo.IsVisibleSettings(ManagementType.SmtpSettings.ToString())) + if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.SmtpSettings))) { throw new BillingException(Resource.ErrorNotAllowedOption, "Smtp"); } diff --git a/web/ASC.Web.Core/PrivacyRoomSettings.cs b/web/ASC.Web.Core/PrivacyRoomSettings.cs index eb5537bc97..e1cea08d23 100644 --- a/web/ASC.Web.Core/PrivacyRoomSettings.cs +++ b/web/ASC.Web.Core/PrivacyRoomSettings.cs @@ -67,7 +67,7 @@ namespace ASC.Web.Studio.Core public static bool IsAvailable(TenantManager tenantManager) { - return SetupInfo.IsVisibleSettings(ManagementType.PrivacyRoom.ToString()) + return SetupInfo.IsVisibleSettings(nameof(ManagementType.PrivacyRoom)) && tenantManager.GetTenantQuota(tenantManager.GetCurrentTenant().TenantId).PrivacyRoom; } } From cec441c9965d68156ff4b5d9d516b3e7a6c71473 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 17 Jan 2022 11:23:40 +0300 Subject: [PATCH 046/167] analizators/U2U1113 --- common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs | 2 +- common/services/ASC.ApiSystem/Classes/CommonMethods.cs | 4 ++-- common/services/ASC.ApiSystem/Controllers/PortalController.cs | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs index d77348d209..af4a0a5cd9 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -231,7 +231,7 @@ namespace ASC.Data.Backup.Tasks foreach (var p in parsed) { - if (string.IsNullOrEmpty(p.Trim())) continue; + if (string.IsNullOrWhiteSpace(p)) continue; var keyValue = p.Split('='); result.Add(keyValue[0].ToLowerInvariant(), keyValue[1]); } diff --git a/common/services/ASC.ApiSystem/Classes/CommonMethods.cs b/common/services/ASC.ApiSystem/Classes/CommonMethods.cs index 298e27cc7d..2ffc148a22 100644 --- a/common/services/ASC.ApiSystem/Classes/CommonMethods.cs +++ b/common/services/ASC.ApiSystem/Classes/CommonMethods.cs @@ -204,7 +204,7 @@ namespace ASC.ApiSystem.Controllers public bool GetTenant(IModel model, out Tenant tenant) { - if (CoreBaseSettings.Standalone && model != null && !string.IsNullOrEmpty((model.PortalName ?? "").Trim())) + if (CoreBaseSettings.Standalone && model != null && !string.IsNullOrWhiteSpace((model.PortalName ?? ""))) { tenant = TenantManager.GetTenant((model.PortalName ?? "").Trim()); return true; @@ -216,7 +216,7 @@ namespace ASC.ApiSystem.Controllers return true; } - if (model != null && !string.IsNullOrEmpty((model.PortalName ?? "").Trim())) + if (model != null && !string.IsNullOrWhiteSpace((model.PortalName ?? ""))) { tenant = HostedSolution.GetTenant((model.PortalName ?? "").Trim()); return true; diff --git a/common/services/ASC.ApiSystem/Controllers/PortalController.cs b/common/services/ASC.ApiSystem/Controllers/PortalController.cs index ce8ecda528..d04822cca7 100644 --- a/common/services/ASC.ApiSystem/Controllers/PortalController.cs +++ b/common/services/ASC.ApiSystem/Controllers/PortalController.cs @@ -477,13 +477,13 @@ namespace ASC.ApiSystem.Controllers var tenants = new List<Tenant>(); var empty = true; - if (!string.IsNullOrEmpty((model.Email ?? "").Trim())) + if (!string.IsNullOrWhiteSpace((model.Email ?? ""))) { empty = false; tenants.AddRange(HostedSolution.FindTenants((model.Email ?? "").Trim())); } - if (!string.IsNullOrEmpty((model.PortalName ?? "").Trim())) + if (!string.IsNullOrWhiteSpace((model.PortalName ?? ""))) { empty = false; var tenant = HostedSolution.GetTenant((model.PortalName ?? "").Trim()); From e63684774fb4e3902106d1052328ffb60cab9bcb Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 17 Jan 2022 11:28:39 +0300 Subject: [PATCH 047/167] analizators/U2U1115 --- common/services/ASC.ApiSystem/Classes/AuthHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/services/ASC.ApiSystem/Classes/AuthHandler.cs b/common/services/ASC.ApiSystem/Classes/AuthHandler.cs index 607ea5d446..e1763c18cb 100644 --- a/common/services/ASC.ApiSystem/Classes/AuthHandler.cs +++ b/common/services/ASC.ApiSystem/Classes/AuthHandler.cs @@ -118,7 +118,7 @@ namespace ASC.ApiSystem.Classes { Log.DebugFormat("Auth failed: invalid token {0}.", header); - return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Unauthorizednameof()))); + return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Unauthorized)))); } var pkey = splitted[0]; From 36c26bc8036441f2aa2cd8008af005eb0bfa0816 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 18 Jan 2022 15:40:28 +0300 Subject: [PATCH 048/167] analizators/U2U1117 --- common/ASC.Common/Utils/HttpRequestExtensions.cs | 4 ++-- common/ASC.Core.Common/BaseCommonLinkUtility.cs | 4 ++-- .../ASC.Data.Backup.Core/Tasks/Modules/MailModuleSpecifics.cs | 2 +- .../ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs | 2 +- .../Tasks/Modules/ProjectsModuleSpecifics.cs | 4 ++-- common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs | 2 +- .../LoginProviders/DocuSignLoginProvider.cs | 2 +- common/services/ASC.ElasticSearch/Core/Selector.cs | 2 +- products/ASC.Files/Core/Model/Binders.cs | 2 +- web/ASC.Web.Api/Controllers/SettingsController.cs | 2 +- web/ASC.Web.Core/Sms/SmsProvider.cs | 2 +- web/ASC.Web.Core/Utility/UrlShortener.cs | 2 +- 12 files changed, 15 insertions(+), 15 deletions(-) diff --git a/common/ASC.Common/Utils/HttpRequestExtensions.cs b/common/ASC.Common/Utils/HttpRequestExtensions.cs index 5d03a133b4..63510288ce 100644 --- a/common/ASC.Common/Utils/HttpRequestExtensions.cs +++ b/common/ASC.Common/Utils/HttpRequestExtensions.cs @@ -186,7 +186,7 @@ namespace System.Web } const StringComparison cmp = StringComparison.OrdinalIgnoreCase; - if (0 < s.Length && (s.StartsWith("0", cmp))) + if (0 < s.Length && (s.StartsWith('0'))) { s = Uri.UriSchemeHttp + s.Substring(1); } @@ -194,7 +194,7 @@ namespace System.Web { s = Uri.UriSchemeHttp + s.Substring(3); } - else if (0 < s.Length && (s.StartsWith("1", cmp))) + else if (0 < s.Length && (s.StartsWith('1'))) { s = Uri.UriSchemeHttps + s.Substring(1); } diff --git a/common/ASC.Core.Common/BaseCommonLinkUtility.cs b/common/ASC.Core.Common/BaseCommonLinkUtility.cs index a8e22097da..495fc732bb 100644 --- a/common/ASC.Core.Common/BaseCommonLinkUtility.cs +++ b/common/ASC.Core.Common/BaseCommonLinkUtility.cs @@ -185,7 +185,7 @@ namespace ASC.Core.Common virtualPath.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) return virtualPath; - if (string.IsNullOrEmpty(virtualPath) || virtualPath.StartsWith("/")) + if (string.IsNullOrEmpty(virtualPath) || virtualPath.StartsWith('/')) { return ServerRootPath + virtualPath; } @@ -199,7 +199,7 @@ namespace ASC.Core.Common return VirtualPathUtility.ToAbsolute(virtualPath); } - if (string.IsNullOrEmpty(virtualPath) || virtualPath.StartsWith("/")) + if (string.IsNullOrEmpty(virtualPath) || virtualPath.StartsWith('/')) { return virtualPath; } diff --git a/common/ASC.Data.Backup.Core/Tasks/Modules/MailModuleSpecifics.cs b/common/ASC.Data.Backup.Core/Tasks/Modules/MailModuleSpecifics.cs index d57e1ccc4e..1aaaa187fb 100644 --- a/common/ASC.Data.Backup.Core/Tasks/Modules/MailModuleSpecifics.cs +++ b/common/ASC.Data.Backup.Core/Tasks/Modules/MailModuleSpecifics.cs @@ -183,7 +183,7 @@ namespace ASC.Data.Backup.Tasks.Modules { //todo: hack: will be changed later filePath = Regex.Replace(filePath, @"^[-\w]+(?=/)", match => dump ? match.Value : columnMapper.GetUserMapping(match.Value)); - return !filePath.StartsWith("/"); + return !filePath.StartsWith('/'); } protected override bool TryPrepareRow(bool dump, DbConnection connection, ColumnMapper columnMapper, TableInfo table, DataRowInfo row, out Dictionary<string, object> preparedRow) diff --git a/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs b/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs index d276c1c46f..06066c8b1c 100644 --- a/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs @@ -130,7 +130,7 @@ namespace ASC.Data.Backup.Tasks.Modules var p = command.CreateParameter(); if (!string.IsNullOrEmpty(name)) { - p.ParameterName = name.StartsWith("@") ? name : "@" + name; + p.ParameterName = name.StartsWith('@') ? name : "@" + name; } p.Value = GetParameterValue(value); diff --git a/common/ASC.Data.Backup.Core/Tasks/Modules/ProjectsModuleSpecifics.cs b/common/ASC.Data.Backup.Core/Tasks/Modules/ProjectsModuleSpecifics.cs index d3b4749aa5..afd364f37b 100644 --- a/common/ASC.Data.Backup.Core/Tasks/Modules/ProjectsModuleSpecifics.cs +++ b/common/ASC.Data.Backup.Core/Tasks/Modules/ProjectsModuleSpecifics.cs @@ -193,7 +193,7 @@ namespace ASC.Data.Backup.Tasks.Modules match => { var mappedId = Convert.ToString(columnMapper.GetMapping("projects_tasks", "id", match.Value.TrimEnd(','))); - return !string.IsNullOrEmpty(mappedId) && match.Value.EndsWith(",") ? mappedId + "," : mappedId; + return !string.IsNullOrEmpty(mappedId) && match.Value.EndsWith(',') ? mappedId + "," : mappedId; }, RegexOptions.Compiled); @@ -203,7 +203,7 @@ namespace ASC.Data.Backup.Tasks.Modules match => { var mappedId = Convert.ToString(columnMapper.GetMapping("projects_milestones", "id", match.Value.TrimEnd(','))); - return !string.IsNullOrEmpty(mappedId) && match.Value.EndsWith(",") ? mappedId + "," : mappedId; + return !string.IsNullOrEmpty(mappedId) && match.Value.EndsWith(',') ? mappedId + "," : mappedId; }, RegexOptions.Compiled); diff --git a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs index 37c1587786..133a3421de 100644 --- a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs @@ -117,7 +117,7 @@ namespace ASC.FederatedLogin.Helpers var json = RequestHelper.PerformRequest(requestUrl, "application/x-www-form-urlencoded", "POST", data); if (json != null) { - if (!json.StartsWith("{")) + if (!json.StartsWith('{')) { json = "{\"" + json.Replace("=", "\":\"").Replace("&", "\",\"") + "\"}"; } diff --git a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs index 58400b1b58..21549f2090 100644 --- a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs @@ -98,7 +98,7 @@ namespace ASC.FederatedLogin.LoginProviders var json = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", data, headers); if (json == null) throw new Exception("Can not get token"); - if (!json.StartsWith("{")) + if (!json.StartsWith('{')) { json = "{\"" + json.Replace("=", "\":\"").Replace("&", "\",\"") + "\"}"; } diff --git a/common/services/ASC.ElasticSearch/Core/Selector.cs b/common/services/ASC.ElasticSearch/Core/Selector.cs index 72eabc0e72..3e3a835c27 100644 --- a/common/services/ASC.ElasticSearch/Core/Selector.cs +++ b/common/services/ASC.ElasticSearch/Core/Selector.cs @@ -382,7 +382,7 @@ namespace ASC.ElasticSearch private bool IsExactly(string searchText) { - return searchText.StartsWith("\"") && searchText.EndsWith("\""); + return searchText.StartsWith('\"') && searchText.EndsWith('\"'); } private QueryContainer MultiMatch(Fields fields, string value) diff --git a/products/ASC.Files/Core/Model/Binders.cs b/products/ASC.Files/Core/Model/Binders.cs index 98caa72046..e510341bf8 100644 --- a/products/ASC.Files/Core/Model/Binders.cs +++ b/products/ASC.Files/Core/Model/Binders.cs @@ -57,7 +57,7 @@ namespace ASC.Files.Model return valueProviderResult.Select(ParseQueryParam).ToList(); } - if (modelName.EndsWith("[]")) + if (modelName.EndsWith("[]", StringComparison.Ordinal)) { return new List<JsonElement>(); } diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index a1c50594de..e10239f87d 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -2618,7 +2618,7 @@ namespace ASC.Api.Settings var hubUrl = Configuration["web:hub"] ?? string.Empty; if (hubUrl.Length != 0) { - if (!hubUrl.EndsWith("/")) + if (!hubUrl.EndsWith('/')) { hubUrl += "/"; } diff --git a/web/ASC.Web.Core/Sms/SmsProvider.cs b/web/ASC.Web.Core/Sms/SmsProvider.cs index aaf04b470b..b7e1edc0a1 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -418,7 +418,7 @@ namespace ASC.Web.Core.Sms public override bool SendMessage(string number, string message) { - if (!number.StartsWith("+")) number = "+" + number; + if (!number.StartsWith('+')) number = "+" + number; var twilioRestClient = new TwilioRestClient(Key, Secret); try diff --git a/web/ASC.Web.Core/Utility/UrlShortener.cs b/web/ASC.Web.Core/Utility/UrlShortener.cs index 2bdac1c3aa..5f80da9fbf 100644 --- a/web/ASC.Web.Core/Utility/UrlShortener.cs +++ b/web/ASC.Web.Core/Utility/UrlShortener.cs @@ -109,7 +109,7 @@ namespace ASC.Web.Core.Utility internalUrl = configuration["web:url-shortener:internal"]; sKey = machinePseudoKeys.GetMachineConstant(); - if (!url.EndsWith("/")) + if (!url.EndsWith('/')) url += '/'; CommonLinkUtility = commonLinkUtility; ClientFactory = clientFactory; From 84638feaf0e1ccfb6e6e5d89a94b153fff7b95eb Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 18 Jan 2022 16:54:24 +0300 Subject: [PATCH 049/167] analizators/U2U1202 --- common/ASC.Api.Core/Model/EmployeeWraperFull.cs | 4 ++-- common/ASC.Common/Utils/DnsLookup.cs | 2 +- common/ASC.Core.Common/Billing/License/LicenseReader.cs | 2 +- common/ASC.Core.Common/Billing/TariffService.cs | 6 +++--- common/ASC.Core.Common/Configuration/Consumer.cs | 4 ++-- common/ASC.Core.Common/Core/DBResourceManager.cs | 2 +- common/ASC.Core.Common/Data/DbAzService.cs | 6 ++---- common/ASC.Core.Common/Data/DbTenantService.cs | 6 +++--- common/ASC.Data.Storage/Encryption/EncryptionOperation.cs | 2 +- common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs | 8 ++++---- .../RackspaceCloud/RackspaceCloudStorage.cs | 6 +++--- common/ASC.Data.Storage/S3/S3Storage.cs | 6 +++--- common/ASC.Data.Storage/WebPath.cs | 2 +- common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs | 2 +- common/ASC.Feed/Data/FeedAggregateDataProvider.cs | 2 +- common/ASC.IPSecurity/IPSecurity.cs | 2 +- common/ASC.MessagingSystem/DbSender/MessagesRepository.cs | 4 ++-- common/ASC.MessagingSystem/MessageTarget.cs | 2 +- common/ASC.VoipService/Dao/CachedVoipDao.cs | 2 +- common/ASC.VoipService/Dao/VoipDao.cs | 2 +- .../services/ASC.AuditTrail/Mappers/AuditActionMapper.cs | 4 ++-- .../ASC.ClearEvents/ClearEventsServiceLauncher.cs | 4 ++-- common/services/ASC.Data.Backup/BackupCleanerService.cs | 2 +- .../ASC.Feed.Aggregator/Service/FeedAggregatorService.cs | 2 +- common/services/ASC.TelegramService/Core/Core.cs | 4 ++-- products/ASC.Files/Core/Model/Binders.cs | 4 ++-- products/ASC.Files/Server/Controllers/FilesController.cs | 2 +- products/ASC.Files/Service/Core/FilesModule.cs | 4 ++-- products/ASC.Files/Service/Core/FoldersModule.cs | 2 +- products/ASC.Files/Service/Thumbnail/FileDataProvider.cs | 2 +- products/ASC.Files/Service/Thumbnail/Worker.cs | 2 +- .../ASC.People/Server/Controllers/PeopleController.cs | 4 ++-- web/ASC.Web.Api/Controllers/PortalController.cs | 2 +- web/ASC.Web.Api/Controllers/SettingsController.cs | 4 ++-- 34 files changed, 56 insertions(+), 58 deletions(-) diff --git a/common/ASC.Api.Core/Model/EmployeeWraperFull.cs b/common/ASC.Api.Core/Model/EmployeeWraperFull.cs index aafc1dd727..ddc5f1095c 100644 --- a/common/ASC.Api.Core/Model/EmployeeWraperFull.cs +++ b/common/ASC.Api.Core/Model/EmployeeWraperFull.cs @@ -262,7 +262,7 @@ namespace ASC.Web.Api.Models { var listAdminModules = userInfo.GetListAdminModules(WebItemSecurity); - if (listAdminModules.Any()) + if (listAdminModules.Count > 0) result.ListAdminModules = listAdminModules; } @@ -283,7 +283,7 @@ namespace ASC.Web.Api.Models } } - if (contacts.Any()) + if (contacts.Count > 0) { employeeWraperFull.Contacts = contacts; } diff --git a/common/ASC.Common/Utils/DnsLookup.cs b/common/ASC.Common/Utils/DnsLookup.cs index c4f99322f4..49eb2c398c 100644 --- a/common/ASC.Common/Utils/DnsLookup.cs +++ b/common/ASC.Common/Utils/DnsLookup.cs @@ -101,7 +101,7 @@ namespace ASC.Common.Utils var dnsMessage = GetDnsMessage(domainName); - return dnsMessage.AnswerRecords.Any(); + return dnsMessage.AnswerRecords.Count != 0; } /// <summary> diff --git a/common/ASC.Core.Common/Billing/License/LicenseReader.cs b/common/ASC.Core.Common/Billing/License/LicenseReader.cs index c8bb46ade0..bcb2518b1c 100644 --- a/common/ASC.Core.Common/Billing/License/LicenseReader.cs +++ b/common/ASC.Core.Common/Billing/License/LicenseReader.cs @@ -189,7 +189,7 @@ namespace ASC.Core.Billing { license.PortalCount = TenantManager.GetTenantQuota(Tenant.DEFAULT_TENANT).CountPortals; } - var activePortals = TenantManager.GetTenants().Count(); + var activePortals = TenantManager.GetTenants().Count; if (activePortals > 1 && license.PortalCount < activePortals) { throw new LicensePortalException("License portal count", license.OriginalLicense); diff --git a/common/ASC.Core.Common/Billing/TariffService.cs b/common/ASC.Core.Common/Billing/TariffService.cs index 8bfd0c5d51..aad10a1f67 100644 --- a/common/ASC.Core.Common/Billing/TariffService.cs +++ b/common/ASC.Core.Common/Billing/TariffService.cs @@ -503,10 +503,10 @@ namespace ASC.Core.Billing using var tx = CoreDbContext.Database.BeginTransaction(); // last record is not the same - var count = CoreDbContext.Tariffs - .Count(r => r.Tenant == tenant && r.Tariff == tariffInfo.QuotaId && r.Stamp == tariffInfo.DueDate && r.Quantity == tariffInfo.Quantity); + var any = CoreDbContext.Tariffs + .Any(r => r.Tenant == tenant && r.Tariff == tariffInfo.QuotaId && r.Stamp == tariffInfo.DueDate && r.Quantity == tariffInfo.Quantity); - if (tariffInfo.DueDate == DateTime.MaxValue || renewal || count == 0) + if (tariffInfo.DueDate == DateTime.MaxValue || renewal || any) { var efTariff = new DbTariff { diff --git a/common/ASC.Core.Common/Configuration/Consumer.cs b/common/ASC.Core.Common/Configuration/Consumer.cs index 6ff6375c34..2a88d89c10 100644 --- a/common/ASC.Core.Common/Configuration/Consumer.cs +++ b/common/ASC.Core.Common/Configuration/Consumer.cs @@ -88,7 +88,7 @@ namespace ASC.Core.Common.Configuration public bool IsSet { - get { return Props.Any() && !Props.All(r => string.IsNullOrEmpty(this[r.Key])); } + get { return Props.Count > 0 && !Props.All(r => string.IsNullOrEmpty(this[r.Key])); } } static Consumer() @@ -152,7 +152,7 @@ namespace ASC.Core.Common.Configuration Props = props ?? new Dictionary<string, string>(); Additional = additional ?? new Dictionary<string, string>(); - if (props != null && props.Any()) + if (props != null && props.Count > 0) { CanSet = props.All(r => string.IsNullOrEmpty(r.Value)); } diff --git a/common/ASC.Core.Common/Core/DBResourceManager.cs b/common/ASC.Core.Common/Core/DBResourceManager.cs index b14ad1bba9..2149e74eae 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -125,7 +125,7 @@ namespace TMResourceData private static bool Accept(Assembly a) { var n = a.GetName().Name; - return (n.StartsWith("ASC.") || n.StartsWith("App_GlobalResources")) && a.GetManifestResourceNames().Any(); + return (n.StartsWith("ASC.") || n.StartsWith("App_GlobalResources")) && a.GetManifestResourceNames().Length > 0; } diff --git a/common/ASC.Core.Common/Data/DbAzService.cs b/common/ASC.Core.Common/Data/DbAzService.cs index b6a5d06f89..978ba30eab 100644 --- a/common/ASC.Core.Common/Data/DbAzService.cs +++ b/common/ASC.Core.Common/Data/DbAzService.cs @@ -126,15 +126,13 @@ namespace ASC.Core.Data private bool ExistEscapeRecord(AzRecord r) { - var count = UserDbContext.Acl + return UserDbContext.Acl .Where(a => a.Tenant == Tenant.DEFAULT_TENANT) .Where(a => a.Subject == r.SubjectId) .Where(a => a.Action == r.ActionId) .Where(a => a.Object == (r.ObjectId ?? string.Empty)) .Where(a => a.AceType == r.Reaction) - .Count(); - - return count != 0; + .Any(); } private void DeleteRecord(AzRecord r) diff --git a/common/ASC.Core.Common/Data/DbTenantService.cs b/common/ASC.Core.Common/Data/DbTenantService.cs index d703aa1ffb..88c2a79111 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -489,13 +489,13 @@ namespace ASC.Core.Data } if (!exists) { - exists = 0 < TenantDbContext.Tenants.Where(r => r.Alias == domain && r.Id != tenantId).Count(); + exists = TenantDbContext.Tenants.Where(r => r.Alias == domain && r.Id != tenantId).Any(); } if (!exists) { - exists = 0 < TenantDbContext.Tenants + exists = TenantDbContext.Tenants .Where(r => r.MappedDomain == domain && r.Id != tenantId && !(r.Status == TenantStatus.RemovePending || r.Status == TenantStatus.Restoring)) - .Count(); + .Any(); } if (exists) { diff --git a/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs b/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs index 8905fef52f..57649e9615 100644 --- a/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs +++ b/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs @@ -191,7 +191,7 @@ namespace ASC.Data.Storage.Encryption { IEnumerable<string> files = targetStore.ListFilesRelative(targetDomain, "\\", "*.*", true); - if (progress.Any()) + if (progress.Count > 0) { files = files.Where(path => !progress.Contains(path)); } diff --git a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs index 78cb2c1fc8..bdac9eefd4 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -390,7 +390,7 @@ namespace ASC.Data.Storage.GoogleCloud public override void DeleteFiles(string domain, List<string> paths) { - if (!paths.Any()) return; + if (paths.Count == 0) return; var keysToDel = new List<string>(); @@ -416,7 +416,7 @@ namespace ASC.Data.Storage.GoogleCloud } } - if (!keysToDel.Any()) return; + if (keysToDel.Count == 0) return; using var storage = GetStorage(); @@ -521,7 +521,7 @@ namespace ASC.Data.Storage.GoogleCloud var objects = storage.ListObjects(_bucket, MakePath(domain, path), null); - return objects.Count() > 0; + return objects.Any(); } public override async Task<bool> IsFileAsync(string domain, string path) @@ -530,7 +530,7 @@ namespace ASC.Data.Storage.GoogleCloud var objects = await storage.ListObjectsAsync(_bucket, MakePath(domain, path)).ReadPageAsync(1); - return objects.Count() > 0; + return objects.Any(); } public override bool IsDirectory(string domain, string path) diff --git a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs index b76ea13260..a044e89d74 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -419,7 +419,7 @@ namespace ASC.Data.Storage.RackspaceCloud public override void DeleteFiles(string domain, List<string> paths) { - if (!paths.Any()) return; + if (paths.Count == 0) return; var keysToDel = new List<string>(); @@ -444,7 +444,7 @@ namespace ASC.Data.Storage.RackspaceCloud } } - if (!keysToDel.Any()) return; + if (keysToDel.Count == 0) return; var client = GetClient(); @@ -537,7 +537,7 @@ namespace ASC.Data.Storage.RackspaceCloud var client = GetClient(); var objects = client.ListObjects(_private_container, null, null, null, MakePath(domain, path), _region); - return objects.Count() > 0; + return objects.Any(); } public override Task<bool> IsFileAsync(string domain, string path) diff --git a/common/ASC.Data.Storage/S3/S3Storage.cs b/common/ASC.Data.Storage/S3/S3Storage.cs index 139a2a92a9..44eefb7c86 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -328,7 +328,7 @@ namespace ASC.Data.Storage.S3 Paths = new Paths { Items = paths.ToList(), - Quantity = paths.Count() + Quantity = paths.Length } } }; @@ -472,7 +472,7 @@ namespace ASC.Data.Storage.S3 public override void DeleteFiles(string domain, List<string> paths) { - if (!paths.Any()) return; + if (paths.Count == 0) return; var keysToDel = new List<string>(); @@ -501,7 +501,7 @@ namespace ASC.Data.Storage.S3 } } - if (!keysToDel.Any()) + if (keysToDel.Count == 0) return; using (var client = GetClient()) diff --git a/common/ASC.Data.Storage/WebPath.cs b/common/ASC.Data.Storage/WebPath.cs index 9b8c519186..fba49e19d6 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -91,7 +91,7 @@ namespace ASC.Data.Storage if (Appenders.Any()) { var avaliableAppenders = Appenders.Where(x => x.Extensions != null && x.Extensions.Split('|').Contains(ext) || string.IsNullOrEmpty(ext)).ToList(); - var avaliableAppendersCount = avaliableAppenders.LongCount(); + var avaliableAppendersCount = avaliableAppenders.Count; Appender appender; if (avaliableAppendersCount > 1) diff --git a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs index 133a3421de..9f4b8d006c 100644 --- a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs @@ -70,7 +70,7 @@ namespace ASC.FederatedLogin.Helpers var stateUriBuilder = new UriBuilder(u.Scheme, u.Host, u.Port, $"thirdparty/{loginProvider.Name.ToLower()}/code"); - if (additionalStateArgs != null && additionalStateArgs.Any()) + if (additionalStateArgs != null && additionalStateArgs.Count > 0) { var stateQuery = ""; stateQuery = additionalStateArgs.Keys diff --git a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs index 5336453e10..f003f0fff7 100644 --- a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs +++ b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs @@ -94,7 +94,7 @@ namespace ASC.Feed.Data SaveFeedsPortion(feedsPortion, aggregatedDate); feedsPortion.Clear(); } - if (feedsPortion.Any()) + if (feedsPortion.Count > 0) { SaveFeedsPortion(feedsPortion, aggregatedDate); } diff --git a/common/ASC.IPSecurity/IPSecurity.cs b/common/ASC.IPSecurity/IPSecurity.cs index a9c2cea17c..a4e7de46f6 100644 --- a/common/ASC.IPSecurity/IPSecurity.cs +++ b/common/ASC.IPSecurity/IPSecurity.cs @@ -92,7 +92,7 @@ namespace ASC.IPSecurity { var restrictions = IPRestrictionsService.Get(tenant.TenantId).ToList(); - if (!restrictions.Any()) return true; + if (restrictions.Count == 0) return true; if (string.IsNullOrWhiteSpace(requestIps = CurrentIpForTest)) { diff --git a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs index d02ee8012a..85a5709df9 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -181,7 +181,7 @@ namespace ASC.MessagingSystem.DbSender Action = (int)message.Action }; - if (message.Description != null && message.Description.Any()) + if (message.Description != null && message.Description.Count > 0) { le.Description = JsonConvert.SerializeObject(message.Description, new JsonSerializerSettings @@ -210,7 +210,7 @@ namespace ASC.MessagingSystem.DbSender Target = message.Target?.ToString() }; - if (message.Description != null && message.Description.Any()) + if (message.Description != null && message.Description.Count > 0) { ae.Description = JsonConvert.SerializeObject(GetSafeDescription(message.Description), new JsonSerializerSettings diff --git a/common/ASC.MessagingSystem/MessageTarget.cs b/common/ASC.MessagingSystem/MessageTarget.cs index c27d472045..7fe9bee69c 100644 --- a/common/ASC.MessagingSystem/MessageTarget.cs +++ b/common/ASC.MessagingSystem/MessageTarget.cs @@ -99,7 +99,7 @@ namespace ASC.MessagingSystem var items = value.Split(','); - if (!items.Any()) return null; + if (items.Count == 0) return null; return new MessageTarget(Option) { diff --git a/common/ASC.VoipService/Dao/CachedVoipDao.cs b/common/ASC.VoipService/Dao/CachedVoipDao.cs index 0a39bf0031..47b4f8566f 100644 --- a/common/ASC.VoipService/Dao/CachedVoipDao.cs +++ b/common/ASC.VoipService/Dao/CachedVoipDao.cs @@ -104,7 +104,7 @@ namespace ASC.VoipService.Dao cache.Insert(GetCacheKey(TenantID), numbers, DateTime.UtcNow.Add(timeout)); } - return ids.Any() ? numbers.Where(r => ids.Contains(r.Id) || ids.Contains(r.Number)).ToList() : numbers; + return ids.Length > 0 ? numbers.Where(r => ids.Contains(r.Id) || ids.Contains(r.Number)).ToList() : numbers; } public static string GetCacheKey(int tenant) diff --git a/common/ASC.VoipService/Dao/VoipDao.cs b/common/ASC.VoipService/Dao/VoipDao.cs index 2ef0656245..bb025abcaa 100644 --- a/common/ASC.VoipService/Dao/VoipDao.cs +++ b/common/ASC.VoipService/Dao/VoipDao.cs @@ -101,7 +101,7 @@ namespace ASC.VoipService.Dao { var numbers = VoipDbContext.VoipNumbers.Where(r => r.TenantId == TenantID); - if (ids.Any()) + if (ids.Length > 0) { numbers = numbers.Where(r => ids.Any(a => a == r.Number || a == r.Id)); } diff --git a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs index 1dc54beeb2..f0afbbb24b 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -71,7 +71,7 @@ namespace ASC.AuditTrail.Mappers { var actionText = Actions[(MessageAction)evt.Action].GetActionText(); - if (evt.Description == null || !evt.Description.Any()) return actionText; + if (evt.Description == null || evt.Description.Count > 0) return actionText; var description = evt.Description .Select(t => t.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) @@ -100,7 +100,7 @@ namespace ASC.AuditTrail.Mappers { var actionText = Actions[(MessageAction)evt.Action].GetActionText(); - if (evt.Description == null || !evt.Description.Any()) return actionText; + if (evt.Description == null || evt.Description.Count > 0) return actionText; var description = evt.Description .Select(t => t.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) diff --git a/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs b/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs index b006aeafe9..3933ee3342 100644 --- a/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs +++ b/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs @@ -115,12 +115,12 @@ namespace ASC.Thumbnails.Svc ids = ae.Select(r => r.ef).ToList(); - if (!ids.Any()) return; + if (ids.Count == 0) return; table.RemoveRange(ids); ef.SaveChanges(); - } while (ids.Any()); + } while (ids.Count > 0); } } diff --git a/common/services/ASC.Data.Backup/BackupCleanerService.cs b/common/services/ASC.Data.Backup/BackupCleanerService.cs index eccf93f26d..a6e548bb9e 100644 --- a/common/services/ASC.Data.Backup/BackupCleanerService.cs +++ b/common/services/ASC.Data.Backup/BackupCleanerService.cs @@ -72,7 +72,7 @@ namespace ASC.Data.Backup.Service if (schedule != null) { var scheduledBackupsToRemove = scheduledBackups.OrderByDescending(r => r.CreatedOn).Skip(schedule.BackupsStored).ToList(); - if (scheduledBackupsToRemove.Any()) + if (scheduledBackupsToRemove.Count > 0) { log.DebugFormat("only last {0} scheduled backup records are to keep for tenant {1} so {2} records must be removed", schedule.BackupsStored, schedule.TenantId, scheduledBackupsToRemove.Count); backupsToRemove.AddRange(scheduledBackupsToRemove); diff --git a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs index 4838978bbd..e39804b568 100644 --- a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs +++ b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs @@ -136,7 +136,7 @@ namespace ASC.Feed.Aggregator var toTime = DateTime.UtcNow; var tenants = Attempt(10, () => module.GetTenantsWithFeeds(fromTime)).ToList(); - Log.DebugFormat("Find {1} tenants for module {0}.", module.GetType().Name, tenants.Count()); + Log.DebugFormat("Find {1} tenants for module {0}.", module.GetType().Name, tenants.Count); foreach (var tenant in tenants) { diff --git a/common/services/ASC.TelegramService/Core/Core.cs b/common/services/ASC.TelegramService/Core/Core.cs index 091a52f309..18df362629 100644 --- a/common/services/ASC.TelegramService/Core/Core.cs +++ b/common/services/ASC.TelegramService/Core/Core.cs @@ -116,8 +116,8 @@ namespace ASC.TelegramService.Core var cmdArgs = cmd.GetParameters(); - if (cmdArgs.Any() && args == null || cmdArgs.Count() != args.Count()) throw new Exception("Wrong parameters count"); - for (var i = 0; i < cmdArgs.Count(); i++) + if (cmdArgs.Length > 0 && args == null || cmdArgs.Length != args.Length) throw new Exception("Wrong parameters count"); + for (var i = 0; i < cmdArgs.Length; i++) { var type = cmdArgs[i].ParameterType; diff --git a/products/ASC.Files/Core/Model/Binders.cs b/products/ASC.Files/Core/Model/Binders.cs index e510341bf8..291a7b29fc 100644 --- a/products/ASC.Files/Core/Model/Binders.cs +++ b/products/ASC.Files/Core/Model/Binders.cs @@ -197,7 +197,7 @@ namespace ASC.Files.Model var defaultBindingContext = bindingContext as DefaultModelBindingContext; var composite = bindingContext.ValueProvider as CompositeValueProvider; - if (defaultBindingContext != null && composite != null && !composite.Any()) + if (defaultBindingContext != null && composite != null && composite.Count == 0) { bindingContext.ValueProvider = defaultBindingContext.OriginalValueProvider; } @@ -245,7 +245,7 @@ namespace ASC.Files.Model var defaultBindingContext = bindingContext as DefaultModelBindingContext; var composite = bindingContext.ValueProvider as CompositeValueProvider; - if (defaultBindingContext != null && composite != null && !composite.Any()) + if (defaultBindingContext != null && composite != null && composite.Count == 0) { bindingContext.ValueProvider = defaultBindingContext.OriginalValueProvider; } diff --git a/products/ASC.Files/Server/Controllers/FilesController.cs b/products/ASC.Files/Server/Controllers/FilesController.cs index ec6137f96f..e7983d370d 100644 --- a/products/ASC.Files/Server/Controllers/FilesController.cs +++ b/products/ASC.Files/Server/Controllers/FilesController.cs @@ -207,7 +207,7 @@ namespace ASC.Api.Documents if (!IsVisitor && !withoutAdditionalFolder - && FileUtility.ExtsWebTemplate.Any() + && FileUtility.ExtsWebTemplate.Count > 0 && FilesSettingsHelper.TemplatesSection) { result.Add(GlobalFolderHelper.FolderTemplates); diff --git a/products/ASC.Files/Service/Core/FilesModule.cs b/products/ASC.Files/Service/Core/FilesModule.cs index a9b2ec8139..5cbd9e9822 100644 --- a/products/ASC.Files/Service/Core/FilesModule.cs +++ b/products/ASC.Files/Service/Core/FilesModule.cs @@ -65,7 +65,7 @@ namespace ASC.Files.Service.Core var owner = (Guid)feed.Target; var groupUsers = UserManager.GetUsersByGroup(owner).Select(x => x.ID).ToList(); - if (!groupUsers.Any()) + if (groupUsers.Count == 0) { groupUsers.Add(owner); } @@ -183,7 +183,7 @@ namespace ASC.Files.Service.Core if (target == null) return true; var owner = (Guid)target; var groupUsers = UserManager.GetUsersByGroup(owner).Select(x => x.ID).ToList(); - if (!groupUsers.Any()) + if (groupUsers.Count == 0) { groupUsers.Add(owner); } diff --git a/products/ASC.Files/Service/Core/FoldersModule.cs b/products/ASC.Files/Service/Core/FoldersModule.cs index 949a499c40..ee7150c264 100644 --- a/products/ASC.Files/Service/Core/FoldersModule.cs +++ b/products/ASC.Files/Service/Core/FoldersModule.cs @@ -62,7 +62,7 @@ namespace ASC.Files.Service.Core var owner = (Guid)feed.Target; var groupUsers = UserManager.GetUsersByGroup(owner).Select(x => x.ID).ToList(); - if (!groupUsers.Any()) + if (groupUsers.Count == 0) { groupUsers.Add(owner); } diff --git a/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs b/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs index 093bbc06c3..0ce47f95d0 100644 --- a/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs +++ b/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs @@ -151,7 +151,7 @@ namespace ASC.Files.ThumbnailBuilder var premiumTenants = GetPremiumTenants(); - if (premiumTenants.Any()) + if (premiumTenants.Length > 0) { result = GetFileData(r => premiumTenants.Contains(r.TenantId)); diff --git a/products/ASC.Files/Service/Thumbnail/Worker.cs b/products/ASC.Files/Service/Thumbnail/Worker.cs index f11031af3b..663b788853 100644 --- a/products/ASC.Files/Service/Thumbnail/Worker.cs +++ b/products/ASC.Files/Service/Thumbnail/Worker.cs @@ -81,7 +81,7 @@ namespace ASC.Files.ThumbnailBuilder var filesWithoutThumbnails = Launcher.Queue.Select(pair => pair.Value).ToList(); - if (!filesWithoutThumbnails.Any()) + if (filesWithoutThumbnails.Count == 0) { logger.TraceFormat("Procedure: Waiting for data. Sleep {0}.", thumbnailSettings.LaunchFrequency); timer.Change(TimeSpan.FromSeconds(thumbnailSettings.LaunchFrequency), TimeSpan.FromMilliseconds(-1)); diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index 2c42145526..35965fd265 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -788,7 +788,7 @@ namespace ASC.Employee.Core.Controllers } // change user type - var canBeGuestFlag = !user.IsOwner(Tenant) && !user.IsAdmin(UserManager) && !user.GetListAdminModules(WebItemSecurity).Any() && !user.IsMe(AuthContext); + var canBeGuestFlag = !user.IsOwner(Tenant) && !user.IsAdmin(UserManager) && user.GetListAdminModules(WebItemSecurity).Count == 0 && !user.IsMe(AuthContext); if (memberModel.IsVisitor && !user.IsVisitor(UserManager) && canBeGuestFlag) { @@ -1378,7 +1378,7 @@ namespace ASC.Employee.Core.Controllers foreach (var user in users) { - if (user.IsOwner(Tenant) || user.IsAdmin(UserManager) || user.IsMe(AuthContext) || user.GetListAdminModules(WebItemSecurity).Any()) + if (user.IsOwner(Tenant) || user.IsAdmin(UserManager) || user.IsMe(AuthContext) || user.GetListAdminModules(WebItemSecurity).Count > 0) continue; switch (type) diff --git a/web/ASC.Web.Api/Controllers/PortalController.cs b/web/ASC.Web.Api/Controllers/PortalController.cs index d4262ac59b..b51f7e4416 100644 --- a/web/ASC.Web.Api/Controllers/PortalController.cs +++ b/web/ASC.Web.Api/Controllers/PortalController.cs @@ -170,7 +170,7 @@ namespace ASC.Web.Api.Controllers [Read("userscount")] public long GetUsersCount() { - return UserManager.GetUserNames(EmployeeStatus.Active).Count(); + return UserManager.GetUserNames(EmployeeStatus.Active).Length; } [Read("tariff")] diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index e10239f87d..ea0e8525f3 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1128,7 +1128,7 @@ namespace ASC.Api.Settings throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel"); } - if (HttpContext.Request.Form?.Files == null || !HttpContext.Request.Form.Files.Any()) + if (HttpContext.Request.Form?.Files == null || HttpContext.Request.Form.Files.Count == 0) { throw new InvalidOperationException("No input files"); } @@ -2264,7 +2264,7 @@ namespace ASC.Api.Settings { var activeTenants = TenantManager.GetTenants(); - if (activeTenants.Any()) + if (activeTenants.Count > 0) { StartEncryption(storageEncryption.NotifyUsers); } From acd5b83026db0aba9da700ad19a7326a28caee0e Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 18 Jan 2022 17:00:28 +0300 Subject: [PATCH 050/167] analiztators/U2U1206 --- common/ASC.Data.Storage/StorageFactory.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/common/ASC.Data.Storage/StorageFactory.cs b/common/ASC.Data.Storage/StorageFactory.cs index d19bc45af1..908124d002 100644 --- a/common/ASC.Data.Storage/StorageFactory.cs +++ b/common/ASC.Data.Storage/StorageFactory.cs @@ -56,8 +56,7 @@ namespace ASC.Data.Storage public IEnumerable<string> GetModuleList(string configpath, bool exceptDisabledMigration = false) { return Section.Module - .Where(x => x.Visible) - .Where(x => !exceptDisabledMigration || !x.DisableMigrate) + .Where(x => x.Visible && (!exceptDisabledMigration || !x.DisableMigrate)) .Select(x => x.Name); } From f1f7a82b3948ebcca983c282135e983b1ca3ec56 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 18 Jan 2022 17:00:48 +0300 Subject: [PATCH 051/167] analizators/U2U1208 --- common/ASC.Core.Common/Data/DbTenantService.cs | 3 +-- common/ASC.Feed/Data/FeedAggregateDataProvider.cs | 2 +- web/ASC.Web.Api/Controllers/SettingsController.cs | 7 +++---- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/common/ASC.Core.Common/Data/DbTenantService.cs b/common/ASC.Core.Common/Data/DbTenantService.cs index 88c2a79111..54598f6ef4 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -221,8 +221,7 @@ namespace ASC.Core.Data .Where(r => r.Email == login) .Where(r => r.Status == EmployeeStatus.Active) .Where(r => !r.Removed) - .Select(r => r.Id) - .ToList(); + .Select(r => r.Id); var passwordHashs = usersQuery.Select(r => GetPasswordHash(r, passwordHash)).ToList(); diff --git a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs index f003f0fff7..e718b5df93 100644 --- a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs +++ b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs @@ -244,7 +244,7 @@ namespace ASC.Feed.Data q = q.Where(r => keys.Any(k => r.aggregates.Keywords.StartsWith(k))); } - var news = q.Select(r => r.aggregates).ToList(); + var news = q.Select(r => r.aggregates); return news.Select(r => new FeedResultItem( r.Json, diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index ea0e8525f3..9332ee1608 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -872,7 +872,6 @@ namespace ASC.Api.Settings { var EnabledModules = WebItemManagerSecurity.GetItems(WebZoneType.All, ItemAvailableState.Normal) .Where(item => !item.IsSubItem() && item.Visible) - .ToList() .Select(item => new { id = item.ProductClassName.HtmlEncode(), @@ -2224,7 +2223,7 @@ namespace ASC.Api.Settings TenantExtra.DemandControlPanelPermission(); var current = SettingsManager.Load<StorageSettings>(); - var consumers = ConsumerFactory.GetAll<DataStoreConsumer>().ToList(); + var consumers = ConsumerFactory.GetAll<DataStoreConsumer>(); return consumers.Select(consumer => new StorageWrapper(consumer, current)).ToList(); } @@ -2522,7 +2521,7 @@ namespace ASC.Api.Settings TenantExtra.DemandControlPanelPermission(); var current = SettingsManager.Load<CdnStorageSettings>(); - var consumers = ConsumerFactory.GetAll<DataStoreConsumer>().Where(r => r.Cdn != null).ToList(); + var consumers = ConsumerFactory.GetAll<DataStoreConsumer>().Where(r => r.Cdn != null); return consumers.Select(consumer => new StorageWrapper(consumer, current)).ToList(); } @@ -2600,7 +2599,7 @@ namespace ASC.Api.Settings }; } - var consumers = ConsumerFactory.GetAll<DataStoreConsumer>().ToList(); + var consumers = ConsumerFactory.GetAll<DataStoreConsumer>(); return consumers.Select(consumer => new StorageWrapper(consumer, current)).ToList(); } From 6c5792583a019221ee5cdd3faca17bcc17334320 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 18 Jan 2022 17:43:46 +0300 Subject: [PATCH 052/167] analizators/U2U1209 --- .../ASC.Common/Logging/SelfCleaningTarget.cs | 4 +- .../ASC.Core.Common/Configuration/Consumer.cs | 9 ++-- common/ASC.Core.Common/Data/DbAzService.cs | 3 +- .../GoogleCloud/GoogleCloudStorage.cs | 13 ++--- .../RackspaceCloud/RackspaceCloudStorage.cs | 19 +++---- common/ASC.Data.Storage/S3/S3Storage.cs | 49 ++++++++----------- .../Data/FeedAggregateDataProvider.cs | 4 +- .../DbSender/MessagesRepository.cs | 4 +- common/ASC.MessagingSystem/MessageTarget.cs | 2 +- .../Service/FeedAggregatorService.cs | 4 +- .../UrlShortenerService.cs | 4 +- 11 files changed, 47 insertions(+), 68 deletions(-) diff --git a/common/ASC.Common/Logging/SelfCleaningTarget.cs b/common/ASC.Common/Logging/SelfCleaningTarget.cs index 613c1dd405..86a7f5c125 100644 --- a/common/ASC.Common/Logging/SelfCleaningTarget.cs +++ b/common/ASC.Common/Logging/SelfCleaningTarget.cs @@ -53,10 +53,8 @@ namespace ASC.Common.Logging const string key = "cleanPeriod"; - if (NLog.LogManager.Configuration.Variables.Keys.Contains(key)) + if (LogManager.Configuration.Variables.TryGetValue(key, out var variable)) { - var variable = NLog.LogManager.Configuration.Variables[key]; - if (variable != null && !string.IsNullOrEmpty(variable.Text)) { int.TryParse(variable.Text, out value); diff --git a/common/ASC.Core.Common/Configuration/Consumer.cs b/common/ASC.Core.Common/Configuration/Consumer.cs index 2a88d89c10..59e5aaa4a5 100644 --- a/common/ASC.Core.Common/Configuration/Consumer.cs +++ b/common/ASC.Core.Common/Configuration/Consumer.cs @@ -245,10 +245,7 @@ namespace ASC.Core.Common.Configuration if (string.IsNullOrEmpty(value)) { - if (AllProps.ContainsKey(name)) - { - value = AllProps[name]; - } + AllProps.TryGetValue(name, out value); } return value; @@ -354,9 +351,9 @@ namespace ASC.Core.Common.Configuration HandlerType = Type.GetType(additional[HandlerTypeKey]); - if (additional.ContainsKey(CdnKey)) + if (additional.TryGetValue(CdnKey, out var value)) { - Cdn = GetCdn(additional[CdnKey]); + Cdn = GetCdn(value); } } diff --git a/common/ASC.Core.Common/Data/DbAzService.cs b/common/ASC.Core.Common/Data/DbAzService.cs index 978ba30eab..b7feb320fd 100644 --- a/common/ASC.Core.Common/Data/DbAzService.cs +++ b/common/ASC.Core.Common/Data/DbAzService.cs @@ -75,9 +75,8 @@ namespace ASC.Core.Data foreach (var a in tenantAces) { var key = string.Concat(a.Tenant.ToString(), a.SubjectId.ToString(), a.ActionId.ToString(), a.ObjectId); - if (commonAces.ContainsKey(key)) + if (commonAces.TryGetValue(key, out var common)) { - var common = commonAces[key]; commonAces.Remove(key); if (common.Reaction == a.Reaction) { diff --git a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs index bdac9eefd4..a62f12e517 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -120,17 +120,14 @@ namespace ASC.Data.Storage.GoogleCloud ? new Uri(props["cnamessl"], UriKind.Absolute) : new Uri("https://storage.googleapis.com/" + _bucket + "/", UriKind.Absolute); - if (props.ContainsKey("lower")) + if (props.TryGetValue("lower", out var value)) { - bool.TryParse(props["lower"], out _lowerCasing); + bool.TryParse(value, out _lowerCasing); } _json = props["json"]; - if (props.ContainsKey("subdir")) - { - _subDir = props["subdir"]; - } + props.TryGetValue("subdir", out _subDir); return this; } @@ -348,9 +345,9 @@ namespace ASC.Data.Storage.GoogleCloud return PredefinedObjectAcl.Private; } - if (_domainsAcl.ContainsKey(domain)) + if (_domainsAcl.TryGetValue(domain, out var value)) { - return _domainsAcl[domain]; + return value; } return _moduleAcl; } diff --git a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs index a044e89d74..27157bdb5c 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -146,15 +146,12 @@ namespace ASC.Data.Storage.RackspaceCloud _apiKey = props["apiKey"]; _username = props["username"]; - if (props.ContainsKey("lower")) + if (props.TryGetValue("lower", out var value)) { - bool.TryParse(props["lower"], out _lowerCasing); + bool.TryParse(value, out _lowerCasing); } - if (props.ContainsKey("subdir")) - { - _subDir = props["subdir"]; - } + props.TryGetValue("subdir", out _subDir); _public_container = props["public_container"]; @@ -193,13 +190,13 @@ namespace ASC.Data.Storage.RackspaceCloud var accounMetaData = client.GetAccountMetaData(_region); string secretKey; - if (accounMetaData.ContainsKey("Temp-Url-Key")) + if (accounMetaData.TryGetValue("Temp-Url-Key", out secretKey)) { - secretKey = accounMetaData["Temp-Url-Key"]; + } else { - secretKey = ASC.Common.Utils.RandomString.Generate(64); + secretKey = Common.Utils.RandomString.Generate(64); accounMetaData.Add("Temp-Url-Key", secretKey); client.UpdateAccountMetadata(accounMetaData, _region); } @@ -380,9 +377,9 @@ namespace ASC.Data.Storage.RackspaceCloud return ACL.Auto; } - if (_domainsAcl.ContainsKey(domain)) + if (_domainsAcl.TryGetValue(domain, out var value)) { - return _domainsAcl[domain]; + return value; } return _moduleAcl; } diff --git a/common/ASC.Data.Storage/S3/S3Storage.cs b/common/ASC.Data.Storage/S3/S3Storage.cs index 44eefb7c86..af7ce40e5d 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -98,9 +98,9 @@ namespace ASC.Data.Storage.S3 return S3CannedACL.Private; } - if (_domainsAcl.ContainsKey(domain)) + if (_domainsAcl.TryGetValue(domain, out var value)) { - return _domainsAcl[domain]; + return value; } return _moduleAcl; } @@ -1116,40 +1116,37 @@ namespace ASC.Data.Storage.S3 _secretAccessKeyId = props["secretaccesskey"]; _bucket = props["bucket"]; - if (props.ContainsKey("recycleDir")) + props.TryGetValue("recycleDir", out _recycleDir); + + if (props.TryGetValue("region", out var region) && !string.IsNullOrEmpty(region)) { - _recycleDir = props["recycleDir"]; + _region = region; } - if (props.ContainsKey("region") && !string.IsNullOrEmpty(props["region"])) + if (props.TryGetValue("serviceurl", out var url) && !string.IsNullOrEmpty(url)) { - _region = props["region"]; + _serviceurl = url; } - if (props.ContainsKey("serviceurl") && !string.IsNullOrEmpty(props["serviceurl"])) + if (props.TryGetValue("forcepathstyle", out var style)) { - _serviceurl = props["serviceurl"]; - } - - if (props.ContainsKey("forcepathstyle")) - { - if (bool.TryParse(props["forcepathstyle"], out var fps)) + if (bool.TryParse(style, out var fps)) { _forcepathstyle = fps; } } - if (props.ContainsKey("usehttp")) + if (props.TryGetValue("usehttp", out var use)) { - if (bool.TryParse(props["usehttp"], out var uh)) + if (bool.TryParse(use, out var uh)) { _useHttp = uh; } } - if (props.ContainsKey("sse") && !string.IsNullOrEmpty(props["sse"])) + if (props.TryGetValue("sse", out var sse) && !string.IsNullOrEmpty(sse)) { - _sse = (props["sse"].ToLower()) switch + _sse = sse.ToLower() switch { "none" => ServerSideEncryptionMethod.None, "aes256" => ServerSideEncryptionMethod.AES256, @@ -1166,23 +1163,17 @@ namespace ASC.Data.Storage.S3 ? new Uri(props["cnamessl"], UriKind.Absolute) : new Uri($"https://s3.{_region}.amazonaws.com/{_bucket}/", UriKind.Absolute); - if (props.ContainsKey("lower")) + if (props.TryGetValue("lower", out var lower)) { - bool.TryParse(props["lower"], out _lowerCasing); + bool.TryParse(lower, out _lowerCasing); } - if (props.ContainsKey("cloudfront")) + if (props.TryGetValue("cloudfront", out var front)) { - bool.TryParse(props["cloudfront"], out _revalidateCloudFront); - } - if (props.ContainsKey("distribution")) - { - _distributionId = props["distribution"]; + bool.TryParse(front, out _revalidateCloudFront); } - if (props.ContainsKey("subdir")) - { - _subDir = props["subdir"]; - } + props.TryGetValue("distribution", out _distributionId); + props.TryGetValue("subdir", out _subDir); return this; } diff --git a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs index e718b5df93..9a9d1c4129 100644 --- a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs +++ b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs @@ -179,9 +179,9 @@ namespace ASC.Feed.Data feedsIteration = GetFeedsInternal(filter); foreach (var feed in feedsIteration) { - if (feeds.ContainsKey(feed.GroupId)) + if (feeds.TryGetValue(feed.GroupId, out var value)) { - feeds[feed.GroupId].Add(feed); + value.Add(feed); } else { diff --git a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs index 85a5709df9..1cc81b31db 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -133,9 +133,9 @@ namespace ASC.MessagingSystem.DbSender ClientInfo clientInfo; - if (dict.ContainsKey(message.UAHeader)) + if (dict.TryGetValue(message.UAHeader, out clientInfo)) { - clientInfo = dict[message.UAHeader]; + } else { diff --git a/common/ASC.MessagingSystem/MessageTarget.cs b/common/ASC.MessagingSystem/MessageTarget.cs index 7fe9bee69c..ab8359fab2 100644 --- a/common/ASC.MessagingSystem/MessageTarget.cs +++ b/common/ASC.MessagingSystem/MessageTarget.cs @@ -99,7 +99,7 @@ namespace ASC.MessagingSystem var items = value.Split(','); - if (items.Count == 0) return null; + if (items.Length == 0) return null; return new MessageTarget(Option) { diff --git a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs index e39804b568..738fedcc57 100644 --- a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs +++ b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs @@ -201,9 +201,9 @@ namespace ASC.Feed.Aggregator { dictionary = new Dictionary<Guid, int>(); } - if (dictionary.ContainsKey(userGuid)) + if (dictionary.TryGetValue(userGuid, out var value)) { - ++dictionary[userGuid]; + ++value; } else { diff --git a/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs b/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs index a343f8dc5b..a5cad6e13e 100644 --- a/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs +++ b/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs @@ -140,9 +140,9 @@ namespace ASC.UrlShortener.Svc if (splited.Length < 2) continue; - if (dict.ContainsKey(splited[0])) + if (dict.TryGetValue(splited[0], out var value)) { - startInfo.EnvironmentVariables.Add("sql:" + dict[splited[0]], splited[1]); + startInfo.EnvironmentVariables.Add("sql:" + dict[value], splited[1]); } } From 78047d3b934c2359feec99bf6015a97c41093111 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 18 Jan 2022 18:29:46 +0300 Subject: [PATCH 053/167] analizators/U2U1210 --- .../RackspaceCloud/RackspaceCloudStorage.cs | 12 ++++++-- common/ASC.FederatedLogin/AccountLinker.cs | 5 ++-- common/ASC.VoipService/Dao/VoipDao.cs | 9 +++--- .../SharePoint/SharePointProviderInfo.cs | 26 +++++++++++++---- .../FileOperations/FileDownloadOperation.cs | 8 +++-- .../FileOperations/FileMoveCopyOperation.cs | 7 ++++- products/ASC.Files/Core/Utils/EntryManager.cs | 13 +++++---- .../ASC.Files/Core/Utils/FileConverter.cs | 16 +++++----- products/ASC.Files/Core/Utils/FileMarker.cs | 29 +++++++++---------- products/ASC.Files/Core/Utils/FileTracker.cs | 19 +++++------- .../Controllers/SettingsController.cs | 6 +++- web/ASC.Web.Core/Calendars/RecurrenceRule.cs | 4 +-- web/ASC.Web.Core/Files/FileUtility.cs | 25 ++++++++-------- 13 files changed, 103 insertions(+), 76 deletions(-) diff --git a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs index 27157bdb5c..3f024cd260 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -404,8 +404,11 @@ namespace ASC.Data.Storage.RackspaceCloud .Where(x => Wildcard.IsMatch(pattern, Path.GetFileName(x.Name))); if (!files.Any()) return; - - files.ToList().ForEach(x => client.DeleteObject(_private_container, x.Name)); + + foreach(var file in files) + { + client.DeleteObject(_private_container, file.Name); + } if (QuotaController != null) { @@ -462,7 +465,10 @@ namespace ASC.Data.Storage.RackspaceCloud if (!files.Any()) return; - files.ToList().ForEach(x => client.DeleteObject(_private_container, x.Name)); + foreach(var file in files) + { + client.DeleteObject(_private_container, file.Name); + } if (QuotaController != null) { diff --git a/common/ASC.FederatedLogin/AccountLinker.cs b/common/ASC.FederatedLogin/AccountLinker.cs index 946609794d..88b01e94b5 100644 --- a/common/ASC.FederatedLogin/AccountLinker.cs +++ b/common/ASC.FederatedLogin/AccountLinker.cs @@ -168,9 +168,8 @@ namespace ASC.FederatedLogin //Retrieve by uinque id return AccountLinks .Where(r => r.Id == obj) - .Select(r => r.Profile) - .ToList() - .ConvertAll(x => LoginProfile.CreateFromSerializedString(Signature, InstanceCrypto, x)); + .Select(x => LoginProfile.CreateFromSerializedString(Signature, InstanceCrypto, x.Profile)) + .ToList(); } public void AddLink(string obj, LoginProfile profile) diff --git a/common/ASC.VoipService/Dao/VoipDao.cs b/common/ASC.VoipService/Dao/VoipDao.cs index bb025abcaa..650430d80a 100644 --- a/common/ASC.VoipService/Dao/VoipDao.cs +++ b/common/ASC.VoipService/Dao/VoipDao.cs @@ -93,8 +93,7 @@ namespace ASC.VoipService.Dao { return VoipDbContext.VoipNumbers .Where(r => r.TenantId == TenantID) - .ToList() - .ConvertAll(ToPhone); + .Select(ToPhone); } public virtual IEnumerable<VoipPhone> GetNumbers(params string[] ids) @@ -106,7 +105,7 @@ namespace ASC.VoipService.Dao numbers = numbers.Where(r => ids.Any(a => a == r.Number || a == r.Id)); } - return numbers.ToList().ConvertAll(ToPhone); + return numbers.Select(ToPhone); } public VoipPhone GetNumber(string id) @@ -204,7 +203,7 @@ namespace ASC.VoipService.Dao query = query.Skip((int)filter.Offset); query = query.Take((int)filter.Max * 3); - var calls = query.ToList().ConvertAll(ToCall); + var calls = query.Select(ToCall); calls = calls.GroupJoin(calls, call => call.Id, h => h.ParentID, (call, h) => { @@ -249,7 +248,7 @@ namespace ASC.VoipService.Dao .Max(tmp => tmp.DialDate) }).Where(r => r.dbVoipCall.DbVoipCall.DialDate >= r.tmpDate || r.tmpDate == default); - return a.ToList().ConvertAll(r => ToCall(r.dbVoipCall)); + return a.Select(r => ToCall(r.dbVoipCall)).ToList(); } private IQueryable<CallContact> GetCallsQuery(VoipCallFilter filter) diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs index 94e9b54d2a..c9363e8942 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs @@ -455,17 +455,31 @@ namespace ASC.Files.Thirdparty.SharePoint var newFolder = CreateFolder(newUrl); if (delete) - { - folder.Folders.ToList().ForEach(r => MoveFolder(r.ServerRelativeUrl, newUrl)); - folder.Files.ToList().ForEach(r => MoveFile(r.ServerRelativeUrl, newUrl)); + { + foreach (var f in folder.Folders) + { + MoveFolder(f.ServerRelativeUrl, newUrl); + } + + foreach (var f in folder.Files) + { + MoveFile(f.ServerRelativeUrl, newUrl); + } folder.DeleteObject(); clientContext.ExecuteQuery(); } else - { - folder.Folders.ToList().ForEach(r => CopyFolder(r.ServerRelativeUrl, newUrl)); - folder.Files.ToList().ForEach(r => CopyFile(r.ServerRelativeUrl, newUrl)); + { + foreach (var f in folder.Folders) + { + CopyFolder(f.ServerRelativeUrl, newUrl); + } + + foreach(var f in folder.Files) + { + CopyFile(f.ServerRelativeUrl, newUrl); + } } return newFolder; diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs index 9ef7231d52..0740150d98 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs @@ -233,8 +233,12 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations } if (0 < Folders.Count) { - FilesSecurity.FilterRead(FolderDao.GetFolders(Files)).Cast<FileEntry<T>>().ToList() - .ForEach(folder => fileMarker.RemoveMarkAsNew(folder)); + var folders = FilesSecurity.FilterRead(FolderDao.GetFolders(Files)); + + foreach(var folder in folders) + { + fileMarker.RemoveMarkAsNew(folder); + } var filesInFolder = GetFilesInFolders(scope, Folders, string.Empty); entriesPathId.Add(filesInFolder); diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMoveCopyOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMoveCopyOperation.cs index f1e5a875c9..3b1c79f589 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMoveCopyOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMoveCopyOperation.cs @@ -174,7 +174,12 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations needToMark.AddRange(MoveOrCopyFolders(scope, Folders, toFolder, _copy)); needToMark.AddRange(MoveOrCopyFiles(scope, Files, toFolder, _copy)); - needToMark.Distinct().ToList().ForEach(x => fileMarker.MarkAsNew(x)); + var ntm = needToMark.Distinct(); + + foreach(var n in ntm) + { + fileMarker.MarkAsNew(n); + } } private List<FileEntry<TTo>> MoveOrCopyFolders<TTo>(IServiceScope scope, List<T> folderIds, Folder<TTo> toFolder, bool copy) diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index 87e1fa8a71..2c879b4f35 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -600,13 +600,14 @@ namespace ASC.Web.Files.Utils if (folderList.Any()) { var securityDao = DaoFactory.GetSecurityDao<string>(); - securityDao.GetPureShareRecords(folderList) + var ids = securityDao.GetPureShareRecords(folderList) //.Where(x => x.Owner == SecurityContext.CurrentAccount.ID) - .Select(x => x.EntryId).Distinct().ToList() - .ForEach(id => - { - folderList.First(y => y.ID.Equals(id)).Shared = true; - }); + .Select(x => x.EntryId).Distinct(); + + foreach(var id in ids) + { + folderList.First(y => y.ID.Equals(id)).Shared = true; + } } } diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index 9b9dd24499..2cac1a500f 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -170,15 +170,15 @@ namespace ASC.Web.Files.Utils { timer.Change(Timeout.Infinite, Timeout.Infinite); - conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) + var queues = conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) && (x.Value.Progress == 100 && DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(1) || - DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(10))) - .ToList() - .ForEach(x => - { - conversionQueue.Remove(x); - cache.Remove(GetKey(x.Key)); - }); + DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(10))); + + foreach (var q in queues) + { + conversionQueue.Remove(q); + cache.Remove(GetKey(q.Key)); + } logger.DebugFormat("Run CheckConvertFilesStatus: count {0}", conversionQueue.Count); diff --git a/products/ASC.Files/Core/Utils/FileMarker.cs b/products/ASC.Files/Core/Utils/FileMarker.cs index 1de062bcdf..35f84548c5 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -172,23 +172,22 @@ namespace ASC.Web.Files.Utils if (obj.FileEntry.ProviderEntry) { userIDs = userIDs.Where(u => !UserManager.GetUsers(u).IsVisitor(UserManager)).ToList(); + } + + foreach(var parentFolder in parentFolders) + { + var ids = filesSecurity + .WhoCanRead(parentFolder) + .Where(userID => userIDs.Contains(userID) && userID != obj.CurrentAccountId); + foreach (var id in ids) + { + if (userEntriesData.TryGetValue(id, out var value)) + value.Add(parentFolder); + else + userEntriesData.Add(id, new List<FileEntry> { parentFolder }); + } } - parentFolders.ForEach(parentFolder => - filesSecurity - .WhoCanRead(parentFolder) - .Where(userID => userIDs.Contains(userID) && userID != obj.CurrentAccountId) - .ToList() - .ForEach(userID => - { - if (userEntriesData.ContainsKey(userID)) - userEntriesData[userID].Add(parentFolder); - else - userEntriesData.Add(userID, new List<FileEntry> { parentFolder }); - }) - ); - - if (obj.FileEntry.RootFolderType == FolderType.USER) { diff --git a/products/ASC.Files/Core/Utils/FileTracker.cs b/products/ASC.Files/Core/Utils/FileTracker.cs index 159766f5e4..e158b1e58e 100644 --- a/products/ASC.Files/Core/Utils/FileTracker.cs +++ b/products/ASC.Files/Core/Utils/FileTracker.cs @@ -168,17 +168,14 @@ namespace ASC.Web.Files.Utils { var tracker = GetTracker(fileId); if (tracker != null) - { - - tracker.EditingBy.Values - .ToList() - .ForEach(i => - { - if (i.UserId == userId || userId == Guid.Empty) - { - i.CheckRightTime = check ? DateTime.MinValue : DateTime.UtcNow; - } - }); + { + foreach(var value in tracker.EditingBy.Values) + { + if (value.UserId == userId || userId == Guid.Empty) + { + value.CheckRightTime = check ? DateTime.MinValue : DateTime.UtcNow; + } + } SetTracker(fileId, tracker); } else diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index 9332ee1608..f9d837c52f 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1106,7 +1106,11 @@ namespace ASC.Api.Settings if (model.Logo != null) { var logoDict = new Dictionary<int, string>(); - model.Logo.ToList().ForEach(n => logoDict.Add(Int32.Parse(n.Key), n.Value)); + + foreach(var l in model.Logo) + { + logoDict.Add(Int32.Parse(l.Key), l.Value); + } TenantWhiteLabelSettingsHelper.SetLogo(settings, logoDict, storage); } diff --git a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs index 314920d7bb..064556c90d 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -238,7 +238,7 @@ namespace ASC.Web.Core.Calendars if (ByMonthDay != null && !ByMonthDay.Contains(d.Day) && !ByMonthDay.Contains(d.Day - d.GetDaysInMonth() + 1)) return false; - if (ByDay != null && !ByDay.ToList().Exists(item => item.DayOfWeek == d.DayOfWeek)) + if (ByDay != null && !ByDay.Any(item => item.DayOfWeek == d.DayOfWeek)) return false; return true; @@ -387,7 +387,7 @@ namespace ASC.Web.Core.Calendars dateRange.RemoveAll(date => (!ByMonthDay.Contains(date.Day) && !ByMonthDay.Contains(date.Day - (date.GetDaysInMonth() + 1)))); if (ByDay != null) - dateRange.RemoveAll(date => !ByDay.ToList().Exists(wd => wd.DayOfWeek == date.DayOfWeek)); + dateRange.RemoveAll(date => !ByDay.Any(wd => wd.DayOfWeek == date.DayOfWeek)); if (ByDay == null && ByMonthDay == null && ByYearDay == null) dateRange.RemoveAll(date => date.Day != d.Day); diff --git a/web/ASC.Web.Core/Files/FileUtility.cs b/web/ASC.Web.Core/Files/FileUtility.cs index b46a985db6..06a680c24e 100644 --- a/web/ASC.Web.Core/Files/FileUtility.cs +++ b/web/ASC.Web.Core/Files/FileUtility.cs @@ -330,19 +330,18 @@ namespace ASC.Web.Core.Files var dbManager = FilesDbContext; var list = dbManager.FilesConverts.Select(r => new { r.Input, r.Output }).ToList(); - - list.ForEach(item => - { - var input = item.Input; - var output = item.Output; - if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(output)) - return; - input = input.ToLower().Trim(); - output = output.ToLower().Trim(); - if (!_extsConvertible.ContainsKey(input)) - _extsConvertible[input] = new List<string>(); - _extsConvertible[input].Add(output); - }); + foreach (var item in list) + { + var input = item.Input; + var output = item.Output; + if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(output)) + continue; + input = input.ToLower().Trim(); + output = output.ToLower().Trim(); + if (!_extsConvertible.ContainsKey(input)) + _extsConvertible[input] = new List<string>(); + _extsConvertible[input].Add(output); + } } return _extsConvertible; } From 769fc55b95a0a7f14ea49e68ceeedb7d2d1b8ab5 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 11:16:58 +0300 Subject: [PATCH 054/167] analizators/U2U1210 --- .../Core/Core/Dao/TeamlabDao/FileDao.cs | 10 ++++++-- .../Core/Core/Dao/TeamlabDao/FolderDao.cs | 11 +++++--- .../Core/Core/Dao/TeamlabDao/TagDao.cs | 2 +- .../ASC.Files/Core/Core/FilesIntegration.cs | 6 ++++- .../Core/Core/Thirdparty/CrossDao.cs | 25 ++++++++++--------- .../Thirdparty/ProviderDao/ProviderDaoBase.cs | 19 +++++++------- 6 files changed, 44 insertions(+), 29 deletions(-) diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index 399b54d6f2..83296e79fa 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -693,7 +693,10 @@ namespace ASC.Files.Core.Data tx.Commit(); - fromFolders.ForEach(folderId => RecalculateFilesCount(folderId)); + foreach(var folderId in fromFolders) + { + RecalculateFilesCount(folderId); + } if (deleteFolder) DeleteFolder(fileId); @@ -770,7 +773,10 @@ namespace ASC.Files.Core.Data FilesDbContext.SaveChanges(); tx.Commit(); - fromFolders.ForEach(folderId => RecalculateFilesCount(folderId)); + foreach(var folderId in fromFolders) + { + RecalculateFilesCount(folderId); + } RecalculateFilesCount(toFolderId); } diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs index 816ebd24bb..a736f5ad77 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs @@ -657,14 +657,17 @@ namespace ASC.Files.Core.Data if (conflict != 0) { - FilesDbContext.Files + var files = FilesDbContext.Files .AsNoTracking() .Join(FilesDbContext.Files, f1 => f1.Title.ToLower(), f2 => f2.Title.ToLower(), (f1, f2) => new { f1, f2 }) .Where(r => r.f1.TenantId == TenantID && r.f1.CurrentVersion && r.f1.FolderId == folderId) .Where(r => r.f2.TenantId == TenantID && r.f2.CurrentVersion && r.f2.FolderId == conflict) - .Select(r => r.f1) - .ToList() - .ForEach(r => result[r.Id] = r.Title); + .Select(r => r.f1); + + foreach (var file in files) + { + result[file.Id] = file.Title; + } var childs = Query(FilesDbContext.Folders) .AsNoTracking() diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs index 11c6380d20..33668e45ff 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs @@ -730,7 +730,7 @@ namespace ASC.Files.Core.Data var monitorFolderIdsInt = monitorFolderIds.OfType<int>().ToList(); var subFoldersSqlQuery = getFolderQuery(FilesDbContext, monitorFolderIdsInt, deepSearch); - monitorFolderIds = monitorFolderIds.Concat(subFoldersSqlQuery.ToList().ConvertAll(r => (object)r)); + monitorFolderIds = monitorFolderIds.Concat(subFoldersSqlQuery.Select(r => (object)r)); var monitorFolderIdsStrings = monitorFolderIds.Select(r => r.ToString()).ToList(); diff --git a/products/ASC.Files/Core/Core/FilesIntegration.cs b/products/ASC.Files/Core/Core/FilesIntegration.cs index 63c88b4de4..70658a8de8 100644 --- a/products/ASC.Files/Core/Core/FilesIntegration.cs +++ b/products/ASC.Files/Core/Core/FilesIntegration.cs @@ -126,7 +126,11 @@ namespace ASC.Web.Files.Api if (provider == null) continue; var data = provider.GetFileSecurity(grouping.ToDictionary(r => r.Key, r => r.Value)); - data.ToList().ForEach(x => result.Add(x.Key, x.Value)); + + foreach(var d in data) + { + result.Add(d.Key, d.Value); + } } return result; diff --git a/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs b/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs index f6a4a4cd89..780ee9b286 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs @@ -86,12 +86,14 @@ namespace ASC.Files.Core.Thirdparty if (deleteSourceFile) { - if (fromFileShareRecords.Any()) - fromFileShareRecords.ToList().ForEach(x => - { - x.EntryId = toFile.ID; - securityDao.SetShare(x); - }); + if (fromFileShareRecords.Any()) + { + foreach (var record in fromFileShareRecords) + { + record.EntryId = toFile.ID; + securityDao.SetShare(record); + } + } var fromFileTags = fromFileNewTags; if (fromFileLockTag != null) fromFileTags.Add(fromFileLockTag); @@ -167,12 +169,11 @@ namespace ASC.Files.Core.Thirdparty .Where(x => x.EntryType == FileEntryType.Folder); if (fromFileShareRecords.Any()) - { - fromFileShareRecords.ToList().ForEach(x => - { - x.EntryId = toFolderId; - securityDao.SetShare(x); - }); + { + foreach(var record in fromFileShareRecords){ + record.EntryId = toFolderId; + securityDao.SetShare(record); + } } var tagDao = ServiceProvider.GetService<ITagDao<TFrom>>(); diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderDaoBase.cs index 5995bafadc..b08a6482fb 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderDaoBase.cs @@ -98,16 +98,17 @@ namespace ASC.Files.Thirdparty.ProviderDao protected void SetSharedProperty(IEnumerable<FileEntry<string>> entries) { - SecurityDao.GetPureShareRecords(entries.ToArray()) + var ids = SecurityDao.GetPureShareRecords(entries.ToArray()) //.Where(x => x.Owner == SecurityContext.CurrentAccount.ID) - .Select(x => x.EntryId).Distinct().ToList() - .ForEach(id => - { - var firstEntry = entries.FirstOrDefault(y => y.ID.Equals(id)); - - if (firstEntry != null) - firstEntry.Shared = true; - }); + .Select(x => x.EntryId).Distinct(); + + foreach(var id in ids) + { + var firstEntry = entries.FirstOrDefault(y => y.ID.Equals(id)); + + if (firstEntry != null) + firstEntry.Shared = true; + } } protected IEnumerable<IDaoSelector> GetSelectors() From 1403afbc1628e4f119a8c91cfb435c066b947e9b Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 11:59:14 +0300 Subject: [PATCH 055/167] analizators/U2U1209 --- .../Middleware/ProductSecurityFilter.cs | 8 ++++---- .../ASC.Core.Common/Billing/BillingClient.cs | 8 +++----- .../ASC.Core.Common/Caching/AzRecordStore.cs | 4 ++-- .../Notify/Senders/SmtpSender.cs | 6 ++---- .../Core/DbBackupProvider.cs | 4 ++-- common/ASC.Data.Backup.Core/Core/DbHelper.cs | 4 ++-- .../DiscStorage/DiscDataStore.cs | 4 ++-- .../LoginProviders/OpenIdLoginProvider.cs | 6 ++---- common/ASC.VoipService/Dao/VoIPCallFilter.cs | 2 +- .../ASC.TelegramService/TelegramHandler.cs | 3 +-- .../Core/Core/Security/FileSecurity.cs | 16 +++++++-------- .../Core/Thirdparty/RegexDaoSelectorBase.cs | 2 +- .../FileOperations/FileDownloadOperation.cs | 7 ++----- .../ASC.Files/Core/Utils/FileConverter.cs | 10 +++------- products/ASC.Files/Core/Utils/FileMarker.cs | 20 +++++++++---------- products/ASC.Files/Core/Utils/FileTracker.cs | 4 ++-- .../Users/Import/TextFileUserImporter.cs | 4 ++-- web/ASC.Web.Core/WebItemSecurity.cs | 4 ++-- 18 files changed, 51 insertions(+), 65 deletions(-) diff --git a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs index cbc2cd13b1..779a5ea9ab 100644 --- a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs +++ b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs @@ -103,16 +103,16 @@ namespace ASC.Api.Core.Middleware if (!string.IsNullOrEmpty(url)) { var module = url.Split('/')[0]; - if (products.ContainsKey(module)) + if (products.TryGetValue(module, out var communityProduct)) { - return products[module]; + return communityProduct; } } } - if (products.ContainsKey(name)) + if (products.TryGetValue(name, out var product)) { - return products[name]; + return product; } return default; } diff --git a/common/ASC.Core.Common/Billing/BillingClient.cs b/common/ASC.Core.Common/Billing/BillingClient.cs index dd07b0f168..3fc3814246 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -187,15 +187,13 @@ namespace ASC.Core.Billing var result = Request("GetProductsPrices", null, parameters.ToArray()); var prices = JsonSerializer.Deserialize<Dictionary<int, Dictionary<string, Dictionary<string, decimal>>>>(result); - if (prices.ContainsKey(AvangatePaymentSystemId)) + if (prices.TryGetValue(AvangatePaymentSystemId, out var pricesPaymentSystem)) { - var pricesPaymentSystem = prices[AvangatePaymentSystemId]; - return productIds.Select(productId => { - if (pricesPaymentSystem.ContainsKey(productId)) + if (pricesPaymentSystem.TryGetValue(productId, out var prices)) { - return new { ProductId = productId, Prices = pricesPaymentSystem[productId] }; + return new { ProductId = productId, Prices = prices }; } return new { ProductId = productId, Prices = new Dictionary<string, decimal>() }; }) diff --git a/common/ASC.Core.Common/Caching/AzRecordStore.cs b/common/ASC.Core.Common/Caching/AzRecordStore.cs index d983357dda..d1230f551d 100644 --- a/common/ASC.Core.Common/Caching/AzRecordStore.cs +++ b/common/ASC.Core.Common/Caching/AzRecordStore.cs @@ -68,9 +68,9 @@ namespace ASC.Core.Caching if (r == null) return; var id = r.ObjectId ?? string.Empty; - if (byObjectId.ContainsKey(id)) + if (byObjectId.TryGetValue(id, out var list)) { - byObjectId[id].RemoveAll(a => a.SubjectId == r.SubjectId && a.ActionId == r.ActionId && a.Reaction == r.Reaction); + list.RemoveAll(a => a.SubjectId == r.SubjectId && a.ActionId == r.ActionId && a.Reaction == r.Reaction); } } diff --git a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs index 370e579f66..7091946bad 100644 --- a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs @@ -80,11 +80,9 @@ namespace ASC.Core.Notify.Senders Host = properties["host"]; Port = properties.ContainsKey("port") ? int.Parse(properties["port"]) : 25; Ssl = properties.ContainsKey("enableSsl") && bool.Parse(properties["enableSsl"]); - if (properties.ContainsKey("userName")) + if (properties.TryGetValue("userName", out var property)) { - Credentials = new NetworkCredential( - properties["userName"], - properties["password"]); + Credentials = new NetworkCredential(property, properties["password"]); } } } diff --git a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs index 9c67a8c3ff..37ede1d558 100644 --- a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs +++ b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs @@ -68,9 +68,9 @@ namespace ASC.Data.Backup xml.Add(node); var connectionKey = connectionString.ProviderName + connectionString.ConnectionString; - if (connectionKeys.ContainsKey(connectionKey)) + if (connectionKeys.TryGetValue(connectionKey, out var value)) { - node.Add(new XAttribute("ref", connectionKeys[connectionKey])); + node.Add(new XAttribute("ref", value)); } else { diff --git a/common/ASC.Data.Backup.Core/Core/DbHelper.cs b/common/ASC.Data.Backup.Core/Core/DbHelper.cs index f4637094d8..8aca730396 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -264,9 +264,9 @@ namespace ASC.Data.Backup { if (tenant == -1) return string.Empty; - if (whereExceptions.ContainsKey(tableName.ToLower())) + if (whereExceptions.TryGetValue(tableName.ToLower(), out var exc)) { - return string.Format(whereExceptions[tableName.ToLower()], tenant); + return string.Format(exc, tenant); } var tenantColumn = GetColumnsFrom(tableName).FirstOrDefault(c => c.StartsWith("tenant", StringComparison.OrdinalIgnoreCase)); return tenantColumn != null ? diff --git a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs index c5b86fde9e..45f667da44 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -666,9 +666,9 @@ namespace ASC.Data.Storage.DiscStorage private MappedPath GetPath(string domain) { if (domain != null) - if (_mappedPaths.ContainsKey(domain)) + if (_mappedPaths.TryGetValue(domain, out var value)) { - return _mappedPaths[domain]; + return value; } return _mappedPaths[string.Empty].AppendDomain(domain); } diff --git a/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs index 285710cfdb..fc6e24bd44 100644 --- a/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs @@ -66,8 +66,7 @@ namespace ASC.FederatedLogin.LoginProviders var realmUrlString = string.Empty; - if (@params.ContainsKey("realmUrl")) - realmUrlString = @params["realmUrl"]; + @params.TryGetValue("realmUrl", out realmUrlString); if (!string.IsNullOrEmpty(realmUrlString)) request = Openid.CreateRequest(id, new Realm(realmUrlString)); @@ -123,8 +122,7 @@ namespace ASC.FederatedLogin.LoginProviders var fetchprofile = response.GetExtension<FetchResponse>(); var realmUrlString = string.Empty; - if (@params.ContainsKey("realmUrl")) - realmUrlString = @params["realmUrl"]; + @params.TryGetValue("realmUrl", out realmUrlString); var profile = ProfileFromOpenId(spprofile, fetchprofile, response.ClaimedIdentifier.ToString(), realmUrlString); return profile; diff --git a/common/ASC.VoipService/Dao/VoIPCallFilter.cs b/common/ASC.VoipService/Dao/VoIPCallFilter.cs index efd8e8a9d7..96947f5e27 100644 --- a/common/ASC.VoipService/Dao/VoIPCallFilter.cs +++ b/common/ASC.VoipService/Dao/VoIPCallFilter.cs @@ -62,7 +62,7 @@ namespace ASC.VoipService.Dao get { if (string.IsNullOrWhiteSpace(Type)) return null; - if (TypeStatuses.ContainsKey(Type)) return TypeStatuses[Type]; + if (TypeStatuses.TryGetValue(Type, out var status)) return status; return null; } diff --git a/common/services/ASC.TelegramService/TelegramHandler.cs b/common/services/ASC.TelegramService/TelegramHandler.cs index 6237cc91c7..cae084da9d 100644 --- a/common/services/ASC.TelegramService/TelegramHandler.cs +++ b/common/services/ASC.TelegramService/TelegramHandler.cs @@ -112,9 +112,8 @@ namespace ASC.TelegramService var telegramHelper = scope.ServiceProvider.GetService<TelegramHelper>(); var newClient = telegramHelper.InitClient(token, proxy); - if (Clients.ContainsKey(tenantId)) + if (Clients.TryGetValue(tenantId, out var client)) { - var client = Clients[tenantId]; client.TokenLifeSpan = tokenLifespan; if (token != client.Token || proxy != client.Proxy) diff --git a/products/ASC.Files/Core/Core/Security/FileSecurity.cs b/products/ASC.Files/Core/Core/Security/FileSecurity.cs index 8da56a2d79..4f7d0f4440 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -755,9 +755,9 @@ namespace ASC.Files.Core.Security files.ForEach(x => { - if (fileIds.ContainsKey(x.ID)) + if (fileIds.TryGetValue(x.ID, out var access)) { - x.Access = fileIds[x.ID]; + x.Access = access; x.FolderIdDisplay = GlobalFolder.GetFolderShare<T>(daoFactory); } }); @@ -775,9 +775,9 @@ namespace ASC.Files.Core.Security } folders.ForEach(x => { - if (folderIds.ContainsKey(x.ID)) + if (folderIds.TryGetValue(x.ID, out var access)) { - x.Access = folderIds[x.ID]; + x.Access = access; x.FolderIdDisplay = GlobalFolder.GetFolderShare<T>(daoFactory); } }); @@ -874,9 +874,9 @@ namespace ASC.Files.Core.Security files.ForEach(x => { - if (fileIds.ContainsKey(x.ID)) + if (fileIds.TryGetValue(x.ID, out var access)) { - x.Access = fileIds[x.ID]; + x.Access = access; x.FolderIdDisplay = GlobalFolder.GetFolderPrivacy<T>(daoFactory); } }); @@ -894,9 +894,9 @@ namespace ASC.Files.Core.Security } folders.ForEach(x => { - if (folderIds.ContainsKey(x.ID)) + if (folderIds.TryGetValue(x.ID, out var access)) { - x.Access = folderIds[x.ID]; + x.Access = access; x.FolderIdDisplay = GlobalFolder.GetFolderPrivacy<T>(daoFactory); } }); diff --git a/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs b/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs index b4f42ceee2..f0653fec6c 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs @@ -116,7 +116,7 @@ namespace ASC.Files.Thirdparty private T1 GetDao<T1>(string id) where T1 : ThirdPartyProviderDao<T> { var providerKey = $"{id}{typeof(T1)}"; - if (Providers.ContainsKey(providerKey)) return (T1)Providers[providerKey]; + if (Providers.TryGetValue(providerKey, out var provider)) return (T1)provider; var res = ServiceProvider.GetService<T1>(); diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs index 0740150d98..58fdea4e41 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs @@ -205,10 +205,8 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations var title = file.Title; - if (files.ContainsKey(file.ID)) + if (files.TryGetValue(file.ID, out var convertToExt)) { - var convertToExt = files[file.ID]; - if (!string.IsNullOrEmpty(convertToExt)) { title = FileUtility.ReplaceFileExtension(title, convertToExt); @@ -317,9 +315,8 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations continue; } - if (files.ContainsKey(file.ID)) + if (files.TryGetValue(file.ID, out convertToExt)) { - convertToExt = files[file.ID]; if (!string.IsNullOrEmpty(convertToExt)) { newtitle = FileUtility.ReplaceFileExtension(path, convertToExt); diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index 2cac1a500f..9e150f1e9d 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -271,9 +271,8 @@ namespace ASC.Web.Files.Utils logger.Error(string.Format("Error convert {0} with url {1}", file.ID, fileUri), exception); lock (locker) { - if (conversionQueue.Keys.Contains(file)) + if (conversionQueue.TryGetValue(file, out var operationResult)) { - var operationResult = conversionQueue[file]; if (operationResult.Delete) { conversionQueue.Remove(file); @@ -297,10 +296,8 @@ namespace ASC.Web.Files.Utils { lock (locker) { - if (conversionQueue.Keys.Contains(file)) + if (conversionQueue.TryGetValue(file, out var operationResult)) { - var operationResult = conversionQueue[file]; - if (DateTime.Now - operationResult.StartDateTime > TimeSpan.FromMinutes(10)) { operationResult.StopDateTime = DateTime.UtcNow; @@ -338,9 +335,8 @@ namespace ASC.Web.Files.Utils { lock (locker) { - if (conversionQueue.Keys.Contains(file)) + if (conversionQueue.TryGetValue(file, out var operationResult)) { - var operationResult = conversionQueue[file]; if (operationResult.Delete) { conversionQueue.Remove(file); diff --git a/products/ASC.Files/Core/Utils/FileMarker.cs b/products/ASC.Files/Core/Utils/FileMarker.cs index 35f84548c5..5c590ec517 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -153,8 +153,8 @@ namespace ASC.Web.Files.Utils userIDs.ForEach(userID => { - if (userEntriesData.ContainsKey(userID)) - userEntriesData[userID].AddRange(entries); + if (userEntriesData.TryGetValue(userID, out var value)) + value.AddRange(entries); else userEntriesData.Add(userID, entries); @@ -217,8 +217,8 @@ namespace ASC.Web.Files.Utils if (rootFolder == null) continue; - if (userEntriesData.ContainsKey(userID)) - userEntriesData[userID].Add(rootFolder); + if (userEntriesData.TryGetValue(userID, out var value)) + value.Add(rootFolder); else userEntriesData.Add(userID, new List<FileEntry> { rootFolder }); @@ -234,8 +234,8 @@ namespace ASC.Web.Files.Utils var commonFolder = folderDao.GetFolder(GlobalFolder.GetFolderCommon<T>(this, DaoFactory)); userIDs.ForEach(userID => { - if (userEntriesData.ContainsKey(userID)) - userEntriesData[userID].Add(commonFolder); + if (userEntriesData.TryGetValue(userID, out var value)) + value.Add(commonFolder); else userEntriesData.Add(userID, new List<FileEntry> { commonFolder }); @@ -253,8 +253,8 @@ namespace ASC.Web.Files.Utils var rootFolder = folderDao.GetFolder(privacyFolderId); if (rootFolder == null) continue; - if (userEntriesData.ContainsKey(userID)) - userEntriesData[userID].Add(rootFolder); + if (userEntriesData.TryGetValue(userID, out var value)) + value.Add(rootFolder); else userEntriesData.Add(userID, new List<FileEntry> { rootFolder }); @@ -264,8 +264,8 @@ namespace ASC.Web.Files.Utils userIDs.ForEach(userID => { - if (userEntriesData.ContainsKey(userID)) - userEntriesData[userID].Add(obj.FileEntry); + if (userEntriesData.TryGetValue(userID, out var value)) + value.Add(obj.FileEntry); else userEntriesData.Add(userID, new List<FileEntry> { obj.FileEntry }); }); diff --git a/products/ASC.Files/Core/Utils/FileTracker.cs b/products/ASC.Files/Core/Utils/FileTracker.cs index e158b1e58e..20c8596d80 100644 --- a/products/ASC.Files/Core/Utils/FileTracker.cs +++ b/products/ASC.Files/Core/Utils/FileTracker.cs @@ -63,9 +63,9 @@ namespace ASC.Web.Files.Utils var tracker = GetTracker(fileId); if (tracker != null && IsEditing(fileId)) { - if (tracker.EditingBy.Keys.Contains(tabId)) + if (tracker.EditingBy.TryGetValue(tabId, out var trackInfo)) { - tracker.EditingBy[tabId].TrackTime = DateTime.UtcNow; + trackInfo.TrackTime = DateTime.UtcNow; checkRight = (DateTime.UtcNow - tracker.EditingBy[tabId].CheckRightTime > CheckRightTimeout); } else diff --git a/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs b/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs index 4932763ba9..9e6634862a 100644 --- a/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs +++ b/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs @@ -150,9 +150,9 @@ namespace ASC.Web.Core.Users.Import foreach (var info in infos) { var propertyField = field.Trim(); - if (NameMapping != null && NameMapping.ContainsKey(propertyField)) + if (NameMapping != null) { - propertyField = NameMapping[propertyField]; + NameMapping.TryGetValue(propertyField, out propertyField); } if (!string.IsNullOrEmpty(propertyField) && !ExcludeList.Contains(propertyField) && propertyField.Equals(info.Name, StringComparison.OrdinalIgnoreCase)) { diff --git a/web/ASC.Web.Core/WebItemSecurity.cs b/web/ASC.Web.Core/WebItemSecurity.cs index f49c21d068..3331287d35 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -148,9 +148,9 @@ namespace ASC.Web.Core { lock (dic) { - if (dic.ContainsKey(id + @for)) + if (dic.TryGetValue(id + @for, out var value)) { - return dic[id + @for]; + return value; } } } From 4b211c0b80a91a5096494ba32010873b39a431a3 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 12:14:50 +0300 Subject: [PATCH 056/167] analizators/U2U1203 --- common/ASC.Common/Caching/AscCache.cs | 4 ++-- common/ASC.Common/Mapping/MappingProfile.cs | 3 +-- products/ASC.Files/Core/Utils/FileMarker.cs | 2 +- products/ASC.Files/Core/Utils/FileTracker.cs | 12 ++++++------ 4 files changed, 10 insertions(+), 11 deletions(-) diff --git a/common/ASC.Common/Caching/AscCache.cs b/common/ASC.Common/Caching/AscCache.cs index 8b593c00f5..056d8321c1 100644 --- a/common/ASC.Common/Caching/AscCache.cs +++ b/common/ASC.Common/Caching/AscCache.cs @@ -55,7 +55,7 @@ namespace ASC.Common.Caching public static void OnClearCache() { - var keys = MemoryCache.Default.Select(r => r.Key).ToList(); + var keys = MemoryCache.Default.Select(r => r.Key); foreach (var k in keys) { @@ -114,7 +114,7 @@ namespace ASC.Common.Caching public void Remove(Regex pattern) { var copy = MemoryCacheKeys.ToDictionary(p => p.Key, p => p.Value); - var keys = copy.Select(p => p.Key).Where(k => pattern.IsMatch(k)).ToArray(); + var keys = copy.Select(p => p.Key).Where(k => pattern.IsMatch(k)); foreach (var key in keys) { diff --git a/common/ASC.Common/Mapping/MappingProfile.cs b/common/ASC.Common/Mapping/MappingProfile.cs index 3d16f3f228..dcd17805ae 100644 --- a/common/ASC.Common/Mapping/MappingProfile.cs +++ b/common/ASC.Common/Mapping/MappingProfile.cs @@ -44,8 +44,7 @@ namespace ASC.Common.Mapping var types = assembly.GetExportedTypes() .Where(t => t.GetInterfaces().Any(i => - i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>))) - .ToList(); + i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>))); foreach (var type in types) { diff --git a/products/ASC.Files/Core/Utils/FileMarker.cs b/products/ASC.Files/Core/Utils/FileMarker.cs index 5c590ec517..9643d3cebf 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -378,7 +378,7 @@ namespace ASC.Web.Files.Utils var folderTags = listTags.Where(tag => tag.EntryType == FileEntryType.Folder); var providerFolderTags = folderTags.Select(tag => new KeyValuePair<Tag, Folder<T>>(tag, folderDao.GetFolder((T)tag.EntryId))) - .Where(pair => pair.Value != null && pair.Value.ProviderEntry).ToList(); + .Where(pair => pair.Value != null && pair.Value.ProviderEntry); foreach (var providerFolderTag in providerFolderTags) { diff --git a/products/ASC.Files/Core/Utils/FileTracker.cs b/products/ASC.Files/Core/Utils/FileTracker.cs index 20c8596d80..a4c3dc0d87 100644 --- a/products/ASC.Files/Core/Utils/FileTracker.cs +++ b/products/ASC.Files/Core/Utils/FileTracker.cs @@ -97,8 +97,8 @@ namespace ASC.Web.Files.Utils if (userId != default) { var listForRemove = tracker.EditingBy - .Where(b => tracker.EditingBy[b.Key].UserId == userId) - .ToList(); + .Where(b => tracker.EditingBy[b.Key].UserId == userId); + foreach (var editTab in listForRemove) { tracker.EditingBy.Remove(editTab.Key); @@ -117,8 +117,8 @@ namespace ASC.Web.Files.Utils if (tracker != null) { var listForRemove = tracker.EditingBy - .Where(b => b.Value.UserId != userId) - .ToList(); + .Where(b => b.Value.UserId != userId); + if (listForRemove.Count() != tracker.EditingBy.Count) { foreach (var forRemove in listForRemove) @@ -138,8 +138,8 @@ namespace ASC.Web.Files.Utils if (tracker != null) { var listForRemove = tracker.EditingBy - .Where(e => !e.Value.NewScheme && (DateTime.UtcNow - e.Value.TrackTime).Duration() > TrackTimeout) - .ToList(); + .Where(e => !e.Value.NewScheme && (DateTime.UtcNow - e.Value.TrackTime).Duration() > TrackTimeout); + foreach (var editTab in listForRemove) { tracker.EditingBy.Remove(editTab.Key); From fbb50e676eb95bfc7e120c40f93c2fb9cb42f146 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 12:51:30 +0300 Subject: [PATCH 057/167] analizators/U2U1202 --- common/ASC.Core.Common/Data/DbUserService.cs | 4 ++-- .../MultiRegionHostedSolution.cs | 2 +- .../Notify/Engine/NotifyEngine.cs | 4 ++-- .../Notify/Model/ISubscriptionProvider.cs | 2 +- .../Notify/RecipientProviderImpl.cs | 2 +- .../Notify/Telegram/Dao/CachedTelegramDao.cs | 2 +- .../ASC.Data.Backup.Core/Core/NotifyHelper.cs | 2 +- .../Tasks/BackupPortalTask.cs | 2 +- .../Tasks/Data/TableInfo.cs | 2 +- .../ASC.ElasticSearch/Core/SearchSettings.cs | 2 +- .../ASC.ElasticSearch/Engine/BaseIndexer.cs | 4 ++-- .../Engine/FactoryIndexer.cs | 4 ++-- .../ASC.ElasticSearch/Service/Service.cs | 2 +- .../Core/Core/Dao/TeamlabDao/FileDao.cs | 8 +++---- .../Core/Core/Dao/TeamlabDao/FolderDao.cs | 4 ++-- .../Core/Core/Dao/TeamlabDao/SecurityDao.cs | 2 +- .../Core/Core/Dao/TeamlabDao/TagDao.cs | 8 +++---- .../ASC.Files/Core/Core/FileStorageService.cs | 14 ++++++------ .../Core/Core/Search/FactoryIndexerFile.cs | 2 +- .../Core/Core/Search/FactoryIndexerFolder.cs | 2 +- .../Core/Core/Security/FileSecurity.cs | 2 +- .../Core/Core/Thirdparty/CrossDao.cs | 4 ++-- .../Core/Thirdparty/IThirdPartyProviderDao.cs | 2 +- .../Thirdparty/ProviderDao/ProviderFileDao.cs | 2 +- .../ProviderDao/ProviderFolderDao.cs | 8 +++---- .../ProviderDao/ProviderSecutiryDao.cs | 6 ++--- .../Core/HttpHandlers/FileHandler.ashx.cs | 2 +- .../DocbuilderReportsUtility.cs | 2 +- .../DocumentService/DocumentServiceHelper.cs | 2 +- .../DocumentService/DocumentServiceTracker.cs | 2 +- .../FileOperations/FileDownloadOperation.cs | 2 +- .../FileOperations/FileMarkAsReadOperation.cs | 4 ++-- .../FileOperations/FileOperationsManager.cs | 2 +- products/ASC.Files/Core/Utils/EntryManager.cs | 2 +- .../ASC.Files/Core/Utils/FileConverter.cs | 4 ++-- products/ASC.Files/Core/Utils/FileMarker.cs | 22 +++++++++---------- products/ASC.Files/Core/Utils/FileSharing.cs | 4 ++-- products/ASC.Files/Core/Utils/FileUploader.cs | 2 +- .../Mobile/MobileAppInstallRegistrator.cs | 2 +- web/ASC.Web.Core/Notify/StudioNotifyHelper.cs | 2 +- .../Notify/StudioNotifyServiceSender.cs | 2 +- .../Notify/StudioPeriodicNotify.cs | 6 ++--- .../Notify/StudioWhatsNewNotify.cs | 2 +- web/ASC.Web.Core/Tfa/TfaAppUserSettings.cs | 2 +- web/ASC.Web.Core/WebItemSecurity.cs | 4 ++-- 45 files changed, 84 insertions(+), 84 deletions(-) diff --git a/common/ASC.Core.Common/Data/DbUserService.cs b/common/ASC.Core.Common/Data/DbUserService.cs index 5915068967..8b4bf71903 100644 --- a/common/ASC.Core.Common/Data/DbUserService.cs +++ b/common/ASC.Core.Common/Data/DbUserService.cs @@ -701,7 +701,7 @@ namespace ASC.Core.Data q = q.Where(r => !r.Removed); - if (includeGroups != null && includeGroups.Any()) + if (includeGroups != null && includeGroups.Count > 0) { Expression or = Expression.Empty(); @@ -711,7 +711,7 @@ namespace ASC.Core.Data } } - if (excludeGroups != null && excludeGroups.Any()) + if (excludeGroups != null && excludeGroups.Count > 0) { foreach (var eg in excludeGroups) { diff --git a/common/ASC.Core.Common/MultiRegionHostedSolution.cs b/common/ASC.Core.Common/MultiRegionHostedSolution.cs index 2bb36d0b11..7a488a6838 100644 --- a/common/ASC.Core.Common/MultiRegionHostedSolution.cs +++ b/common/ASC.Core.Common/MultiRegionHostedSolution.cs @@ -107,7 +107,7 @@ namespace ASC.Core error = exception; } } - if (!result.Any() && error != null) + if (result.Count == 0 && error != null) { throw error; } diff --git a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs index f031c7b886..c5074392dc 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -205,7 +205,7 @@ namespace ASC.Notify.Engine NotifyRequest request = null; lock (requests) { - if (requests.Any()) + if (requests.Count > 0) { request = requests.Dequeue(); } @@ -425,7 +425,7 @@ namespace ASC.Notify.Engine var recipient = request.Recipient as IDirectRecipient; var addresses = recipient.Addresses; - if (addresses == null || !addresses.Any()) + if (addresses == null || addresses.Length == 0) { addresses = recipientProvider.GetRecipientAddresses(request.Recipient as IDirectRecipient, sender); recipient = new DirectRecipient(request.Recipient.ID, request.Recipient.Name, addresses); diff --git a/common/ASC.Core.Common/Notify/Model/ISubscriptionProvider.cs b/common/ASC.Core.Common/Notify/Model/ISubscriptionProvider.cs index cbd06ee77d..23eebf1016 100644 --- a/common/ASC.Core.Common/Notify/Model/ISubscriptionProvider.cs +++ b/common/ASC.Core.Common/Notify/Model/ISubscriptionProvider.cs @@ -69,7 +69,7 @@ namespace ASC.Notify.Model if (subscriptionRecord != null) { var properties = subscriptionRecord.GetType().GetProperties(); - if (properties.Any()) + if (properties.Length > 0) { var property = properties.Single(p => p.Name == "Subscribed"); if (property != null) diff --git a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs index 6d4788ff94..d86468d01e 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -125,7 +125,7 @@ namespace ASC.Core.Notify if (recipient.CheckActivation) { //It's direct email - if (recipient.Addresses != null && recipient.Addresses.Any()) + if (recipient.Addresses != null && recipient.Addresses.Length > 0) { //Filtering only missing users and users who activated already var filteredAddresses = from address in recipient.Addresses diff --git a/common/ASC.Core.Common/Notify/Telegram/Dao/CachedTelegramDao.cs b/common/ASC.Core.Common/Notify/Telegram/Dao/CachedTelegramDao.cs index aba43cb9b2..da2395908b 100644 --- a/common/ASC.Core.Common/Notify/Telegram/Dao/CachedTelegramDao.cs +++ b/common/ASC.Core.Common/Notify/Telegram/Dao/CachedTelegramDao.cs @@ -107,7 +107,7 @@ namespace ASC.Core.Common.Notify.Telegram if (users != null) return users; users = TgDao.GetUser(telegramId); - if (users.Any()) Cache.Insert(key, users, Expiration); + if (users.Count > 0) Cache.Insert(key, users, Expiration); return users; } diff --git a/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs b/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs index db8968d5c6..dabab637f1 100644 --- a/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs @@ -145,7 +145,7 @@ namespace ASC.Data.Backup .Where(u => notify ? u.ActivationStatus.HasFlag(EmployeeActivationStatus.Activated) : u.IsOwner(tenant)) .ToArray(); - if (users.Any()) + if (users.Length > 0) { var args = CreateArgs(scope, region, url); if (action == Actions.MigrationPortalSuccessV115) diff --git a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs index 4b7c73cd98..050127ab14 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -393,7 +393,7 @@ namespace ASC.Data.Backup.Tasks { Logger.DebugFormat("save to file {0}", t); List<object[]> portion; - while ((portion = data.Take(BatchLimit).ToList()).Any()) + while ((portion = data.Take(BatchLimit).ToList()).Count > 0) { using (var sw = new StreamWriter(path, true)) using (var writer = new JsonTextWriter(sw)) diff --git a/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs b/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs index dd54560f00..c52d383545 100644 --- a/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs +++ b/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs @@ -74,7 +74,7 @@ namespace ASC.Data.Backup.Tasks.Data public bool HasDateColumns() { - return DateColumns.Any(); + return DateColumns.Count > 0; } public bool HasTenantColumn() diff --git a/common/services/ASC.ElasticSearch/Core/SearchSettings.cs b/common/services/ASC.ElasticSearch/Core/SearchSettings.cs index cc049827d4..667258ec70 100644 --- a/common/services/ASC.ElasticSearch/Core/SearchSettings.cs +++ b/common/services/ASC.ElasticSearch/Core/SearchSettings.cs @@ -136,7 +136,7 @@ namespace ASC.ElasticSearch.Core var settings = SettingsManager.Load<SearchSettings>(); var settingsItems = settings.Items; - var toReIndex = !settingsItems.Any() ? items.Where(r => r.Enabled).ToList() : items.Where(item => settingsItems.Any(r => r.ID == item.ID && r.Enabled != item.Enabled)).ToList(); + var toReIndex = settingsItems.Count == 0 ? items.Where(r => r.Enabled).ToList() : items.Where(item => settingsItems.Any(r => r.ID == item.ID && r.Enabled != item.Enabled)).ToList(); settings.Items = items; settings.Data = JsonConvert.SerializeObject(items); diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index 59ce729c99..5841592e67 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -122,7 +122,7 @@ namespace ASC.ElasticSearch internal void Index(List<T> data, bool immediately = true) { - if (!data.Any()) return; + if (data.Count == 0) return; CreateIfNotExist(data[0]); @@ -495,7 +495,7 @@ namespace ASC.ElasticSearch { var result = request.Index(IndexName); - if (fields.Any()) + if (fields.Length > 0) { result.Script(GetScriptUpdateByQuery(data, fields)); } diff --git a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs index 4c23f20347..3d16cfe71a 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -207,7 +207,7 @@ namespace ASC.ElasticSearch public void Index(List<T> data, bool immediately = true, int retry = 0) { var t = ServiceProvider.GetService<T>(); - if (!Support(t) || !data.Any()) return; + if (!Support(t) || data.Count == 0) return; try { @@ -276,7 +276,7 @@ namespace ASC.ElasticSearch public Task IndexAsync(List<T> data, bool immediately = true, int retry = 0) { var t = ServiceProvider.GetService<T>(); - if (!Support(t) || !data.Any()) return Task.CompletedTask; + if (!Support(t) || data.Count == 0) return Task.CompletedTask; return InternalIndexAsync(data, immediately, retry); } diff --git a/common/services/ASC.ElasticSearch/Service/Service.cs b/common/services/ASC.ElasticSearch/Service/Service.cs index 12a2b4462e..214e73c737 100644 --- a/common/services/ASC.ElasticSearch/Service/Service.cs +++ b/common/services/ASC.ElasticSearch/Service/Service.cs @@ -79,7 +79,7 @@ namespace ASC.ElasticSearch.Service tasks.Add(instance.ReIndex()); } - if (!tasks.Any()) return; + if (tasks.Count == 0) return; Task.WhenAll(tasks).ContinueWith(r => { diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index 83296e79fa..89ad6fb695 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -457,7 +457,7 @@ namespace ASC.Files.Core.Data parentFoldersIds = parentFolders.Select(r => r.ParentId).ToList(); - if (parentFoldersIds.Any()) + if (parentFoldersIds.Count == 0) { var folderToUpdate = FilesDbContext.Folders .Where(r => parentFoldersIds.Contains(r.Id)); @@ -581,7 +581,7 @@ namespace ASC.Files.Core.Data parentFoldersIds = parentFolders.Select(r => r.ParentId).ToList(); - if (parentFoldersIds.Any()) + if (parentFoldersIds.Count > 0) { var folderToUpdate = FilesDbContext.Folders .Where(r => parentFoldersIds.Contains(r.Id)); @@ -1268,14 +1268,14 @@ namespace ASC.Files.Core.Data var q1 = FilesDbContext.Files .Where(r => r.ModifiedOn > fromTime) .GroupBy(r => r.TenantId) - .Where(r => r.Count() > 0) + .Where(r => r.Any()) .Select(r => r.Key) .ToList(); var q2 = FilesDbContext.Security .Where(r => r.TimeStamp > fromTime) .GroupBy(r => r.TenantId) - .Where(r => r.Count() > 0) + .Where(r => r.Any()) .Select(r => r.Key) .ToList(); diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs index a736f5ad77..ea62a3f9a9 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs @@ -1219,14 +1219,14 @@ namespace ASC.Files.Core.Data var q1 = FilesDbContext.Files .Where(r => r.ModifiedOn > fromTime) .GroupBy(r => r.TenantId) - .Where(r => r.Count() > 0) + .Where(r => r.Any()) .Select(r => r.Key) .ToList(); var q2 = FilesDbContext.Security .Where(r => r.TimeStamp > fromTime) .GroupBy(r => r.TenantId) - .Where(r => r.Count() > 0) + .Where(r => r.Any()) .Select(r => r.Key) .ToList(); diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/SecurityDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/SecurityDao.cs index 0f2e9d25b5..d54f60f935 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/SecurityDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/SecurityDao.cs @@ -217,7 +217,7 @@ namespace ASC.Files.Core.Data var q = GetQuery(r => folders.Contains(r.EntryId) && r.EntryType == FileEntryType.Folder); - if (files.Any()) + if (files.Count > 0) { q = q.Union(GetQuery(r => files.Contains(r.EntryId) && r.EntryType == FileEntryType.File)); } diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs index 33668e45ff..8766c941a1 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs @@ -441,8 +441,8 @@ namespace ASC.Files.Core.Data FilesDbContext.TagLink.RemoveRange(toDelete); FilesDbContext.SaveChanges(); - var count = Query(FilesDbContext.TagLink).Count(r => r.TagId == id); - if (count == 0) + var any = Query(FilesDbContext.TagLink).Any(r => r.TagId == id); + if (!any) { var tagToDelete = Query(FilesDbContext.Tag).Where(r => r.Id == id); FilesDbContext.Tag.RemoveRange(tagToDelete); @@ -479,7 +479,7 @@ namespace ASC.Files.Core.Data entryTypes.Add((int)entryType); } - if (entryIds.Any()) + if (entryIds.Count > 0) { var sqlQuery = Query(FilesDbContext.Tag) .Join(FilesDbContext.TagLink, r => r.Id, l => l.TagId, (tag, link) => new TagLinkData { Tag = tag, Link = link }) @@ -751,7 +751,7 @@ namespace ASC.Files.Core.Data .Concat(folderIds.ConvertAll(r => $"onedrive-{r}")) .ToList(); - if (thirdpartyFolderIds.Any()) + if (thirdpartyFolderIds.Count > 0) { result.AddRange(FromQuery(newTagsForSBoxQuery(FilesDbContext, tenantId, subject, thirdpartyFolderIds))); } diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index cfd0c2a3d7..fa4915d6a2 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -306,7 +306,7 @@ namespace ASC.Web.Files.Services.WCFService var breadCrumbs = EntryManager.GetBreadCrumbs(parentId, folderDao); - var prevVisible = breadCrumbs.ElementAtOrDefault(breadCrumbs.Count() - 2); + var prevVisible = breadCrumbs.ElementAtOrDefault(breadCrumbs.Count - 2); if (prevVisible != null) { if (prevVisible is Folder<string> f1) parent.FolderID = (T)Convert.ChangeType(f1.ID, typeof(T)); @@ -985,7 +985,7 @@ namespace ASC.Web.Files.Services.WCFService } var usersDrop = FileTracker.GetEditingBy(file.ID).Where(uid => uid != AuthContext.CurrentAccount.ID).Select(u => u.ToString()).ToArray(); - if (usersDrop.Any()) + if (usersDrop.Length > 0) { var fileStable = file.Forcesave == ForcesaveType.None ? file : fileDao.GetFileStable(file.ID, file.Version); var docKey = DocumentServiceHelper.GetDocKey(fileStable); @@ -1164,7 +1164,7 @@ namespace ASC.Web.Files.Services.WCFService result = new List<FileEntry>(EntryManager.SortEntries<T>(result, new OrderBy(SortedByType.DateAndTime, false))); - if (!result.Any()) + if (result.Count == 0) { MarkAsRead(new List<JsonElement>() { JsonDocument.Parse(JsonSerializer.Serialize(folderId)).RootElement }, new List<JsonElement>() { }); //TODO } @@ -1180,7 +1180,7 @@ namespace ASC.Web.Files.Services.WCFService public List<FileOperationResult> MarkAsRead(List<JsonElement> foldersId, List<JsonElement> filesId) { - if (!foldersId.Any() && !filesId.Any()) return GetTasksStatuses(); + if (foldersId.Count == 0 && filesId.Count == 0) return GetTasksStatuses(); return FileOperationsManager.MarkAsRead(AuthContext.CurrentAccount.ID, TenantManager.GetCurrentTenant(), foldersId, filesId); } @@ -1385,7 +1385,7 @@ namespace ASC.Web.Files.Services.WCFService public List<FileOperationResult> BulkDownload(Dictionary<JsonElement, string> folders, Dictionary<JsonElement, string> files) { - ErrorIf(!folders.Any() && !files.Any(), FilesCommonResource.ErrorMassage_BadRequest); + ErrorIf(folders.Count == 0 && files.Count == 0, FilesCommonResource.ErrorMassage_BadRequest); return FileOperationsManager.Download(AuthContext.CurrentAccount.ID, TenantManager.GetCurrentTenant(), folders, files, GetHttpHeaders()); } @@ -1452,7 +1452,7 @@ namespace ASC.Web.Files.Services.WCFService var folders = folderDao.GetFolders(foldersId); var foldersProject = folders.Where(folder => folder.FolderType == FolderType.BUNCH).ToList(); - if (foldersProject.Any()) + if (foldersProject.Count > 0) { var toSubfolders = destFolderDao.GetFolders(toFolder.ID); @@ -1487,7 +1487,7 @@ namespace ASC.Web.Files.Services.WCFService public List<FileOperationResult> MoveOrCopyItems(List<JsonElement> foldersId, List<JsonElement> filesId, JsonElement destFolderId, FileConflictResolveType resolve, bool ic, bool deleteAfter = false) { List<FileOperationResult> result; - if (foldersId.Any() || filesId.Any()) + if (foldersId.Count > 0 || filesId.Count > 0) { result = FileOperationsManager.MoveOrCopy(AuthContext.CurrentAccount.ID, TenantManager.GetCurrentTenant(), foldersId, filesId, destFolderId, ic, resolve, !deleteAfter, GetHttpHeaders()); } diff --git a/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs b/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs index 8657ba9f83..bf8820cade 100644 --- a/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs +++ b/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs @@ -171,7 +171,7 @@ namespace ASC.Web.Files.Core.Search } } - if (tasks.Any()) + if (tasks.Count > 0) { Task.WaitAll(tasks.ToArray()); } diff --git a/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs b/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs index 2b0b51931a..0c2d8d54d3 100644 --- a/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs +++ b/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs @@ -155,7 +155,7 @@ namespace ASC.Web.Files.Core.Search } } - if (tasks.Any()) + if (tasks.Count > 0) { Task.WaitAll(tasks.ToArray()); } diff --git a/products/ASC.Files/Core/Core/Security/FileSecurity.cs b/products/ASC.Files/Core/Core/Security/FileSecurity.cs index 4f7d0f4440..2278b55040 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -817,7 +817,7 @@ namespace ASC.Files.Core.Security failedRecords.Add(failedRecord); } - if (failedRecords.Any()) + if (failedRecords.Count > 0) { securityDao.DeleteShareRecords(failedRecords); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs b/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs index 780ee9b286..b04414464c 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs @@ -100,7 +100,7 @@ namespace ASC.Files.Core.Thirdparty if (fromFileFavoriteTag != null) fromFileTags.AddRange(fromFileFavoriteTag); if (fromFileTemplateTag != null) fromFileTags.AddRange(fromFileTemplateTag); - if (fromFileTags.Any()) + if (fromFileTags.Count > 0) { fromFileTags.ForEach(x => x.EntryId = toFile.ID); @@ -179,7 +179,7 @@ namespace ASC.Files.Core.Thirdparty var tagDao = ServiceProvider.GetService<ITagDao<TFrom>>(); var fromFileNewTags = tagDao.GetNewTags(Guid.Empty, fromFolder).ToList(); - if (fromFileNewTags.Any()) + if (fromFileNewTags.Count > 0) { fromFileNewTags.ForEach(x => x.EntryId = toFolderId); diff --git a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs index f420f61908..fe1f4973c0 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs @@ -495,7 +495,7 @@ namespace ASC.Files.Thirdparty .Select(r => r.HashId) .ToList(); - if (!entryIDs.Any()) return new List<Tag>(); + if (entryIDs.Count == 0) return new List<Tag>(); var q = from r in FilesDbContext.Tag from l in FilesDbContext.TagLink.Where(a => a.TenantId == r.TenantId && a.TagId == r.Id).DefaultIfEmpty() diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFileDao.cs index fb81dd414d..7bb179e8b5 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFileDao.cs @@ -188,7 +188,7 @@ namespace ASC.Files.Thirdparty.ProviderDao .GetFiles(selector.ConvertId(parentId), orderBy, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders) .Where(r => r != null).ToList(); - if (!result.Any()) return new List<File<string>>(); + if (result.Count > 0) return new List<File<string>>(); SetSharedProperty(result); diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs index 0e6a04e9da..7794693459 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs @@ -103,7 +103,7 @@ namespace ASC.Files.Thirdparty.ProviderDao var result = folderDao.GetFolders(selector.ConvertId(parentId), orderBy, filterType, subjectGroup, subjectID, searchText, withSubfolders) .Where(r => r != null).ToList(); - if (!result.Any()) return new List<Folder<string>>(); + if (result.Count > 0) return new List<Folder<string>>(); SetSharedProperty(result); @@ -119,7 +119,7 @@ namespace ASC.Files.Thirdparty.ProviderDao var selectorLocal = selector; var matchedIds = folderIds.Where(selectorLocal.IsMatch).ToList(); - if (!matchedIds.Any()) continue; + if (matchedIds.Count > 0) continue; result = result.Concat(matchedIds.GroupBy(selectorLocal.GetIdCode) .SelectMany(matchedId => @@ -261,12 +261,12 @@ filterType, subjectGroup, subjectID, searchText, searchSubfolders, checkShare); public IDictionary<string, string> CanMoveOrCopy(string[] folderIds, string to) { - if (!folderIds.Any()) return new Dictionary<string, string>(); + if (folderIds.Length > 0) return new Dictionary<string, string>(); var selector = GetSelector(to); var matchedIds = folderIds.Where(selector.IsMatch).ToArray(); - if (!matchedIds.Any()) return new Dictionary<string, string>(); + if (matchedIds.Length > 0) return new Dictionary<string, string>(); var folderDao = selector.GetFolderDao(matchedIds.FirstOrDefault()); return folderDao.CanMoveOrCopy(matchedIds, to); diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderSecutiryDao.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderSecutiryDao.cs index 4ba1a889dd..b377ffce77 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderSecutiryDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderSecutiryDao.cs @@ -64,7 +64,7 @@ namespace ASC.Files.Thirdparty.ProviderDao var files = entries.Where(x => x.FileEntryType == FileEntryType.File).ToArray(); var folders = entries.Where(x => x.FileEntryType == FileEntryType.Folder).ToList(); - if (files.Any()) + if (files.Length > 0) { var folderIds = files.Select(x => ((File<string>)x).FolderID).Distinct(); foreach (var folderId in folderIds) @@ -135,7 +135,7 @@ namespace ASC.Files.Thirdparty.ProviderDao private List<FileShareRecord> GetShareForFolders(IReadOnlyCollection<FileEntry<string>> folders) { - if (!folders.Any()) return new List<FileShareRecord>(); + if (folders.Count > 0) return new List<FileShareRecord>(); var result = new List<FileShareRecord>(); @@ -146,7 +146,7 @@ namespace ASC.Files.Thirdparty.ProviderDao if (folderDao == null) continue; var parentFolders = folderDao.GetParentFolders(selector.ConvertId(folder.ID)); - if (parentFolders == null || !parentFolders.Any()) continue; + if (parentFolders == null || parentFolders.Count > 0) continue; parentFolders.Reverse(); var pureShareRecords = GetPureShareRecords(parentFolders); diff --git a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs index 75ba36c129..6a687a9f52 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -535,7 +535,7 @@ namespace ASC.Web.Files var range = context.Request.Headers["Range"].FirstOrDefault().Split(new[] { '=', '-' }); offset = Convert.ToInt64(range[1]); - if (range.Count() > 2 && !string.IsNullOrEmpty(range[2])) + if (range.Length > 2 && !string.IsNullOrEmpty(range[2])) { endOffset = Convert.ToInt64(range[2]); } diff --git a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs index 1ea0b2a1b6..44cabcb9ae 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs @@ -189,7 +189,7 @@ namespace ASC.Web.Files.Services.DocumentService if (builderKey == null) throw new NullReferenceException(); - if (urls != null && !urls.Any()) throw new Exception("Empty response"); + if (urls != null && urls.Count > 0) throw new Exception("Empty response"); if (urls != null && urls.ContainsKey(TmpFileName)) break; diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs index 0d6a4a0993..9d3baf7539 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs @@ -371,7 +371,7 @@ namespace ASC.Web.Files.Services.DocumentService }) .Select(u => u.ToString()).ToArray(); - if (!usersDrop.Any()) return; + if (usersDrop.Length == 0) return; var fileStable = file; if (file.Forcesave != ForcesaveType.None) diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs index f8acf8736e..7ba2b75fa2 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -326,7 +326,7 @@ namespace ASC.Web.Files.Services.DocumentService } } - if (usersDrop.Any()) + if (usersDrop.Count > 0) { if (!DocumentServiceHelper.DropUser(fileData.Key, usersDrop.ToArray(), fileId)) { diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs index 58fdea4e41..62ee115cfa 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs @@ -177,7 +177,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations protected override void Do(IServiceScope scope) { - if (!Files.Any() && !Folders.Any()) return; + if (Files.Count == 0 && Folders.Count == 0) return; entriesPathId = GetEntriesPathId(scope); diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMarkAsReadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMarkAsReadOperation.cs index b69b4e5595..92314b7e83 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMarkAsReadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMarkAsReadOperation.cs @@ -91,11 +91,11 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations var scopeClass = scope.ServiceProvider.GetService<FileMarkAsReadOperationScope>(); var (fileMarker, globalFolder, daoFactory, settingsManager) = scopeClass; var entries = new List<FileEntry<T>>(); - if (Folders.Any()) + if (Folders.Count > 0) { entries.AddRange(FolderDao.GetFolders(Folders)); } - if (Files.Any()) + if (Files.Count > 0) { entries.AddRange(FileDao.GetFiles(Files)); } diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperationsManager.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperationsManager.cs index ea9d56e9eb..a537332643 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperationsManager.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperationsManager.cs @@ -61,7 +61,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations var processlist = Process.GetProcesses(); //TODO: replace with distributed cache - if (processlist.Any()) + if (processlist.Length > 0) { foreach (var o in operations.Where(o => processlist.All(p => p.Id != o.InstanceId))) { diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index 2c879b4f35..688c87a4aa 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -597,7 +597,7 @@ namespace ASC.Web.Files.Utils .Select(providerInfo => GetFakeThirdpartyFolder<T>(providerInfo, parent.ID.ToString())) .Where(r => fileSecurity.CanRead(r)).ToList(); - if (folderList.Any()) + if (folderList.Count > 0) { var securityDao = DaoFactory.GetSecurityDao<string>(); var ids = securityDao.GetPureShareRecords(folderList) diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index 9e150f1e9d..9823b5f056 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -619,7 +619,7 @@ namespace ASC.Web.Files.Utils public bool EnableAsUploaded { - get { return FileUtility.ExtsMustConvert.Any() && !string.IsNullOrEmpty(FilesLinkUtility.DocServiceConverterUrl); } + get { return FileUtility.ExtsMustConvert.Count > 0 && !string.IsNullOrEmpty(FilesLinkUtility.DocServiceConverterUrl); } } public bool MustConvert<T>(File<T> file) @@ -880,7 +880,7 @@ namespace ASC.Web.Files.Utils var tagDao = DaoFactory.GetTagDao<T>(); var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList(); - if (tags.Any()) + if (tags.Count > 0) { tags.ForEach(r => r.EntryId = newFile.ID); tagDao.SaveTags(tags); diff --git a/products/ASC.Files/Core/Utils/FileMarker.cs b/products/ASC.Files/Core/Utils/FileMarker.cs index 9643d3cebf..c73370ba48 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -144,7 +144,7 @@ namespace ASC.Web.Files.Utils if (obj.FileEntry.RootFolderType == FolderType.BUNCH) { - if (!userIDs.Any()) return; + if (userIDs.Count == 0) return; parentFolders.Add(folderDao.GetFolder(GlobalFolder.GetFolderProjects<T>(DaoFactory))); @@ -165,7 +165,7 @@ namespace ASC.Web.Files.Utils { var filesSecurity = FileSecurity; - if (!userIDs.Any()) + if (userIDs.Count == 0) { userIDs = filesSecurity.WhoCanRead(obj.FileEntry).Where(x => x != obj.CurrentAccountId).ToList(); } @@ -286,9 +286,9 @@ namespace ASC.Web.Files.Utils GetNewTags(userID, entries.OfType<FileEntry<string>>().ToList()); } - if (updateTags.Any()) + if (updateTags.Count > 0) tagDao.UpdateNewTags(updateTags); - if (newTags.Any()) + if (newTags.Count > 0) tagDao.SaveTags(newTags); void GetNewTags<T1>(Guid userID, List<FileEntry<T1>> entries) @@ -320,7 +320,7 @@ namespace ASC.Web.Files.Utils taskData.FileEntry = (FileEntry<T>)fileEntry.Clone(); taskData.UserIDs = userIDs; - if (fileEntry.RootFolderType == FolderType.BUNCH && !userIDs.Any()) + if (fileEntry.RootFolderType == FolderType.BUNCH && userIDs.Count == 0) { var folderDao = DaoFactory.GetFolderDao<T>(); var path = folderDao.GetBunchObjectID(fileEntry.RootFolderId); @@ -331,7 +331,7 @@ namespace ASC.Web.Files.Utils var projectTeam = FileSecurity.WhoCanRead(fileEntry) .Where(x => x != AuthContext.CurrentAccount.ID).ToList(); - if (!projectTeam.Any()) return; + if (projectTeam.Count == 0) return; taskData.UserIDs = projectTeam; } @@ -449,9 +449,9 @@ namespace ASC.Web.Files.Utils UpdateRemoveTags(parentFolder); } - if (updateTags.Any()) + if (updateTags.Count > 0) tagDao.UpdateNewTags(updateTags); - if (removeTags.Any()) + if (removeTags.Count > 0) tagDao.RemoveTags(removeTags); void UpdateRemoveTags<TFolder>(Folder<TFolder> folder) @@ -524,7 +524,7 @@ namespace ASC.Web.Files.Utils var providerTagDao = DaoFactory.GetTagDao<string>(); var tags = (tagDao.GetNewTags(AuthContext.CurrentAccount.ID, folder, true) ?? new List<Tag>()).ToList(); - if (!tags.Any()) return new List<FileEntry>(); + if (tags.Count == 0) return new List<FileEntry>(); if (Equals(folder.ID, GlobalFolder.GetFolderMy(this, DaoFactory)) || Equals(folder.ID, GlobalFolder.GetFolderCommon(this, DaoFactory)) || @@ -645,7 +645,7 @@ namespace ASC.Web.Files.Utils var folderDao = DaoFactory.GetFolderDao<T>(); var totalTags = tagDao.GetNewTags(AuthContext.CurrentAccount.ID, parent, false).ToList(); - if (totalTags.Any()) + if (totalTags.Count > 0) { var parentFolderTag = Equals(GlobalFolder.GetFolderShare<T>(DaoFactory), parent.ID) ? tagDao.GetNewTags(AuthContext.CurrentAccount.ID, folderDao.GetFolder(GlobalFolder.GetFolderShare<T>(DaoFactory))).FirstOrDefault() @@ -682,7 +682,7 @@ namespace ASC.Web.Files.Utils parentsList.Reverse(); parentsList.Remove(parent); - if (parentsList.Any()) + if (parentsList.Count > 0) { var rootFolder = parentsList.Last(); T rootFolderId = default; diff --git a/products/ASC.Files/Core/Utils/FileSharing.cs b/products/ASC.Files/Core/Utils/FileSharing.cs index 4b4c118961..ba65129f43 100644 --- a/products/ASC.Files/Core/Utils/FileSharing.cs +++ b/products/ASC.Files/Core/Utils/FileSharing.cs @@ -167,7 +167,7 @@ namespace ASC.Web.Files.Utils DocumentServiceHelper.CheckUsersForDrop((File<T>)entry); } - if (recipients.Any()) + if (recipients.Count > 0) { if (entryType == FileEntryType.File || ((Folder<T>)entry).TotalSubFolders + ((Folder<T>)entry).TotalFiles > 0 @@ -467,7 +467,7 @@ namespace ASC.Web.Files.Utils var duplicate = result.FirstOrDefault(ace => ace.SubjectId == aceForObject.SubjectId); if (duplicate == null) { - if (result.Any()) + if (result.Count > 0) { aceForObject.Owner = false; aceForObject.Share = FileShare.Varies; diff --git a/products/ASC.Files/Core/Utils/FileUploader.cs b/products/ASC.Files/Core/Utils/FileUploader.cs index dc8ed2e5c5..594b2eee1a 100644 --- a/products/ASC.Files/Core/Utils/FileUploader.cs +++ b/products/ASC.Files/Core/Utils/FileUploader.cs @@ -205,7 +205,7 @@ namespace ASC.Web.Files.Utils if (!FileSecurity.CanCreate(folder)) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create); - if (relativePath != null && relativePath.Any()) + if (relativePath != null && relativePath.Count > 0) { var subFolderTitle = Global.ReplaceInvalidCharsAndTruncate(relativePath.FirstOrDefault()); diff --git a/web/ASC.Web.Core/Mobile/MobileAppInstallRegistrator.cs b/web/ASC.Web.Core/Mobile/MobileAppInstallRegistrator.cs index 6de24e1302..ee47b36b5c 100644 --- a/web/ASC.Web.Core/Mobile/MobileAppInstallRegistrator.cs +++ b/web/ASC.Web.Core/Mobile/MobileAppInstallRegistrator.cs @@ -69,7 +69,7 @@ namespace ASC.Web.Core.Mobile q = q.Where(r => r.AppType == (int)appType.Value); } - return q.Count() > 0; + return q.Any(); } } } \ No newline at end of file diff --git a/web/ASC.Web.Core/Notify/StudioNotifyHelper.cs b/web/ASC.Web.Core/Notify/StudioNotifyHelper.cs index 0a438cd3a4..c163ee188e 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyHelper.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyHelper.cs @@ -170,7 +170,7 @@ namespace ASC.Web.Studio.Core.Notify var sended = spamEmailSettings.MailsSended; var mayTake = Math.Max(0, CountMailsToNotActivated - sended); - var tryCount = res.Count(); + var tryCount = res.Count; if (mayTake < tryCount) { res = res.Take(mayTake).ToList(); diff --git a/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs b/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs index 2d03e70a64..09f70166d0 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs @@ -101,7 +101,7 @@ namespace ASC.Web.Studio.Core.Notify (NotifyAction)item.Action, item.ObjectID, item.Recipients?.Select(r => r.IsGroup ? new RecipientsGroup(r.ID, r.Name) : (IRecipient)new DirectRecipient(r.ID, r.Name, r.Addresses.ToArray(), r.CheckActivation)).ToArray(), - item.SenderNames.Any() ? item.SenderNames.ToArray() : null, + item.SenderNames.Count > 0 ? item.SenderNames.ToArray() : null, item.CheckSubsciption, item.Tags.Select(r => new TagValue(r.Tag_, r.Value)).ToArray()); } diff --git a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs index e11e034ee1..5d82611ae7 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -437,7 +437,7 @@ namespace ASC.Web.Studio.Core.Notify new[] { senderName }, new TagValue(Tags.UserName, u.FirstName.HtmlEncode()), new TagValue(Tags.PricingPage, commonLinkUtility.GetFullAbsolutePath("~/tariffs.aspx")), - new TagValue(Tags.ActiveUsers, userManager.GetUsers().Count()), + new TagValue(Tags.ActiveUsers, userManager.GetUsers().Length), new TagValue(Tags.Price, rquota.Price), new TagValue(Tags.PricePeriod, rquota.Year3 ? UserControlsCommonResource.TariffPerYear3 : rquota.Year ? UserControlsCommonResource.TariffPerYear : UserControlsCommonResource.TariffPerMonth), new TagValue(Tags.DueDate, dueDate.ToLongDateString()), @@ -616,7 +616,7 @@ namespace ASC.Web.Studio.Core.Notify #region 4 days after registration to admins ENTERPRISE TRIAL + only 1 user + defaultRebranding - else if (createdDate.AddDays(4) == nowDate && userManager.GetUsers().Count() == 1) + else if (createdDate.AddDays(4) == nowDate && userManager.GetUsers().Length == 1) { action = Actions.EnterpriseAdminInviteTeammatesV10; paymentMessage = false; @@ -839,7 +839,7 @@ namespace ASC.Web.Studio.Core.Notify new[] { senderName }, new TagValue(Tags.UserName, u.FirstName.HtmlEncode()), new TagValue(Tags.PricingPage, commonLinkUtility.GetFullAbsolutePath("~/tariffs.aspx")), - new TagValue(Tags.ActiveUsers, userManager.GetUsers().Count()), + new TagValue(Tags.ActiveUsers, userManager.GetUsers().Length), new TagValue(Tags.Price, rquota.Price), new TagValue(Tags.PricePeriod, rquota.Year3 ? UserControlsCommonResource.TariffPerYear3 : rquota.Year ? UserControlsCommonResource.TariffPerYear : UserControlsCommonResource.TariffPerMonth), new TagValue(Tags.DueDate, dueDate.ToLongDateString()), diff --git a/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs b/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs index 7ee1f26c4d..081862b2c9 100644 --- a/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs @@ -174,7 +174,7 @@ namespace ASC.Web.Studio.Core.Notify foreach (var gr in groupByPrjs) { var grlist = gr.ToList(); - for (var i = 0; i < grlist.Count(); i++) + for (var i = 0; i < grlist.Count; i++) { var ls = grlist[i]; whatsNewUserActivityGroupByPrjs.Add( diff --git a/web/ASC.Web.Core/Tfa/TfaAppUserSettings.cs b/web/ASC.Web.Core/Tfa/TfaAppUserSettings.cs index 1517b28bfc..ffd56d9200 100644 --- a/web/ASC.Web.Core/Tfa/TfaAppUserSettings.cs +++ b/web/ASC.Web.Core/Tfa/TfaAppUserSettings.cs @@ -80,7 +80,7 @@ namespace ASC.Web.Studio.Core.TFA var settings = settingsManager.LoadForUser<TfaAppUserSettings>(userId); var query = settings.CodesSetting.Where(x => x.Code == code).ToList(); - if (query.Any()) + if (query.Count > 0) query.First().IsUsed = true; settingsManager.SaveForUser(settings, userId); diff --git a/web/ASC.Web.Core/WebItemSecurity.cs b/web/ASC.Web.Core/WebItemSecurity.cs index 3331287d35..9c47739209 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -253,7 +253,7 @@ namespace ASC.Web.Core { WebItemId = id, - Enabled = !info.Any() || (!module && info.Any(i => i.Item2)) || (module && info.All(i => i.Item2)), + Enabled = info.Count == 0 || (!module && info.Any(i => i.Item2)) || (module && info.All(i => i.Item2)), Users = info .Select(i => UserManager.GetUsers(i.Item1)) @@ -273,7 +273,7 @@ namespace ASC.Web.Core .GroupBy(a => a.SubjectId) .Select(a => Tuple.Create(a.Key, a.First().Reaction == AceType.Allow)) .ToList(); - if (!result.Any()) + if (result.Count == 0) { result.Add(Tuple.Create(ASC.Core.Users.Constants.GroupEveryone.ID, false)); } From a30b276711a35f32bc2bf1d7c360208c3ff1e28f Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 13:00:16 +0300 Subject: [PATCH 058/167] analizators/U2U1015 --- common/services/ASC.TelegramService/Core/Core.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/common/services/ASC.TelegramService/Core/Core.cs b/common/services/ASC.TelegramService/Core/Core.cs index 18df362629..5e4f66b4ca 100644 --- a/common/services/ASC.TelegramService/Core/Core.cs +++ b/common/services/ASC.TelegramService/Core/Core.cs @@ -120,16 +120,16 @@ namespace ASC.TelegramService.Core for (var i = 0; i < cmdArgs.Length; i++) { var type = cmdArgs[i].ParameterType; - + var arg = args[i]; if (type == typeof(string)) { - parsedParams.Add(args[i]); + parsedParams.Add(arg); continue; } if (!parsers.ContainsKey(type)) throw new Exception(string.Format("No parser found for type '{0}'", type)); - parsedParams.Add(parsers[cmdArgs[i].ParameterType].FromString(args[i])); + parsedParams.Add(parsers[type].FromString(arg)); } return parsedParams.ToArray(); From 20b60958a831be779b86d98c8618a2fd22ed5768 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 13:24:11 +0300 Subject: [PATCH 059/167] analizators/U2U1022 --- .../Caching/CachedTenantService.cs | 5 ++-- .../Context/Impl/SubscriptionManager.cs | 2 +- common/ASC.Core.Common/Core/UserInfo.cs | 2 +- common/ASC.Core.Common/Data/DbUserService.cs | 2 +- .../Notify/Engine/NotifyEngine.cs | 6 ++--- .../Notify/Patterns/PatternFormatter.cs | 2 +- .../Notify/RecipientProviderImpl.cs | 2 +- .../Notify/TopSubscriptionProvider.cs | 6 ++--- common/ASC.Core.Common/Tenants/TenantQuota.cs | 2 +- .../DiscStorage/DiscDataStore.cs | 4 +-- common/ASC.Data.Storage/StorageHandler.cs | 2 +- common/ASC.IPSecurity/IPSecurity.cs | 2 +- common/ASC.MessagingSystem/MessagePolicy.cs | 2 +- .../Sharpbox/SharpBoxProviderInfo.cs | 2 +- .../Core/Helpers/ThirdpartyConfiguration.cs | 2 +- .../Core/Services/FFmpegService/FFmpeg.cs | 2 +- web/ASC.Web.Core/Files/FileUtility.cs | 26 +++++++++---------- .../Notify/StudioWhatsNewNotify.cs | 6 ++--- .../Users/Import/TextFileUserImporter.cs | 2 +- 19 files changed, 40 insertions(+), 39 deletions(-) diff --git a/common/ASC.Core.Common/Caching/CachedTenantService.cs b/common/ASC.Core.Common/Caching/CachedTenantService.cs index 04fc243e34..8981515906 100644 --- a/common/ASC.Core.Common/Caching/CachedTenantService.cs +++ b/common/ASC.Core.Common/Caching/CachedTenantService.cs @@ -294,8 +294,9 @@ namespace ASC.Core.Caching var data = cache.Get<byte[]>(cacheKey); if (data == null) { - data = Service.GetTenantSettings(tenant, key); - cache.Insert(cacheKey, data ?? new byte[0], DateTime.UtcNow + SettingsExpiration); + data = Service.GetTenantSettings(tenant, key); + + cache.Insert(cacheKey, data ?? Array.Empty<byte>(), DateTime.UtcNow + SettingsExpiration); } return data == null ? null : data.Length == 0 ? null : data; } diff --git a/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs b/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs index c2a048e892..5a8d54f609 100644 --- a/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs +++ b/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs @@ -117,7 +117,7 @@ namespace ASC.Core m = methods.FirstOrDefault(); } - return m != null ? m.Methods : new string[0]; + return m != null ? m.Methods : Array.Empty<string>(); } public string[] GetRecipients(string sourceID, string actionID, string objectID) diff --git a/common/ASC.Core.Common/Core/UserInfo.cs b/common/ASC.Core.Common/Core/UserInfo.cs index d13357cdf6..f7dde01308 100644 --- a/common/ASC.Core.Common/Core/UserInfo.cs +++ b/common/ASC.Core.Common/Core/UserInfo.cs @@ -138,7 +138,7 @@ namespace ASC.Core.Users string[] IDirectRecipient.Addresses { - get { return !string.IsNullOrEmpty(Email) ? new[] { Email } : new string[0]; } + get { return !string.IsNullOrEmpty(Email) ? new[] { Email } : Array.Empty<string>(); } } public bool CheckActivation diff --git a/common/ASC.Core.Common/Data/DbUserService.cs b/common/ASC.Core.Common/Data/DbUserService.cs index 8b4bf71903..2416310efa 100644 --- a/common/ASC.Core.Common/Data/DbUserService.cs +++ b/common/ASC.Core.Common/Data/DbUserService.cs @@ -365,7 +365,7 @@ namespace ASC.Core.Data .Select(r => r.Photo) .FirstOrDefault(); - return photo ?? new byte[0]; + return photo ?? Array.Empty<byte>(); } public IEnumerable<UserInfo> GetUsers(int tenant) diff --git a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs index c5074392dc..b8cb130cd8 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -507,7 +507,7 @@ namespace ASC.Notify.Engine var subscriptionProvider = request.GetSubscriptionProvider(serviceScope); var senderNames = new List<string>(); - senderNames.AddRange(subscriptionProvider.GetSubscriptionMethod(request.NotifyAction, request.Recipient) ?? new string[0]); + senderNames.AddRange(subscriptionProvider.GetSubscriptionMethod(request.NotifyAction, request.Recipient) ?? Array.Empty<string>()); senderNames.AddRange(request.Arguments.OfType<AdditionalSenderTag>().Select(tag => (string)tag.Value)); request.SenderNames = senderNames.ToArray(); @@ -554,12 +554,12 @@ namespace ASC.Notify.Engine { throw new NotifyException(string.Format("For pattern \"{0}\" formatter not instanced.", pattern), exc); } - var tags = new string[0]; + var tags = Array.Empty<string>(); try { if (formatter != null) { - tags = formatter.GetTags(pattern) ?? new string[0]; + tags = formatter.GetTags(pattern) ?? Array.Empty<string>(); } } catch (Exception exc) diff --git a/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs b/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs index 7722248520..40a0d196a6 100644 --- a/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs +++ b/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs @@ -98,7 +98,7 @@ namespace ASC.Notify.Patterns protected virtual string[] SearchTags(string text) { - if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(tagSearchPattern)) return new string[0]; + if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(tagSearchPattern)) return Array.Empty<string>(); var maches = RegEx.Matches(text); var findedTags = new List<string>(maches.Count); diff --git a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs index d86468d01e..e57bbbd7ee 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -111,7 +111,7 @@ namespace ASC.Core.Notify if (senderName == ASC.Core.Configuration.Constants.NotifyTelegramSenderSysName) return new[] { user.ID.ToString() }; } } - return new string[0]; + return Array.Empty<string>(); } /// <summary> diff --git a/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs b/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs index 1d8c92f0cb..01351c226d 100644 --- a/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs +++ b/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs @@ -34,7 +34,7 @@ namespace ASC.Notify.Model { public class TopSubscriptionProvider : ISubscriptionProvider { - private readonly string[] defaultSenderMethods = new string[0]; + private readonly string[] defaultSenderMethods = Array.Empty<string>(); private readonly ISubscriptionProvider subscriptionProvider; private readonly IRecipientProvider recipientProvider; @@ -165,12 +165,12 @@ namespace ASC.Notify.Model if (action == null) throw new ArgumentNullException("action"); var objects = new List<string>(); - var direct = subscriptionProvider.GetSubscriptions(action, recipient, checkSubscription) ?? new string[0]; + var direct = subscriptionProvider.GetSubscriptions(action, recipient, checkSubscription) ?? Array.Empty<string>(); MergeObjects(objects, direct); var parents = WalkUp(recipient); foreach (var parent in parents) { - direct = subscriptionProvider.GetSubscriptions(action, parent, checkSubscription) ?? new string[0]; + direct = subscriptionProvider.GetSubscriptions(action, parent, checkSubscription) ?? Array.Empty<string>(); if (recipient is IDirectRecipient) { foreach (var groupsubscr in direct) diff --git a/common/ASC.Core.Common/Tenants/TenantQuota.cs b/common/ASC.Core.Common/Tenants/TenantQuota.cs index 32b0778d96..a6b3a2070b 100644 --- a/common/ASC.Core.Common/Tenants/TenantQuota.cs +++ b/common/ASC.Core.Common/Tenants/TenantQuota.cs @@ -307,7 +307,7 @@ namespace ASC.Core.Tenants internal void SetFeature(string feature, bool set) { var features = (Features == null - ? new string[] { } + ? Array.Empty<string>() : Features.Split(' ', ',', ';')).ToList(); if (set && !features.Contains(feature)) { diff --git a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs index 45f667da44..6bce910864 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -543,7 +543,7 @@ namespace ASC.Data.Storage.DiscStorage entries, x => x.Substring(targetDir.Length)); } - return new string[0]; + return Array.Empty<string>(); } public override string[] ListFilesRelative(string domain, string path, string pattern, bool recursive) @@ -560,7 +560,7 @@ namespace ASC.Data.Storage.DiscStorage entries, x => x.Substring(targetDir.Length)); } - return new string[0]; + return Array.Empty<string>(); } public override bool IsFile(string domain, string path) diff --git a/common/ASC.Data.Storage/StorageHandler.cs b/common/ASC.Data.Storage/StorageHandler.cs index 6a26f7c3e8..280e6597f4 100644 --- a/common/ASC.Data.Storage/StorageHandler.cs +++ b/common/ASC.Data.Storage/StorageHandler.cs @@ -102,7 +102,7 @@ namespace ASC.Data.Storage.DiscStorage return Task.CompletedTask; } - var headers = header.Length > 0 ? header.Split('&').Select(HttpUtility.UrlDecode) : new string[] { }; + var headers = header.Length > 0 ? header.Split('&').Select(HttpUtility.UrlDecode) : Array.Empty<string>(); if (storage.IsSupportInternalUri) { diff --git a/common/ASC.IPSecurity/IPSecurity.cs b/common/ASC.IPSecurity/IPSecurity.cs index a4e7de46f6..aedd723466 100644 --- a/common/ASC.IPSecurity/IPSecurity.cs +++ b/common/ASC.IPSecurity/IPSecurity.cs @@ -101,7 +101,7 @@ namespace ASC.IPSecurity } var ips = string.IsNullOrWhiteSpace(requestIps) - ? new string[] { } + ? Array.Empty<string>() : requestIps.Split(new[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries); if (ips.Any(requestIp => restrictions.Any(restriction => MatchIPs(GetIpWithoutPort(requestIp), restriction.Ip)))) diff --git a/common/ASC.MessagingSystem/MessagePolicy.cs b/common/ASC.MessagingSystem/MessagePolicy.cs index 5ea1803eeb..8637aa30aa 100644 --- a/common/ASC.MessagingSystem/MessagePolicy.cs +++ b/common/ASC.MessagingSystem/MessagePolicy.cs @@ -43,7 +43,7 @@ namespace ASC.MessagingSystem { secretIps = configuration["messaging.secret-ips"] == null - ? new string[] { } + ? Array.Empty<string>() : configuration["messaging.secret-ips"].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxProviderInfo.cs index b8f1a4b192..6234ca6a48 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxProviderInfo.cs @@ -141,7 +141,7 @@ namespace ASC.Files.Thirdparty.Sharpbox internal CloudStorage CreateStorage(AuthData _authData, nSupportedCloudConfigurations _providerKey) { - var prms = new object[] { }; + var prms = Array.Empty<object>(); if (!string.IsNullOrEmpty(_authData.Url)) { var uri = _authData.Url; diff --git a/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs b/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs index 201f663950..741ed1b3d0 100644 --- a/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs +++ b/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs @@ -47,7 +47,7 @@ namespace ASC.Web.Files.Helpers { get { - return thirdPartyProviders ??= (Configuration.GetSection("files:thirdparty:enable").Get<string[]>() ?? new string[] { }).ToList(); + return thirdPartyProviders ??= (Configuration.GetSection("files:thirdparty:enable").Get<string[]>() ?? Array.Empty<string>()).ToList(); } } public ThirdpartyConfigurationData(IConfiguration configuration) diff --git a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs index 14686197a3..a5672a9ee8 100644 --- a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs +++ b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs @@ -64,7 +64,7 @@ namespace ASC.Web.Files.Services.FFmpegService FFmpegPath = configuration["files:ffmpeg:value"]; FFmpegArgs = configuration["files:ffmpeg:args"] ?? "-i - -preset ultrafast -movflags frag_keyframe+empty_moov -f {0} -"; - ConvertableMedia = (configuration.GetSection("files:ffmpeg:exts").Get<string[]>() ?? new string[] { }).ToList(); + ConvertableMedia = (configuration.GetSection("files:ffmpeg:exts").Get<string[]>() ?? Array.Empty<string>()).ToList(); if (string.IsNullOrEmpty(FFmpegPath)) { diff --git a/web/ASC.Web.Core/Files/FileUtility.cs b/web/ASC.Web.Core/Files/FileUtility.cs index 06a680c24e..39f569d493 100644 --- a/web/ASC.Web.Core/Files/FileUtility.cs +++ b/web/ASC.Web.Core/Files/FileUtility.cs @@ -49,20 +49,20 @@ namespace ASC.Web.Core.Files } private List<string> extsIndexing; - public List<string> ExtsIndexing { get => extsIndexing ??= (Configuration.GetSection("files:index").Get<string[]>() ?? new string[] { }).ToList(); } + public List<string> ExtsIndexing { get => extsIndexing ??= (Configuration.GetSection("files:index").Get<string[]>() ?? Array.Empty<string>()).ToList(); } private List<string> extsImagePreviewed; - public List<string> ExtsImagePreviewed { get => extsImagePreviewed ??= (Configuration.GetSection("files:viewed-images").Get<string[]>() ?? new string[] { }).ToList(); } + public List<string> ExtsImagePreviewed { get => extsImagePreviewed ??= (Configuration.GetSection("files:viewed-images").Get<string[]>() ?? Array.Empty<string>()).ToList(); } private List<string> extsMediaPreviewed; - public List<string> ExtsMediaPreviewed { get => extsMediaPreviewed ??= (Configuration.GetSection("files:viewed-media").Get<string[]>() ?? new string[] { }).ToList(); } + public List<string> ExtsMediaPreviewed { get => extsMediaPreviewed ??= (Configuration.GetSection("files:viewed-media").Get<string[]>() ?? Array.Empty<string>()).ToList(); } private List<string> extsWebPreviewed; public List<string> ExtsWebPreviewed { get { - return extsWebPreviewed ??= (Configuration.GetSection("files:docservice:viewed-docs").Get<string[]>() ?? new string[] { }).ToList(); + return extsWebPreviewed ??= (Configuration.GetSection("files:docservice:viewed-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } } @@ -71,19 +71,19 @@ namespace ASC.Web.Core.Files { get { - return extsWebEdited ??= (Configuration.GetSection("files:docservice:edited-docs").Get<string[]>() ?? new string[] { }).ToList(); + return extsWebEdited ??= (Configuration.GetSection("files:docservice:edited-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } } private List<string> extsWebEncrypt; - public List<string> ExtsWebEncrypt { get => extsWebEncrypt ??= (Configuration.GetSection("files:docservice:encrypted-docs").Get<string[]>() ?? new string[] { }).ToList(); } + public List<string> ExtsWebEncrypt { get => extsWebEncrypt ??= (Configuration.GetSection("files:docservice:encrypted-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } private List<string> extsWebReviewed; public List<string> ExtsWebReviewed { get { - return extsWebReviewed ??= (Configuration.GetSection("files:docservice:reviewed-docs").Get<string[]>() ?? new string[] { }).ToList(); + return extsWebReviewed ??= (Configuration.GetSection("files:docservice:reviewed-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } } @@ -92,7 +92,7 @@ namespace ASC.Web.Core.Files { get { - return extsWebCustomFilterEditing ??= (Configuration.GetSection("files:docservice:customfilter-docs").Get<string[]>() ?? new string[] { }).ToList(); + return extsWebCustomFilterEditing ??= (Configuration.GetSection("files:docservice:customfilter-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } } @@ -101,7 +101,7 @@ namespace ASC.Web.Core.Files { get { - return extsWebRestrictedEditing ??= (Configuration.GetSection("files:docservice:formfilling-docs").Get<string[]>() ?? new string[] { }).ToList(); + return extsWebRestrictedEditing ??= (Configuration.GetSection("files:docservice:formfilling-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } } @@ -110,7 +110,7 @@ namespace ASC.Web.Core.Files { get { - return extsWebCommented ??= (Configuration.GetSection("files:docservice:commented-docs").Get<string[]>() ?? new string[] { }).ToList(); + return extsWebCommented ??= (Configuration.GetSection("files:docservice:commented-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } } @@ -119,7 +119,7 @@ namespace ASC.Web.Core.Files { get { - return extsWebTemplate ??= (Configuration.GetSection("files:docservice:template-docs").Get<string[]>() ?? new string[] { }).ToList(); + return extsWebTemplate ??= (Configuration.GetSection("files:docservice:template-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } } @@ -128,14 +128,14 @@ namespace ASC.Web.Core.Files { get { - return extsMustConvert ??= (Configuration.GetSection("files:docservice:convert-docs").Get<string[]>() ?? new string[] { }).ToList(); + return extsMustConvert ??= (Configuration.GetSection("files:docservice:convert-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } } private List<string> extsCoAuthoring; public List<string> ExtsCoAuthoring { - get => extsCoAuthoring ??= (Configuration.GetSection("files:docservice:coauthor-docs").Get<string[]>() ?? new string[] { }).ToList(); + get => extsCoAuthoring ??= (Configuration.GetSection("files:docservice:coauthor-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } public Dictionary<FileType, string> InternalExtension diff --git a/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs b/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs index 081862b2c9..bee1e9770d 100644 --- a/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs @@ -142,7 +142,7 @@ namespace ASC.Web.Studio.Core.Notify UserAbsoluteURL = f.Author != null && f.Author.UserInfo != null ? commonLinkUtility.GetFullAbsolutePath(f.Author.UserInfo.GetUserProfilePageURL(commonLinkUtility)) : string.Empty, Title = HtmlUtil.GetText(f.Title, 512), URL = commonLinkUtility.GetFullAbsolutePath(f.ItemUrl), - BreadCrumbs = new string[0], + BreadCrumbs = Array.Empty<string>(), Action = GetWhatsNewActionText(f) }).ToList()); @@ -165,7 +165,7 @@ namespace ASC.Web.Studio.Core.Notify UserAbsoluteURL = prawbc.Author != null && prawbc.Author.UserInfo != null ? commonLinkUtility.GetFullAbsolutePath(prawbc.Author.UserInfo.GetUserProfilePageURL(commonLinkUtility)) : string.Empty, Title = HtmlUtil.GetText(prawbc.Title, 512), URL = commonLinkUtility.GetFullAbsolutePath(prawbc.ItemUrl), - BreadCrumbs = new string[0], + BreadCrumbs = Array.Empty<string>(), Action = GetWhatsNewActionText(prawbc) }); } @@ -185,7 +185,7 @@ namespace ASC.Web.Studio.Core.Notify UserAbsoluteURL = ls.Author != null && ls.Author.UserInfo != null ? commonLinkUtility.GetFullAbsolutePath(ls.Author.UserInfo.GetUserProfilePageURL(commonLinkUtility)) : string.Empty, Title = HtmlUtil.GetText(ls.Title, 512), URL = commonLinkUtility.GetFullAbsolutePath(ls.ItemUrl), - BreadCrumbs = i == 0 ? new string[1] { gr.Key } : new string[0], + BreadCrumbs = i == 0 ? new string[1] { gr.Key } : Array.Empty<string>(), Action = GetWhatsNewActionText(ls) }); } diff --git a/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs b/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs index 9e6634862a..1f46253b11 100644 --- a/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs +++ b/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs @@ -115,7 +115,7 @@ namespace ASC.Web.Core.Users.Import var value = ConvertFromString(dataFields[j], propinfo.PropertyType); if (value != null) { - propinfo.SetValue(exportedUser, value, new object[] { }); + propinfo.SetValue(exportedUser, value, Array.Empty<object>()); } } } From 85f1660b394957f40c48b88822a0187cf57fedb4 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 13:46:21 +0300 Subject: [PATCH 060/167] analizators/U2U1203 --- common/ASC.Core.Common/Context/Impl/AuthorizationManager.cs | 2 +- common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs | 2 +- products/ASC.Files/Core/Core/FileStorageService.cs | 2 +- web/ASC.Web.Core/QuotaSync.cs | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/common/ASC.Core.Common/Context/Impl/AuthorizationManager.cs b/common/ASC.Core.Common/Context/Impl/AuthorizationManager.cs index 5f0e9609f5..87ef0515ba 100644 --- a/common/ASC.Core.Common/Context/Impl/AuthorizationManager.cs +++ b/common/ASC.Core.Common/Context/Impl/AuthorizationManager.cs @@ -100,7 +100,7 @@ namespace ASC.Core public void RemoveAllAces(ISecurityObjectId id) { - foreach (var r in GetAces(Guid.Empty, Guid.Empty, id).ToArray()) + foreach (var r in GetAces(Guid.Empty, Guid.Empty, id)) { RemoveAce(r); } diff --git a/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs index 5cc0841441..2888a72d7b 100644 --- a/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs @@ -89,7 +89,7 @@ namespace ASC.Data.Backup.Tasks foreach (var module in storageModules) { var storage = StorageFactory.GetStorage(ConfigPath, TenantId.ToString(), module); - var domains = StorageFactoryConfig.GetDomainList(ConfigPath, module).ToList(); + var domains = StorageFactoryConfig.GetDomainList(ConfigPath, module); foreach (var domain in domains) { ActionInvoker.Try(state => storage.DeleteFiles((string)state, "\\", "*.*", true), domain, 5, diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index fa4915d6a2..88f8bb0308 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -1602,7 +1602,7 @@ namespace ASC.Web.Files.Services.WCFService if (providerDao != null) { var providersInfo = providerDao.GetProvidersInfo(userFrom.ID); - var commonProvidersInfo = providersInfo.Where(provider => provider.RootFolderType == FolderType.COMMON).ToList(); + var commonProvidersInfo = providersInfo.Where(provider => provider.RootFolderType == FolderType.COMMON); //move common thirdparty storage userFrom foreach (var commonProviderInfo in commonProvidersInfo) diff --git a/web/ASC.Web.Core/QuotaSync.cs b/web/ASC.Web.Core/QuotaSync.cs index bfe2b7a48f..de0cce7a79 100644 --- a/web/ASC.Web.Core/QuotaSync.cs +++ b/web/ASC.Web.Core/QuotaSync.cs @@ -56,14 +56,14 @@ namespace ASC.Web.Studio.Core.Quota var (tenantManager, storageFactoryConfig, storageFactory) = scopeClass; tenantManager.SetCurrentTenant(TenantId); - var storageModules = storageFactoryConfig.GetModuleList(string.Empty).ToList(); + var storageModules = storageFactoryConfig.GetModuleList(string.Empty); foreach (var module in storageModules) { var storage = storageFactory.GetStorage(TenantId.ToString(), module); storage.ResetQuota(""); - var domains = storageFactoryConfig.GetDomainList(string.Empty, module).ToList(); + var domains = storageFactoryConfig.GetDomainList(string.Empty, module); foreach (var domain in domains) { storage.ResetQuota(domain); From e046f6f8dfc451aa937ad0ab2d3752631f67e01f Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 16:14:51 +0300 Subject: [PATCH 061/167] analizators/s1006 --- common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs | 2 +- .../LoginProviders/GosUslugiLoginProvider.cs | 2 +- .../ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs | 2 +- .../ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs | 2 +- common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs | 2 +- .../ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs | 2 +- products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs | 2 +- products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs | 4 ++-- products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs | 2 +- products/ASC.Files/Core/Core/Thirdparty/Box/BoxFolderDao.cs | 2 +- .../ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs | 2 +- .../Core/Core/Thirdparty/Dropbox/DropboxFolderDao.cs | 2 +- .../Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs | 2 +- .../Core/Core/Thirdparty/GoogleDrive/GoogleDriveFolderDao.cs | 2 +- .../Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs | 2 +- .../Core/Core/Thirdparty/OneDrive/OneDriveFolderDao.cs | 2 +- .../Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs | 2 +- .../Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs | 2 +- .../Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs | 2 +- .../Core/Core/Thirdparty/Sharpbox/SharpBoxFolderDao.cs | 2 +- 20 files changed, 21 insertions(+), 21 deletions(-) diff --git a/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs index 89cefcaaed..95f3c2e24c 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs @@ -113,7 +113,7 @@ namespace ASC.FederatedLogin.LoginProviders InstanceCrypto = instanceCrypto; } - public virtual LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs = null) + public virtual LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs) { try { diff --git a/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs index a9e477a798..505932ddda 100644 --- a/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs @@ -114,7 +114,7 @@ namespace ASC.FederatedLogin.LoginProviders } - public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs = null) + public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs) { try { diff --git a/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs index 6f73b71e5d..70678a26bc 100644 --- a/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs @@ -97,7 +97,7 @@ namespace ASC.FederatedLogin.LoginProviders { } - public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs = null) + public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs) { try { diff --git a/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs index fc6e24bd44..40edb0b444 100644 --- a/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs @@ -53,7 +53,7 @@ namespace ASC.FederatedLogin.LoginProviders ConsumerFactory = consumerFactory; } - public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs = null) + public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs) { var response = Openid.GetResponse(); if (response == null) diff --git a/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs index 1a4f6b9516..15450112c6 100644 --- a/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs @@ -102,7 +102,7 @@ namespace ASC.FederatedLogin.LoginProviders } - public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs = null) + public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs) { try { diff --git a/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs index 96a96c4840..d803e38c5b 100644 --- a/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs @@ -94,7 +94,7 @@ namespace ASC.FederatedLogin.LoginProviders { } - public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs = null) + public override LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params, IDictionary<string, string> additionalStateArgs) { try { diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index 89ad6fb695..3e760291e4 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -1128,7 +1128,7 @@ namespace ASC.Files.Core.Data return FromQueryWithShared(q).Select(ToFile).ToList(); } - public IEnumerable<File<int>> Search(string searchText, bool bunch) + public IEnumerable<File<int>> Search(string searchText, bool bunch = false) { if (FactoryIndexer.TrySelectIds(s => s.MatchAll(searchText), out var ids)) { diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs index ea62a3f9a9..f3808eff58 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs @@ -758,7 +758,7 @@ namespace ASC.Files.Core.Data return true; } - public long GetMaxUploadSize(int folderId, bool chunkedUpload) + public long GetMaxUploadSize(int folderId, bool chunkedUpload = false) { var tmp = long.MaxValue; @@ -801,7 +801,7 @@ namespace ASC.Files.Core.Data } - public IEnumerable<Folder<int>> SearchFolders(string text, bool bunch) + public IEnumerable<Folder<int>> SearchFolders(string text, bool bunch = false) { return Search(text).Where(f => bunch ? f.RootFolderType == FolderType.BUNCH diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs index dfd6f18af0..627b4ed816 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs @@ -99,7 +99,7 @@ namespace ASC.Files.Thirdparty.Box .FirstOrDefault(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase)) as BoxFile); } - public File<string> GetFileStable(string fileId, int fileVersion) + public File<string> GetFileStable(string fileId, int fileVersion = -1) { return ToFile(GetBoxFile(fileId)); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFolderDao.cs index 121493da3a..99ee0e9a96 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFolderDao.cs @@ -433,7 +433,7 @@ namespace ASC.Files.Thirdparty.Box return false; } - public long GetMaxUploadSize(string folderId, bool chunkedUpload) + public long GetMaxUploadSize(string folderId, bool chunkedUpload = false) { var storageMaxUploadSize = ProviderInfo.Storage.GetMaxUploadSize(); diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs index 5a7c652ed6..540e57aaa9 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs @@ -103,7 +103,7 @@ namespace ASC.Files.Thirdparty.Dropbox : ToFile(metadata.AsFile); } - public File<string> GetFileStable(string fileId, int fileVersion) + public File<string> GetFileStable(string fileId, int fileVersion = -1) { return ToFile(GetDropboxFile(fileId)); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFolderDao.cs index 41953eb923..d7751a8ad9 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFolderDao.cs @@ -430,7 +430,7 @@ namespace ASC.Files.Thirdparty.Dropbox return false; } - public long GetMaxUploadSize(string folderId, bool chunkedUpload) + public long GetMaxUploadSize(string folderId, bool chunkedUpload = false) { var storageMaxUploadSize = ProviderInfo.Storage.MaxChunkedUploadFileSize; diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs index 715c0c8856..ffaf005bb4 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs @@ -100,7 +100,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive .FirstOrDefault(file => file.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase))); } - public File<string> GetFileStable(string fileId, int fileVersion) + public File<string> GetFileStable(string fileId, int fileVersion = -1) { return ToFile(GetDriveEntry(fileId)); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFolderDao.cs index eed396f844..28b26accd3 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFolderDao.cs @@ -422,7 +422,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive return false; } - public long GetMaxUploadSize(string folderId, bool chunkedUpload) + public long GetMaxUploadSize(string folderId, bool chunkedUpload = false) { var storageMaxUploadSize = ProviderInfo.Storage.GetMaxUploadSize(); diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs index f60c9a7c97..60f36ce492 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs @@ -99,7 +99,7 @@ namespace ASC.Files.Thirdparty.OneDrive .FirstOrDefault(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase) && item.File != null)); } - public File<string> GetFileStable(string fileId, int fileVersion) + public File<string> GetFileStable(string fileId, int fileVersion = -1) { return ToFile(GetOneDriveItem(fileId)); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFolderDao.cs index bfd01a065d..7a0bfda7f4 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFolderDao.cs @@ -433,7 +433,7 @@ namespace ASC.Files.Thirdparty.OneDrive return true; } - public long GetMaxUploadSize(string folderId, bool chunkedUpload) + public long GetMaxUploadSize(string folderId, bool chunkedUpload = false) { var storageMaxUploadSize = ProviderInfo.Storage.MaxChunkedUploadFileSize; diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs index 7794693459..4a3b3a38b7 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs @@ -338,7 +338,7 @@ filterType, subjectGroup, subjectID, searchText, searchSubfolders, checkShare); return folderDao.CanCalculateSubitems(entryId); } - public long GetMaxUploadSize(string folderId, bool chunkedUpload) + public long GetMaxUploadSize(string folderId, bool chunkedUpload = false) { var selector = GetSelector(folderId); var folderDao = selector.GetFolderDao(folderId); diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs index 86c68236cc..86c11d4058 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs @@ -92,7 +92,7 @@ namespace ASC.Files.Thirdparty.SharePoint return ProviderInfo.ToFile(ProviderInfo.GetFolderFiles(parentId).FirstOrDefault(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase))); } - public File<string> GetFileStable(string fileId, int fileVersion) + public File<string> GetFileStable(string fileId, int fileVersion = -1) { return ProviderInfo.ToFile(ProviderInfo.GetFileById(fileId)); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs index 887438298a..9b0e6829bc 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs @@ -100,7 +100,7 @@ namespace ASC.Files.Thirdparty.Sharpbox return ToFile(GetFolderFiles(parentId).FirstOrDefault(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase))); } - public File<string> GetFileStable(string fileId, int fileVersion) + public File<string> GetFileStable(string fileId, int fileVersion = -1) { return ToFile(GetFileById(fileId)); } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFolderDao.cs index 5f99a29e49..96877abb9b 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFolderDao.cs @@ -448,7 +448,7 @@ namespace ASC.Files.Thirdparty.Sharpbox return false; } - public long GetMaxUploadSize(string folderId, bool chunkedUpload) + public long GetMaxUploadSize(string folderId, bool chunkedUpload = false) { var storageMaxUploadSize = chunkedUpload From 547b78b72f6cf45febaac3bad55185e667283cad Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 16:36:03 +0300 Subject: [PATCH 062/167] analizators/2178 --- common/services/ASC.AuditTrail/AuditEventsRepository.cs | 2 +- common/services/ASC.AuditTrail/LoginEventsRepository.cs | 2 +- .../ASC.Files/Core/Configuration/FilesSpaceUsageStatManager.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/common/services/ASC.AuditTrail/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/AuditEventsRepository.cs index 00727d4ced..ca9c60a4fe 100644 --- a/common/services/ASC.AuditTrail/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/AuditEventsRepository.cs @@ -86,7 +86,7 @@ namespace ASC.AuditTrail if (fromDate.HasValue && to.HasValue) { - query = query.Where(q => q.AuditEvent.Date >= fromDate & q.AuditEvent.Date <= to); + query = query.Where(q => q.AuditEvent.Date >= fromDate && q.AuditEvent.Date <= to); } if (limit.HasValue) diff --git a/common/services/ASC.AuditTrail/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/LoginEventsRepository.cs index 78b913da76..a364647bfb 100644 --- a/common/services/ASC.AuditTrail/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/LoginEventsRepository.cs @@ -101,7 +101,7 @@ namespace ASC.AuditTrail.Data if (from.HasValue && to.HasValue) { - query = query.Where(l => l.Date >= from & l.Date <= to); + query = query.Where(l => l.Date >= from && l.Date <= to); } return query.Count(); diff --git a/products/ASC.Files/Core/Configuration/FilesSpaceUsageStatManager.cs b/products/ASC.Files/Core/Configuration/FilesSpaceUsageStatManager.cs index 8a357e95d5..ef33da3615 100644 --- a/products/ASC.Files/Core/Configuration/FilesSpaceUsageStatManager.cs +++ b/products/ASC.Files/Core/Configuration/FilesSpaceUsageStatManager.cs @@ -83,7 +83,7 @@ namespace ASC.Web.Files .Join(FilesDbContext.BunchObjects, a => a.tree.ParentId.ToString(), b => b.LeftNode, (fileTree, bunch) => new { fileTree.file, fileTree.tree, bunch }) .Where(r => r.file.TenantId == r.bunch.TenantId) .Where(r => r.file.TenantId == TenantManager.GetCurrentTenant().TenantId) - .Where(r => r.bunch.RightNode.StartsWith("files/my/") | r.bunch.RightNode.StartsWith("files/trash/")) + .Where(r => r.bunch.RightNode.StartsWith("files/my/") || r.bunch.RightNode.StartsWith("files/trash/")) .GroupBy(r => r.file.CreateBy) .Select(r => new { CreateBy = r.Key, Size = r.Sum(a => a.file.ContentLength) }); From 25050cb5fd6f973a26b75d8c0ac9a88554a8b827 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 17:16:15 +0300 Subject: [PATCH 063/167] analizators/s2223 --- common/ASC.Core.Common/Configuration/SmtpSettings.cs | 2 +- common/ASC.Core.Common/Core/DBResourceManager.cs | 2 +- common/ASC.Core.Common/EF/Context/BaseDbContext.cs | 2 +- common/ASC.Core.Common/Tenants/TenantAuditSettings.cs | 2 +- common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs | 2 +- web/ASC.Web.Core/Files/DocumentService.cs | 4 ++-- web/ASC.Web.Core/Notify/Tags.cs | 4 ++-- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/common/ASC.Core.Common/Configuration/SmtpSettings.cs b/common/ASC.Core.Common/Configuration/SmtpSettings.cs index 70161bcf61..7348d06ef1 100644 --- a/common/ASC.Core.Common/Configuration/SmtpSettings.cs +++ b/common/ASC.Core.Common/Configuration/SmtpSettings.cs @@ -54,7 +54,7 @@ namespace ASC.Core.Configuration public bool IsDefaultSettings { get; internal set; } - public static SmtpSettings Empty = new SmtpSettings(); + public static readonly SmtpSettings Empty = new SmtpSettings(); private SmtpSettings() { diff --git a/common/ASC.Core.Common/Core/DBResourceManager.cs b/common/ASC.Core.Common/Core/DBResourceManager.cs index 2149e74eae..9a17b26acb 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -50,7 +50,7 @@ namespace TMResourceData { public class DBResourceManager : ResourceManager { - public static bool WhiteLableEnabled = false; + public static readonly bool WhiteLableEnabled = false; private readonly ConcurrentDictionary<string, ResourceSet> resourceSets = new ConcurrentDictionary<string, ResourceSet>(); public DBResourceManager(string filename, Assembly assembly) diff --git a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs index e61b9536c2..86509365cb 100644 --- a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs @@ -29,7 +29,7 @@ namespace ASC.Core.Common.EF public ConnectionStringSettings ConnectionStringSettings { get; set; } protected internal Provider Provider { get; set; } - public static ServerVersion ServerVersion = ServerVersion.Parse("8.0.25"); + public static readonly ServerVersion ServerVersion = ServerVersion.Parse("8.0.25"); protected virtual Dictionary<Provider, Func<BaseDbContext>> ProviderContext { get { return null; } diff --git a/common/ASC.Core.Common/Tenants/TenantAuditSettings.cs b/common/ASC.Core.Common/Tenants/TenantAuditSettings.cs index c23f69ef33..0a9036e2e7 100644 --- a/common/ASC.Core.Common/Tenants/TenantAuditSettings.cs +++ b/common/ASC.Core.Common/Tenants/TenantAuditSettings.cs @@ -39,7 +39,7 @@ namespace ASC.Core.Tenants public int AuditTrailLifeTime { get; set; } - public static Guid Guid = new Guid("{8337D0FB-AD67-4552-8297-802312E7F503}"); + public static readonly Guid Guid = new Guid("{8337D0FB-AD67-4552-8297-802312E7F503}"); public Guid ID { get { return Guid; } diff --git a/common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs b/common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs index 97953837bc..85ddffe722 100644 --- a/common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs +++ b/common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs @@ -41,7 +41,7 @@ namespace ASC.FederatedLogin.LoginProviders [Scope] public class ProviderManager { - public static List<string> AuthProviders = new List<string> + public static readonly List<string> AuthProviders = new List<string> { ProviderConstants.Google, ProviderConstants.Facebook, diff --git a/web/ASC.Web.Core/Files/DocumentService.cs b/web/ASC.Web.Core/Files/DocumentService.cs index 73f1bbee1b..422e979f5d 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -55,13 +55,13 @@ namespace ASC.Web.Core.Files /// <summary> /// Timeout to request conversion /// </summary> - public static int Timeout = 120000; + public static readonly int Timeout = 120000; //public static int Timeout = Convert.ToInt32(ConfigurationManagerExtension.AppSettings["files.docservice.timeout"] ?? "120000"); /// <summary> /// Number of tries request conversion /// </summary> - public static int MaxTry = 3; + public static readonly int MaxTry = 3; /// <summary> /// Translation key to a supported form. diff --git a/web/ASC.Web.Core/Notify/Tags.cs b/web/ASC.Web.Core/Notify/Tags.cs index f408fdee39..058685ac9d 100644 --- a/web/ASC.Web.Core/Notify/Tags.cs +++ b/web/ASC.Web.Core/Notify/Tags.cs @@ -112,9 +112,9 @@ namespace ASC.Web.Studio.Core.Notify public const string Culture = "Culture"; - public static string Footer = "Footer"; + public static readonly string Footer = "Footer"; - public static string MasterTemplate = "MasterTemplate"; + public static readonly string MasterTemplate = "MasterTemplate"; public const string HelpLink = "__HelpLink"; From cbab9c45247188de9a3733519d93d0dd026aef9d Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 17:16:34 +0300 Subject: [PATCH 064/167] analizators/s2178 --- common/services/ASC.AuditTrail/AuditEventsRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/services/ASC.AuditTrail/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/AuditEventsRepository.cs index ca9c60a4fe..80dcd7049a 100644 --- a/common/services/ASC.AuditTrail/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/AuditEventsRepository.cs @@ -105,7 +105,7 @@ namespace ASC.AuditTrail if (from.HasValue && to.HasValue) { - query = query.Where(a => a.Date >= from & a.Date <= to); + query = query.Where(a => a.Date >= from && a.Date <= to); } return query.Count(); From f2e33fa4aa6597bce4967e0b20e6279f855df379 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 18:16:59 +0300 Subject: [PATCH 065/167] analizators/s2365 --- .../ASC.Core.Common/Configuration/Consumer.cs | 6 ++--- .../ASC.ElasticSearch/Core/SearchSettings.cs | 6 ++--- web/ASC.Web.Core/Files/FileUtility.cs | 26 +++++++++---------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/common/ASC.Core.Common/Configuration/Consumer.cs b/common/ASC.Core.Common/Configuration/Consumer.cs index 59e5aaa4a5..a86dfba373 100644 --- a/common/ASC.Core.Common/Configuration/Consumer.cs +++ b/common/ASC.Core.Common/Configuration/Consumer.cs @@ -50,13 +50,13 @@ namespace ASC.Core.Common.Configuration protected readonly Dictionary<string, string> Props; public IEnumerable<string> ManagedKeys { - get { return Props.Select(r => r.Key).ToList(); } + get { return Props.Select(r => r.Key); } } protected readonly Dictionary<string, string> Additional; public virtual IEnumerable<string> AdditionalKeys { - get { return Additional.Select(r => r.Key).ToList(); } + get { return Additional.Select(r => r.Key); } } public ICollection<string> Keys { get { return AllProps.Keys; } } @@ -336,7 +336,7 @@ namespace ASC.Core.Common.Configuration public override IEnumerable<string> AdditionalKeys { - get { return base.AdditionalKeys.Where(r => r != HandlerTypeKey && r != "cdn").ToList(); } + get { return base.AdditionalKeys.Where(r => r != HandlerTypeKey && r != "cdn"); } } protected override string GetSettingsKey(string name) diff --git a/common/services/ASC.ElasticSearch/Core/SearchSettings.cs b/common/services/ASC.ElasticSearch/Core/SearchSettings.cs index 667258ec70..9d9a111d1a 100644 --- a/common/services/ASC.ElasticSearch/Core/SearchSettings.cs +++ b/common/services/ASC.ElasticSearch/Core/SearchSettings.cs @@ -120,12 +120,12 @@ namespace ASC.ElasticSearch.Core }).ToList(); } - private List<IFactoryIndexer> allItems; - internal List<IFactoryIndexer> AllItems + private IEnumerable<IFactoryIndexer> allItems; + internal IEnumerable<IFactoryIndexer> AllItems { get { - return allItems ??= ServiceProvider.GetService<IEnumerable<IFactoryIndexer>>().ToList(); + return allItems ??= ServiceProvider.GetService<IEnumerable<IFactoryIndexer>>(); } } diff --git a/web/ASC.Web.Core/Files/FileUtility.cs b/web/ASC.Web.Core/Files/FileUtility.cs index 39f569d493..aaba482e55 100644 --- a/web/ASC.Web.Core/Files/FileUtility.cs +++ b/web/ASC.Web.Core/Files/FileUtility.cs @@ -49,20 +49,20 @@ namespace ASC.Web.Core.Files } private List<string> extsIndexing; - public List<string> ExtsIndexing { get => extsIndexing ??= (Configuration.GetSection("files:index").Get<string[]>() ?? Array.Empty<string>()).ToList(); } + public List<string> ExtsIndexing { get => extsIndexing ??= Configuration.GetSection("files:index").Get<List<string>>() ?? new List<string>(); } private List<string> extsImagePreviewed; - public List<string> ExtsImagePreviewed { get => extsImagePreviewed ??= (Configuration.GetSection("files:viewed-images").Get<string[]>() ?? Array.Empty<string>()).ToList(); } + public List<string> ExtsImagePreviewed { get => extsImagePreviewed ??= Configuration.GetSection("files:viewed-images").Get<List<string>>() ?? new List<string>(); } private List<string> extsMediaPreviewed; - public List<string> ExtsMediaPreviewed { get => extsMediaPreviewed ??= (Configuration.GetSection("files:viewed-media").Get<string[]>() ?? Array.Empty<string>()).ToList(); } + public List<string> ExtsMediaPreviewed { get => extsMediaPreviewed ??= Configuration.GetSection("files:viewed-media").Get<List<string>>() ?? new List<string>(); } private List<string> extsWebPreviewed; public List<string> ExtsWebPreviewed { get { - return extsWebPreviewed ??= (Configuration.GetSection("files:docservice:viewed-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); + return extsWebPreviewed ??= Configuration.GetSection("files:docservice:viewed-docs").Get<List<string>>() ?? new List<string>(); } } @@ -71,19 +71,19 @@ namespace ASC.Web.Core.Files { get { - return extsWebEdited ??= (Configuration.GetSection("files:docservice:edited-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); + return extsWebEdited ??= Configuration.GetSection("files:docservice:edited-docs").Get<List<string>>() ?? new List<string>(); } } private List<string> extsWebEncrypt; - public List<string> ExtsWebEncrypt { get => extsWebEncrypt ??= (Configuration.GetSection("files:docservice:encrypted-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); } + public List<string> ExtsWebEncrypt { get => extsWebEncrypt ??= Configuration.GetSection("files:docservice:encrypted-docs").Get<List<string>>() ?? new List<string>(); } private List<string> extsWebReviewed; public List<string> ExtsWebReviewed { get { - return extsWebReviewed ??= (Configuration.GetSection("files:docservice:reviewed-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); + return extsWebReviewed ??= Configuration.GetSection("files:docservice:reviewed-docs").Get<List<string>>() ?? new List<string>(); } } @@ -92,7 +92,7 @@ namespace ASC.Web.Core.Files { get { - return extsWebCustomFilterEditing ??= (Configuration.GetSection("files:docservice:customfilter-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); + return extsWebCustomFilterEditing ??= Configuration.GetSection("files:docservice:customfilter-docs").Get<List<string>>() ?? new List<string>(); } } @@ -101,7 +101,7 @@ namespace ASC.Web.Core.Files { get { - return extsWebRestrictedEditing ??= (Configuration.GetSection("files:docservice:formfilling-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); + return extsWebRestrictedEditing ??= Configuration.GetSection("files:docservice:formfilling-docs").Get<List<string>>() ?? new List<string>(); } } @@ -110,7 +110,7 @@ namespace ASC.Web.Core.Files { get { - return extsWebCommented ??= (Configuration.GetSection("files:docservice:commented-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); + return extsWebCommented ??= Configuration.GetSection("files:docservice:commented-docs").Get<List<string>>() ?? new List<string>(); } } @@ -119,7 +119,7 @@ namespace ASC.Web.Core.Files { get { - return extsWebTemplate ??= (Configuration.GetSection("files:docservice:template-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); + return extsWebTemplate ??= Configuration.GetSection("files:docservice:template-docs").Get<List<string>>() ?? new List<string>(); } } @@ -128,14 +128,14 @@ namespace ASC.Web.Core.Files { get { - return extsMustConvert ??= (Configuration.GetSection("files:docservice:convert-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); + return extsMustConvert ??= Configuration.GetSection("files:docservice:convert-docs").Get<List<string>>() ?? new List<string>(); } } private List<string> extsCoAuthoring; public List<string> ExtsCoAuthoring { - get => extsCoAuthoring ??= (Configuration.GetSection("files:docservice:coauthor-docs").Get<string[]>() ?? Array.Empty<string>()).ToList(); + get => extsCoAuthoring ??= Configuration.GetSection("files:docservice:coauthor-docs").Get<List<string>>() ?? new List<string>(); } public Dictionary<FileType, string> InternalExtension From f0dbdded9f057408fa8a2d011a5f55e469f3fdb0 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 18:29:04 +0300 Subject: [PATCH 066/167] analizators/s2692 --- common/ASC.IPSecurity/IPSecurity.cs | 2 +- common/services/ASC.ElasticSearch/Core/Selector.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/common/ASC.IPSecurity/IPSecurity.cs b/common/ASC.IPSecurity/IPSecurity.cs index aedd723466..dda9889f25 100644 --- a/common/ASC.IPSecurity/IPSecurity.cs +++ b/common/ASC.IPSecurity/IPSecurity.cs @@ -122,7 +122,7 @@ namespace ASC.IPSecurity private static bool MatchIPs(string requestIp, string restrictionIp) { var dividerIdx = restrictionIp.IndexOf('-'); - if (restrictionIp.IndexOf('-') > 0) + if (dividerIdx > -1) { var lower = IPAddress.Parse(restrictionIp.Substring(0, dividerIdx).Trim()); var upper = IPAddress.Parse(restrictionIp.Substring(dividerIdx + 1).Trim()); diff --git a/common/services/ASC.ElasticSearch/Core/Selector.cs b/common/services/ASC.ElasticSearch/Core/Selector.cs index 3e3a835c27..8b0c33fdbc 100644 --- a/common/services/ASC.ElasticSearch/Core/Selector.cs +++ b/common/services/ASC.ElasticSearch/Core/Selector.cs @@ -341,7 +341,7 @@ namespace ASC.ElasticSearch if (string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(fieldSelector.Name) && - fieldSelector.Name.IndexOf('.') > 0) + fieldSelector.Name.IndexOf('.') > -1) { var splitted = fieldSelector.Name.Split(':')[1]; path = splitted.Split('.')[0]; From edd627ee2358d2b0e550793f47f447cc0c6dc33c Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 19 Jan 2022 18:33:27 +0300 Subject: [PATCH 067/167] analizators/s2696 --- common/ASC.MessagingSystem/DbSender/MessagesRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs index 1cc81b31db..ec60b04bd0 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -50,7 +50,7 @@ namespace ASC.MessagingSystem.DbSender [Singletone(Additional = typeof(MessagesRepositoryExtension))] public class MessagesRepository: IDisposable { - private static DateTime lastSave = DateTime.UtcNow; + private DateTime lastSave = DateTime.UtcNow; private readonly TimeSpan CacheTime; private readonly IDictionary<string, EventMessage> Cache; private Parser Parser { get; set; } From 66643c074be9c4be5c03930b6ec4c791327709d3 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Thu, 20 Jan 2022 10:57:54 +0300 Subject: [PATCH 068/167] analizators/s2365 --- products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs | 2 +- products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs b/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs index 741ed1b3d0..cccc309a71 100644 --- a/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs +++ b/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs @@ -47,7 +47,7 @@ namespace ASC.Web.Files.Helpers { get { - return thirdPartyProviders ??= (Configuration.GetSection("files:thirdparty:enable").Get<string[]>() ?? Array.Empty<string>()).ToList(); + return thirdPartyProviders ??= Configuration.GetSection("files:thirdparty:enable").Get<List<string>>() ?? new List<string>(); } } public ThirdpartyConfigurationData(IConfiguration configuration) diff --git a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs index a5672a9ee8..a69b74d318 100644 --- a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs +++ b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs @@ -24,7 +24,7 @@ namespace ASC.Web.Files.Services.FFmpegService get { if (string.IsNullOrEmpty(FFmpegPath)) return new List<string>(); - return ConvertableMedia.ToList(); + return ConvertableMedia; } } From 3f28dfe78a4f8777403a065616287afc8af4360b Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Thu, 20 Jan 2022 11:36:42 +0300 Subject: [PATCH 069/167] analizators/s3237 --- .../Services/DocumentService/Configuration.cs | 26 ------------------- .../DocumentService/DocumentServiceTracker.cs | 1 - .../WCFService/Wrappers/MentionWrapper.cs | 3 --- web/ASC.Web.Core/Sms/SmsProvider.cs | 8 ------ 4 files changed, 38 deletions(-) diff --git a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs index f123c249b2..e8b7e6c87b 100644 --- a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs +++ b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs @@ -99,7 +99,6 @@ namespace ASC.Web.Files.Services.DocumentService public string DocumentType { - set { } get { DocType.TryGetValue(GetFileType, out var documentType); @@ -119,7 +118,6 @@ namespace ASC.Web.Files.Services.DocumentService internal FileType GetFileType { - set { } get { if (_fileTypeCache == FileType.Unknown) @@ -160,7 +158,6 @@ namespace ASC.Web.Files.Services.DocumentService public string FileType { - set { } get { return Info.GetFile().ConvertedExtension.Trim('.'); } } @@ -218,7 +215,6 @@ namespace ASC.Web.Files.Services.DocumentService public bool? Favorite { - set { } get { if (!SecurityContext.IsAuthenticated || UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor(UserManager)) return null; @@ -229,7 +225,6 @@ namespace ASC.Web.Files.Services.DocumentService public string Folder { - set { } get { if (Type == EditorType.Embedded || Type == EditorType.External) return null; @@ -247,19 +242,16 @@ namespace ASC.Web.Files.Services.DocumentService public string Owner { - set { } get { return File.CreateByString; } } public string Uploaded { - set { } get { return File.CreateOnString; } } public List<AceShortWrapper> SharingSettings { - set { } get { if (Type == EditorType.Embedded @@ -420,7 +412,6 @@ namespace ASC.Web.Files.Services.DocumentService public string CreateUrl { - set { } get { if (_configuration.Document.Info.Type != EditorType.Desktop) return null; @@ -448,13 +439,11 @@ namespace ASC.Web.Files.Services.DocumentService public string Lang { - set { } get { return _userInfo.GetCulture().Name; } } public string Mode { - set { } get { return ModeWrite ? "edit" : "view"; } } @@ -559,19 +548,16 @@ namespace ASC.Web.Files.Services.DocumentService public string EmbedUrl { - set { } get { return BaseCommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=embedded" + ShareLinkParam); } } public string SaveUrl { - set { } get { return BaseCommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath + "?" + FilesLinkUtility.Action + "=download" + ShareLinkParam); } } public string ShareUrl { - set { } get { return BaseCommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=view" + ShareLinkParam); } } @@ -602,7 +588,6 @@ namespace ASC.Web.Files.Services.DocumentService { public string[] PluginsData { - set { } get { var plugins = new List<string>(); @@ -693,7 +678,6 @@ namespace ASC.Web.Files.Services.DocumentService public bool About { - set { } get { return !CoreBaseSettings.Standalone && !CoreBaseSettings.CustomMode; } } @@ -701,7 +685,6 @@ namespace ASC.Web.Files.Services.DocumentService public FeedbackConfig Feedback { - set { } get { if (CoreBaseSettings.Standalone) return null; @@ -719,7 +702,6 @@ namespace ASC.Web.Files.Services.DocumentService public bool? Forcesave { - set { } get { return FileUtility.CanForcesave @@ -731,7 +713,6 @@ namespace ASC.Web.Files.Services.DocumentService public GobackConfig Goback { - set { } get { if (_configuration.EditorType == EditorType.Embedded || _configuration.EditorType == EditorType.External) return null; @@ -780,7 +761,6 @@ namespace ASC.Web.Files.Services.DocumentService public bool MentionShare { - set { } get { return AuthContext.IsAuthenticated @@ -791,7 +771,6 @@ namespace ASC.Web.Files.Services.DocumentService public string ReviewDisplay { - set { } get { return _configuration.EditorConfig.ModeWrite ? null : "markup"; } } @@ -828,13 +807,11 @@ namespace ASC.Web.Files.Services.DocumentService public string Logo { - set { } get { return BaseCommonLinkUtility.GetFullAbsolutePath(TenantLogoHelper.GetLogo(WhiteLabelLogoTypeEnum.Dark, !_configuration.EditorConfig.Customization.IsRetina)); } } public string Name { - set { } get { return (SettingsManager.Load<TenantWhiteLabelSettings>().GetLogoText(SettingsManager) ?? "") @@ -880,7 +857,6 @@ namespace ASC.Web.Files.Services.DocumentService public string Image { - set { } get { return @@ -892,7 +868,6 @@ namespace ASC.Web.Files.Services.DocumentService public string ImageEmbedded { - set { } get { return @@ -904,7 +879,6 @@ namespace ASC.Web.Files.Services.DocumentService public string Url { - set { } get { return CompanyWhiteLabelSettings.Instance(SettingsManager).Site; } } diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs index 7ba2b75fa2..c5e26c8de9 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -138,7 +138,6 @@ namespace ASC.Web.Files.Services.DocumentService { public int Error { - set { } get { return string.IsNullOrEmpty(Message) diff --git a/products/ASC.Files/Core/Services/WCFService/Wrappers/MentionWrapper.cs b/products/ASC.Files/Core/Services/WCFService/Wrappers/MentionWrapper.cs index eac97faedc..0eb5785345 100644 --- a/products/ASC.Files/Core/Services/WCFService/Wrappers/MentionWrapper.cs +++ b/products/ASC.Files/Core/Services/WCFService/Wrappers/MentionWrapper.cs @@ -37,13 +37,11 @@ namespace ASC.Web.Files.Services.WCFService public string Email { get { return User.Email; } - set { } } public string Id { get { return User.ID.ToString(); } - set { } } public bool HasAccess { get; set; } @@ -51,7 +49,6 @@ namespace ASC.Web.Files.Services.WCFService public string Name { get { return User.DisplayUserName(false, DisplayUserSettingsHelper); } - set { } } private DisplayUserSettingsHelper DisplayUserSettingsHelper { get; } diff --git a/web/ASC.Web.Core/Sms/SmsProvider.cs b/web/ASC.Web.Core/Sms/SmsProvider.cs index b7e1edc0a1..fd27730e5c 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -219,13 +219,11 @@ namespace ASC.Web.Core.Sms protected override string SendMessageUrlFormat { get { return "https://smsc.ru/sys/send.php?login={key}&psw={secret}&phones={phone}&mes={text}&fmt=3&sender={sender}&charset=utf-8"; } - set { } } protected override string GetBalanceUrlFormat { get { return "https://smsc.ru/sys/balance.php?login={key}&psw={secret}"; } - set { } } protected override string Key @@ -319,19 +317,16 @@ namespace ASC.Web.Core.Sms protected override string SendMessageUrlFormat { get { return "https://platform.clickatell.com/messages/http/send?apiKey={secret}&to={phone}&content={text}&from={sender}"; } - set { } } protected override string Secret { get { return this["clickatellapiKey"]; } - set { } } protected override string Sender { get { return this["clickatellSender"]; } - set { } } public override bool Enable() @@ -387,19 +382,16 @@ namespace ASC.Web.Core.Sms protected override string Key { get { return this["twilioAccountSid"]; } - set { } } protected override string Secret { get { return this["twilioAuthToken"]; } - set { } } protected override string Sender { get { return this["twiliosender"]; } - set { } } public AuthContext AuthContext { get; } From eb9a33c6604e88eb427bf492c6f460ed604b3d45 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Thu, 20 Jan 2022 11:36:56 +0300 Subject: [PATCH 070/167] analizators/s3218 --- web/ASC.Web.Core/Calendars/RecurrenceRule.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs index 064556c90d..1ddd5c5a8f 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -160,7 +160,7 @@ namespace ASC.Web.Core.Calendars return dates; } - public static WeekDay Parse(string iCalStrValue) + public static WeekDay ParseWeekDay(string iCalStrValue) { var d = new WeekDay(); @@ -215,7 +215,7 @@ namespace ASC.Web.Core.Calendars this.Until = DateTime.MinValue; this.Count = -1; this.Interval = 1; - this.WKST = WeekDay.Parse("mo"); + this.WKST = WeekDay.ParseWeekDay("mo"); this.ExDates = new List<ExDate>(); } @@ -931,7 +931,7 @@ namespace ASC.Web.Core.Calendars break; case "byday": - rr.ByDay = val.Split(',').Select(v => RecurrenceRule.WeekDay.Parse(v)).ToArray(); + rr.ByDay = val.Split(',').Select(v => RecurrenceRule.WeekDay.ParseWeekDay(v)).ToArray(); break; case "bymonthday": @@ -955,7 +955,7 @@ namespace ASC.Web.Core.Calendars break; case "wkst": - rr.WKST = RecurrenceRule.WeekDay.Parse(val); + rr.WKST = RecurrenceRule.WeekDay.ParseWeekDay(val); break; case "exdates": @@ -1020,11 +1020,11 @@ namespace ASC.Web.Core.Calendars { var days = new List<WeekDay>(); foreach (var d in ByDay) - days.Add(WeekDay.Parse(d.ToString())); + days.Add(WeekDay.ParseWeekDay(d.ToString())); o.ByDay = days.ToArray(); } - o.WKST = WeekDay.Parse(this.WKST.ToString()); + o.WKST = WeekDay.ParseWeekDay(this.WKST.ToString()); return o; } From 50a7bd68568599832f917594cc09b75a2976bdc6 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Thu, 20 Jan 2022 11:40:21 +0300 Subject: [PATCH 071/167] analizators/s3265 --- products/ASC.People/Server/Controllers/PeopleController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index 35965fd265..f70a34b548 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -2099,7 +2099,7 @@ namespace ASC.Employee.Core.Controllers if (!files.StartsWith("http://") && !files.StartsWith("https://")) { - files = new Uri(ApiContext.HttpContextAccessor.HttpContext.Request.GetDisplayUrl()).GetLeftPart(UriPartial.Scheme | UriPartial.Authority) + "/" + files.TrimStart('/'); + files = new Uri(ApiContext.HttpContextAccessor.HttpContext.Request.GetDisplayUrl()).GetLeftPart(UriPartial.Authority) + "/" + files.TrimStart('/'); } var request = new HttpRequestMessage(); request.RequestUri = new Uri(files); From f956ad22faf1b432a38b44abd4d4e555a23bd249 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Thu, 20 Jan 2022 11:53:38 +0300 Subject: [PATCH 072/167] analizators/s2223 --- .../LoginProviders/GoogleLoginProvider.cs | 6 +++--- products/ASC.Files/Core/Core/Compress/CompressToArchive.cs | 4 ++-- .../Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs | 4 ++-- products/ASC.Files/Core/Helpers/DocuSignHelper.cs | 4 ++-- .../Core/Services/DocumentService/Configuration.cs | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs index d52237aaaf..4447af379a 100644 --- a/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs @@ -58,9 +58,9 @@ namespace ASC.FederatedLogin.LoginProviders public const string GoogleUrlProfile = "https://people.googleapis.com/v1/people/me"; public static readonly string[] GoogleDriveExt = new[] { ".gdoc", ".gsheet", ".gslides", ".gdraw" }; - public static string GoogleDriveMimeTypeFolder = "application/vnd.google-apps.folder"; - public static string FilesFields = "id,name,mimeType,parents,createdTime,modifiedTime,owners/displayName,lastModifyingUser/displayName,capabilities/canEdit,size"; - public static string ProfileFields = "emailAddresses,genders,names"; + public static readonly string GoogleDriveMimeTypeFolder = "application/vnd.google-apps.folder"; + public static readonly string FilesFields = "id,name,mimeType,parents,createdTime,modifiedTime,owners/displayName,lastModifyingUser/displayName,capabilities/canEdit,size"; + public static readonly string ProfileFields = "emailAddresses,genders,names"; public override string AccessTokenUrl { get { return "https://www.googleapis.com/oauth2/v4/token"; } } public override string CodeUrl { get { return "https://accounts.google.com/o/oauth2/v2/auth"; } } diff --git a/products/ASC.Files/Core/Core/Compress/CompressToArchive.cs b/products/ASC.Files/Core/Core/Compress/CompressToArchive.cs index 9627dc9c8f..942f4b3015 100644 --- a/products/ASC.Files/Core/Core/Compress/CompressToArchive.cs +++ b/products/ASC.Files/Core/Core/Compress/CompressToArchive.cs @@ -33,8 +33,8 @@ namespace ASC.Web.Files.Core.Compress { private readonly ICompress compress; - internal static string TarExt = ".tar.gz"; - internal static string ZipExt = ".zip"; + internal static readonly string TarExt = ".tar.gz"; + internal static readonly string ZipExt = ".zip"; private static List<string> Exts = new List<string>(2) { TarExt, ZipExt }; public CompressToArchive(FilesSettingsHelper filesSettings, CompressToTarGz compressToTarGz, CompressToZip compressToZip) diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs index 4ac0611721..fd901dca45 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs @@ -109,8 +109,8 @@ namespace ASC.Files.Thirdparty.OneDrive } - public static string RootPath = "/drive/root:"; - public static string ApiVersion = "v1.0"; + public static readonly string RootPath = "/drive/root:"; + public static readonly string ApiVersion = "v1.0"; public static string MakeOneDrivePath(string parentPath, string name) { diff --git a/products/ASC.Files/Core/Helpers/DocuSignHelper.cs b/products/ASC.Files/Core/Helpers/DocuSignHelper.cs index 13f24d05a9..75e9d3c991 100644 --- a/products/ASC.Files/Core/Helpers/DocuSignHelper.cs +++ b/products/ASC.Files/Core/Helpers/DocuSignHelper.cs @@ -149,9 +149,9 @@ namespace ASC.Web.Files.Helpers ".csv", ".et", ".ett", ".xls", ".xlsm", ".xlsx", ".xlt" }; - public static long MaxFileSize = 25L * 1024L * 1024L; + public static readonly long MaxFileSize = 25L * 1024L * 1024L; - public static int MaxEmailLength = 10000; + public static readonly int MaxEmailLength = 10000; private DocuSignToken DocuSignToken { get; } private FileSecurity FileSecurity { get; } diff --git a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs index e8b7e6c87b..2aa61b5450 100644 --- a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs +++ b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs @@ -67,7 +67,7 @@ namespace ASC.Web.Files.Services.DocumentService public class Configuration<T> { - internal static Dictionary<FileType, string> DocType = new Dictionary<FileType, string> + internal static readonly Dictionary<FileType, string> DocType = new Dictionary<FileType, string> { { FileType.Document, "text" }, { FileType.Spreadsheet, "spreadsheet" }, From 2f4d05a847c71fe40824fac663b911abbf23b546 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Thu, 20 Jan 2022 11:54:19 +0300 Subject: [PATCH 073/167] analizators/s2692 --- .../Services/WCFService/FileOperations/FileDownloadOperation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs index 62ee115cfa..3decb77678 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs @@ -330,7 +330,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations if (!Equals(entryId, default(T))) { - newtitle = 0 < newtitle.IndexOf('.') ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix) : newtitle + suffix; + newtitle = newtitle.IndexOf('.') > -1 ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix) : newtitle + suffix; } else { From 5f78b37e25cdcfc1fd50193e529543d51b97d6ba Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Thu, 20 Jan 2022 12:28:48 +0300 Subject: [PATCH 074/167] analizators/U2U1000 --- .../ASC.Core.Common/Notify/Jabber/JabberServiceClient.cs | 2 +- .../ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs | 2 +- common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs | 2 +- .../RackspaceCloud/RackspaceCloudStorage.cs | 2 +- common/ASC.Data.Storage/StaticUploader.cs | 2 +- products/ASC.Files/Core/Helpers/EasyBibHelper.cs | 2 +- products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs | 2 +- products/ASC.Files/Core/Utils/EntryManager.cs | 4 ++-- products/ASC.Files/Core/Utils/MailMergeTask.cs | 4 ++-- web/ASC.Web.Api/Controllers/SettingsController.cs | 2 +- web/ASC.Web.Core/Notify/TagValues.cs | 8 ++++---- 11 files changed, 16 insertions(+), 16 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Jabber/JabberServiceClient.cs b/common/ASC.Core.Common/Notify/Jabber/JabberServiceClient.cs index 838cc814dd..23f176a39b 100644 --- a/common/ASC.Core.Common/Notify/Jabber/JabberServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Jabber/JabberServiceClient.cs @@ -94,7 +94,7 @@ namespace ASC.Core.Notify.Jabber public int GetNewMessagesCount() { - var result = 0; + const int result = 0; if (IsServiceProbablyNotAvailable()) return result; using (var service = GetService()) diff --git a/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs b/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs index ffb0f0aa40..b7ac18be60 100644 --- a/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs +++ b/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs @@ -52,7 +52,7 @@ namespace ASC.Core.Notify { try { - var result = SendResult.OK; + const SendResult result = SendResult.OK; var m = new NotifyMessage { To = message.Recipient.ID, diff --git a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs index a62f12e517..915c3659c4 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -764,7 +764,7 @@ namespace ASC.Data.Storage.GoogleCloud request.Content = new StreamContent(stream); - long MAX_RETRIES = 100; + const int MAX_RETRIES = 100; int millisecondsTimeout; for (var i = 0; i < MAX_RETRIES; i++) diff --git a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs index 3f024cd260..8c3b0eb24b 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -709,7 +709,7 @@ namespace ASC.Data.Storage.RackspaceCloud public override string UploadChunk(string domain, string path, string filePath, Stream stream, long defaultChunkSize, int chunkNumber, long chunkLength) { - var BufferSize = 4096; + const int BufferSize = 4096; var mode = chunkNumber == 0 ? FileMode.Create : FileMode.Append; diff --git a/common/ASC.Data.Storage/StaticUploader.cs b/common/ASC.Data.Storage/StaticUploader.cs index 39d4cdc39b..f65539a372 100644 --- a/common/ASC.Data.Storage/StaticUploader.cs +++ b/common/ASC.Data.Storage/StaticUploader.cs @@ -255,7 +255,7 @@ namespace ASC.Data.Storage this.relativePath = relativePath; this.mappedPath = mappedPath; - var extensions = ".png|.jpeg|.jpg|.gif|.ico|.swf|.mp3|.ogg|.eot|.svg|.ttf|.woff|.woff2|.css|.less|.js"; + const string extensions = ".png|.jpeg|.jpg|.gif|.ico|.swf|.mp3|.ogg|.eot|.svg|.ttf|.woff|.woff2|.css|.less|.js"; var extensionsArray = extensions.Split('|'); directoryFiles = Directory.GetFiles(mappedPath, "*", SearchOption.AllDirectories) diff --git a/products/ASC.Files/Core/Helpers/EasyBibHelper.cs b/products/ASC.Files/Core/Helpers/EasyBibHelper.cs index 8a2bbd69eb..c722e4d8c9 100644 --- a/products/ASC.Files/Core/Helpers/EasyBibHelper.cs +++ b/products/ASC.Files/Core/Helpers/EasyBibHelper.cs @@ -141,7 +141,7 @@ namespace ASC.Web.Files.Helpers jsonBlogInfo.Add("key", easyBibappkey); var citationData = jsonBlogInfo.ToString(); - var uri = "https://api.citation-api.com/2.0/rest/cite"; + const string uri = "https://api.citation-api.com/2.0/rest/cite"; const string contentType = "application/json"; const string method = "POST"; var body = citationData; diff --git a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs index 6a687a9f52..867ec54e2f 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -1062,7 +1062,7 @@ namespace ASC.Web.Files //var refererURL = context.Request.GetUrlRewriter().AbsoluteUri; //context.Session["refererURL"] = refererURL; - var authUrl = "~/Auth.aspx"; + const string authUrl = "~/Auth.aspx"; context.Response.Redirect(authUrl, true); return Task.CompletedTask; } diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index 688c87a4aa..acddd669a5 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -347,7 +347,7 @@ namespace ASC.Web.Files.Utils //var apiServer = new ASC.Api.ApiServer(); //var apiUrl = string.Format("{0}project/maxlastmodified.json", SetupInfo.WebApiBaseUrl); - string responseBody = null;// apiServer.GetApiResponse(apiUrl, "GET"); + const string responseBody = null;// apiServer.GetApiResponse(apiUrl, "GET"); if (responseBody != null) { var responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(responseBody))); @@ -367,7 +367,7 @@ namespace ASC.Web.Files.Utils if (!(responseData is JArray)) return entries.ToList(); folderIDProjectTitle = new Dictionary<int, KeyValuePair<int, string>>(); - foreach (JObject projectInfo in responseData.Children()) + foreach (JObject projectInfo in responseData.Children().OfType<JObject>()) { var projectID = projectInfo["id"].Value<int>(); var projectTitle = Global.ReplaceInvalidCharsAndTruncate(projectInfo["title"].Value<string>()); diff --git a/products/ASC.Files/Core/Utils/MailMergeTask.cs b/products/ASC.Files/Core/Utils/MailMergeTask.cs index f23c194e37..9c7dbc11b7 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -110,7 +110,7 @@ namespace ASC.Web.Files.Utils HttpUtility.UrlEncode(mailMergeTask.To), HttpUtility.UrlEncode(mailMergeTask.Message)); - string responseCreateString = null; //TODO: Encoding.UTF8.GetString(Convert.FromBase64String(Api.GetApiResponse(apiUrlCreate, "PUT", bodyCreate))); + const string responseCreateString = null; //TODO: Encoding.UTF8.GetString(Convert.FromBase64String(Api.GetApiResponse(apiUrlCreate, "PUT", bodyCreate))); var responseCreate = JObject.Parse(responseCreateString); if (responseCreate["statusCode"].Value<int>() != (int)HttpStatusCode.OK) @@ -185,7 +185,7 @@ namespace ASC.Web.Files.Utils bodySend += bodySendAttach; - string responseSendString = null;//TODO: Encoding.UTF8.GetString(Convert.FromBase64String(Api.GetApiResponse(apiUrlSend, "PUT", bodySend))); + const string responseSendString = null;//TODO: Encoding.UTF8.GetString(Convert.FromBase64String(Api.GetApiResponse(apiUrlSend, "PUT", bodySend))); var responseSend = JObject.Parse(responseSendString); if (responseSend["statusCode"].Value<int>() != (int)HttpStatusCode.OK) diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index f9d837c52f..2d5b62d775 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1942,7 +1942,7 @@ namespace ASC.Api.Settings TenantManager.SaveTenantQuota(quota); - var DEFAULT_TRIAL_PERIOD = 30; + const int DEFAULT_TRIAL_PERIOD = 30; var tariff = new Tariff { diff --git a/web/ASC.Web.Core/Notify/TagValues.cs b/web/ASC.Web.Core/Notify/TagValues.cs index 06b09bb682..a9c2b84ba8 100644 --- a/web/ASC.Web.Core/Notify/TagValues.cs +++ b/web/ASC.Web.Core/Notify/TagValues.cs @@ -53,8 +53,8 @@ namespace ASC.Web.Studio.Core.Notify string action() { var btnText = btnTextFunc != null ? btnTextFunc() ?? string.Empty : string.Empty; - var td = "<td style=\"height: 48px; width: 80px; margin:0; padding:0;\"> </td>"; - var color = "color: #fff; font-family: Helvetica, Arial, Tahoma; font-size: 18px; font-weight: 600; vertical-align: middle; display: block; padding: 12px 0; text-align: center; text-decoration: none; background-color: #66b76d;"; + const string td = "<td style=\"height: 48px; width: 80px; margin:0; padding:0;\"> </td>"; + const string color = "color: #fff; font-family: Helvetica, Arial, Tahoma; font-size: 18px; font-weight: 600; vertical-align: middle; display: block; padding: 12px 0; text-align: center; text-decoration: none; background-color: #66b76d;"; return $@"<table style=""height: 48px; width: 540px; border-collapse: collapse; empty-cells: show; vertical-align: middle; text-align: center; margin: 30px auto; padding: 0;""><tbody><tr cellpadding=""0"" cellspacing=""0"" border=""0"">{td}<td style=""height: 48px; width: 380px; margin:0; padding:0; background-color: #66b76d; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px;""><a style=""{color}"" target=""_blank"" href=""{btnUrl}"">{btnText}</a></td>{td}</tr></tbody></table>"; } @@ -67,8 +67,8 @@ namespace ASC.Web.Studio.Core.Notify string action() { var btnText = btnTextFunc != null ? btnTextFunc() ?? string.Empty : string.Empty; - var td = "<td style=\"height: 48px; width: 80px; margin:0; padding:0;\"> </td>"; - var color = "color: #fff; font-family: Helvetica, Arial, Tahoma; font-size: 18px; font-weight: 600; vertical-align: middle; display: block; padding: 12px 0; text-align: center; text-decoration: none; background-color: #66b76d;"; + const string td = "<td style=\"height: 48px; width: 80px; margin:0; padding:0;\"> </td>"; + const string color = "color: #fff; font-family: Helvetica, Arial, Tahoma; font-size: 18px; font-weight: 600; vertical-align: middle; display: block; padding: 12px 0; text-align: center; text-decoration: none; background-color: #66b76d;"; return $@"<table style=""height: 48px; width: 540px; border-collapse: collapse; empty-cells: show; vertical-align: middle; text-align: center; margin: 30px auto; padding: 0;""><tbody><tr cellpadding=""0"" cellspacing=""0"" border=""0"">{td}<td style=""height: 48px; width: 380px; margin:0; padding:0; background-color: #66b76d; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px;""><a style=""{3}"" target=""_blank"" href=""{btnUrl}"">{btnText}</a></td>{td}</tr></tbody></table>"; } From bf3b0395a5c23d1c118b8581bf2ee10a2800c832 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 11:04:08 +0300 Subject: [PATCH 075/167] analizators/s1116 --- common/ASC.Core.Common/Caching/CachedUserService.cs | 2 +- common/ASC.Core.Common/Data/DbSubscriptionService.cs | 2 +- common/ASC.Core.Common/Notify/Cron/CronExpression.cs | 4 ++-- common/ASC.Data.Storage/StorageFactory.cs | 2 +- common/services/ASC.Webhooks.Service/WebhookSender.cs | 2 +- web/ASC.Web.Api/Controllers/AuthenticationController.cs | 2 +- web/ASC.Web.Core/Calendars/RecurrenceRule.cs | 2 +- web/ASC.Web.Core/Users/UserPhotoManager.cs | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/common/ASC.Core.Common/Caching/CachedUserService.cs b/common/ASC.Core.Common/Caching/CachedUserService.cs index 6be6a6de18..4dda7d2354 100644 --- a/common/ASC.Core.Common/Caching/CachedUserService.cs +++ b/common/ASC.Core.Common/Caching/CachedUserService.cs @@ -318,7 +318,7 @@ namespace ASC.Core.Caching group = Service.GetGroup(tenant, id); if (group != null) Cache.Insert(key, group, CacheExpiration); - }; + } return group; } diff --git a/common/ASC.Core.Common/Data/DbSubscriptionService.cs b/common/ASC.Core.Common/Data/DbSubscriptionService.cs index c97f98f197..60fdd42fbf 100644 --- a/common/ASC.Core.Common/Data/DbSubscriptionService.cs +++ b/common/ASC.Core.Common/Data/DbSubscriptionService.cs @@ -136,7 +136,7 @@ namespace ASC.Core.Data } else { - q = q = q.Where(r => r.Object == string.Empty);; + q = q = q.Where(r => r.Object == string.Empty); } return q.Any(); diff --git a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs index 17ac36d4c7..0e36f0d3ff 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -806,7 +806,7 @@ namespace ASC.Notify.Cron { for (; i < s.Length && (s[i] == ' ' || s[i] == '\t'); i++) { - ; + } return i; } @@ -815,7 +815,7 @@ namespace ASC.Notify.Cron { for (; i < s.Length && (s[i] != ' ' || s[i] != '\t'); i++) { - ; + } return i; } diff --git a/common/ASC.Data.Storage/StorageFactory.cs b/common/ASC.Data.Storage/StorageFactory.cs index 908124d002..cfb0a16193 100644 --- a/common/ASC.Data.Storage/StorageFactory.cs +++ b/common/ASC.Data.Storage/StorageFactory.cs @@ -251,7 +251,7 @@ namespace ASC.Data.Storage props = handler.Property.ToDictionary(r => r.Name, r => r.Value); } - ; + return ((IDataStore)ActivatorUtilities.CreateInstance(ServiceProvider, instanceType)) .Configure(tenant, handler, moduleElement, props) .SetQuotaController(moduleElement.Count ? controller : null diff --git a/common/services/ASC.Webhooks.Service/WebhookSender.cs b/common/services/ASC.Webhooks.Service/WebhookSender.cs index 929d49bc8d..0055177d9c 100644 --- a/common/services/ASC.Webhooks.Service/WebhookSender.cs +++ b/common/services/ASC.Webhooks.Service/WebhookSender.cs @@ -111,7 +111,7 @@ namespace ASC.Webhooks.Service { var responseContent = streamReader.ReadToEnd(); responsePayload = JsonSerializer.Serialize(responseContent); - }; + } dbWorker.UpdateWebhookJournal(id, status, responsePayload, responseHeaders, requestHeaders); } diff --git a/web/ASC.Web.Api/Controllers/AuthenticationController.cs b/web/ASC.Web.Api/Controllers/AuthenticationController.cs index b2ea929c69..f0e073e22c 100644 --- a/web/ASC.Web.Api/Controllers/AuthenticationController.cs +++ b/web/ASC.Web.Api/Controllers/AuthenticationController.cs @@ -348,7 +348,7 @@ namespace ASC.Web.Api.Controllers var token = SecurityContext.AuthenticateMe(user.ID); MessageService.Send(sms ? MessageAction.LoginSuccessViaApiSms : MessageAction.LoginSuccessViaApiTfa); - ; + var expires = TenantCookieSettingsHelper.GetExpiresTime(tenant); var result = new AuthenticationTokenData diff --git a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs index 1ddd5c5a8f..e99749ff90 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -513,7 +513,7 @@ namespace ASC.Web.Core.Calendars dateRange.RemoveAll(date => { var weekOfYear = date.GetWeekOfYear(this.WKST.DayOfWeek); - return ((!ByWeekNo.Contains(weekOfYear) && !ByWeekNo.Contains(weekOfYear - (date.GetWeekOfYearCount(this.WKST.DayOfWeek) + 1)))); + return !ByWeekNo.Contains(weekOfYear) && !ByWeekNo.Contains(weekOfYear - (date.GetWeekOfYearCount(this.WKST.DayOfWeek) + 1)); }); } isFirst = false; diff --git a/web/ASC.Web.Core/Users/UserPhotoManager.cs b/web/ASC.Web.Core/Users/UserPhotoManager.cs index 8680bd8e50..6619757da5 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -808,7 +808,7 @@ namespace ASC.Web.Core.Users var store = GetDataStore(); store.DeleteFiles(_tempDomainName, "", fileNameWithoutExt + "*.*", false); } - catch { }; + catch { } } From 728c1b896e4739aa80a9247a08ca1b80b5444528 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 12:19:57 +0300 Subject: [PATCH 076/167] analizators/s1104 --- common/ASC.Api.Core/Core/ApiContext.cs | 4 +-- .../ASC.Core.Common/Core/DBResourceManager.cs | 2 +- .../EF/Context/BaseDbContext.cs | 1 - .../EF/Context/ConfigureDbContext.cs | 6 ++--- .../Notify/Cron/CronExpression.cs | 26 +++++++++---------- .../Notify/Signalr/SignalrServiceClient.cs | 2 +- .../Tenants/TenantExceptions.cs | 4 +-- common/ASC.Core.Common/Users/UserFormatter.cs | 2 +- .../Tasks/Modules/ModuleProvider.cs | 2 +- common/ASC.Data.Reassigns/QueueWorker.cs | 4 +-- .../Core/Core/Entries/EditHistory.cs | 8 +++--- .../ASC.Files/Core/Core/Entries/FileEntry.cs | 2 +- .../SharePoint/SharePointProviderInfo.cs | 3 +-- products/ASC.Files/Core/Helpers/Global.cs | 2 +- .../Services/DocumentService/Configuration.cs | 16 ++++++------ .../DocumentService/DocumentServiceTracker.cs | 4 +-- .../WCFService/Wrappers/MentionWrapper.cs | 2 +- .../ASC.Files/Core/Utils/MailMergeTask.cs | 16 ++++++------ web/ASC.Web.Core/Files/DocumentService.cs | 2 +- .../Subscriptions/SubscriptionType.cs | 4 +-- web/ASC.Web.Core/Users/UserPhotoManager.cs | 24 ++++++++--------- 21 files changed, 66 insertions(+), 70 deletions(-) diff --git a/common/ASC.Api.Core/Core/ApiContext.cs b/common/ASC.Api.Core/Core/ApiContext.cs index 62f61ba1ba..09215626e2 100644 --- a/common/ASC.Api.Core/Core/ApiContext.cs +++ b/common/ASC.Api.Core/Core/ApiContext.cs @@ -41,8 +41,8 @@ namespace ASC.Api.Core { private static int MaxCount = 1000; public IHttpContextAccessor HttpContextAccessor { get; set; } - public Tenant tenant; - public Tenant Tenant { get { return tenant ??= TenantManager.GetCurrentTenant(HttpContextAccessor?.HttpContext); } } + private Tenant _tenant; + public Tenant Tenant { get { return _tenant ??= TenantManager.GetCurrentTenant(HttpContextAccessor?.HttpContext); } } public ApiContext(IHttpContextAccessor httpContextAccessor, SecurityContext securityContext, TenantManager tenantManager) { diff --git a/common/ASC.Core.Common/Core/DBResourceManager.cs b/common/ASC.Core.Common/Core/DBResourceManager.cs index 9a17b26acb..714b9bb9cd 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -283,7 +283,7 @@ namespace TMResourceData { private readonly ILog log; private readonly ConcurrentDictionary<int, string> whiteLabelDictionary; - public string DefaultLogoText; + public string DefaultLogoText { get; } private IConfiguration Configuration { get; } diff --git a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs index 86509365cb..32dacc35bf 100644 --- a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs @@ -17,7 +17,6 @@ namespace ASC.Core.Common.EF public class BaseDbContext : DbContext { - public string baseName; public BaseDbContext() { } public BaseDbContext(DbContextOptions options) : base(options) { diff --git a/common/ASC.Core.Common/EF/Context/ConfigureDbContext.cs b/common/ASC.Core.Common/EF/Context/ConfigureDbContext.cs index a77ab7943f..275913a117 100644 --- a/common/ASC.Core.Common/EF/Context/ConfigureDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/ConfigureDbContext.cs @@ -39,7 +39,7 @@ namespace ASC.Core.Common.EF public class ConfigureMultiRegionalDbContext<T> : IConfigureNamedOptions<MultiRegionalDbContext<T>> where T : BaseDbContext, new() { - public string baseName = "default"; + private readonly string _baseName = "default"; private ConfigurationExtension Configuration { get; } private DbContextManager<T> DbContext { get; } @@ -57,7 +57,7 @@ namespace ASC.Core.Common.EF foreach (var c in Configuration.GetConnectionStrings().Where(r => r.Name.Equals(name, cmp) || r.Name.StartsWith(name + ".", cmp) || - r.Name.Equals(baseName, cmp) || r.Name.StartsWith(baseName + ".", cmp) + r.Name.Equals(_baseName, cmp) || r.Name.StartsWith(_baseName + ".", cmp) )) { context.Context.Add(DbContext.Get(c.Name)); @@ -66,7 +66,7 @@ namespace ASC.Core.Common.EF public void Configure(MultiRegionalDbContext<T> context) { - Configure(baseName, context); + Configure(_baseName, context); } } } diff --git a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs index 0e36f0d3ff..0a28a3cdc8 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -547,8 +547,8 @@ namespace ASC.Notify.Cron if (c >= '0' && c <= '9') { var vs = GetValue(val, s, i); - val = vs.theValue; - i = vs.pos; + val = vs.TheValue; + i = vs.Pos; } i = CheckNext(i, s, val, type); return i; @@ -665,9 +665,9 @@ namespace ASC.Notify.Cron if (c >= '0' && c <= '9') { var vs = GetValue(v, s, i); - var v1 = vs.theValue; + var v1 = vs.TheValue; end = v1; - i = vs.pos; + i = vs.Pos; } if (i < s.Length && ((s[i]) == '/')) { @@ -684,9 +684,9 @@ namespace ASC.Notify.Cron if (c >= '0' && c <= '9') { var vs = GetValue(v2, s, i); - var v3 = vs.theValue; + var v3 = vs.TheValue; AddToSet(val, end, v3, type); - i = vs.pos; + i = vs.Pos; return i; } else @@ -716,9 +716,9 @@ namespace ASC.Notify.Cron if (c >= '0' && c <= '9') { var vs = GetValue(v2, s, i); - var v3 = vs.theValue; + var v3 = vs.TheValue; AddToSet(val, end, v3, type); - i = vs.pos; + i = vs.Pos; return i; } else @@ -1018,13 +1018,13 @@ namespace ASC.Notify.Cron var val = new ValueSet(); if (i < s.Length) { - val.pos = i; + val.Pos = i; } else { - val.pos = i + 1; + val.Pos = i + 1; } - val.theValue = Convert.ToInt32(s1, CultureInfo.InvariantCulture); + val.TheValue = Convert.ToInt32(s1, CultureInfo.InvariantCulture); return val; } @@ -1526,7 +1526,7 @@ namespace ASC.Notify.Cron public class ValueSet { - public int pos; - public int theValue; + public int Pos { get; set; } + public int TheValue { get; set; } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs index 558fd6a282..433a28cbe4 100644 --- a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs @@ -113,7 +113,7 @@ namespace ASC.Core.Notify.Signalr private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(1); internal ILog Log; private static DateTime lastErrorTime; - public bool EnableSignalr; + public bool EnableSignalr { get; set; } internal byte[] SKey; internal string Url; internal bool JabberReplaceDomain; diff --git a/common/ASC.Core.Common/Tenants/TenantExceptions.cs b/common/ASC.Core.Common/Tenants/TenantExceptions.cs index ad573ae653..278bf02b2a 100644 --- a/common/ASC.Core.Common/Tenants/TenantExceptions.cs +++ b/common/ASC.Core.Common/Tenants/TenantExceptions.cs @@ -34,8 +34,8 @@ namespace ASC.Core.Tenants [Serializable] public class TenantTooShortException : Exception { - public int MinLength = 0; - public int MaxLength = 0; + public int MinLength { get; set; } = 0; + public int MaxLength { get; set; } = 0; public TenantTooShortException(string message) : base(message) diff --git a/common/ASC.Core.Common/Users/UserFormatter.cs b/common/ASC.Core.Common/Users/UserFormatter.cs index 77999e0c0c..c18650fadc 100644 --- a/common/ASC.Core.Common/Users/UserFormatter.cs +++ b/common/ASC.Core.Common/Users/UserFormatter.cs @@ -135,7 +135,7 @@ namespace ASC.Core.Users return format.IndexOf("{0}") < format.IndexOf("{1}") ? DisplayUserNameFormat.FirstLast : DisplayUserNameFormat.LastFirst; } - public Regex UserNameRegex; + public Regex UserNameRegex { get; set; } private IConfiguration Configuration { get; } diff --git a/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleProvider.cs b/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleProvider.cs index 1bf2817cb7..36d25e62c4 100644 --- a/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleProvider.cs +++ b/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleProvider.cs @@ -38,7 +38,7 @@ namespace ASC.Data.Backup.Tasks.Modules [Scope] public class ModuleProvider { - public List<IModuleSpecifics> AllModules; + public List<IModuleSpecifics> AllModules { get; } public ModuleProvider(IOptionsMonitor<ILog> options, Helpers helpers, CoreSettings coreSettings) { diff --git a/common/ASC.Data.Reassigns/QueueWorker.cs b/common/ASC.Data.Reassigns/QueueWorker.cs index 4a17d0e1ee..ea6fad274a 100644 --- a/common/ASC.Data.Reassigns/QueueWorker.cs +++ b/common/ASC.Data.Reassigns/QueueWorker.cs @@ -52,7 +52,7 @@ namespace ASC.Data.Reassigns protected IHttpContextAccessor HttpContextAccessor { get; } protected IServiceProvider ServiceProvider { get; } - public object SynchRoot = new object(); + private readonly object _synchRoot = new object(); public QueueWorker( IHttpContextAccessor httpContextAccessor, @@ -87,7 +87,7 @@ namespace ASC.Data.Reassigns protected DistributedTaskProgress Start(int tenantId, Guid userId, Func<T> constructor) { - lock (SynchRoot) + lock (_synchRoot) { var task = GetProgressItemStatus(tenantId, userId); diff --git a/products/ASC.Files/Core/Core/Entries/EditHistory.cs b/products/ASC.Files/Core/Core/Entries/EditHistory.cs index 01ee58cb18..b7f6eadcbc 100644 --- a/products/ASC.Files/Core/Core/Entries/EditHistory.cs +++ b/products/ASC.Files/Core/Core/Entries/EditHistory.cs @@ -79,9 +79,9 @@ namespace ASC.Files.Core try { var jObject = JObject.Parse(ChangesString); - ServerVersion = jObject.Value<string>("serverVersion"); + var serverVersion = jObject.Value<string>("serverVersion"); - if (string.IsNullOrEmpty(ServerVersion)) + if (string.IsNullOrEmpty(serverVersion)) return changes; var jChanges = jObject.Value<JArray>("changes"); @@ -113,7 +113,7 @@ namespace ASC.Files.Core set { throw new NotImplementedException(); } } - public DateTime ModifiedOn; + public DateTime ModifiedOn { get; set; } [JsonPropertyName("created")] public string ModifiedOnString @@ -126,8 +126,6 @@ namespace ASC.Files.Core private TenantUtil TenantUtil { get; } private UserManager UserManager { get; } private DisplayUserSettingsHelper DisplayUserSettingsHelper { get; } - - public string ServerVersion; } [DebuggerDisplay("{Id} {Name}")] diff --git a/products/ASC.Files/Core/Core/Entries/FileEntry.cs b/products/ASC.Files/Core/Core/Entries/FileEntry.cs index 1370b91d3e..8cd5501161 100644 --- a/products/ASC.Files/Core/Core/Entries/FileEntry.cs +++ b/products/ASC.Files/Core/Core/Entries/FileEntry.cs @@ -110,7 +110,7 @@ namespace ASC.Files.Core public abstract bool IsNew { get; set; } - public FileEntryType FileEntryType; + public FileEntryType FileEntryType { get; set; } private string _modifiedByString; private string _createByString; diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs index c9363e8942..352d94bffb 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs @@ -60,8 +60,7 @@ namespace ASC.Files.Thirdparty.SharePoint public DateTime CreateOn { get; set; } public string CustomerTitle { get; set; } public string RootFolderId { get { return "spoint-" + ID; } } - - public string SpRootFolderId = "/Shared Documents"; + public string SpRootFolderId { get; set; } = "/Shared Documents"; public SharePointProviderInfo( IOptionsMonitor<ILog> options, diff --git a/products/ASC.Files/Core/Helpers/Global.cs b/products/ASC.Files/Core/Helpers/Global.cs index f2a0fb6577..d3d6786b1d 100644 --- a/products/ASC.Files/Core/Helpers/Global.cs +++ b/products/ASC.Files/Core/Helpers/Global.cs @@ -135,7 +135,7 @@ namespace ASC.Web.Files.Classes #region Property - public string ThumbnailExtension; + public string ThumbnailExtension { get; set; } public const int MaxTitle = 170; diff --git a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs index 2aa61b5450..3dd17d8964 100644 --- a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs +++ b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs @@ -141,7 +141,7 @@ namespace ASC.Web.Files.Services.DocumentService [Transient] public class DocumentConfig<T> { - public string SharedLinkKey; + private string _sharedLinkKey; public DocumentConfig(DocumentServiceConnector documentServiceConnector, PathProvider pathProvider, InfoConfig<T> infoConfig) { @@ -185,7 +185,7 @@ namespace ASC.Web.Files.Services.DocumentService if (!string.IsNullOrEmpty(_fileUri)) return _fileUri; var last = Permissions.Edit || Permissions.Review || Permissions.Comment; - _fileUri = DocumentServiceConnector.ReplaceCommunityAdress(PathProvider.GetFileStreamUrl(Info.GetFile(), SharedLinkKey, last)); + _fileUri = DocumentServiceConnector.ReplaceCommunityAdress(PathProvider.GetFileStreamUrl(Info.GetFile(), _sharedLinkKey, last)); return _fileUri; } } @@ -202,7 +202,7 @@ namespace ASC.Web.Files.Services.DocumentService public File<T> GetFile() => File; public void SetFile(File<T> file) => File = file; - public EditorType Type = EditorType.Desktop; + public EditorType Type { get; set; } = EditorType.Desktop; private string _breadCrumbs; public InfoConfig(BreadCrumbsManager breadCrumbsManager, FileSharing fileSharing, SecurityContext securityContext, UserManager userManager) @@ -336,7 +336,7 @@ namespace ASC.Web.Files.Services.DocumentService } } - public bool ModeWrite = false; + public bool ModeWrite { get; set; } = false; private Configuration<T> _configuration; @@ -672,8 +672,8 @@ namespace ASC.Web.Files.Services.DocumentService Logo.SetConfiguration(_configuration); } - public string GobackUrl; - public bool IsRetina = false; + private string _gobackUrl; + public bool IsRetina { get; set; } = false; public bool About @@ -717,11 +717,11 @@ namespace ASC.Web.Files.Services.DocumentService { if (_configuration.EditorType == EditorType.Embedded || _configuration.EditorType == EditorType.External) return null; if (!AuthContext.IsAuthenticated) return null; - if (GobackUrl != null) + if (_gobackUrl != null) { return new GobackConfig { - Url = GobackUrl, + Url = _gobackUrl, }; } diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs index c5e26c8de9..1e9841d6ee 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -98,8 +98,8 @@ namespace ASC.Web.Files.Services.DocumentService [DebuggerDisplay("{Type} - {UserId}")] public class Action { - public string Type; - public string UserId; + public string Type { get; set; } + public string UserId { get; set; } } public enum ForceSaveInitiator diff --git a/products/ASC.Files/Core/Services/WCFService/Wrappers/MentionWrapper.cs b/products/ASC.Files/Core/Services/WCFService/Wrappers/MentionWrapper.cs index 0eb5785345..3b3efb88c3 100644 --- a/products/ASC.Files/Core/Services/WCFService/Wrappers/MentionWrapper.cs +++ b/products/ASC.Files/Core/Services/WCFService/Wrappers/MentionWrapper.cs @@ -53,7 +53,7 @@ namespace ASC.Web.Files.Services.WCFService private DisplayUserSettingsHelper DisplayUserSettingsHelper { get; } - public UserInfo User; + public UserInfo User { get; set; } public MentionWrapper(UserInfo user, DisplayUserSettingsHelper displayUserSettingsHelper) { diff --git a/products/ASC.Files/Core/Utils/MailMergeTask.cs b/products/ASC.Files/Core/Utils/MailMergeTask.cs index 9c7dbc11b7..3895e56532 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -44,14 +44,14 @@ namespace ASC.Web.Files.Utils { internal const string MessageBodyFormat = "id={0}&from={1}&subject={2}&to%5B%5D={3}&body={4}&mimeReplyToId="; - public string From; - public string Subject; - public string To; - public string Message; - public string AttachTitle; - public Stream Attach; - public int MessageId; - public string StreamId; + public string From { get; set; } + public string Subject { get; set; } + public string To { get; set; } + public string Message { get; set; } + public string AttachTitle { get; set; } + public Stream Attach { get; set; } + public int MessageId { get; set; } + public string StreamId { get; set; } public MailMergeTask() { diff --git a/web/ASC.Web.Core/Files/DocumentService.cs b/web/ASC.Web.Core/Files/DocumentService.cs index 422e979f5d..1b5e8d3357 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -616,7 +616,7 @@ namespace ASC.Web.Core.Files [Serializable] public class DocumentServiceException : Exception { - public ErrorCode Code; + public ErrorCode Code { get; set; } public DocumentServiceException(ErrorCode errorCode, string message) : base(message) diff --git a/web/ASC.Web.Core/Subscriptions/SubscriptionType.cs b/web/ASC.Web.Core/Subscriptions/SubscriptionType.cs index 42c38ee875..f9aef8e83f 100644 --- a/web/ASC.Web.Core/Subscriptions/SubscriptionType.cs +++ b/web/ASC.Web.Core/Subscriptions/SubscriptionType.cs @@ -47,9 +47,9 @@ namespace ASC.Web.Core.Subscriptions public bool CanSubscribe { get; set; } - public IsEmptySubscriptionTypeDelegate IsEmptySubscriptionType; + public IsEmptySubscriptionTypeDelegate IsEmptySubscriptionType { get; set; } - public GetSubscriptionObjectsDelegate GetSubscriptionObjects; + public GetSubscriptionObjectsDelegate GetSubscriptionObjects { get; set; } } } diff --git a/web/ASC.Web.Core/Users/UserPhotoManager.cs b/web/ASC.Web.Core/Users/UserPhotoManager.cs index 6619757da5..3bcaa95604 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -233,10 +233,10 @@ namespace ASC.Web.Core.Users Log = options.Get("ASC.Web.Photo"); } - public string defaultAbsoluteWebPath; + private string _defaultAbsoluteWebPath; public string GetDefaultPhotoAbsoluteWebPath() { - return defaultAbsoluteWebPath ??= WebImageSupplier.GetAbsoluteWebPath(_defaultAvatar); + return _defaultAbsoluteWebPath ??= WebImageSupplier.GetAbsoluteWebPath(_defaultAvatar); } public string GetRetinaPhotoURL(Guid userID) @@ -296,34 +296,34 @@ namespace ASC.Web.Core.Users } - public string defaultSmallPhotoURL; + private string _defaultSmallPhotoURL; public string GetDefaultSmallPhotoURL() { - return defaultSmallPhotoURL ??= GetDefaultPhotoAbsoluteWebPath(SmallFotoSize); + return _defaultSmallPhotoURL ??= GetDefaultPhotoAbsoluteWebPath(SmallFotoSize); } - public string defaultMediumPhotoURL; + private string _defaultMediumPhotoURL; public string GetDefaultMediumPhotoURL() { - return defaultMediumPhotoURL ??= GetDefaultPhotoAbsoluteWebPath(MediumFotoSize); + return _defaultMediumPhotoURL ??= GetDefaultPhotoAbsoluteWebPath(MediumFotoSize); } - public string defaultBigPhotoURL; + private string _defaultBigPhotoURL; public string GetDefaultBigPhotoURL() { - return defaultBigPhotoURL ??= GetDefaultPhotoAbsoluteWebPath(BigFotoSize); + return _defaultBigPhotoURL ??= GetDefaultPhotoAbsoluteWebPath(BigFotoSize); } - public string defaultMaxPhotoURL; + private string _defaultMaxPhotoURL; public string GetDefaultMaxPhotoURL() { - return defaultMaxPhotoURL ??= GetDefaultPhotoAbsoluteWebPath(MaxFotoSize); + return _defaultMaxPhotoURL ??= GetDefaultPhotoAbsoluteWebPath(MaxFotoSize); } - public string defaultRetinaPhotoURL; + private string _defaultRetinaPhotoURL; public string GetDefaultRetinaPhotoURL() { - return defaultRetinaPhotoURL ??= GetDefaultPhotoAbsoluteWebPath(RetinaFotoSize); + return _defaultRetinaPhotoURL ??= GetDefaultPhotoAbsoluteWebPath(RetinaFotoSize); } From ae53ed0d6277a8ad45eead4c30403f7b843200a7 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 12:27:39 +0300 Subject: [PATCH 077/167] analizators/s1117 --- common/ASC.Common/Security/AscRandom.cs | 16 ++++++------- common/ASC.Core.Common/Users/UserFormatter.cs | 6 ++--- .../FileOperations/FileDownloadOperation.cs | 24 +++++++++---------- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/common/ASC.Common/Security/AscRandom.cs b/common/ASC.Common/Security/AscRandom.cs index 2e3fe2c5f2..c84035be2a 100644 --- a/common/ASC.Common/Security/AscRandom.cs +++ b/common/ASC.Common/Security/AscRandom.cs @@ -30,8 +30,8 @@ namespace ASC.Common.Security { public class AscRandom : Random { - private int inext; - private int inextp; + private int _inext; + private int _inextp; private const int MBIG = int.MaxValue; private const int MSEED = 161803398; private const int MZ = 0; @@ -71,8 +71,8 @@ namespace ASC.Common.Security } } } - inext = 0; - inextp = 21; + _inext = 0; + _inextp = 21; } public override int Next(int maxValue) @@ -96,8 +96,8 @@ namespace ASC.Common.Security private int InternalSample() { - var inext = this.inext; - var inextp = this.inextp; + var inext = this._inext; + var inextp = this._inextp; if (++inext >= seeds.Length - 1) { inext = 1; @@ -116,8 +116,8 @@ namespace ASC.Common.Security num += int.MaxValue; } seeds[inext] = num; - this.inext = inext; - this.inextp = inextp; + this._inext = inext; + this._inextp = inextp; return num; } } diff --git a/common/ASC.Core.Common/Users/UserFormatter.cs b/common/ASC.Core.Common/Users/UserFormatter.cs index c18650fadc..0936dfb3cb 100644 --- a/common/ASC.Core.Common/Users/UserFormatter.cs +++ b/common/ASC.Core.Common/Users/UserFormatter.cs @@ -38,13 +38,13 @@ namespace ASC.Core.Users [Singletone] public class UserFormatter : IComparer<UserInfo> { - private readonly DisplayUserNameFormat format; + private readonly DisplayUserNameFormat _format; private static bool forceFormatChecked; private static string forceFormat; public UserFormatter(IConfiguration configuration) { - format = DisplayUserNameFormat.Default; + _format = DisplayUserNameFormat.Default; Configuration = configuration; UserNameRegex = new Regex(Configuration["core:username:regex"] ?? ""); } @@ -69,7 +69,7 @@ namespace ASC.Core.Users int IComparer<UserInfo>.Compare(UserInfo x, UserInfo y) { - return Compare(x, y, format); + return Compare(x, y, _format); } public static int Compare(UserInfo x, UserInfo y) diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs index 3decb77678..c9a6edf1e6 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs @@ -160,9 +160,9 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations class FileDownloadOperation<T> : FileOperation<FileDownloadOperationData<T>, T> { - private readonly Dictionary<T, string> files; + private readonly Dictionary<T, string> _files; private readonly IDictionary<string, StringValues> headers; - ItemNameValueCollection<T> entriesPathId; + private ItemNameValueCollection<T> _entriesPathId; public override FileOperationType OperationType { get { return FileOperationType.Download; } @@ -171,7 +171,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations public FileDownloadOperation(IServiceProvider serviceProvider, FileDownloadOperationData<T> fileDownloadOperationData) : base(serviceProvider, fileDownloadOperationData) { - files = fileDownloadOperationData.FilesDownload; + _files = fileDownloadOperationData.FilesDownload; headers = fileDownloadOperationData.Headers; } @@ -179,9 +179,9 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations { if (Files.Count == 0 && Folders.Count == 0) return; - entriesPathId = GetEntriesPathId(scope); + _entriesPathId = GetEntriesPathId(scope); - if (entriesPathId == null || entriesPathId.Count == 0) + if (_entriesPathId == null || _entriesPathId.Count == 0) { if (Files.Count > 0) { @@ -191,9 +191,9 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound); } - ReplaceLongPath(entriesPathId); + ReplaceLongPath(_entriesPathId); - Total = entriesPathId.Count; + Total = _entriesPathId.Count; TaskInfo.PublishChanges(); } @@ -205,7 +205,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations var title = file.Title; - if (files.TryGetValue(file.ID, out var convertToExt)) + if (_files.TryGetValue(file.ID, out var convertToExt)) { if (!string.IsNullOrEmpty(convertToExt)) { @@ -280,7 +280,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations internal void CompressToZip(Stream stream, IServiceScope scope) { - if (entriesPathId == null) return; + if (_entriesPathId == null) return; var scopeClass = scope.ServiceProvider.GetService<FileDownloadOperationScope>(); var (_, _, _, fileConverter, filesMessageService) = scopeClass; var FileDao = scope.ServiceProvider.GetService<IFileDao<T>>(); @@ -289,10 +289,10 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations { compressTo.SetStream(stream); - foreach (var path in entriesPathId.AllKeys) + foreach (var path in _entriesPathId.AllKeys) { var counter = 0; - foreach (var entryId in entriesPathId[path]) + foreach (var entryId in _entriesPathId[path]) { if (CancellationToken.IsCancellationRequested) { @@ -315,7 +315,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations continue; } - if (files.TryGetValue(file.ID, out convertToExt)) + if (_files.TryGetValue(file.ID, out convertToExt)) { if (!string.IsNullOrEmpty(convertToExt)) { From 473259657e85e97231ef486c53aaa509e2284eab Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 13:47:56 +0300 Subject: [PATCH 078/167] analizators/s1118 --- common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs | 2 +- common/ASC.Common/Logging/Log.cs | 6 +++--- common/ASC.Common/Security/Authorizing/Constants.cs | 2 +- common/ASC.Common/Security/Cryptography/Hasher.cs | 2 +- common/ASC.Common/Utils/JsonWebToken.cs | 2 +- common/ASC.Common/Utils/VelocityFormatter.cs | 2 +- common/ASC.Common/Web/VirtualPathUtility.cs | 2 +- common/ASC.Core.Common/Configuration/Constants.cs | 2 +- common/ASC.Core.Common/Context/WorkContext.cs | 2 +- common/ASC.Core.Common/Notify/Senders/AWSSender.cs | 2 +- common/ASC.Core.Common/Notify/Senders/JabberSender.cs | 2 +- common/ASC.Core.Common/Notify/Senders/SmtpSender.cs | 2 +- common/ASC.Core.Common/Security/Crypto.cs | 2 +- common/ASC.Core.Common/WhiteLabel/BaseWhiteLabelSettings.cs | 2 +- common/ASC.Data.Backup.Core/Core/NotifyHelper.cs | 2 +- common/ASC.Data.Backup.Core/Service/BackupWorker.cs | 4 ++-- common/ASC.Data.Reassigns/QueueWorker.cs | 2 +- common/ASC.Data.Reassigns/ReassignProgressItem.cs | 2 +- common/ASC.Data.Storage/Configuration/StorageSettings.cs | 2 +- common/ASC.Data.Storage/Constants.cs | 2 +- common/ASC.Data.Storage/Encryption/EncryptionOperation.cs | 2 +- common/ASC.Data.Storage/Encryption/EncryptionWorker.cs | 2 +- common/ASC.Data.Storage/StorageFactory.cs | 2 +- common/ASC.Data.Storage/TenantPath.cs | 2 +- common/ASC.Data.Storage/Wildcard.cs | 2 +- common/ASC.FederatedLogin/Helpers/HashHelper.cs | 2 +- common/ASC.FederatedLogin/Helpers/JsCallbackHelper.cs | 2 +- common/ASC.FederatedLogin/Helpers/RequestHelper.cs | 2 +- common/ASC.FederatedLogin/Helpers/XrdsHelper.cs | 2 +- .../ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs | 2 +- common/ASC.FederatedLogin/Profile/WellKnownFields.cs | 2 +- common/ASC.Feed/Core/Constants.cs | 2 +- common/ASC.MessagingSystem/DbSender/MessagesRepository.cs | 2 +- common/ASC.Textile/Blocks/BlockAttributesParser.cs | 2 +- common/ASC.Textile/Globals.cs | 2 +- common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs | 2 +- .../ASC.AuditTrail/Mappers/DocumentsActionMapper.cs | 2 +- common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs | 2 +- .../services/ASC.AuditTrail/Mappers/OthersActionMapper.cs | 2 +- .../services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs | 2 +- .../services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs | 2 +- .../services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs | 2 +- .../services/ASC.ClearEvents/ClearEventsServiceLauncher.cs | 2 +- common/services/ASC.ClearEvents/Program.cs | 2 +- common/services/ASC.Data.Backup/BackupCleanerService.cs | 2 +- common/services/ASC.Data.Backup/BackupSchedulerService.cs | 2 +- common/services/ASC.Data.Backup/Program.cs | 2 +- common/services/ASC.ElasticSearch/Service/Launcher.cs | 2 +- common/services/ASC.ElasticSearch/Service/Service.cs | 2 +- .../ASC.Feed.Aggregator/Service/FeedAggregatorService.cs | 2 +- common/services/ASC.Notify/DbWorker.cs | 2 +- common/services/ASC.Notify/NotifyService.cs | 2 +- common/services/ASC.Notify/Program.cs | 2 +- common/services/ASC.Studio.Notify/Program.cs | 2 +- common/services/ASC.TelegramService/Program.cs | 2 +- common/services/ASC.TelegramService/TelegramHandler.cs | 2 +- common/services/ASC.TelegramService/TelegramLauncher.cs | 2 +- common/services/ASC.UrlShortener.Svc/Program.cs | 2 +- common/services/ASC.Webhooks.Service/Program.cs | 2 +- products/ASC.Files/Core/Core/Dao/TeamlabDao/DaoFactory.cs | 2 +- products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs | 2 +- products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs | 2 +- .../ASC.Files/Core/Core/Thirdparty/Box/BoxDaoSelector.cs | 2 +- products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs | 2 +- .../Core/Core/Thirdparty/Dropbox/DropboxDaoSelector.cs | 2 +- .../Core/Thirdparty/GoogleDrive/GoogleDriveDaoSelector.cs | 2 +- .../Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs | 2 +- .../Core/Core/Thirdparty/OneDrive/OneDriveDaoSelector.cs | 2 +- .../Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs | 2 +- .../ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs | 2 +- .../Core/Thirdparty/SharePoint/SharePointDaoSelector.cs | 2 +- .../Core/Core/Thirdparty/Sharpbox/SharpBoxDaoSelector.cs | 2 +- .../ASC.Files/Core/Services/NotifyService/NotifyClient.cs | 2 +- .../WCFService/FileOperations/FileOperationsManager.cs | 2 +- products/ASC.Files/Core/ThirdPartyApp/IThirdPartyApp.cs | 2 +- products/ASC.Files/Core/Utils/FileConverter.cs | 4 ++-- products/ASC.Files/Core/Utils/FileMarker.cs | 2 +- products/ASC.Files/Server/Program.cs | 2 +- products/ASC.Files/Service/Program.cs | 2 +- products/ASC.Files/Service/Thumbnail/Worker.cs | 2 +- products/ASC.People/Server/Program.cs | 2 +- web/ASC.Web.Api/Program.cs | 2 +- web/ASC.Web.Core/CommonPhotoManager.cs | 2 +- web/ASC.Web.Core/Helpers/GrammaticalHelper.cs | 2 +- web/ASC.Web.Core/Notify/NotifyConfiguration.cs | 2 +- web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs | 2 +- web/ASC.Web.Core/Notify/Tags.cs | 2 +- web/ASC.Web.Core/SecutiryConstants.cs | 2 +- web/ASC.Web.Core/Users/UserPhotoManager.cs | 2 +- web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs | 2 +- web/ASC.Web.HealthChecks.UI/Program.cs | 2 +- web/ASC.Web.Studio/Program.cs | 2 +- 92 files changed, 96 insertions(+), 96 deletions(-) diff --git a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs index 4b3bf08b28..29f1cba800 100644 --- a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs @@ -112,7 +112,7 @@ namespace ASC.Api.Core.Auth } } - public class ConfirmAuthHandlerExtension + public static class ConfirmAuthHandlerExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Common/Logging/Log.cs b/common/ASC.Common/Logging/Log.cs index 56f8e4eab5..15bbd01e03 100644 --- a/common/ASC.Common/Logging/Log.cs +++ b/common/ASC.Common/Logging/Log.cs @@ -875,7 +875,7 @@ namespace ASC.Common.Logging } } - public class LoggerExtension<T> where T : class, ILog, new() + public static class LoggerExtension<T> where T : class, ILog, new() { public static void RegisterLog(DIHelper services) { @@ -883,11 +883,11 @@ namespace ASC.Common.Logging } } - public class LogNLogExtension : LoggerExtension<LogNLog> + public static class LogNLogExtension { public static void Register(DIHelper services) { - RegisterLog(services); + LoggerExtension<LogNLog>.RegisterLog(services); } } } diff --git a/common/ASC.Common/Security/Authorizing/Constants.cs b/common/ASC.Common/Security/Authorizing/Constants.cs index e327050929..f325f1951a 100644 --- a/common/ASC.Common/Security/Authorizing/Constants.cs +++ b/common/ASC.Common/Security/Authorizing/Constants.cs @@ -28,7 +28,7 @@ using System; namespace ASC.Common.Security.Authorizing { - public sealed class Constants + public static class Constants { public static readonly Role Admin = new Role(new Guid("cd84e66b-b803-40fc-99f9-b2969a54a1de"), "Admin"); diff --git a/common/ASC.Common/Security/Cryptography/Hasher.cs b/common/ASC.Common/Security/Cryptography/Hasher.cs index f404b66370..c25cdc2eac 100644 --- a/common/ASC.Common/Security/Cryptography/Hasher.cs +++ b/common/ASC.Common/Security/Cryptography/Hasher.cs @@ -30,7 +30,7 @@ using System.Text; namespace ASC.Security.Cryptography { - public sealed class Hasher + public static class Hasher { private const HashAlg DefaultAlg = HashAlg.SHA256; diff --git a/common/ASC.Common/Utils/JsonWebToken.cs b/common/ASC.Common/Utils/JsonWebToken.cs index 25481d3cb8..f68576bb39 100644 --- a/common/ASC.Common/Utils/JsonWebToken.cs +++ b/common/ASC.Common/Utils/JsonWebToken.cs @@ -37,7 +37,7 @@ using Formatting = Newtonsoft.Json.Formatting; namespace ASC.Web.Core.Files { - public class JsonWebToken + public static class JsonWebToken { public static string Encode(object payload, string key) { diff --git a/common/ASC.Common/Utils/VelocityFormatter.cs b/common/ASC.Common/Utils/VelocityFormatter.cs index fecb88be69..b6e532c002 100644 --- a/common/ASC.Common/Utils/VelocityFormatter.cs +++ b/common/ASC.Common/Utils/VelocityFormatter.cs @@ -58,7 +58,7 @@ namespace ASC.Common.Utils } } - public class VelocityFormatter + public static class VelocityFormatter { private static bool initialized; private static readonly ConcurrentDictionary<string, Template> patterns = new ConcurrentDictionary<string, Template>(); diff --git a/common/ASC.Common/Web/VirtualPathUtility.cs b/common/ASC.Common/Web/VirtualPathUtility.cs index dc08c41c32..da4916e11f 100644 --- a/common/ASC.Common/Web/VirtualPathUtility.cs +++ b/common/ASC.Common/Web/VirtualPathUtility.cs @@ -2,7 +2,7 @@ namespace ASC.Common.Web { - public class VirtualPathUtility + public static class VirtualPathUtility { public static string ToAbsolute(string virtualPath) { diff --git a/common/ASC.Core.Common/Configuration/Constants.cs b/common/ASC.Core.Common/Configuration/Constants.cs index 98bfcedb06..852ebdd246 100644 --- a/common/ASC.Core.Common/Configuration/Constants.cs +++ b/common/ASC.Core.Common/Configuration/Constants.cs @@ -32,7 +32,7 @@ using ASC.Common.Security.Authorizing; namespace ASC.Core.Configuration { - public sealed class Constants + public static class Constants { public static readonly string NotifyEMailSenderSysName = "email.sender"; diff --git a/common/ASC.Core.Common/Context/WorkContext.cs b/common/ASC.Core.Common/Context/WorkContext.cs index c9d5f1f75a..68abd257e2 100644 --- a/common/ASC.Core.Common/Context/WorkContext.cs +++ b/common/ASC.Core.Common/Context/WorkContext.cs @@ -171,7 +171,7 @@ namespace ASC.Core } } - public class WorkContextExtension + public static class WorkContextExtension { public static void Register(DIHelper dIHelper) { diff --git a/common/ASC.Core.Common/Notify/Senders/AWSSender.cs b/common/ASC.Core.Common/Notify/Senders/AWSSender.cs index 2ba94163cd..bf756542cb 100644 --- a/common/ASC.Core.Common/Notify/Senders/AWSSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/AWSSender.cs @@ -249,7 +249,7 @@ namespace ASC.Core.Notify.Senders } } - public class AWSSenderExtension + public static class AWSSenderExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Core.Common/Notify/Senders/JabberSender.cs b/common/ASC.Core.Common/Notify/Senders/JabberSender.cs index 1adf0f70af..6cc3a236c0 100644 --- a/common/ASC.Core.Common/Notify/Senders/JabberSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/JabberSender.cs @@ -78,7 +78,7 @@ namespace ASC.Core.Notify.Senders } } - public class JabberSenderExtension + public static class JabberSenderExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs index 7091946bad..aab41d246f 100644 --- a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs @@ -334,7 +334,7 @@ namespace ASC.Core.Notify.Senders } } - public class SmtpSenderExtension + public static class SmtpSenderExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Core.Common/Security/Crypto.cs b/common/ASC.Core.Common/Security/Crypto.cs index 2f71b74967..8cd772396b 100644 --- a/common/ASC.Core.Common/Security/Crypto.cs +++ b/common/ASC.Core.Common/Security/Crypto.cs @@ -33,7 +33,7 @@ using ASC.Common.Security; namespace ASC.Core { - public class Crypto + public static class Crypto { private static byte[] GetSK1(bool rewrite) { diff --git a/common/ASC.Core.Common/WhiteLabel/BaseWhiteLabelSettings.cs b/common/ASC.Core.Common/WhiteLabel/BaseWhiteLabelSettings.cs index a1314dd754..1775abd292 100644 --- a/common/ASC.Core.Common/WhiteLabel/BaseWhiteLabelSettings.cs +++ b/common/ASC.Core.Common/WhiteLabel/BaseWhiteLabelSettings.cs @@ -1,6 +1,6 @@ namespace ASC.Core.Common.WhiteLabel { - public class BaseWhiteLabelSettings + public static class BaseWhiteLabelSettings { public const string DefaultLogoText = "ONLYOFFICE"; } diff --git a/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs b/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs index dabab637f1..bb54190e51 100644 --- a/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs @@ -238,7 +238,7 @@ namespace ASC.Data.Backup } } - public class NotifyHelperExtension + public static class NotifyHelperExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs index 634a54d7d3..07c919bbbd 100644 --- a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs +++ b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs @@ -881,7 +881,7 @@ namespace ASC.Data.Backup.Service } } - public class BackupWorkerExtension + public static class BackupWorkerExtension { public static void Register(DIHelper services) { @@ -890,7 +890,7 @@ namespace ASC.Data.Backup.Service } } - public class FactoryProgressItemExtension + public static class FactoryProgressItemExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Data.Reassigns/QueueWorker.cs b/common/ASC.Data.Reassigns/QueueWorker.cs index ea6fad274a..638510b2eb 100644 --- a/common/ASC.Data.Reassigns/QueueWorker.cs +++ b/common/ASC.Data.Reassigns/QueueWorker.cs @@ -37,7 +37,7 @@ using Microsoft.Extensions.Primitives; namespace ASC.Data.Reassigns { - public class QueueWorker + public static class QueueWorker { public static IDictionary<string, StringValues> GetHttpHeaders(HttpRequest httpRequest) { diff --git a/common/ASC.Data.Reassigns/ReassignProgressItem.cs b/common/ASC.Data.Reassigns/ReassignProgressItem.cs index 6a40b23afc..54db156b61 100644 --- a/common/ASC.Data.Reassigns/ReassignProgressItem.cs +++ b/common/ASC.Data.Reassigns/ReassignProgressItem.cs @@ -273,7 +273,7 @@ namespace ASC.Data.Reassigns } } - public class ReassignProgressItemExtension + public static class ReassignProgressItemExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Data.Storage/Configuration/StorageSettings.cs b/common/ASC.Data.Storage/Configuration/StorageSettings.cs index c533a93760..b3978d6a1f 100644 --- a/common/ASC.Data.Storage/Configuration/StorageSettings.cs +++ b/common/ASC.Data.Storage/Configuration/StorageSettings.cs @@ -249,7 +249,7 @@ namespace ASC.Data.Storage.Configuration } } - public class StorageSettingsExtension + public static class StorageSettingsExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Data.Storage/Constants.cs b/common/ASC.Data.Storage/Constants.cs index 6ec20d9cbd..a0acdb0997 100644 --- a/common/ASC.Data.Storage/Constants.cs +++ b/common/ASC.Data.Storage/Constants.cs @@ -26,7 +26,7 @@ namespace ASC.Data.Storage { - class Constants + static class Constants { public const string CONFIG_DIR = "CONFIG_DIR"; public const string STORAGE_ROOT_PARAM = "$STORAGE_ROOT"; diff --git a/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs b/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs index 57649e9615..c933dc371f 100644 --- a/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs +++ b/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs @@ -378,7 +378,7 @@ namespace ASC.Data.Storage.Encryption } } - public class EncryptionOperationExtension + public static class EncryptionOperationExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Data.Storage/Encryption/EncryptionWorker.cs b/common/ASC.Data.Storage/Encryption/EncryptionWorker.cs index 3c7c079591..618cd178f3 100644 --- a/common/ASC.Data.Storage/Encryption/EncryptionWorker.cs +++ b/common/ASC.Data.Storage/Encryption/EncryptionWorker.cs @@ -95,7 +95,7 @@ namespace ASC.Data.Storage.Encryption } } - public class FactoryOperationExtension + public static class FactoryOperationExtension { public static void Register(DIHelper dIHelper) { diff --git a/common/ASC.Data.Storage/StorageFactory.cs b/common/ASC.Data.Storage/StorageFactory.cs index cfb0a16193..40a45f1151 100644 --- a/common/ASC.Data.Storage/StorageFactory.cs +++ b/common/ASC.Data.Storage/StorageFactory.cs @@ -259,7 +259,7 @@ namespace ASC.Data.Storage } } - public class StorageFactoryExtension + public static class StorageFactoryExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Data.Storage/TenantPath.cs b/common/ASC.Data.Storage/TenantPath.cs index 1f49776515..36e2fe49a1 100644 --- a/common/ASC.Data.Storage/TenantPath.cs +++ b/common/ASC.Data.Storage/TenantPath.cs @@ -29,7 +29,7 @@ using System.Globalization; namespace ASC.Data.Storage { - public class TenantPath + public static class TenantPath { public static string CreatePath(string tenant) { diff --git a/common/ASC.Data.Storage/Wildcard.cs b/common/ASC.Data.Storage/Wildcard.cs index 7fec130992..a945ed3166 100644 --- a/common/ASC.Data.Storage/Wildcard.cs +++ b/common/ASC.Data.Storage/Wildcard.cs @@ -26,7 +26,7 @@ namespace ASC.Data.Storage { - public class Wildcard + public static class Wildcard { public static bool IsMatch(string pattern, string input) { diff --git a/common/ASC.FederatedLogin/Helpers/HashHelper.cs b/common/ASC.FederatedLogin/Helpers/HashHelper.cs index 1c9f6024a9..6d7d828e38 100644 --- a/common/ASC.FederatedLogin/Helpers/HashHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/HashHelper.cs @@ -28,7 +28,7 @@ using System.Text; namespace ASC.FederatedLogin.Helpers { - public class HashHelper + public static class HashHelper { public static int CombineHashCodes(int hash1, int hash2) { diff --git a/common/ASC.FederatedLogin/Helpers/JsCallbackHelper.cs b/common/ASC.FederatedLogin/Helpers/JsCallbackHelper.cs index 17bdc13f3f..5e610c6d23 100644 --- a/common/ASC.FederatedLogin/Helpers/JsCallbackHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/JsCallbackHelper.cs @@ -29,7 +29,7 @@ using System.Reflection; namespace ASC.FederatedLogin.Helpers { - public class JsCallbackHelper + public static class JsCallbackHelper { public static string GetCallbackPage() { diff --git a/common/ASC.FederatedLogin/Helpers/RequestHelper.cs b/common/ASC.FederatedLogin/Helpers/RequestHelper.cs index 8758502162..1ee9a7d6ea 100644 --- a/common/ASC.FederatedLogin/Helpers/RequestHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/RequestHelper.cs @@ -32,7 +32,7 @@ using System.Text; namespace ASC.FederatedLogin.Helpers { - public class RequestHelper + public static class RequestHelper { private static HttpClient HttpClient { get; } = new HttpClient(); diff --git a/common/ASC.FederatedLogin/Helpers/XrdsHelper.cs b/common/ASC.FederatedLogin/Helpers/XrdsHelper.cs index 43932ad3f6..8011ad223a 100644 --- a/common/ASC.FederatedLogin/Helpers/XrdsHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/XrdsHelper.cs @@ -30,7 +30,7 @@ using Microsoft.AspNetCore.Http; namespace ASC.FederatedLogin.Helpers { - public class XrdsHelper + public static class XrdsHelper { internal static async Task RenderXrds(HttpResponse responce, string location, string iconlink) { diff --git a/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs index 95f3c2e24c..d00ae65afa 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs @@ -163,7 +163,7 @@ namespace ASC.FederatedLogin.LoginProviders public abstract LoginProfile GetLoginProfile(string accessToken); } - public class BaseLoginProviderExtension + public static class BaseLoginProviderExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.FederatedLogin/Profile/WellKnownFields.cs b/common/ASC.FederatedLogin/Profile/WellKnownFields.cs index acce11684e..595cdaf358 100644 --- a/common/ASC.FederatedLogin/Profile/WellKnownFields.cs +++ b/common/ASC.FederatedLogin/Profile/WellKnownFields.cs @@ -26,7 +26,7 @@ namespace ASC.FederatedLogin.Profile { - public class WellKnownFields + public static class WellKnownFields { //Constants public const string Id = "Id"; diff --git a/common/ASC.Feed/Core/Constants.cs b/common/ASC.Feed/Core/Constants.cs index 11d9b1c529..eecbac306e 100644 --- a/common/ASC.Feed/Core/Constants.cs +++ b/common/ASC.Feed/Core/Constants.cs @@ -26,7 +26,7 @@ namespace ASC.Feed { - public class Constants + public static class Constants { public const string FeedDbId = "core"; public const string ProjectsDbId = "projects"; diff --git a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs index ec60b04bd0..1436632d11 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -276,7 +276,7 @@ namespace ASC.MessagingSystem.DbSender public DbSet<DbTenant> Tenants { get; set; } public DbSet<DbWebstudioSettings> WebstudioSettings { get; set; } } - public class MessagesRepositoryExtension + public static class MessagesRepositoryExtension { public static void Register(DIHelper services) { diff --git a/common/ASC.Textile/Blocks/BlockAttributesParser.cs b/common/ASC.Textile/Blocks/BlockAttributesParser.cs index 56a2237a97..361992aeea 100644 --- a/common/ASC.Textile/Blocks/BlockAttributesParser.cs +++ b/common/ASC.Textile/Blocks/BlockAttributesParser.cs @@ -17,7 +17,7 @@ using System.Text.RegularExpressions; namespace Textile.Blocks { - public class BlockAttributesParser + public static class BlockAttributesParser { public static StyleReader Styler { get; set; } diff --git a/common/ASC.Textile/Globals.cs b/common/ASC.Textile/Globals.cs index 89dc5eca1c..6a0c0fa422 100644 --- a/common/ASC.Textile/Globals.cs +++ b/common/ASC.Textile/Globals.cs @@ -20,7 +20,7 @@ namespace Textile /// <summary> /// A utility class for global things used by the TextileFormatter. /// </summary> - class Globals + static class Globals { #region Global Regex Patterns diff --git a/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs index 6f0a9170fe..a311eef439 100644 --- a/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs @@ -32,7 +32,7 @@ using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { - internal class CrmActionMapper + internal static class CrmActionMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { diff --git a/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs index 0189838e04..9e46f41daa 100644 --- a/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs @@ -31,7 +31,7 @@ using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { - internal class DocumentsActionMapper + internal static class DocumentsActionMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { diff --git a/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs index 0ad37f1fd2..bffafbc2a4 100644 --- a/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs @@ -32,7 +32,7 @@ using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { - internal class LoginActionsMapper + internal static class LoginActionsMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { diff --git a/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs index 572e0644a1..f0bf259b4b 100644 --- a/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs @@ -32,7 +32,7 @@ using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { - internal class OthersActionsMapper + internal static class OthersActionsMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { diff --git a/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs index a67feacb0d..5aa563afeb 100644 --- a/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs @@ -32,7 +32,7 @@ using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { - internal class PeopleActionMapper + internal static class PeopleActionMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { diff --git a/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs index ac3de67f0f..00135f8c7d 100644 --- a/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs @@ -31,7 +31,7 @@ using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { - internal class ProjectsActionsMapper + internal static class ProjectsActionsMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { diff --git a/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs index 74904ef51f..8298a4b2f3 100644 --- a/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs @@ -31,7 +31,7 @@ using ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { - internal class SettingsActionsMapper + internal static class SettingsActionsMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { diff --git a/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs b/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs index 3933ee3342..c3d92d8732 100644 --- a/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs +++ b/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs @@ -131,7 +131,7 @@ namespace ASC.Thumbnails.Svc public DbSet<DbWebstudioSettings> WebstudioSettings { get; } } -public class MessagesRepositoryExtension + public static class MessagesRepositoryExtension { public static void Register(DIHelper services) { diff --git a/common/services/ASC.ClearEvents/Program.cs b/common/services/ASC.ClearEvents/Program.cs index 2214cf7600..0514c12027 100644 --- a/common/services/ASC.ClearEvents/Program.cs +++ b/common/services/ASC.ClearEvents/Program.cs @@ -44,7 +44,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.Thumbnails.Svc { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/common/services/ASC.Data.Backup/BackupCleanerService.cs b/common/services/ASC.Data.Backup/BackupCleanerService.cs index a6e548bb9e..6c85492eed 100644 --- a/common/services/ASC.Data.Backup/BackupCleanerService.cs +++ b/common/services/ASC.Data.Backup/BackupCleanerService.cs @@ -182,7 +182,7 @@ namespace ASC.Data.Backup.Service } } - public class BackupCleanerServiceExtension + public static class BackupCleanerServiceExtension { public static void Register(DIHelper services) { diff --git a/common/services/ASC.Data.Backup/BackupSchedulerService.cs b/common/services/ASC.Data.Backup/BackupSchedulerService.cs index b26a3033f5..c5d88c85a4 100644 --- a/common/services/ASC.Data.Backup/BackupSchedulerService.cs +++ b/common/services/ASC.Data.Backup/BackupSchedulerService.cs @@ -177,7 +177,7 @@ namespace ASC.Data.Backup.Service } } - public class BackupSchedulerServiceExtension + public static class BackupSchedulerServiceExtension { public static void Register(DIHelper services) { diff --git a/common/services/ASC.Data.Backup/Program.cs b/common/services/ASC.Data.Backup/Program.cs index ef4dcd44eb..bb8fc3cc9b 100644 --- a/common/services/ASC.Data.Backup/Program.cs +++ b/common/services/ASC.Data.Backup/Program.cs @@ -15,7 +15,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.Data.Backup { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/common/services/ASC.ElasticSearch/Service/Launcher.cs b/common/services/ASC.ElasticSearch/Service/Launcher.cs index b8e35eac30..6576a8f32c 100644 --- a/common/services/ASC.ElasticSearch/Service/Launcher.cs +++ b/common/services/ASC.ElasticSearch/Service/Launcher.cs @@ -211,7 +211,7 @@ namespace ASC.ElasticSearch } } - public class ServiceLauncherExtension + public static class ServiceLauncherExtension { public static void Register(DIHelper services) { diff --git a/common/services/ASC.ElasticSearch/Service/Service.cs b/common/services/ASC.ElasticSearch/Service/Service.cs index 214e73c737..ba619f2c9e 100644 --- a/common/services/ASC.ElasticSearch/Service/Service.cs +++ b/common/services/ASC.ElasticSearch/Service/Service.cs @@ -120,7 +120,7 @@ namespace ASC.ElasticSearch.Service } } - internal class ServiceExtension + internal static class ServiceExtension { public static void Register(DIHelper services) { diff --git a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs index 738fedcc57..c38b72f6a3 100644 --- a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs +++ b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs @@ -337,7 +337,7 @@ namespace ASC.Feed.Aggregator } } - public class FeedAggregatorServiceExtension + public static class FeedAggregatorServiceExtension { public static void Register(DIHelper services) { diff --git a/common/services/ASC.Notify/DbWorker.cs b/common/services/ASC.Notify/DbWorker.cs index 17f92e59aa..b726ca5325 100644 --- a/common/services/ASC.Notify/DbWorker.cs +++ b/common/services/ASC.Notify/DbWorker.cs @@ -224,7 +224,7 @@ namespace ASC.Notify } } - public class DbWorkerExtension + public static class DbWorkerExtension { public static void Register(DIHelper services) { diff --git a/common/services/ASC.Notify/NotifyService.cs b/common/services/ASC.Notify/NotifyService.cs index 7507390e16..970d37f296 100644 --- a/common/services/ASC.Notify/NotifyService.cs +++ b/common/services/ASC.Notify/NotifyService.cs @@ -142,7 +142,7 @@ namespace ASC.Notify } } - public class NotifyServiceExtension + public static class NotifyServiceExtension { public static void Register(DIHelper services) { diff --git a/common/services/ASC.Notify/Program.cs b/common/services/ASC.Notify/Program.cs index 9f6a50c95b..ae8e6ad1d7 100644 --- a/common/services/ASC.Notify/Program.cs +++ b/common/services/ASC.Notify/Program.cs @@ -20,7 +20,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.Notify { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/common/services/ASC.Studio.Notify/Program.cs b/common/services/ASC.Studio.Notify/Program.cs index 2d7ab1da66..82bf751432 100644 --- a/common/services/ASC.Studio.Notify/Program.cs +++ b/common/services/ASC.Studio.Notify/Program.cs @@ -21,7 +21,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.Studio.Notify { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/common/services/ASC.TelegramService/Program.cs b/common/services/ASC.TelegramService/Program.cs index cc2b79f536..2345f62cea 100644 --- a/common/services/ASC.TelegramService/Program.cs +++ b/common/services/ASC.TelegramService/Program.cs @@ -39,7 +39,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.TelegramService { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/common/services/ASC.TelegramService/TelegramHandler.cs b/common/services/ASC.TelegramService/TelegramHandler.cs index cae084da9d..9035834a2d 100644 --- a/common/services/ASC.TelegramService/TelegramHandler.cs +++ b/common/services/ASC.TelegramService/TelegramHandler.cs @@ -185,7 +185,7 @@ namespace ASC.TelegramService } } - public class TelegramHandlerExtension + public static class TelegramHandlerExtension { public static void Register(DIHelper services) { diff --git a/common/services/ASC.TelegramService/TelegramLauncher.cs b/common/services/ASC.TelegramService/TelegramLauncher.cs index 0f022e809a..c46a10ac12 100644 --- a/common/services/ASC.TelegramService/TelegramLauncher.cs +++ b/common/services/ASC.TelegramService/TelegramLauncher.cs @@ -100,7 +100,7 @@ namespace ASC.TelegramService } } - public class TelegramLauncherExtension + public static class TelegramLauncherExtension { public static void Register(DIHelper services) { diff --git a/common/services/ASC.UrlShortener.Svc/Program.cs b/common/services/ASC.UrlShortener.Svc/Program.cs index f3a8c32cce..c60a537ac1 100644 --- a/common/services/ASC.UrlShortener.Svc/Program.cs +++ b/common/services/ASC.UrlShortener.Svc/Program.cs @@ -44,7 +44,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.UrlShortener.Svc { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/common/services/ASC.Webhooks.Service/Program.cs b/common/services/ASC.Webhooks.Service/Program.cs index 1fdd02c81a..13679ca1aa 100644 --- a/common/services/ASC.Webhooks.Service/Program.cs +++ b/common/services/ASC.Webhooks.Service/Program.cs @@ -19,7 +19,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.Webhooks.Service { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/DaoFactory.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/DaoFactory.cs index d239835e94..2ea5562740 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/DaoFactory.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/DaoFactory.cs @@ -67,7 +67,7 @@ namespace ASC.Files.Core.Data } } - public class DaoFactoryExtension + public static class DaoFactoryExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs b/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs index bf8820cade..d215112583 100644 --- a/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs +++ b/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs @@ -196,7 +196,7 @@ namespace ASC.Web.Files.Core.Search public DbFile DbFile { get; set; } } - public class FactoryIndexerFileExtension + public static class FactoryIndexerFileExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs b/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs index 0c2d8d54d3..8aee027f25 100644 --- a/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs +++ b/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs @@ -174,7 +174,7 @@ namespace ASC.Web.Files.Core.Search public DbFolder DbFolder { get; set; } } - public class FactoryIndexerFolderExtension + public static class FactoryIndexerFolderExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoSelector.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoSelector.cs index 897ef9e01e..99ec198360 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoSelector.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoSelector.cs @@ -63,7 +63,7 @@ namespace ASC.Files.Thirdparty.Box return base.GetSecurityDao<BoxSecurityDao>(id); } } - public class BoxDaoSelectorExtension + public static class BoxDaoSelectorExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs b/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs index b04414464c..8ffc3b05fd 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs @@ -196,7 +196,7 @@ namespace ASC.Files.Core.Thirdparty } } - public class CrossDaoExtension + public static class CrossDaoExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoSelector.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoSelector.cs index 937bb13f2c..529a392475 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoSelector.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoSelector.cs @@ -64,7 +64,7 @@ namespace ASC.Files.Thirdparty.Dropbox } } - public class DropboxDaoSelectorExtension + public static class DropboxDaoSelectorExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoSelector.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoSelector.cs index 6eebee8067..f3f9ab73b5 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoSelector.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoSelector.cs @@ -63,7 +63,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive } } - public class GoogleDriveDaoSelectorExtension + public static class GoogleDriveDaoSelectorExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs index fce1658a43..fefce56444 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs @@ -366,7 +366,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive } } - public class GoogleDriveProviderInfoExtention + public static class GoogleDriveProviderInfoExtention { public static void Register(DIHelper dIHelper) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoSelector.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoSelector.cs index f5d1510da5..57d36beb93 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoSelector.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoSelector.cs @@ -64,7 +64,7 @@ namespace ASC.Files.Thirdparty.OneDrive } } - public class OneDriveDaoSelectorExtension + public static class OneDriveDaoSelectorExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs index 475e472427..bc3c5e4562 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs @@ -258,7 +258,7 @@ namespace ASC.Files.Thirdparty.OneDrive } } } - public class OneDriveProviderInfoExtention + public static class OneDriveProviderInfoExtention { public static void Register(DIHelper dIHelper) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs index 43b626445a..a3900ab6c2 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs @@ -593,7 +593,7 @@ namespace ASC.Files.Thirdparty } } - public class ProviderAccountDaoExtension + public static class ProviderAccountDaoExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoSelector.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoSelector.cs index 618b3bfb60..4159c99fb1 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoSelector.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointDaoSelector.cs @@ -77,7 +77,7 @@ namespace ASC.Files.Thirdparty.SharePoint } } - public class SharePointDaoSelectorExtension + public static class SharePointDaoSelectorExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoSelector.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoSelector.cs index 7caba01af8..b9ab818ed1 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoSelector.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoSelector.cs @@ -64,7 +64,7 @@ namespace ASC.Files.Thirdparty.Sharpbox } } - public class SharpBoxDaoSelectorExtension + public static class SharpBoxDaoSelectorExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs b/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs index e2c13b3938..3cb2a3b6a1 100644 --- a/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs +++ b/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs @@ -258,7 +258,7 @@ namespace ASC.Files.Core.Services.NotifyService } } - public class NotifyClientExtension + public static class NotifyClientExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperationsManager.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperationsManager.cs index a537332643..3242aac74d 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperationsManager.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperationsManager.cs @@ -254,7 +254,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations } } - public class FileOperationsManagerHelperExtention + public static class FileOperationsManagerHelperExtention { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/ThirdPartyApp/IThirdPartyApp.cs b/products/ASC.Files/Core/ThirdPartyApp/IThirdPartyApp.cs index fec6bb4e06..2d9df9b6a8 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/IThirdPartyApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/IThirdPartyApp.cs @@ -46,7 +46,7 @@ namespace ASC.Web.Files.ThirdPartyApp void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream); } - public class ThirdPartySelector + public static class ThirdPartySelector { public const string AppAttr = "app"; public static readonly Regex AppRegex = new Regex("^" + AppAttr + @"-(\S+)\|(\S+)$", RegexOptions.Singleline | RegexOptions.Compiled); diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index 9823b5f056..d382ca9889 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -927,7 +927,7 @@ namespace ASC.Web.Files.Utils public string ServerRootPath { get; set; } } - public class FileConverterQueueExtension + public static class FileConverterQueueExtension { public static void Register(DIHelper services) { @@ -935,7 +935,7 @@ namespace ASC.Web.Files.Utils } } - public class FileConverterExtension + public static class FileConverterExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Core/Utils/FileMarker.cs b/products/ASC.Files/Core/Utils/FileMarker.cs index c73370ba48..78fd5938f9 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -798,7 +798,7 @@ namespace ASC.Web.Files.Utils public Guid CurrentAccountId { get; set; } } - public class FileMarkerExtention + public static class FileMarkerExtention { public static void Register(DIHelper services) { diff --git a/products/ASC.Files/Server/Program.cs b/products/ASC.Files/Server/Program.cs index 302baa18db..e0f1d0df48 100644 --- a/products/ASC.Files/Server/Program.cs +++ b/products/ASC.Files/Server/Program.cs @@ -15,7 +15,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.Files { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/products/ASC.Files/Service/Program.cs b/products/ASC.Files/Service/Program.cs index e4c4d7e261..ab5a266afb 100644 --- a/products/ASC.Files/Service/Program.cs +++ b/products/ASC.Files/Service/Program.cs @@ -22,7 +22,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.Files.Service { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/products/ASC.Files/Service/Thumbnail/Worker.cs b/products/ASC.Files/Service/Thumbnail/Worker.cs index 663b788853..433d68e4c0 100644 --- a/products/ASC.Files/Service/Thumbnail/Worker.cs +++ b/products/ASC.Files/Service/Thumbnail/Worker.cs @@ -106,7 +106,7 @@ namespace ASC.Files.ThumbnailBuilder } } - public class WorkerExtension + public static class WorkerExtension { public static void Register(DIHelper services) { diff --git a/products/ASC.People/Server/Program.cs b/products/ASC.People/Server/Program.cs index 12409ef8af..234c25f7df 100644 --- a/products/ASC.People/Server/Program.cs +++ b/products/ASC.People/Server/Program.cs @@ -15,7 +15,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.People { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/web/ASC.Web.Api/Program.cs b/web/ASC.Web.Api/Program.cs index f79fc93f87..c081b2a6a6 100644 --- a/web/ASC.Web.Api/Program.cs +++ b/web/ASC.Web.Api/Program.cs @@ -15,7 +15,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.Web.Api { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/web/ASC.Web.Core/CommonPhotoManager.cs b/web/ASC.Web.Core/CommonPhotoManager.cs index 073bfa5d9f..05df7623f8 100644 --- a/web/ASC.Web.Core/CommonPhotoManager.cs +++ b/web/ASC.Web.Core/CommonPhotoManager.cs @@ -36,7 +36,7 @@ using SixLabors.ImageSharp.Processing; namespace ASC.Web.Core { - public class CommonPhotoManager + public static class CommonPhotoManager { public static Image DoThumbnail(Image image, Size size, bool crop, bool transparent, bool rectangle) diff --git a/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs b/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs index 3ed1a568aa..c19fd9e50a 100644 --- a/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs +++ b/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs @@ -28,7 +28,7 @@ using System; namespace ASC.Web.Core.Helpers { - public class GrammaticalHelper + public static class GrammaticalHelper { public static string ChooseNumeralCase(int number, string nominative, string genitiveSingular, string genitivePlural) { diff --git a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs index 8726484552..2a381adb07 100644 --- a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs +++ b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs @@ -455,7 +455,7 @@ namespace ASC.Web.Studio.Core.Notify } } - public class NotifyConfigurationExtension + public static class NotifyConfigurationExtension { public static void Register(DIHelper services) { diff --git a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs index 5d82611ae7..023b30a159 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -1167,7 +1167,7 @@ namespace ASC.Web.Studio.Core.Notify } } - public class StudioPeriodicNotifyExtension + public static class StudioPeriodicNotifyExtension { public static void Register(DIHelper services) { diff --git a/web/ASC.Web.Core/Notify/Tags.cs b/web/ASC.Web.Core/Notify/Tags.cs index 058685ac9d..9bc5de9f29 100644 --- a/web/ASC.Web.Core/Notify/Tags.cs +++ b/web/ASC.Web.Core/Notify/Tags.cs @@ -82,7 +82,7 @@ namespace ASC.Web.Studio.Core.Notify public const string SmtpPort = "SmtpPort"; } - public sealed class CommonTags + public static class CommonTags { public const string VirtualRootPath = "__VirtualRootPath"; diff --git a/web/ASC.Web.Core/SecutiryConstants.cs b/web/ASC.Web.Core/SecutiryConstants.cs index 50e9146bee..5aeeb83070 100644 --- a/web/ASC.Web.Core/SecutiryConstants.cs +++ b/web/ASC.Web.Core/SecutiryConstants.cs @@ -28,7 +28,7 @@ using ASC.Common.Security.Authorizing; namespace ASC.Web.Studio.Core { - public sealed class SecutiryConstants + public static class SecutiryConstants { public static readonly Action EditPortalSettings = new Action(new System.Guid("{60DB830E-80A8-4997-8B83-3D6EA525749B}"), "Edit Portal Settings"); } diff --git a/web/ASC.Web.Core/Users/UserPhotoManager.cs b/web/ASC.Web.Core/Users/UserPhotoManager.cs index 3bcaa95604..8bf97a2294 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -1025,7 +1025,7 @@ namespace ASC.Web.Core.Users } } - public class ResizeWorkerItemExtension + public static class ResizeWorkerItemExtension { public static void Register(DIHelper services) { diff --git a/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs b/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs index d58dbc6f7d..bd21457672 100644 --- a/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs @@ -35,7 +35,7 @@ using SixLabors.ImageSharp.Processing; namespace ASC.Web.Core.Users { - public class UserPhotoThumbnailManager + public static class UserPhotoThumbnailManager { public static List<ThumbnailItem> SaveThumbnails(UserPhotoManager userPhotoManager, SettingsManager settingsManager, int x, int y, int width, int height, Guid userId) { diff --git a/web/ASC.Web.HealthChecks.UI/Program.cs b/web/ASC.Web.HealthChecks.UI/Program.cs index 5261aa70ec..e0f94d0fe8 100644 --- a/web/ASC.Web.HealthChecks.UI/Program.cs +++ b/web/ASC.Web.HealthChecks.UI/Program.cs @@ -7,7 +7,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.Web.HealthChecks.UI { - public class Program + public static class Program { public async static Task Main(string[] args) { diff --git a/web/ASC.Web.Studio/Program.cs b/web/ASC.Web.Studio/Program.cs index fb8a125ffb..d821a0dc7f 100644 --- a/web/ASC.Web.Studio/Program.cs +++ b/web/ASC.Web.Studio/Program.cs @@ -15,7 +15,7 @@ using Microsoft.Extensions.Hosting; namespace ASC.Web.Studio { - public class Program + public static class Program { public async static Task Main(string[] args) { From cd12b41cc67a6e88d1785d1af026528541ec94b2 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 14:01:52 +0300 Subject: [PATCH 079/167] analizators/s1125 --- common/ASC.Data.Backup.Core/Storage/BackupRepository.cs | 2 +- common/ASC.Textile/Blocks/GlyphBlockModifier.cs | 2 +- common/ASC.Textile/States/TableFormatterState.cs | 2 +- products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs | 2 +- web/ASC.Web.Api/Controllers/SettingsController.cs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs b/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs index a3f7e74fa9..3d0ff495d5 100644 --- a/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs +++ b/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs @@ -73,7 +73,7 @@ namespace ASC.Data.Backup.Storage public List<BackupRecord> GetScheduledBackupRecords() { - return BackupContext.Backups.Where(b => b.IsScheduled == true).ToList(); + return BackupContext.Backups.Where(b => b.IsScheduled).ToList(); } public List<BackupRecord> GetBackupRecordsByTenantId(int tenantId) diff --git a/common/ASC.Textile/Blocks/GlyphBlockModifier.cs b/common/ASC.Textile/Blocks/GlyphBlockModifier.cs index 716707a299..3426666833 100644 --- a/common/ASC.Textile/Blocks/GlyphBlockModifier.cs +++ b/common/ASC.Textile/Blocks/GlyphBlockModifier.cs @@ -75,7 +75,7 @@ namespace Textile.Blocks } // do htmlspecial if between <code> - if (codepre == true) + if (codepre) { //TODO: htmlspecialchars(line) //line = Regex.Replace(line, @"<(\/?" + offtags + ")>", "<$1>"); diff --git a/common/ASC.Textile/States/TableFormatterState.cs b/common/ASC.Textile/States/TableFormatterState.cs index e60dd91b58..93dbb96189 100644 --- a/common/ASC.Textile/States/TableFormatterState.cs +++ b/common/ASC.Textile/States/TableFormatterState.cs @@ -58,7 +58,7 @@ namespace Textile.States @"(\.\s?)?(?<tag>\|)" + @"(?<content>.*)(?=\|)" ); - return (m.Success == false); + return (!m.Success); } protected string FormattedStylesAndAlignment() diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index 3e760291e4..e91fcb4a02 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -151,7 +151,7 @@ namespace ASC.Files.Core.Data { if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(title); - var query = GetFileQuery(r => r.Title == title && r.CurrentVersion == true && r.FolderId == parentId) + var query = GetFileQuery(r => r.Title == title && r.CurrentVersion && r.FolderId == parentId) .AsNoTracking() .OrderBy(r => r.CreateOn); diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index 2d5b62d775..5f427f9933 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -2315,7 +2315,7 @@ namespace ASC.Api.Settings foreach (var tenant in tenants) { var progress = BackupAjaxHandler.GetBackupProgress(tenant.TenantId); - if (progress != null && progress.IsCompleted == false) + if (progress != null && !progress.IsCompleted) { throw new Exception(); } From 2029c34f9c78db6a06a3308df38e92538bbfe97c Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 14:02:17 +0300 Subject: [PATCH 080/167] analizators/s1121 --- common/ASC.Core.Common/Billing/BillingClient.cs | 16 ++++++++++++---- .../ASC.Core.Common/Caching/CachedAzService.cs | 5 +++-- .../Caching/CachedSubscriptionService.cs | 3 ++- .../Caching/CachedTenantService.cs | 5 +++-- .../Context/Impl/CoreConfiguration.cs | 5 +++-- common/ASC.Core.Common/Core/DBResourceManager.cs | 5 +++-- common/ASC.Core.Common/Data/DbSettingsManager.cs | 12 ++++++++++-- common/ASC.Core.Common/Data/DbTenantService.cs | 10 ++++++---- common/ASC.Core.Common/Notify/Cron/TreeSet.cs | 4 ++-- .../Tasks/BackupPortalTask.cs | 4 ++-- common/ASC.FederatedLogin/AccountLinker.cs | 3 ++- common/ASC.IPSecurity/IPRestrictionsService.cs | 3 ++- common/ASC.IPSecurity/IPSecurity.cs | 4 +++- .../ASC.ElasticSearch/Engine/BaseIndexer.cs | 10 ++++++---- .../Core/Core/Dao/TeamlabDao/AbstractDao.cs | 8 +++++++- .../ASC.Files/Core/Core/Entries/EditHistory.cs | 4 ++-- .../Core/Core/Thirdparty/Box/BoxFileDao.cs | 8 ++++---- .../Core/Thirdparty/Dropbox/DropboxFileDao.cs | 8 ++++---- .../Thirdparty/GoogleDrive/GoogleDriveFileDao.cs | 8 ++++---- .../Core/Thirdparty/OneDrive/OneDriveFileDao.cs | 8 ++++---- .../Core/Core/Thirdparty/ProviderAccountDao.cs | 9 ++++++++- .../Thirdparty/ProviderDao/ProviderDaoBase.cs | 9 ++++++++- .../Thirdparty/SharePoint/SharePointFileDao.cs | 8 ++++---- .../Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs | 8 ++++---- .../DocumentService/DocumentServiceConnector.cs | 4 ++-- .../DocumentService/DocumentServiceHelper.cs | 4 ++-- products/ASC.Files/Core/Utils/EntryManager.cs | 4 +++- .../Server/Controllers/PeopleController.cs | 4 ++-- web/ASC.Web.Core/Mobile/MobileDetector.cs | 3 ++- web/ASC.Web.Core/Sms/SmsProvider.cs | 4 ++-- web/ASC.Web.Core/Utility/TenantExtra.cs | 8 ++++---- web/ASC.Web.Core/WebItemSecurity.cs | 3 ++- 32 files changed, 127 insertions(+), 74 deletions(-) diff --git a/common/ASC.Core.Common/Billing/BillingClient.cs b/common/ASC.Core.Common/Billing/BillingClient.cs index 3fc3814246..f51f9aca6b 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -161,13 +161,21 @@ namespace ASC.Core.Billing string url; var paymentUrl = (Uri)null; var upgradeUrl = (Uri)null; - if (paymentUrls.TryGetValue(p, out url) && !string.IsNullOrEmpty(url = ToUrl(url))) + if (paymentUrls.TryGetValue(p, out url)) { - paymentUrl = new Uri(url); + url = ToUrl(url); + if (!string.IsNullOrEmpty(url)) + { + paymentUrl = new Uri(url); + } } - if (upgradeUrls.TryGetValue(p, out url) && !string.IsNullOrEmpty(url = ToUrl(url))) + if (upgradeUrls.TryGetValue(p, out url)) { - upgradeUrl = new Uri(url); + url = ToUrl(url); + if (!string.IsNullOrEmpty(url)) + { + upgradeUrl = new Uri(url); + } } urls[p] = Tuple.Create(paymentUrl, upgradeUrl); } diff --git a/common/ASC.Core.Common/Caching/CachedAzService.cs b/common/ASC.Core.Common/Caching/CachedAzService.cs index 9aecec13d9..50e9817d2f 100644 --- a/common/ASC.Core.Common/Caching/CachedAzService.cs +++ b/common/ASC.Core.Common/Caching/CachedAzService.cs @@ -100,8 +100,9 @@ namespace ASC.Core.Caching var aces = Cache.Get<AzRecordStore>(key); if (aces == null) { - var records = service.GetAces(tenant, default); - Cache.Insert(key, aces = new AzRecordStore(records), DateTime.UtcNow.Add(CacheExpiration)); + var records = service.GetAces(tenant, default); + aces = new AzRecordStore(records); + Cache.Insert(key, aces, DateTime.UtcNow.Add(CacheExpiration)); } return aces; } diff --git a/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs b/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs index fbe6d7bc15..e8b4b6a746 100644 --- a/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs +++ b/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs @@ -201,7 +201,8 @@ namespace ASC.Core.Caching { var records = service.GetSubscriptions(tenant, sourceId, actionId); var methods = service.GetSubscriptionMethods(tenant, sourceId, actionId, null); - cache.Insert(key, store = new SubsciptionsStore(records, methods), DateTime.UtcNow.Add(CacheExpiration)); + store = new SubsciptionsStore(records, methods); + cache.Insert(key, store, DateTime.UtcNow.Add(CacheExpiration)); } return store; } diff --git a/common/ASC.Core.Common/Caching/CachedTenantService.cs b/common/ASC.Core.Common/Caching/CachedTenantService.cs index 8981515906..b9dbc6553f 100644 --- a/common/ASC.Core.Common/Caching/CachedTenantService.cs +++ b/common/ASC.Core.Common/Caching/CachedTenantService.cs @@ -73,8 +73,9 @@ namespace ASC.Core.Caching { var store = Cache.Get<TenantStore>(KEY); if (store == null) - { - Cache.Insert(KEY, store = new TenantStore(), DateTime.UtcNow.Add(CacheExpiration)); + { + store = new TenantStore(); + Cache.Insert(KEY, store, DateTime.UtcNow.Add(CacheExpiration)); } return store; } diff --git a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs index dc54200cae..153c890ffe 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -214,8 +214,9 @@ namespace ASC.Core // thread safe key = GetSetting("PortalId"); if (string.IsNullOrEmpty(key)) - { - SaveSetting("PortalId", key = Guid.NewGuid().ToString()); + { + key = Guid.NewGuid().ToString(); + SaveSetting("PortalId", key); } } } diff --git a/common/ASC.Core.Common/Core/DBResourceManager.cs b/common/ASC.Core.Common/Core/DBResourceManager.cs index 714b9bb9cd..0ef86e4d58 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -257,7 +257,8 @@ namespace TMResourceData if (dic == null) { var policy = cacheTimeout == TimeSpan.Zero ? null : new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.Add(cacheTimeout) }; - cache.Set(key, dic = LoadResourceSet(filename, culture), policy); + dic = LoadResourceSet(filename, culture); + cache.Set(key, dic, policy); } } } @@ -283,7 +284,7 @@ namespace TMResourceData { private readonly ILog log; private readonly ConcurrentDictionary<int, string> whiteLabelDictionary; - public string DefaultLogoText { get; } + public string DefaultLogoText { get; set; } private IConfiguration Configuration { get; } diff --git a/common/ASC.Core.Common/Data/DbSettingsManager.cs b/common/ASC.Core.Common/Data/DbSettingsManager.cs index d83a3c85d7..7dd6fdaebc 100644 --- a/common/ASC.Core.Common/Data/DbSettingsManager.cs +++ b/common/ASC.Core.Common/Data/DbSettingsManager.cs @@ -148,13 +148,21 @@ namespace ASC.Core.Data private int tenantID; private int TenantID { - get { return tenantID != 0 ? tenantID : (tenantID = TenantManager.GetCurrentTenant().TenantId); } + get + { + if (tenantID == 0) tenantID = TenantManager.GetCurrentTenant().TenantId; + return tenantID; + } } // private Guid? currentUserID; private Guid CurrentUserID { - get { return ((Guid?)(currentUserID ??= AuthContext.CurrentAccount.ID)).Value; } + get + { + currentUserID ??= AuthContext.CurrentAccount.ID; + return currentUserID.Value; + } } public bool SaveSettings<T>(T settings, int tenantId) where T : ISettings diff --git a/common/ASC.Core.Common/Data/DbTenantService.cs b/common/ASC.Core.Common/Data/DbTenantService.cs index 54598f6ef4..ad2caf1a04 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -176,7 +176,7 @@ namespace ASC.Core.Data }) .Where(r => r.User.Status == EmployeeStatus.Active) .Where(r => r.DbTenant.Status == TenantStatus.Active) - .Where(r => r.User.Removed == false); + .Where(r => !r.User.Removed); if (passwordHash == null) { @@ -292,7 +292,9 @@ namespace ASC.Core.Data .Where(r => r.DefaultVersion == 1 || r.Id == 0) .OrderByDescending(r => r.Id) .Select(r => r.Id) - .FirstOrDefault(); + .FirstOrDefault(); + + t.LastModified = DateTime.UtcNow; var tenant = new DbTenant { @@ -311,7 +313,7 @@ namespace ASC.Core.Data Status = t.Status, StatusChanged = t.StatusChangeDate, PaymentId = t.PaymentId, - LastModified = t.LastModified = DateTime.UtcNow, + LastModified = t.LastModified, Industry = t.Industry, Spam = t.Spam, Calls = t.Calls @@ -413,7 +415,7 @@ namespace ASC.Core.Data public IEnumerable<TenantVersion> GetTenantVersions() { return TenantDbContext.TenantVersion - .Where(r => r.Visible == true) + .Where(r => r.Visible) .Select(r => new TenantVersion(r.Id, r.Version)) .ToList(); } diff --git a/common/ASC.Core.Common/Notify/Cron/TreeSet.cs b/common/ASC.Core.Common/Notify/Cron/TreeSet.cs index 4624d5528c..5caa0046ad 100644 --- a/common/ASC.Core.Common/Notify/Cron/TreeSet.cs +++ b/common/ASC.Core.Common/Notify/Cron/TreeSet.cs @@ -139,8 +139,8 @@ namespace ASC.Notify.Cron private bool AddWithoutSorting(object obj) { - bool inserted; - if (!(inserted = Contains(obj))) + bool inserted = Contains(obj); + if (!inserted) { base.Add(obj); } diff --git a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs index 050127ab14..f5ddd47fe4 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -392,8 +392,8 @@ namespace ASC.Data.Backup.Tasks private void SaveToFile(string path, string t, IReadOnlyCollection<string> columns, List<object[]> data) { Logger.DebugFormat("save to file {0}", t); - List<object[]> portion; - while ((portion = data.Take(BatchLimit).ToList()).Count > 0) + List<object[]> portion = data.Take(BatchLimit).ToList(); + while (portion.Count > 0) { using (var sw = new StreamWriter(path, true)) using (var writer = new JsonTextWriter(sw)) diff --git a/common/ASC.FederatedLogin/AccountLinker.cs b/common/ASC.FederatedLogin/AccountLinker.cs index 88b01e94b5..45794e2c74 100644 --- a/common/ASC.FederatedLogin/AccountLinker.cs +++ b/common/ASC.FederatedLogin/AccountLinker.cs @@ -65,7 +65,8 @@ namespace ASC.FederatedLogin var profiles = cache.Get<List<LoginProfile>>(obj); if (profiles == null) { - cache.Insert(obj, profiles = fromDb(obj), DateTime.UtcNow + TimeSpan.FromMinutes(10)); + profiles = fromDb(obj); + cache.Insert(obj, profiles, DateTime.UtcNow + TimeSpan.FromMinutes(10)); } return profiles; } diff --git a/common/ASC.IPSecurity/IPRestrictionsService.cs b/common/ASC.IPSecurity/IPRestrictionsService.cs index aa4d5483d1..3f459bf4df 100644 --- a/common/ASC.IPSecurity/IPRestrictionsService.cs +++ b/common/ASC.IPSecurity/IPRestrictionsService.cs @@ -77,7 +77,8 @@ namespace ASC.IPSecurity var restrictions = cache.Get<List<IPRestriction>>(key); if (restrictions == null) { - cache.Insert(key, restrictions = IPRestrictionsRepository.Get(tenant), timeout); + restrictions = IPRestrictionsRepository.Get(tenant); + cache.Insert(key, restrictions, timeout); } return restrictions; } diff --git a/common/ASC.IPSecurity/IPSecurity.cs b/common/ASC.IPSecurity/IPSecurity.cs index dda9889f25..52996a77ad 100644 --- a/common/ASC.IPSecurity/IPSecurity.cs +++ b/common/ASC.IPSecurity/IPSecurity.cs @@ -94,7 +94,9 @@ namespace ASC.IPSecurity if (restrictions.Count == 0) return true; - if (string.IsNullOrWhiteSpace(requestIps = CurrentIpForTest)) + requestIps = CurrentIpForTest; + + if (string.IsNullOrWhiteSpace(requestIps)) { var request = HttpContextAccessor.HttpContext.Request; requestIps = request.Headers["X-Forwarded-For"].FirstOrDefault() ?? request.GetUserHostAddress(); diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index 5841592e67..82c61b09df 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -529,8 +529,9 @@ namespace ASC.ElasticSearch var sourceExprText = ""; - - while (!string.IsNullOrEmpty(name = TryGetName(expression, out var member))) + + name = TryGetName(expression, out var member); + while (!string.IsNullOrEmpty(name)) { sourceExprText = "." + name + sourceExprText; expression = member.Expression; @@ -583,8 +584,9 @@ namespace ASC.ElasticSearch var expression = fields.Body; var sourceExprText = ""; - - while (!string.IsNullOrEmpty(name = TryGetName(expression, out var member))) + + name = TryGetName(expression, out var member); + while (!string.IsNullOrEmpty(name)) { sourceExprText = "." + name + sourceExprText; expression = member.Expression; diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/AbstractDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/AbstractDao.cs index 8232d5e40e..be4c017f4c 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/AbstractDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/AbstractDao.cs @@ -56,7 +56,13 @@ namespace ASC.Files.Core.Data public TenantDbContext TenantDbContext { get => LazyTenantDbContext.Value; } private int tenantID; - protected internal int TenantID { get => tenantID != 0 ? tenantID : (tenantID = TenantManager.GetCurrentTenant().TenantId); } + protected internal int TenantID { + get + { + if (tenantID == 0) tenantID = TenantManager.GetCurrentTenant().TenantId; + return tenantID; + } + } protected UserManager UserManager { get; } protected TenantManager TenantManager { get; } protected TenantUtil TenantUtil { get; } diff --git a/products/ASC.Files/Core/Core/Entries/EditHistory.cs b/products/ASC.Files/Core/Core/Entries/EditHistory.cs index b7f6eadcbc..50791a410d 100644 --- a/products/ASC.Files/Core/Core/Entries/EditHistory.cs +++ b/products/ASC.Files/Core/Core/Entries/EditHistory.cs @@ -147,11 +147,11 @@ namespace ASC.Files.Core { get { - UserInfo user; + UserInfo user = UserManager.GetUsers(Id); return Id.Equals(Guid.Empty) || Id.Equals(ASC.Core.Configuration.Constants.Guest.ID) - || (user = UserManager.GetUsers(Id)).Equals(Constants.LostUser) + || user.Equals(Constants.LostUser) ? string.IsNullOrEmpty(_name) ? FilesCommonResource.Guest : _name diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs index 627b4ed816..c7cf70574c 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs @@ -151,8 +151,8 @@ namespace ASC.Files.Thirdparty.Box case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: @@ -209,8 +209,8 @@ namespace ASC.Files.Thirdparty.Box case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs index 540e57aaa9..901a2fde36 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs @@ -155,8 +155,8 @@ namespace ASC.Files.Thirdparty.Dropbox case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: @@ -213,8 +213,8 @@ namespace ASC.Files.Thirdparty.Dropbox case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs index ffaf005bb4..08a92a8074 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs @@ -152,8 +152,8 @@ namespace ASC.Files.Thirdparty.GoogleDrive case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: @@ -210,8 +210,8 @@ namespace ASC.Files.Thirdparty.GoogleDrive case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs index 60f36ce492..3c9cd22b84 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs @@ -151,8 +151,8 @@ namespace ASC.Files.Thirdparty.OneDrive case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: @@ -209,8 +209,8 @@ namespace ASC.Files.Thirdparty.OneDrive case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs index a3900ab6c2..8bc41e0058 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs @@ -81,7 +81,14 @@ namespace ASC.Files.Thirdparty internal class ProviderAccountDao : IProviderDao { private int tenantID; - protected int TenantID { get => tenantID != 0 ? tenantID : (tenantID = TenantManager.GetCurrentTenant().TenantId); } + protected int TenantID + { + get + { + if (tenantID == 0) tenantID = TenantManager.GetCurrentTenant().TenantId; + return tenantID; + } + } private Lazy<FilesDbContext> LazyFilesDbContext { get; } private FilesDbContext FilesDbContext { get => LazyFilesDbContext.Value; } public ILog Logger { get; } diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderDaoBase.cs index b08a6482fb..2c37a93abc 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderDaoBase.cs @@ -62,7 +62,14 @@ namespace ASC.Files.Thirdparty.ProviderDao } private int tenantID; - private int TenantID { get => tenantID != 0 ? tenantID : (tenantID = TenantManager.GetCurrentTenant().TenantId); } + private int TenantID + { + get + { + if (tenantID == 0) tenantID = TenantManager.GetCurrentTenant().TenantId; + return tenantID; + } + } public ProviderDaoBase( IServiceProvider serviceProvider, diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs index 86c11d4058..ff159ff5a9 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs @@ -143,8 +143,8 @@ namespace ASC.Files.Thirdparty.SharePoint case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: @@ -201,8 +201,8 @@ namespace ASC.Files.Thirdparty.SharePoint case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs index 9b0e6829bc..b9783258ef 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs @@ -151,8 +151,8 @@ namespace ASC.Files.Thirdparty.Sharpbox case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: @@ -213,8 +213,8 @@ namespace ASC.Files.Thirdparty.Sharpbox case FilterType.MediaOnly: files = files.Where(x => { - FileType fileType; - return (fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video; + FileType fileType = FileUtility.GetFileTypeByFileName(x.Title); + return fileType == FileType.Audio || fileType == FileType.Video; }); break; case FilterType.ByExtension: diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs index 04829daa84..6ec7cff64d 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs @@ -335,9 +335,9 @@ namespace ASC.Web.Files.Services.DocumentService if (string.IsNullOrEmpty(docServicePortalUrl)) { - Tenant tenant; + Tenant tenant = TenantManager.GetCurrentTenant(); if (!TenantExtra.Saas - || string.IsNullOrEmpty((tenant = TenantManager.GetCurrentTenant()).MappedDomain) + || string.IsNullOrEmpty(tenant.MappedDomain) || !url.StartsWith("https://" + tenant.MappedDomain)) { return url; diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs index 9d3baf7539..a7664ccc0f 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs @@ -251,10 +251,10 @@ namespace ASC.Web.Files.Services.DocumentService { rightChangeHistory = false; - bool coauth; + bool coauth = FileUtility.CanCoAuhtoring(file.Title); if ((editPossible || reviewPossible || fillFormsPossible || commentPossible) && tryCoauth - && (!(coauth = FileUtility.CanCoAuhtoring(file.Title)) || FileTracker.IsEditingAlone(file.ID))) + && (!coauth || FileTracker.IsEditingAlone(file.ID))) { if (tryEdit) { diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index acddd669a5..ee8a8f0e9e 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -752,8 +752,10 @@ namespace ASC.Web.Files.Utils { entries = entries.Where(where).ToList(); } + + searchText = (searchText ?? string.Empty).ToLower().Trim(); - if ((!searchInContent || filter == FilterType.ByExtension) && !string.IsNullOrEmpty(searchText = (searchText ?? string.Empty).ToLower().Trim())) + if ((!searchInContent || filter == FilterType.ByExtension) && !string.IsNullOrEmpty(searchText)) { entries = entries.Where(f => f.Title.Contains(searchText, StringComparison.InvariantCultureIgnoreCase)).ToList(); } diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index f70a34b548..618e5c2305 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -1175,8 +1175,8 @@ namespace ASC.Employee.Core.Controllers private object SendUserPassword(MemberModel memberModel) { - string error; - if (!string.IsNullOrEmpty(error = UserManagerWrapper.SendUserPassword(memberModel.Email))) + string error = UserManagerWrapper.SendUserPassword(memberModel.Email); + if (!string.IsNullOrEmpty(error)) { Log.ErrorFormat("Password recovery ({0}): {1}", memberModel.Email, error); } diff --git a/web/ASC.Web.Core/Mobile/MobileDetector.cs b/web/ASC.Web.Core/Mobile/MobileDetector.cs index 1d289aa8be..e06196ee79 100644 --- a/web/ASC.Web.Core/Mobile/MobileDetector.cs +++ b/web/ASC.Web.Core/Mobile/MobileDetector.cs @@ -78,7 +78,8 @@ namespace ASC.Web.Core.Mobile } else { - cache.Insert(key, (result = regex.IsMatch(ua)).ToString(), TimeSpan.FromMinutes(10)); + result = regex.IsMatch(ua); + cache.Insert(key, result.ToString(), TimeSpan.FromMinutes(10)); } } return result.GetValueOrDefault(); diff --git a/web/ASC.Web.Core/Sms/SmsProvider.cs b/web/ASC.Web.Core/Sms/SmsProvider.cs index fd27730e5c..af3e3d9e9d 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -83,9 +83,9 @@ namespace ASC.Web.Core.Sms provider = ClickatellProvider; } - string smsUsa; + string smsUsa = ClickatellProvider["clickatellUSA"]; if (ClickatellUSAProvider.Enable() - && !string.IsNullOrEmpty(smsUsa = ClickatellProvider["clickatellUSA"]) && Regex.IsMatch(number, smsUsa)) + && !string.IsNullOrEmpty(smsUsa) && Regex.IsMatch(number, smsUsa)) { provider = ClickatellUSAProvider; } diff --git a/web/ASC.Web.Core/Utility/TenantExtra.cs b/web/ASC.Web.Core/Utility/TenantExtra.cs index b102438855..50b287e1f1 100644 --- a/web/ASC.Web.Core/Utility/TenantExtra.cs +++ b/web/ASC.Web.Core/Utility/TenantExtra.cs @@ -207,9 +207,9 @@ namespace ASC.Web.Studio.Utility { get { - DateTime licenseDay; + DateTime licenseDay = GetCurrentTariff().LicenseDate.Date; return CoreBaseSettings.Standalone - && (licenseDay = GetCurrentTariff().LicenseDate.Date) < DateTime.Today + && licenseDay < DateTime.Today && licenseDay < LicenseReader.VersionReleaseDate; } } @@ -224,9 +224,9 @@ namespace ASC.Web.Studio.Utility public bool IsNotPaid() { - Tariff tariff; + Tariff tariff = GetCurrentTariff(); return EnableTariffSettings - && ((tariff = GetCurrentTariff()).State >= TariffState.NotPaid + && (tariff.State >= TariffState.NotPaid || Enterprise && !EnterprisePaid && tariff.LicenseDate == DateTime.MaxValue); } diff --git a/web/ASC.Web.Core/WebItemSecurity.cs b/web/ASC.Web.Core/WebItemSecurity.cs index 9c47739209..bc143a935a 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -84,7 +84,8 @@ namespace ASC.Web.Core var dic = Get(tenantId); if (dic == null) { - Cache.Insert(GetCacheKey(tenantId), dic = new Dictionary<string, bool>(), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); + dic = new Dictionary<string, bool>(); + Cache.Insert(GetCacheKey(tenantId), dic, DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); } return dic; From 3d635a48243dd1966a762c42a6c0e3687ee45597 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:12:05 +0300 Subject: [PATCH 081/167] analizators/1643 --- .../Authorizing/AuthorizingException.cs | 7 ++-- .../Notify/Cron/CronExpression.cs | 7 ++-- .../Tasks/PortalTaskBase.cs | 5 +-- common/ASC.Notify.Textile/JabberStyler.cs | 13 +++++--- .../ASC.Textile/Blocks/GlyphBlockModifier.cs | 10 +++--- .../FileOperations/FileMoveCopyOperation.cs | 32 +++++++++++-------- web/ASC.Web.Core/Users/UserManagerWrapper.cs | 6 ++-- 7 files changed, 47 insertions(+), 33 deletions(-) diff --git a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs index 3f980fb994..3b2e59f9fa 100644 --- a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs +++ b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs @@ -28,6 +28,7 @@ using System; using System.Runtime.Serialization; +using System.Text; #endregion @@ -95,7 +96,8 @@ namespace ASC.Common.Security.Authorizing if (denyActions == null || denyActions.Length == 0) throw new ArgumentNullException(nameof(denyActions)); if (actions.Length != denySubjects.Length || actions.Length != denyActions.Length) throw new ArgumentException(); - var reasons = ""; + + var sb = new StringBuilder(); for (var i = 0; i < actions.Length; i++) { var action = actions[i]; @@ -109,8 +111,9 @@ namespace ASC.Common.Security.Authorizing reason = $"{action.Name}: access denied."; if (i != actions.Length - 1) reason += ", "; - reasons += reason; + sb.Append(reason); } + var reasons = sb.ToString(); var sactions = ""; Array.ForEach(actions, action => { sactions += action.ToString() + ", "; }); var message = $"\"{(subject is IRole ? "role:" : "") + subject.Name}\" access denied \"{sactions}\". Cause: {reasons}."; diff --git a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs index 0a28a3cdc8..066ce000a5 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -1004,10 +1004,11 @@ namespace ASC.Notify.Cron protected virtual ValueSet GetValue(int v, string s, int i) { var c = s[i]; - var s1 = v.ToString(CultureInfo.InvariantCulture); + var sb = new StringBuilder(); + sb.Append(v.ToString(CultureInfo.InvariantCulture)); while (c >= '0' && c <= '9') { - s1 += c; + sb.Append(c); i++; if (i >= s.Length) { @@ -1024,7 +1025,7 @@ namespace ASC.Notify.Cron { val.Pos = i + 1; } - val.TheValue = Convert.ToInt32(s1, CultureInfo.InvariantCulture); + val.TheValue = Convert.ToInt32(sb.ToString(), CultureInfo.InvariantCulture); return val; } diff --git a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs index af4a0a5cd9..fe6aae0e9e 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -294,6 +294,7 @@ namespace ASC.Data.Backup.Tasks while ((commandText = await reader.ReadLineAsync()) != null) { + var sb = new StringBuilder(commandText); while (!commandText.EndsWith(delimiter)) { var newline = await reader.ReadLineAsync(); @@ -301,9 +302,9 @@ namespace ASC.Data.Backup.Tasks { break; } - commandText += newline; + sb.Append(newline); } - + commandText = sb.ToString(); try { diff --git a/common/ASC.Notify.Textile/JabberStyler.cs b/common/ASC.Notify.Textile/JabberStyler.cs index 3a2f26c493..5ea7a7547e 100644 --- a/common/ASC.Notify.Textile/JabberStyler.cs +++ b/common/ASC.Notify.Textile/JabberStyler.cs @@ -25,6 +25,7 @@ using System; +using System.Text; using System.Text.RegularExpressions; using System.Web; @@ -48,25 +49,27 @@ namespace ASC.Notify.Textile public void ApplyFormating(NoticeMessage message) { - var body = string.Empty; + var sb = new StringBuilder(); if (!string.IsNullOrEmpty(message.Subject)) { - body += VelocityArguments.Replace(message.Subject, ArgMatchReplace) + Environment.NewLine; + sb.AppendLine(VelocityArguments.Replace(message.Subject, ArgMatchReplace)); message.Subject = string.Empty; } if (string.IsNullOrEmpty(message.Body)) return; var lines = message.Body.Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.None); + for (var i = 0; i < lines.Length - 1; i++) { ref var line = ref lines[i]; - if (string.IsNullOrEmpty(line)) { body += Environment.NewLine; continue; } + if (string.IsNullOrEmpty(line)) { sb.AppendLine(); continue; } line = VelocityArguments.Replace(line, ArgMatchReplace); - body += LinkReplacer.Replace(line, EvalLink) + Environment.NewLine; + sb.AppendLine(LinkReplacer.Replace(line, EvalLink)); } ref var lastLine = ref lines[^1]; lastLine = VelocityArguments.Replace(lastLine, ArgMatchReplace); - body += LinkReplacer.Replace(lastLine, EvalLink); + sb.Append(LinkReplacer.Replace(lastLine, EvalLink)); + var body = sb.ToString(); body = TextileReplacer.Replace(HttpUtility.HtmlDecode(body), ""); //Kill textile markup body = BrReplacer.Replace(body, Environment.NewLine); body = ClosedTagsReplacer.Replace(body, Environment.NewLine); diff --git a/common/ASC.Textile/Blocks/GlyphBlockModifier.cs b/common/ASC.Textile/Blocks/GlyphBlockModifier.cs index 3426666833..24a9f2e408 100644 --- a/common/ASC.Textile/Blocks/GlyphBlockModifier.cs +++ b/common/ASC.Textile/Blocks/GlyphBlockModifier.cs @@ -11,6 +11,7 @@ #endregion #region Using Statements +using System.Text; using System.Text.RegularExpressions; #endregion @@ -39,7 +40,7 @@ namespace Textile.Blocks { @"\b ?[([](C|c)[])]", "©" } // copyright }; - var output = ""; + var sb = new StringBuilder(); if (!Regex.IsMatch(line, "<.*>")) { @@ -48,13 +49,14 @@ namespace Textile.Blocks { line = Regex.Replace(line, glyphs[i, 0], glyphs[i, 1]); } - output = line; + sb.Append(line); } else { var splits = Regex.Split(line, "(<.*?>)"); var offtags = "code|pre|notextile"; var codepre = false; + foreach (var split in splits) { var modifiedSplit = split; @@ -82,11 +84,11 @@ namespace Textile.Blocks //line = line.Replace("&#", "&#"); } - output += modifiedSplit; + sb.Append(modifiedSplit); } } - return output; + return sb.ToString(); } } } diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMoveCopyOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMoveCopyOperation.cs index 3b1c79f589..75de729100 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMoveCopyOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileMoveCopyOperation.cs @@ -27,6 +27,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; using System.Text.Json; using ASC.Common; @@ -195,7 +196,8 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations var toFolderId = toFolder.ID; var isToFolder = Equals(toFolderId, DaoFolderId); - + var sb = new StringBuilder(); + sb.Append(Result); foreach (var folderId in folderIds) { CancellationToken.ThrowIfCancellationRequested(); @@ -243,7 +245,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations if (ProcessedFolder(folderId)) { - Result += string.Format("folder_{0}{1}", newFolder.ID, SPLIT_CHAR); + sb.Append($"folder_{newFolder.ID}{SPLIT_CHAR}"); } } @@ -263,7 +265,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations FolderDao.DeleteFolder(folder.ID); if (ProcessedFolder(folderId)) { - Result += string.Format("folder_{0}{1}", newFolder.ID, SPLIT_CHAR); + sb.Append($"folder_{newFolder.ID}{SPLIT_CHAR}"); } } } @@ -284,7 +286,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations if (ProcessedFolder(folderId)) { - Result += string.Format("folder_{0}{1}", newFolderId, SPLIT_CHAR); + sb.Append($"folder_{newFolderId}{SPLIT_CHAR}"); } } else if (!FilesSecurity.CanDelete(folder)) @@ -316,7 +318,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations if (ProcessedFolder(folderId)) { - Result += string.Format("folder_{0}{1}", newFolderId, SPLIT_CHAR); + sb.Append($"folder_{newFolderId}{SPLIT_CHAR}"); } } } @@ -353,10 +355,11 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations if (ProcessedFolder(folderId)) { - Result += string.Format("folder_{0}{1}", newFolderId, SPLIT_CHAR); + sb.Append($"folder_{newFolderId}{SPLIT_CHAR}"); } } - } + } + Result = sb.ToString(); } catch (Exception ex) { @@ -382,7 +385,8 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations var fileDao = scope.ServiceProvider.GetService<IFileDao<TTo>>(); var fileTracker = scope.ServiceProvider.GetService<FileTrackerHelper>(); - var toFolderId = toFolder.ID; + var toFolderId = toFolder.ID; + var sb = new StringBuilder(); foreach (var fileId in fileIds) { CancellationToken.ThrowIfCancellationRequested(); @@ -432,7 +436,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations if (ProcessedFile(fileId)) { - Result += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR); + sb.Append($"file_{newFile.ID}{SPLIT_CHAR}"); } } catch @@ -480,7 +484,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations if (ProcessedFile(fileId)) { - Result += string.Format("file_{0}{1}", newFileId, SPLIT_CHAR); + sb.Append($"file_{newFileId}{SPLIT_CHAR}"); } } } @@ -535,7 +539,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations filesMessageService.Send(newFile, toFolder, _headers, MessageAction.FileCopiedWithOverwriting, newFile.Title, parentFolder.Title, toFolder.Title); if (ProcessedFile(fileId)) { - Result += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR); + sb.Append($"file_{newFile.ID}{SPLIT_CHAR}"); } } else @@ -544,7 +548,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations { if (ProcessedFile(fileId)) { - Result += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR); + sb.Append($"file_{newFile.ID}{SPLIT_CHAR}"); } } else @@ -568,7 +572,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations if (ProcessedFile(fileId)) { - Result += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR); + sb.Append($"file_{newFile.ID}{SPLIT_CHAR}"); } } } @@ -589,7 +593,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations } ProgressStep(fileId: FolderDao.CanCalculateSubitems(fileId) ? default : fileId); } - + Result = sb.ToString(); return needToMark; } diff --git a/web/ASC.Web.Core/Users/UserManagerWrapper.cs b/web/ASC.Web.Core/Users/UserManagerWrapper.cs index 032e7cb6f7..d30b2f968a 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -299,12 +299,12 @@ namespace ASC.Web.Core.Users { var length = RandomNumberGenerator.GetInt32(minLength, maxLength + 1); - var pwd = string.Empty; + var sb = new StringBuilder(); while (length-- > 0) { - pwd += noise[RandomNumberGenerator.GetInt32(noise.Length - 1)]; + sb.Append(noise[RandomNumberGenerator.GetInt32(noise.Length - 1)]); } - return pwd; + return sb.ToString(); } internal static string GenerateErrorMessage(PasswordSettings passwordSettings) From 7c60d02bb4f776f6c5cb69e4922010047815b072 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:12:53 +0300 Subject: [PATCH 082/167] analizators/s1643 --- common/ASC.Textile/States/TableRowFormatterState.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/common/ASC.Textile/States/TableRowFormatterState.cs b/common/ASC.Textile/States/TableRowFormatterState.cs index c7d83ae786..247b08dcf8 100644 --- a/common/ASC.Textile/States/TableRowFormatterState.cs +++ b/common/ASC.Textile/States/TableRowFormatterState.cs @@ -1,3 +1,4 @@ +using System.Text; using System.Text.RegularExpressions; namespace Textile.States @@ -50,17 +51,16 @@ namespace Textile.States { // can get: Align & Classes - var formattedLine = ""; - + var sb = new StringBuilder(); var cellsInput = input.Split('|'); for (var i = 1; i < cellsInput.Length - 1; i++) { var cellInput = cellsInput[i]; var tcp = new TableCellParser(cellInput); - formattedLine += tcp.GetLineFragmentFormatting(); + sb.Append(tcp.GetLineFragmentFormatting()); } - Formatter.Output.WriteLine(formattedLine); + Formatter.Output.WriteLine(sb.ToString()); } public override bool ShouldExit(string input) From fb65d3a09d3c99e2cb13d8d7f2ac29b5c958b290 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:15:15 +0300 Subject: [PATCH 083/167] analizators/1481 --- common/ASC.Api.Core/Core/BaseStartup.cs | 2 +- common/ASC.Core.Common/Data/DbUserService.cs | 2 -- .../MultiRegionHostedSolution.cs | 3 +-- .../Notify/Senders/SmtpSender.cs | 3 --- .../ASC.Data.Backup.Core/Core/NotifyHelper.cs | 1 - .../Service/BackupWorker.cs | 1 - .../Tasks/RestorePortalTask.cs | 10 -------- .../ReassignProgressItem.cs | 1 - .../ASC.Data.Reassigns/RemoveProgressItem.cs | 1 - .../GoogleCloud/GoogleCloudStorage.cs | 8 ------- common/ASC.IPSecurity/IPSecurity.cs | 1 - .../Blocks/BlockAttributesParser.cs | 1 - common/services/ASC.ClearEvents/Program.cs | 4 ++-- .../ASC.ElasticSearch/Engine/BaseIndexer.cs | 8 ------- .../ASC.ElasticSearch/Engine/Client.cs | 2 -- .../Core/Core/Dao/TeamlabDao/FileDao.cs | 1 - .../ASC.Files/Core/Core/FileStorageService.cs | 1 - .../Core/Core/Thirdparty/Box/BoxStorage.cs | 8 ++----- .../Core/Thirdparty/Dropbox/DropboxStorage.cs | 6 +---- .../Core/HttpHandlers/SearchHandler.cs | 4 ++-- .../DocbuilderReportsUtility.cs | 1 - .../Core/ThirdPartyApp/GoogleDriveApp.cs | 1 - products/ASC.Files/Core/Utils/EntryManager.cs | 6 ----- products/ASC.Files/Core/Utils/FileMarker.cs | 2 -- .../ASC.Files/Core/Utils/MailMergeTask.cs | 23 ------------------- .../Server/Helpers/FilesControllerHelper.cs | 2 -- web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs | 3 --- .../Notify/StudioPeriodicNotify.cs | 1 - web/ASC.Web.Core/Notify/TagValues.cs | 4 ++-- web/ASC.Web.Core/Sms/SmsManager.cs | 2 +- .../WhiteLabel/TenantWhiteLabelSettings.cs | 5 ++-- 31 files changed, 14 insertions(+), 104 deletions(-) diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index 27f17952cf..48404e7fdc 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -109,7 +109,7 @@ namespace ASC.Api.Core DIHelper.RegisterProducts(Configuration, HostEnvironment.ContentRootPath); } - var builder = services.AddMvcCore(config => + services.AddMvcCore(config => { config.Conventions.Add(new ControllerNameAttributeConvention()); diff --git a/common/ASC.Core.Common/Data/DbUserService.cs b/common/ASC.Core.Common/Data/DbUserService.cs index 2416310efa..c82834bb99 100644 --- a/common/ASC.Core.Common/Data/DbUserService.cs +++ b/common/ASC.Core.Common/Data/DbUserService.cs @@ -703,8 +703,6 @@ namespace ASC.Core.Data if (includeGroups != null && includeGroups.Count > 0) { - Expression or = Expression.Empty(); - foreach (var ig in includeGroups) { q = q.Where(r => r.Groups.Any(a => !a.Removed && a.Tenant == r.Tenant && a.UserId == r.Id && ig.Any(r => r == a.GroupId))); diff --git a/common/ASC.Core.Common/MultiRegionHostedSolution.cs b/common/ASC.Core.Common/MultiRegionHostedSolution.cs index 7a488a6838..e8d11ae066 100644 --- a/common/ASC.Core.Common/MultiRegionHostedSolution.cs +++ b/common/ASC.Core.Common/MultiRegionHostedSolution.cs @@ -204,11 +204,10 @@ namespace ASC.Core private void Initialize() { var connectionStrings = ConfigurationExtension.GetConnectionStrings(); - var dbConnectionStrings = ConfigurationExtension.GetConnectionStrings(dbid); if (Convert.ToBoolean(Configuraion["core.multi-hosted.config-only"] ?? "false")) { - foreach (var cs in ConfigurationExtension.GetConnectionStrings()) + foreach (var cs in connectionStrings) { if (cs.Name.StartsWith(dbid + ".")) { diff --git a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs index aab41d246f..3d9cfa5504 100644 --- a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs @@ -277,9 +277,6 @@ namespace ASC.Core.Notify.Senders private MailKit.Net.Smtp.SmtpClient GetSmtpClient() { - var sslCertificatePermit = Configuration["mail:certificate-permit"] != null && - Convert.ToBoolean(Configuration["mail:certificate-permit"]); - var smtpClient = new MailKit.Net.Smtp.SmtpClient { Timeout = NETWORK_TIMEOUT diff --git a/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs b/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs index bb54190e51..bce7596186 100644 --- a/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs @@ -112,7 +112,6 @@ namespace ASC.Data.Backup var (userManager, studioNotifyHelper, studioNotifySource, displayUserSettingsHelper, authManager) = scopeClass; var client = WorkContext.NotifyContext.NotifyService.RegisterClient(studioNotifySource, scope); - var owner = userManager.GetUsers(tenant.OwnerId); var users = notifyAllUsers ? userManager.GetUsers(EmployeeStatus.Active) : new[] { userManager.GetUsers(tenantManager.GetCurrentTenant().OwnerId) }; diff --git a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs index 07c919bbbd..6d6a618577 100644 --- a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs +++ b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs @@ -405,7 +405,6 @@ namespace ASC.Data.Backup.Service var scopeClass = scope.ServiceProvider.GetService<BackupWorkerScope>(); var (tenantManager, backupStorageFactory, notifyHelper, backupRepository, backupWorker, backupPortalTask, _, _, coreBaseSettings) = scopeClass; - var tenant = tenantManager.GetTenant(TenantId); var dateTime = coreBaseSettings.Standalone ? DateTime.Now : DateTime.UtcNow; var backupName = string.Format("{0}_{1:yyyy-MM-dd_HH-mm-ss}.{2}", tenantManager.GetTenant(TenantId).TenantAlias, dateTime, ArchiveFormat); diff --git a/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs index 95ad6c19c3..16d9e1db71 100644 --- a/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs @@ -369,16 +369,6 @@ namespace ASC.Data.Backup.Tasks private void SetTenantActive(int tenantId) { using var connection = DbFactory.OpenConnection(); - var commandText = string.Format( - "update tenants_tenants " + - "set " + - " status={0}, " + - " last_modified='{1}', " + - " statuschanged='{1}' " + - "where id = '{2}'", - (int)TenantStatus.Active, - DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"), - tenantId); connection.CreateCommand().WithTimeout(120).ExecuteNonQuery(); } diff --git a/common/ASC.Data.Reassigns/ReassignProgressItem.cs b/common/ASC.Data.Reassigns/ReassignProgressItem.cs index 54db156b61..4606febd22 100644 --- a/common/ASC.Data.Reassigns/ReassignProgressItem.cs +++ b/common/ASC.Data.Reassigns/ReassignProgressItem.cs @@ -102,7 +102,6 @@ namespace ASC.Data.Reassigns var scopeClass = scope.ServiceProvider.GetService<ReassignProgressItemScope>(); var (tenantManager, coreBaseSettings, messageService, studioNotifyService, securityContext, userManager, userPhotoManager, displayUserSettingsHelper, messageTarget, options) = scopeClass; var logger = options.Get("ASC.Web"); - var tenant = tenantManager.SetCurrentTenant(_tenantId); try { diff --git a/common/ASC.Data.Reassigns/RemoveProgressItem.cs b/common/ASC.Data.Reassigns/RemoveProgressItem.cs index 1bb12dafdf..f035389f52 100644 --- a/common/ASC.Data.Reassigns/RemoveProgressItem.cs +++ b/common/ASC.Data.Reassigns/RemoveProgressItem.cs @@ -98,7 +98,6 @@ namespace ASC.Data.Reassigns var scopeClass = scope.ServiceProvider.GetService<RemoveProgressItemScope>(); var (tenantManager, coreBaseSettings, messageService, studioNotifyService, securityContext, userManager, messageTarget, webItemManagerSecurity, storageFactory, userFormatter, options) = scopeClass; var logger = options.Get("ASC.Web"); - var tenant = tenantManager.SetCurrentTenant(_tenantId); var userName = userFormatter.GetUserName(User, DisplayUserNameFormat.Default); try diff --git a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs index 915c3659c4..1e50085105 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -626,9 +626,6 @@ namespace ASC.Data.Storage.GoogleCloud { using var storage = GetStorage(); - var srcKey = MakePath(srcdomain, srcpath); - var dstKey = MakePath(newdomain, newpath); - var size = GetFileSize(srcdomain, srcpath); var options = new CopyObjectOptions @@ -651,9 +648,6 @@ namespace ASC.Data.Storage.GoogleCloud using var storage = GetStorage(); - - var options = new ListObjectsOptions(); - var objects = storage.ListObjects(_bucket, srckey); foreach (var obj in objects) @@ -672,7 +666,6 @@ namespace ASC.Data.Storage.GoogleCloud { using var storage = GetStorage(); - var objectKey = MakePath(domain, path); var buffered = TempStream.GetBuffered(stream); var uploadObjectOptions = new UploadObjectOptions @@ -775,7 +768,6 @@ namespace ASC.Data.Storage.GoogleCloud { var httpClient = ClientFactory.CreateClient(); using var response = httpClient.Send(request); - var status = response.StatusCode; break; } diff --git a/common/ASC.IPSecurity/IPSecurity.cs b/common/ASC.IPSecurity/IPSecurity.cs index 52996a77ad..0153b97949 100644 --- a/common/ASC.IPSecurity/IPSecurity.cs +++ b/common/ASC.IPSecurity/IPSecurity.cs @@ -79,7 +79,6 @@ namespace ASC.IPSecurity public bool Verify() { var tenant = TenantManager.GetCurrentTenant(); - var settings = SettingsManager.Load<IPRestrictionsSettings>(); if (!IpSecurityEnabled) return true; diff --git a/common/ASC.Textile/Blocks/BlockAttributesParser.cs b/common/ASC.Textile/Blocks/BlockAttributesParser.cs index 361992aeea..288fa0998a 100644 --- a/common/ASC.Textile/Blocks/BlockAttributesParser.cs +++ b/common/ASC.Textile/Blocks/BlockAttributesParser.cs @@ -45,7 +45,6 @@ namespace Textile.Blocks var colspan = string.Empty; var rowspan = string.Empty; var id = string.Empty; - var atts = string.Empty; if (Styler != null) { diff --git a/common/services/ASC.ClearEvents/Program.cs b/common/services/ASC.ClearEvents/Program.cs index 0514c12027..a3b6860901 100644 --- a/common/services/ASC.ClearEvents/Program.cs +++ b/common/services/ASC.ClearEvents/Program.cs @@ -66,8 +66,8 @@ namespace ASC.Thumbnails.Svc { path = Path.GetFullPath(CrossPlatform.PathCombine(hostContext.HostingEnvironment.ContentRootPath, path)); } - config.SetBasePath(path); - var env = hostContext.Configuration.GetValue("ENVIRONMENT", "Production"); + config.SetBasePath(path); + config .AddJsonFile("appsettings.json") .AddEnvironmentVariables() diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index 82c61b09df..7973707461 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -446,14 +446,6 @@ namespace ASC.ElasticSearch return b; } - var createIndexResponse = Client.Instance.Indices.Create(data.IndexName, - c => - c.Map<T>(m => m.AutoMap()) - .Settings(r => r.Analysis(a => - a.Analyzers(analyzers) - .CharFilters(d => d.HtmlStrip(nameof(CharFilter.html)) - .Mapping(nameof(CharFilter.io), m => m.Mappings("Ñ‘ => е", "Ð => Е")))))); - IsExist = true; } } diff --git a/common/services/ASC.ElasticSearch/Engine/Client.cs b/common/services/ASC.ElasticSearch/Engine/Client.cs index 38b7c21285..fbeec7eb1a 100644 --- a/common/services/ASC.ElasticSearch/Engine/Client.cs +++ b/common/services/ASC.ElasticSearch/Engine/Client.cs @@ -104,8 +104,6 @@ namespace ASC.ElasticSearch { var result = client.Ping(new PingRequest()); - var isValid = result.IsValid; - if (result.IsValid) { client.Ingest.PutPipeline("attachments", p => p diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index e91fcb4a02..b650ad93a5 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -676,7 +676,6 @@ namespace ASC.Files.Core.Data FactoryIndexer.DeleteAsync(d); } - var toDeleteLinks = Query(FilesDbContext.TagLink).Where(r => r.EntryId == fileId.ToString() && r.EntryType == FileEntryType.File); FilesDbContext.RemoveRange(toDeleteFiles); var tagsToRemove = Query(FilesDbContext.Tag) diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index 88f8bb0308..09ded4768a 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -256,7 +256,6 @@ namespace ASC.Web.Files.Services.WCFService var subjectId = string.IsNullOrEmpty(ssubject) ? Guid.Empty : new Guid(ssubject); var folderDao = GetFolderDao(); - var fileDao = GetFileDao(); Folder<T> parent = null; try diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxStorage.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxStorage.cs index a8ea44b03e..ed3d602c65 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxStorage.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxStorage.cs @@ -43,8 +43,6 @@ namespace ASC.Files.Thirdparty.Box { internal class BoxStorage { - private OAuth20Token _token; - private BoxClient _boxClient; private readonly List<string> _boxFields = new List<string> { "created_at", "modified_at", "name", "parent", "size" }; @@ -64,10 +62,8 @@ namespace ASC.Files.Thirdparty.Box if (IsOpened) return; - _token = token; - - var config = new BoxConfig(_token.ClientID, _token.ClientSecret, new Uri(_token.RedirectUri)); - var session = new OAuthSession(_token.AccessToken, _token.RefreshToken, (int)_token.ExpiresIn, "bearer"); + var config = new BoxConfig(token.ClientID, token.ClientSecret, new Uri(token.RedirectUri)); + var session = new OAuthSession(token.AccessToken, token.RefreshToken, (int)token.ExpiresIn, "bearer"); _boxClient = new BoxClient(config, session); IsOpened = true; diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxStorage.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxStorage.cs index 0e94297ab2..d5807a398a 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxStorage.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxStorage.cs @@ -38,8 +38,6 @@ namespace ASC.Files.Thirdparty.Dropbox { internal class DropboxStorage : IDisposable { - private OAuth20Token _token; - private DropboxClient dropboxClient; public bool IsOpened { get; private set; } @@ -57,9 +55,7 @@ namespace ASC.Files.Thirdparty.Dropbox if (IsOpened) return; - _token = token; - - dropboxClient = new DropboxClient(_token.AccessToken); + dropboxClient = new DropboxClient(token.AccessToken); IsOpened = true; } diff --git a/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs b/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs index 072cb6a981..0a0f113ee2 100644 --- a/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs +++ b/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs @@ -115,12 +115,12 @@ namespace ASC.Web.Files.Configuration var id = GlobalFolderHelper.FolderMy; if (!Equals(id, 0)) { - var folderMy = folderDao.GetFolder(id); + //var folderMy = folderDao.GetFolder(id); //result = result.Concat(EntryManager.GetThirpartyFolders(folderMy, text)); } id = GlobalFolderHelper.FolderCommon; - var folderCommon = folderDao.GetFolder(id); + //var folderCommon = folderDao.GetFolder(id); //result = result.Concat(EntryManager.GetThirpartyFolders(folderCommon, text)); } diff --git a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs index 44cabcb9ae..e4b8a3d817 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs @@ -301,7 +301,6 @@ namespace ASC.Web.Files.Services.DocumentService var result = ReportState.FromTask(task, httpContextAccessor, tenantId, userId); var status = task.GetProperty<ReportStatus>("status"); - var id = task.GetProperty<ReportStatus>("status"); if ((int)status > 1) { diff --git a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs index 39ba1eba9d..8ee058f56b 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -332,7 +332,6 @@ namespace ASC.Web.Files.ThirdPartyApp } else { - var downloadRequest = new HttpRequestMessage(); using var response = httpClient.Send(request); using var downloadStream = new ResponseStream(response); diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index ee8a8f0e9e..a04f5bab04 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -352,8 +352,6 @@ namespace ASC.Web.Files.Utils { var responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(responseBody))); - var projectLastModified = responseApi["response"].Value<string>(); - var projectListCacheKey = string.Format("documents/projectFolders/{0}", AuthContext.CurrentAccount.ID); Dictionary<int, KeyValuePair<int, string>> folderIDProjectTitle = null; if (folderIDProjectTitle == null) @@ -461,9 +459,6 @@ namespace ASC.Web.Files.Utils } else if (parent.FolderType == FolderType.Favorites) { - var fileDao = DaoFactory.GetFileDao<T>(); - var folderDao = DaoFactory.GetFolderDao<T>(); - var (files, folders) = GetFavorites(filter, subjectGroup, subjectId, searchText, searchInContent); entries = entries.Concat(folders); @@ -660,7 +655,6 @@ namespace ASC.Web.Files.Utils public (IEnumerable<FileEntry>, IEnumerable<FileEntry>) GetFavorites(FilterType filter, bool subjectGroup, Guid subjectId, string searchText, bool searchInContent) { - var fileSecurity = FileSecurity; var tagDao = DaoFactory.GetTagDao<int>(); var tags = tagDao.GetTags(AuthContext.CurrentAccount.ID, TagType.Favorite); diff --git a/products/ASC.Files/Core/Utils/FileMarker.cs b/products/ASC.Files/Core/Utils/FileMarker.cs index 78fd5938f9..86738e3c01 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -518,8 +518,6 @@ namespace ASC.Web.Files.Utils if (folder.RootFolderType == FolderType.TRASH && !Equals(folder.ID, GlobalFolder.GetFolderTrash<T>(DaoFactory))) throw new SecurityException(FilesCommonResource.ErrorMassage_ViewTrashItem); var tagDao = DaoFactory.GetTagDao<T>(); - var fileDao = DaoFactory.GetFileDao<T>(); - var folderDao = DaoFactory.GetFolderDao<T>(); var providerFolderDao = DaoFactory.GetFolderDao<string>(); var providerTagDao = DaoFactory.GetTagDao<string>(); var tags = (tagDao.GetNewTags(AuthContext.CurrentAccount.ID, folder, true) ?? new List<Tag>()).ToList(); diff --git a/products/ASC.Files/Core/Utils/MailMergeTask.cs b/products/ASC.Files/Core/Utils/MailMergeTask.cs index 3895e56532..a75e6c8de3 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -100,16 +100,6 @@ namespace ASC.Web.Files.Utils private void CreateDraftMail(MailMergeTask mailMergeTask) { - var apiUrlCreate = $"{SetupInfo.WebApiBaseUrl}mail/drafts/save.json"; - var bodyCreate = - string.Format( - MailMergeTask.MessageBodyFormat, - mailMergeTask.MessageId, - HttpUtility.UrlEncode(mailMergeTask.From), - HttpUtility.UrlEncode(mailMergeTask.Subject), - HttpUtility.UrlEncode(mailMergeTask.To), - HttpUtility.UrlEncode(mailMergeTask.Message)); - const string responseCreateString = null; //TODO: Encoding.UTF8.GetString(Convert.FromBase64String(Api.GetApiResponse(apiUrlCreate, "PUT", bodyCreate))); var responseCreate = JObject.Parse(responseCreateString); @@ -172,19 +162,6 @@ namespace ASC.Web.Files.Utils private string SendMail(MailMergeTask mailMergeTask, string bodySendAttach) { - var apiUrlSend = $"{SetupInfo.WebApiBaseUrl}mail/messages/send.json"; - - var bodySend = - string.Format( - MailMergeTask.MessageBodyFormat, - mailMergeTask.MessageId, - HttpUtility.UrlEncode(mailMergeTask.From), - HttpUtility.UrlEncode(mailMergeTask.Subject), - HttpUtility.UrlEncode(mailMergeTask.To), - HttpUtility.UrlEncode(mailMergeTask.Message)); - - bodySend += bodySendAttach; - const string responseSendString = null;//TODO: Encoding.UTF8.GetString(Convert.FromBase64String(Api.GetApiResponse(apiUrlSend, "PUT", bodySend))); var responseSend = JObject.Parse(responseSendString); diff --git a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs index dfde169ca7..bbcec0bd94 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -598,8 +598,6 @@ namespace ASC.Files.Helpers public string GenerateSharedLink(T fileId, FileShare share) { - var file = GetFileInfo(fileId); - var sharedInfo = FileStorageService.GetSharedInfo(new List<T> { fileId }, new List<T> { }).Find(r => r.SubjectId == FileConstant.ShareLinkId); if (sharedInfo == null || sharedInfo.Share != share) { diff --git a/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs b/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs index e678767dae..df85dedbef 100644 --- a/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs +++ b/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs @@ -221,9 +221,6 @@ namespace ASC.Api.Settings.Smtp public SmtpClient GetSmtpClient() { - var sslCertificatePermit = Configuration["mail.certificate-permit"] != null && - Convert.ToBoolean(Configuration["mail.certificate-permit"]); - var client = new SmtpClient { Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds diff --git a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs index 023b30a159..d3a7037418 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -73,7 +73,6 @@ namespace ASC.Web.Studio.Core.Notify Log.Info("Start SendSaasTariffLetters"); var activeTenants = new List<Tenant>(); - var monthQuotasIds = new List<int>(); using (var scope = ServiceProvider.CreateScope()) { diff --git a/web/ASC.Web.Core/Notify/TagValues.cs b/web/ASC.Web.Core/Notify/TagValues.cs index a9c2b84ba8..3082af2943 100644 --- a/web/ASC.Web.Core/Notify/TagValues.cs +++ b/web/ASC.Web.Core/Notify/TagValues.cs @@ -70,8 +70,8 @@ namespace ASC.Web.Studio.Core.Notify const string td = "<td style=\"height: 48px; width: 80px; margin:0; padding:0;\"> </td>"; const string color = "color: #fff; font-family: Helvetica, Arial, Tahoma; font-size: 18px; font-weight: 600; vertical-align: middle; display: block; padding: 12px 0; text-align: center; text-decoration: none; background-color: #66b76d;"; - return $@"<table style=""height: 48px; width: 540px; border-collapse: collapse; empty-cells: show; vertical-align: middle; text-align: center; margin: 30px auto; padding: 0;""><tbody><tr cellpadding=""0"" cellspacing=""0"" border=""0"">{td}<td style=""height: 48px; width: 380px; margin:0; padding:0; background-color: #66b76d; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px;""><a style=""{3}"" target=""_blank"" href=""{btnUrl}"">{btnText}</a></td>{td}</tr></tbody></table>"; - } + return $@"<table style=""height: 48px; width: 540px; border-collapse: collapse; empty-cells: show; vertical-align: middle; text-align: center; margin: 30px auto; padding: 0;""><tbody><tr cellpadding=""0"" cellspacing=""0"" border=""0"">{td}<td style=""height: 48px; width: 380px; margin:0; padding:0; background-color: #66b76d; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px;""><a style=""{color}"" target=""_blank"" href=""{btnUrl}"">{btnText}</a></td>{td}</tr></tbody></table>"; + } return new TagActionValue("GreenButton", action); } diff --git a/web/ASC.Web.Core/Sms/SmsManager.cs b/web/ASC.Web.Core/Sms/SmsManager.cs index ca670c2867..6465c80bdc 100644 --- a/web/ASC.Web.Core/Sms/SmsManager.cs +++ b/web/ASC.Web.Core/Sms/SmsManager.cs @@ -140,7 +140,7 @@ namespace ASC.Web.Studio.Core.SMS if (!SecurityContext.IsAuthenticated) { - var cookiesKey = SecurityContext.AuthenticateMe(user.ID); + //var cookiesKey = SecurityContext.AuthenticateMe(user.ID); //CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey); } diff --git a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs index 5c049aca8b..474b4a4f45 100644 --- a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs +++ b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs @@ -327,7 +327,6 @@ namespace ASC.Web.Core.WhiteLabel using (var memory = new MemoryStream(data)) using (var image = Image.Load(memory)) { - var logoSize = image.Size(); var logoFileName = BuildLogoFileName(type, logoFileExt, false); memory.Seek(0, SeekOrigin.Begin); @@ -532,8 +531,8 @@ namespace ASC.Web.Core.WhiteLabel try { using var stream = new MemoryStream(data); - using var img = Image.Load(stream, out var format); - var imgFormat = format; + using var img = Image.Load(stream, out var format); + if (size != img.Size()) { using var img2 = CommonPhotoManager.DoThumbnail(img, size, false, true, false); From c05d9fe6bc337590f8c98ffacc3d60641f977c3f Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:15:29 +0300 Subject: [PATCH 084/167] analizators/s1450 --- common/ASC.Core.Common/Notify/Channels/SenderChannel.cs | 6 +++--- common/ASC.Data.Backup.Core/Core/ZipOperator.cs | 6 ++---- common/ASC.Data.Storage/Configuration/StorageSettings.cs | 8 +++----- .../services/ASC.UrlShortener.Svc/UrlShortenerService.cs | 3 +-- 4 files changed, 9 insertions(+), 14 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs b/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs index ead6ec0a20..c000ddf737 100644 --- a/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs +++ b/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs @@ -35,7 +35,6 @@ namespace ASC.Notify.Channels { private readonly ISink firstSink; private readonly ISink senderSink; - private readonly Context context; public string SenderName @@ -47,12 +46,13 @@ namespace ASC.Notify.Channels public SenderChannel(Context context, string senderName, ISink decorateSink, ISink senderSink) { - this.context = context ?? throw new ArgumentNullException("context"); this.SenderName = senderName ?? throw new ArgumentNullException("senderName"); this.firstSink = decorateSink; this.senderSink = senderSink ?? throw new ApplicationException($"channel with tag {senderName} not created sender sink"); - var dispatcherSink = new DispatchSink(SenderName, this.context.DispatchEngine); + + context = context ?? throw new ArgumentNullException("context"); + var dispatcherSink = new DispatchSink(SenderName, context.DispatchEngine); this.firstSink = AddSink(firstSink, dispatcherSink); } diff --git a/common/ASC.Data.Backup.Core/Core/ZipOperator.cs b/common/ASC.Data.Backup.Core/Core/ZipOperator.cs index 764080ab7c..56d45d8b6e 100644 --- a/common/ASC.Data.Backup.Core/Core/ZipOperator.cs +++ b/common/ASC.Data.Backup.Core/Core/ZipOperator.cs @@ -37,16 +37,14 @@ namespace ASC.Data.Backup { public class ZipWriteOperator : IDataWriteOperator { - private readonly GZipOutputStream gZipOutputStream; private readonly TarOutputStream tarOutputStream; - private readonly Stream file; private TempStream TempStream { get; } public ZipWriteOperator(TempStream tempStream, string targetFile) { - file = new FileStream(targetFile, FileMode.Create); - gZipOutputStream = new GZipOutputStream(file); + var file = new FileStream(targetFile, FileMode.Create); + var gZipOutputStream = new GZipOutputStream(file); tarOutputStream = new TarOutputStream(gZipOutputStream, Encoding.UTF8); TempStream = tempStream; } diff --git a/common/ASC.Data.Storage/Configuration/StorageSettings.cs b/common/ASC.Data.Storage/Configuration/StorageSettings.cs index b3978d6a1f..5a1992cfc4 100644 --- a/common/ASC.Data.Storage/Configuration/StorageSettings.cs +++ b/common/ASC.Data.Storage/Configuration/StorageSettings.cs @@ -174,7 +174,6 @@ namespace ASC.Data.Storage.Configuration public bool Save<T>(BaseStorageSettings<T> baseStorageSettings) where T : class, ISettings, new() { ClearDataStoreCache(); - dataStoreConsumer = null; return SettingsManager.Save(baseStorageSettings); } @@ -195,16 +194,15 @@ namespace ASC.Data.Storage.Configuration Save(baseStorageSettings); } - private DataStoreConsumer dataStoreConsumer; public DataStoreConsumer DataStoreConsumer<T>(BaseStorageSettings<T> baseStorageSettings) where T : class, ISettings, new() { - if (string.IsNullOrEmpty(baseStorageSettings.Module) || baseStorageSettings.Props == null) return dataStoreConsumer = new DataStoreConsumer(); + if (string.IsNullOrEmpty(baseStorageSettings.Module) || baseStorageSettings.Props == null) return new DataStoreConsumer(); var consumer = ConsumerFactory.GetByKey<DataStoreConsumer>(baseStorageSettings.Module); - if (!consumer.IsSet) return dataStoreConsumer = new DataStoreConsumer(); + if (!consumer.IsSet) return new DataStoreConsumer(); - dataStoreConsumer = (DataStoreConsumer)consumer.Clone(); + var dataStoreConsumer = (DataStoreConsumer)consumer.Clone(); foreach (var prop in baseStorageSettings.Props) { diff --git a/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs b/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs index a5cad6e13e..7e189d8bf5 100644 --- a/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs +++ b/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs @@ -50,7 +50,6 @@ namespace ASC.UrlShortener.Svc private readonly IHostEnvironment hostEnvironment; private readonly ConfigurationExtension configurationExtension; - private ProcessStartInfo processStartInfo; private Process process; @@ -74,7 +73,7 @@ namespace ASC.UrlShortener.Svc { Stop(); - processStartInfo = GetProcessStartInfo(); + var processStartInfo = GetProcessStartInfo(); process = Process.Start(processStartInfo); } catch (Exception e) From 143f0a5dda9348f75e4efa047262bebc53661726 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:22:56 +0300 Subject: [PATCH 085/167] Analizators/s1854 --- common/ASC.Core.Common/Data/DbSubscriptionService.cs | 2 +- common/ASC.Core.Common/EF/Context/BaseDbContext.cs | 2 +- common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs | 2 +- common/ASC.Data.Storage/CrossModuleTransferUtility.cs | 1 - .../RackspaceCloud/RackspaceCloudStorage.cs | 4 ---- common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs | 2 -- .../services/ASC.ElasticSearch/Engine/FactoryIndexer.cs | 8 ++++---- 7 files changed, 7 insertions(+), 14 deletions(-) diff --git a/common/ASC.Core.Common/Data/DbSubscriptionService.cs b/common/ASC.Core.Common/Data/DbSubscriptionService.cs index 60fdd42fbf..563d4a889e 100644 --- a/common/ASC.Core.Common/Data/DbSubscriptionService.cs +++ b/common/ASC.Core.Common/Data/DbSubscriptionService.cs @@ -136,7 +136,7 @@ namespace ASC.Core.Data } else { - q = q = q.Where(r => r.Object == string.Empty); + q = q.Where(r => r.Object == string.Empty); } return q.Any(); diff --git a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs index 32dacc35bf..8509b4e565 100644 --- a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs @@ -65,7 +65,7 @@ namespace ASC.Core.Common.EF { if (!string.IsNullOrEmpty(MigrateAssembly)) { - r = r.MigrationsAssembly(MigrateAssembly); + r.MigrationsAssembly(MigrateAssembly); } }); break; diff --git a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs index b8cb130cd8..29b040578a 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -261,7 +261,7 @@ namespace ASC.Notify.Engine } else { - result = new NotifyResult(sendResponces.Aggregate((SendResult)0, (s, r) => s |= r.Result), sendResponces); + result = new NotifyResult(sendResponces.Aggregate((SendResult)0, (s, r) => r.Result), sendResponces); } log.Debug(result); return result; diff --git a/common/ASC.Data.Storage/CrossModuleTransferUtility.cs b/common/ASC.Data.Storage/CrossModuleTransferUtility.cs index e8499f95c0..97abdc3d1b 100644 --- a/common/ASC.Data.Storage/CrossModuleTransferUtility.cs +++ b/common/ASC.Data.Storage/CrossModuleTransferUtility.cs @@ -90,7 +90,6 @@ namespace ASC.Data.Storage memstream.Seek(0, SeekOrigin.Begin); holder.UploadChunk(session, memstream, chunksize); memstream.Dispose(); - memstream = null; } } finally diff --git a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs index 8c3b0eb24b..9d9a026ccc 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -288,10 +288,6 @@ namespace ASC.Data.Storage.RackspaceCloud ? MimeMapping.GetMimeMapping(Path.GetFileName(path)) : contentType; - if (mime == "application/octet-stream") - { - contentDisposition = "attachment"; - } var customHeaders = new Dictionary<string, string>(); diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index 7973707461..0d832015d4 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -526,7 +526,6 @@ namespace ASC.ElasticSearch while (!string.IsNullOrEmpty(name)) { sourceExprText = "." + name + sourceExprText; - expression = member.Expression; } if (isList) @@ -581,7 +580,6 @@ namespace ASC.ElasticSearch while (!string.IsNullOrEmpty(name)) { sourceExprText = "." + name + sourceExprText; - expression = member.Expression; } var parameters = new Dictionary<string, object>(); diff --git a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs index 3d16cfe71a..bd01d3db47 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -230,7 +230,7 @@ namespace ASC.ElasticSearch Thread.Sleep(60000); if (retry < 5) { - Index(data, immediately, retry++); + Index(data, immediately, retry + 1); return; } @@ -259,7 +259,7 @@ namespace ASC.ElasticSearch Thread.Sleep(60000); if (retry < 5) { - Index(data, immediately, retry++); + Index(data, immediately, retry + 1); return; } @@ -304,7 +304,7 @@ namespace ASC.ElasticSearch await Task.Delay(60000); if (retry < 5) { - await IndexAsync(data, immediately, retry++); + await IndexAsync(data, immediately, retry + 1); return; } @@ -333,7 +333,7 @@ namespace ASC.ElasticSearch await Task.Delay(60000); if (retry < 5) { - await IndexAsync(data, immediately, retry++); + await IndexAsync(data, immediately, retry + 1); return; } From ca658e4b02f90457d0d594767469abdcbb583950 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:23:25 +0300 Subject: [PATCH 086/167] analizators/s1905 --- common/ASC.Data.Storage/WebPath.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/ASC.Data.Storage/WebPath.cs b/common/ASC.Data.Storage/WebPath.cs index fba49e19d6..a9e233dba3 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -96,7 +96,7 @@ namespace ASC.Data.Storage Appender appender; if (avaliableAppendersCount > 1) { - appender = avaliableAppenders[(int)(relativePath.Length % avaliableAppendersCount)]; + appender = avaliableAppenders[(relativePath.Length % avaliableAppendersCount)]; } else if (avaliableAppendersCount == 1) { From 2f5a70e6ef0387efeba37366050d6a9a56de6ef6 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:27:09 +0300 Subject: [PATCH 087/167] analizators/s1940 --- web/ASC.Web.Api/Controllers/PortalController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/ASC.Web.Api/Controllers/PortalController.cs b/web/ASC.Web.Api/Controllers/PortalController.cs index b51f7e4416..7627303edf 100644 --- a/web/ASC.Web.Api/Controllers/PortalController.cs +++ b/web/ASC.Web.Api/Controllers/PortalController.cs @@ -208,7 +208,7 @@ namespace ASC.Web.Api.Controllers [Read("thumb")] public FileResult GetThumb(string url) { - if (!SecurityContext.IsAuthenticated || !(Configuration["bookmarking:thumbnail-url"] != null)) + if (!SecurityContext.IsAuthenticated || Configuration["bookmarking:thumbnail-url"] == null) { return null; } From f3d8b8d17ae2d86bf35efd037aacf7d3567f5b53 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:36:36 +0300 Subject: [PATCH 088/167] analizators/s1854 --- common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs | 2 -- products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs | 7 +------ products/ASC.Files/Core/HttpHandlers/SearchHandler.cs | 2 +- products/ASC.Files/Core/Utils/EntryManager.cs | 2 +- web/ASC.Web.Api/Controllers/SettingsController.cs | 2 +- web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs | 4 ++-- web/ASC.Web.Core/Sms/SmsKeyStorage.cs | 2 +- web/ASC.Web.Core/Tfa/TfaManager.cs | 4 ++-- 8 files changed, 9 insertions(+), 16 deletions(-) diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index 0d832015d4..febed6aed5 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -258,7 +258,6 @@ namespace ASC.ElasticSearch { wwd.Document.Data = null; wwd.Document = null; - wwd = null; GC.Collect(); } continue; @@ -288,7 +287,6 @@ namespace ASC.ElasticSearch doc.Document.Data = null; doc.Document = null; } - doc = null; } portionStart = i; diff --git a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs index 867ec54e2f..16e425a4c9 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -272,18 +272,13 @@ namespace ASC.Web.Files { try { - var flushed = false; using (var readStream = store.GetReadStream(FileConstant.StorageDomainTmp, path)) { long offset = 0; - var length = readStream.Length; if (readStream.CanSeek) { - length = ProcessRangeHeader(context, readStream.Length, ref offset); readStream.Seek(offset, SeekOrigin.Begin); - } - - flushed = await SendStreamByChunksAsync(context, length, FileConstant.DownloadTitle + ext, readStream, flushed); + } } await context.Response.Body.FlushAsync(); diff --git a/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs b/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs index 0a0f113ee2..b14d6a41cd 100644 --- a/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs +++ b/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs @@ -119,7 +119,7 @@ namespace ASC.Web.Files.Configuration //result = result.Concat(EntryManager.GetThirpartyFolders(folderMy, text)); } - id = GlobalFolderHelper.FolderCommon; + //id = GlobalFolderHelper.FolderCommon; //var folderCommon = folderDao.GetFolder(id); //result = result.Concat(EntryManager.GetThirpartyFolders(folderCommon, text)); } diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index a04f5bab04..d794bc8124 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -350,7 +350,7 @@ namespace ASC.Web.Files.Utils const string responseBody = null;// apiServer.GetApiResponse(apiUrl, "GET"); if (responseBody != null) { - var responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(responseBody))); + JObject responseApi; Dictionary<int, KeyValuePair<int, string>> folderIDProjectTitle = null; diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index 5f427f9933..c6aeefaf99 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -3011,7 +3011,7 @@ namespace ASC.Api.Settings throw new Exception(Resource.ErrorRequestLimitExceeded); } - MemoryCache.Set(key, ++count, TimeSpan.FromMinutes(expirationMinutes)); + MemoryCache.Set(key, count + 1, TimeSpan.FromMinutes(expirationMinutes)); } } } \ No newline at end of file diff --git a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs index d3a7037418..372deb48f1 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -72,7 +72,7 @@ namespace ASC.Web.Studio.Core.Notify Log.Info("Start SendSaasTariffLetters"); - var activeTenants = new List<Tenant>(); + List<Tenant> activeTenants; using (var scope = ServiceProvider.CreateScope()) { @@ -871,7 +871,7 @@ namespace ASC.Web.Studio.Core.Notify Log.Info("Start SendOpensourceTariffLetters"); - var activeTenants = new List<Tenant>(); + List<Tenant> activeTenants; using (var scope = ServiceProvider.CreateScope()) { diff --git a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs index 0d892d4398..11d094284c 100644 --- a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs +++ b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs @@ -174,7 +174,7 @@ namespace ASC.Web.Core.Sms if (createDate.Add(StoreInterval) < DateTime.UtcNow) return Result.Timeout; - CheckCache.Insert(cacheCheck, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(StoreInterval)); + CheckCache.Insert(cacheCheck, (counter - 1).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(StoreInterval)); return Result.Ok; } } diff --git a/web/ASC.Web.Core/Tfa/TfaManager.cs b/web/ASC.Web.Core/Tfa/TfaManager.cs index 1ec6a08ee1..fe357f2875 100644 --- a/web/ASC.Web.Core/Tfa/TfaManager.cs +++ b/web/ASC.Web.Core/Tfa/TfaManager.cs @@ -155,7 +155,7 @@ namespace ASC.Web.Studio.Core.TFA } } - Cache.Insert("tfa/" + user.ID, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); + Cache.Insert("tfa/" + user.ID, (counter - 1).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1))); if (!SecurityContext.IsAuthenticated) { @@ -179,7 +179,7 @@ namespace ASC.Web.Studio.Core.TFA const string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"; - var data = new byte[length]; + byte[] data; var list = new List<BackupCode>(); From cc53cd53e87b9f3cdb55c2b7d7e6e20fe2ec1207 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:40:08 +0300 Subject: [PATCH 089/167] Analizators/s1939 --- common/ASC.Core.Common/Notify/Cron/ISet.cs | 2 +- common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs | 2 +- products/ASC.Files/Core/Core/Entries/FileEntry.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/common/ASC.Core.Common/Notify/Cron/ISet.cs b/common/ASC.Core.Common/Notify/Cron/ISet.cs index 10f8cb5538..3995ba2896 100644 --- a/common/ASC.Core.Common/Notify/Cron/ISet.cs +++ b/common/ASC.Core.Common/Notify/Cron/ISet.cs @@ -37,7 +37,7 @@ namespace ASC.Notify.Cron #endregion - public interface ISet : ICollection, IList + public interface ISet : IList { #region Methods diff --git a/common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs b/common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs index b0d2a2b178..8961e34aa5 100644 --- a/common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs +++ b/common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs @@ -32,7 +32,7 @@ using ASC.Core.Common.Notify.Jabber; namespace ASC.Core.Notify.Jabber { - public class JabberServiceClientWcf : BaseWcfClient<IJabberService>, IJabberService, IDisposable + public class JabberServiceClientWcf : BaseWcfClient<IJabberService>, IJabberService { public JabberServiceClientWcf() { diff --git a/products/ASC.Files/Core/Core/Entries/FileEntry.cs b/products/ASC.Files/Core/Core/Entries/FileEntry.cs index 8cd5501161..9a681671e5 100644 --- a/products/ASC.Files/Core/Core/Entries/FileEntry.cs +++ b/products/ASC.Files/Core/Core/Entries/FileEntry.cs @@ -127,7 +127,7 @@ namespace ASC.Files.Core } [Serializable] - public abstract class FileEntry<T> : FileEntry, ICloneable + public abstract class FileEntry<T> : FileEntry { public T ID { get; set; } From 510bd4d731a6a005212b0ca00b80161f18bec84a Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:42:02 +0300 Subject: [PATCH 090/167] analizators/s2219 --- common/ASC.Api.Core/Core/ApiDateTime.cs | 2 +- .../ChunkedUploader/CommonChunkedUploadSession.cs | 2 +- products/ASC.Files/Core/Core/Security/FileSecurity.cs | 8 ++++---- products/ASC.Files/Core/Utils/FileMarker.cs | 6 +++--- web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs | 2 +- web/ASC.Web.Core/Users/UserPhotoManager.cs | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/common/ASC.Api.Core/Core/ApiDateTime.cs b/common/ASC.Api.Core/Core/ApiDateTime.cs index 7e83a7d834..daeddcdd3e 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -251,7 +251,7 @@ namespace ASC.Api.Core { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != typeof(ApiDateTime)) return false; + if (!(obj is ApiDateTime)) return false; return Equals((ApiDateTime)obj); } diff --git a/common/ASC.Data.Storage/ChunkedUploader/CommonChunkedUploadSession.cs b/common/ASC.Data.Storage/ChunkedUploader/CommonChunkedUploadSession.cs index fd00bd4e16..ef76304537 100644 --- a/common/ASC.Data.Storage/ChunkedUploader/CommonChunkedUploadSession.cs +++ b/common/ASC.Data.Storage/ChunkedUploader/CommonChunkedUploadSession.cs @@ -111,7 +111,7 @@ namespace ASC.Core.ChunkedUploader { if (item.Value != null) { - if (item.Value.GetType() == typeof(JsonElement)) + if (item.Value is JsonElement) { var value = (JsonElement)item.Value; if (value.ValueKind == JsonValueKind.String) diff --git a/products/ASC.Files/Core/Core/Security/FileSecurity.cs b/products/ASC.Files/Core/Core/Security/FileSecurity.cs index 2278b55040..c177c363ae 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -712,8 +712,8 @@ namespace ASC.Files.Core.Security var records = securityDao.GetShares(subjects); var result = new List<FileEntry>(); - result.AddRange(GetSharesForMe<int>(records.Where(r => r.EntryId.GetType() == typeof(int)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); - result.AddRange(GetSharesForMe<string>(records.Where(r => r.EntryId.GetType() == typeof(string)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); + result.AddRange(GetSharesForMe<int>(records.Where(r => (r.EntryId is int)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); + result.AddRange(GetSharesForMe<string>(records.Where(r => (r.EntryId is string)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); return result; } @@ -832,8 +832,8 @@ namespace ASC.Files.Core.Security var records = securityDao.GetShares(subjects); var result = new List<FileEntry>(); - result.AddRange(GetPrivacyForMe<int>(records.Where(r => r.EntryId.GetType() == typeof(int)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); - result.AddRange(GetPrivacyForMe<string>(records.Where(r => r.EntryId.GetType() == typeof(string)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); + result.AddRange(GetPrivacyForMe<int>(records.Where(r => (r.EntryId is int)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); + result.AddRange(GetPrivacyForMe<string>(records.Where(r => (r.EntryId is string)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); return result; } diff --git a/products/ASC.Files/Core/Utils/FileMarker.cs b/products/ASC.Files/Core/Utils/FileMarker.cs index 86738e3c01..1dd1c569b4 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -528,7 +528,7 @@ namespace ASC.Web.Files.Utils Equals(folder.ID, GlobalFolder.GetFolderCommon(this, DaoFactory)) || Equals(folder.ID, GlobalFolder.GetFolderShare(DaoFactory))) { - var folderTags = tags.Where(tag => tag.EntryType == FileEntryType.Folder && tag.EntryId.GetType() == typeof(string)); + var folderTags = tags.Where(tag => tag.EntryType == FileEntryType.Folder && (tag.EntryId is string)); var providerFolderTags = folderTags .Select(tag => new KeyValuePair<Tag, Folder<string>>(tag, providerFolderDao.GetFolder(tag.EntryId.ToString()))) @@ -549,8 +549,8 @@ namespace ASC.Web.Files.Utils .ToList(); //TODO: refactoring - var entryTagsProvider = GetEntryTags<string>(tags.Where(r=> r.EntryId.GetType() == typeof(string))); - var entryTagsInternal = GetEntryTags<int>(tags.Where(r=> r.EntryId.GetType() == typeof(int))); + var entryTagsProvider = GetEntryTags<string>(tags.Where(r=> (r.EntryId is string))); + var entryTagsInternal = GetEntryTags<int>(tags.Where(r=> (r.EntryId is int))); foreach (var entryTag in entryTagsInternal) { diff --git a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs index 372deb48f1..3cf016e4ca 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -472,7 +472,7 @@ namespace ASC.Web.Studio.Core.Notify Log.Info("Start SendTariffEnterpriseLetters"); - var activeTenants = new List<Tenant>(); + List<Tenant> activeTenants; using (var scope = ServiceProvider.CreateScope()) { diff --git a/web/ASC.Web.Core/Users/UserPhotoManager.cs b/web/ASC.Web.Core/Users/UserPhotoManager.cs index 8bf97a2294..ace0e0c302 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -83,7 +83,7 @@ namespace ASC.Web.Core.Users { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != typeof(ResizeWorkerItem)) return false; + if (!(obj is ResizeWorkerItem)) return false; return Equals((ResizeWorkerItem)obj); } From 667697f933cc7f4d7ee467830c3f6fbeed67f0bd Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:46:30 +0300 Subject: [PATCH 091/167] analizators/s2259 --- common/ASC.Common/Caching/KafkaCache.cs | 2 +- common/ASC.Common/Security/AscRandom.cs | 2 +- .../ASC.Common/Utils/HttpRequestExtensions.cs | 4 +-- common/ASC.Common/Utils/Wildcard.cs | 2 +- .../Context/Impl/PaymentManager.cs | 2 +- .../Notify/Cron/CronExpression.cs | 36 +++++++++---------- .../Notify/RecipientProviderImpl.cs | 2 +- .../Security/Authorizing/RoleProvider.cs | 2 +- .../Tenants/TenantCookieSettings.cs | 4 +-- common/ASC.Data.Backup.Core/Core/DbHelper.cs | 2 +- .../Service/BackupWorker.cs | 4 +-- .../Tasks/BackupPortalTask.cs | 2 +- .../Tasks/DeletePortalTask.cs | 4 +-- .../Tasks/TransferPortalTask.cs | 2 +- common/ASC.Data.Storage/S3/S3Storage.cs | 18 +++++----- common/ASC.Data.Storage/WebPath.cs | 2 +- common/ASC.Data.Storage/Wildcard.cs | 2 +- .../ASC.FederatedLogin/Helpers/HashHelper.cs | 2 +- .../Helpers/OAuth20TokenHelper.cs | 4 +-- common/ASC.IPSecurity/IPAddressRange.cs | 4 +-- .../Blocks/BlockAttributesParser.cs | 6 ++-- .../ASC.Textile/States/ListFormatterState.cs | 2 +- .../States/SimpleBlockFormatterState.cs | 4 +-- .../ASC.Textile/States/TableFormatterState.cs | 2 +- .../ASC.ElasticSearch/Core/Selector.cs | 2 +- .../Core/Core/Dao/TeamlabDao/FolderDao.cs | 2 +- .../ASC.Files/Core/Core/FileStorageService.cs | 4 +-- .../Core/Core/Security/FileSecurity.cs | 8 ++--- .../Thirdparty/OneDrive/OneDriveDaoBase.cs | 4 +-- .../SharePoint/SharePointProviderInfo.cs | 4 +-- .../Thirdparty/Sharpbox/SharpBoxDaoBase.cs | 2 +- .../Thirdparty/Sharpbox/SharpBoxFileDao.cs | 2 +- .../Thirdparty/Sharpbox/SharpBoxFolderDao.cs | 2 +- .../DocumentService/DocumentServiceTracker.cs | 2 +- products/ASC.Files/Core/Utils/EntryManager.cs | 2 +- products/ASC.Files/Core/Utils/FileMarker.cs | 4 +-- products/ASC.Files/Core/Utils/FileSharing.cs | 2 +- products/ASC.Files/Core/Utils/FileTracker.cs | 2 +- .../Server/Helpers/FilesControllerHelper.cs | 2 +- .../Service/Thumbnail/FileDataProvider.cs | 4 +-- .../Controllers/SettingsController.cs | 6 ++-- web/ASC.Web.Core/Calendars/RecurrenceRule.cs | 26 +++++++------- web/ASC.Web.Core/CommonPhotoManager.cs | 2 +- web/ASC.Web.Core/Helpers/GrammaticalHelper.cs | 2 +- .../Helpers/ResourceEnumConverter.cs | 6 ++-- .../Notify/StudioNotifyService.cs | 2 +- .../Notify/StudioPeriodicNotify.cs | 2 +- web/ASC.Web.Core/Tfa/TfaManager.cs | 2 +- web/ASC.Web.Core/Users/UserPhotoManager.cs | 2 +- .../WhiteLabel/TenantWhiteLabelSettings.cs | 2 +- 50 files changed, 108 insertions(+), 108 deletions(-) diff --git a/common/ASC.Common/Caching/KafkaCache.cs b/common/ASC.Common/Caching/KafkaCache.cs index 2931de38e1..a1740505bf 100644 --- a/common/ASC.Common/Caching/KafkaCache.cs +++ b/common/ASC.Common/Caching/KafkaCache.cs @@ -159,7 +159,7 @@ namespace ASC.Common.Caching try { var cr = c.Consume(Cts[channelName].Token); - if (cr != null && cr.Message != null && cr.Message.Value != null && !(new Guid(cr.Message.Key.Id.ToByteArray())).Equals(Key) && Actions.TryGetValue(channelName, out var act)) + if (cr != null && cr.Message != null && cr.Message.Value != null && !new Guid(cr.Message.Key.Id.ToByteArray()).Equals(Key) && Actions.TryGetValue(channelName, out var act)) { try { diff --git a/common/ASC.Common/Security/AscRandom.cs b/common/ASC.Common/Security/AscRandom.cs index c84035be2a..e50ea7fe2c 100644 --- a/common/ASC.Common/Security/AscRandom.cs +++ b/common/ASC.Common/Security/AscRandom.cs @@ -51,7 +51,7 @@ namespace ASC.Common.Security var num3 = 1; for (var i = 1; i < seeds.Length - 1; i++) { - var index = (21 * i) % (seeds.Length - 1); + var index = 21 * i % (seeds.Length - 1); seeds[index] = num3; num3 = num2 - num3; if (num3 < 0) diff --git a/common/ASC.Common/Utils/HttpRequestExtensions.cs b/common/ASC.Common/Utils/HttpRequestExtensions.cs index 63510288ce..5ecccafd33 100644 --- a/common/ASC.Common/Utils/HttpRequestExtensions.cs +++ b/common/ASC.Common/Utils/HttpRequestExtensions.cs @@ -186,7 +186,7 @@ namespace System.Web } const StringComparison cmp = StringComparison.OrdinalIgnoreCase; - if (0 < s.Length && (s.StartsWith('0'))) + if (0 < s.Length && s.StartsWith('0')) { s = Uri.UriSchemeHttp + s.Substring(1); } @@ -194,7 +194,7 @@ namespace System.Web { s = Uri.UriSchemeHttp + s.Substring(3); } - else if (0 < s.Length && (s.StartsWith('1'))) + else if (0 < s.Length && s.StartsWith('1')) { s = Uri.UriSchemeHttps + s.Substring(1); } diff --git a/common/ASC.Common/Utils/Wildcard.cs b/common/ASC.Common/Utils/Wildcard.cs index e3a36da22c..b0db7e137d 100644 --- a/common/ASC.Common/Utils/Wildcard.cs +++ b/common/ASC.Common/Utils/Wildcard.cs @@ -98,7 +98,7 @@ namespace ASC.Common.Utils while (i < pattern.Length && pattern[i] == '*') ++i; - return (offsetInput == input.Length); + return offsetInput == input.Length; } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs index 12dcf9a966..07c096202b 100644 --- a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs +++ b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs @@ -59,7 +59,7 @@ namespace ASC.Core this.tariffService = tariffService; Configuration = configuration; partnerUrl = (Configuration["core:payment:partners"] ?? "https://partners.onlyoffice.com/api").TrimEnd('/'); - partnerKey = (Configuration["core:machinekey"] ?? "C5C1F4E85A3A43F5B3202C24D97351DF"); + partnerKey = Configuration["core:machinekey"] ?? "C5C1F4E85A3A43F5B3202C24D97351DF"; ClientFactory = clientFactory; } diff --git a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs index 066ce000a5..ea1e8fe9c9 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -420,13 +420,13 @@ namespace ASC.Notify.Cron incr = 1; } AddToSet(sval, eval, incr, type); - return (i + 3); + return i + 3; } if (c == '?') { i++; if ((i + 1) < s.Length - && (s[i] != ' ' && s[i + 1] != '\t')) + && s[i] != ' ' && s[i + 1] != '\t') { throw new FormatException("Illegal character after '?': " + s[i]); @@ -669,7 +669,7 @@ namespace ASC.Notify.Cron end = v1; i = vs.Pos; } - if (i < s.Length && ((s[i]) == '/')) + if (i < s.Length && (s[i] == '/')) { i++; c = s[i]; @@ -1117,7 +1117,7 @@ namespace ASC.Notify.Cron } else { - sec = ((int)seconds.First()); + sec = (int)seconds.First(); d = d.AddMinutes(1); } d = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, sec, d.Millisecond); @@ -1129,7 +1129,7 @@ namespace ASC.Notify.Cron if (st != null && st.Count != 0) { t = min; - min = ((int)st.First()); + min = (int)st.First(); } else { @@ -1249,7 +1249,7 @@ namespace ASC.Notify.Cron tcal = new DateTime(tcal.Year, mon, day, hr, min, sec); if (tcal.ToUniversalTime() < afterTimeUtc) { - day = ((int)daysOfMonth.First()); + day = (int)daysOfMonth.First(); mon++; } } @@ -1267,7 +1267,7 @@ namespace ASC.Notify.Cron } else { - day = ((int)daysOfMonth.First()); + day = (int)daysOfMonth.First(); mon++; } if (day != t || mon != tmon) @@ -1295,9 +1295,9 @@ namespace ASC.Notify.Cron { if (lastdayOfWeek) { - var dow = ((int)daysOfWeek.First()); + var dow = (int)daysOfWeek.First(); - var cDow = ((int)d.DayOfWeek); + var cDow = (int)d.DayOfWeek; var daysToAdd = 0; if (cDow < dow) { @@ -1338,9 +1338,9 @@ namespace ASC.Notify.Cron } else if (nthdayOfWeek != 0) { - var dow = ((int)daysOfWeek.First()); + var dow = (int)daysOfWeek.First(); - var cDow = ((int)d.DayOfWeek); + var cDow = (int)d.DayOfWeek; var daysToAdd = 0; if (cDow < dow) { @@ -1389,12 +1389,12 @@ namespace ASC.Notify.Cron else { var cDow = ((int)d.DayOfWeek) + 1; - var dow = ((int)daysOfWeek.First()); + var dow = (int)daysOfWeek.First(); st = daysOfWeek.TailSet(cDow); if (st != null && st.Count > 0) { - dow = ((int)st.First()); + dow = (int)st.First(); } var daysToAdd = 0; if (cDow < dow) @@ -1444,15 +1444,15 @@ namespace ASC.Notify.Cron return null; } - st = months.TailSet((mon)); + st = months.TailSet(mon); if (st != null && st.Count != 0) { t = mon; - mon = ((int)st.First()); + mon = (int)st.First(); } else { - mon = ((int)months.First()); + mon = (int)months.First(); year++; } if (mon != t) @@ -1462,11 +1462,11 @@ namespace ASC.Notify.Cron } d = new DateTime(d.Year, mon, d.Day, d.Hour, d.Minute, d.Second); year = d.Year; - st = years.TailSet((year)); + st = years.TailSet(year); if (st != null && st.Count != 0) { t = year; - year = ((int)st.First()); + year = (int)st.First(); } else { diff --git a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs index e57bbbd7ee..77b11a7b07 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -38,7 +38,7 @@ namespace ASC.Core.Notify private UserManager UserManager { get; } public RecipientProviderImpl(UserManager userManager) => - (UserManager) = (userManager); + UserManager = userManager; public virtual IRecipient GetRecipient(string id) { if (TryParseGuid(id, out var recID)) diff --git a/common/ASC.Core.Common/Security/Authorizing/RoleProvider.cs b/common/ASC.Core.Common/Security/Authorizing/RoleProvider.cs index b89b13757f..72d094e6f9 100644 --- a/common/ASC.Core.Common/Security/Authorizing/RoleProvider.cs +++ b/common/ASC.Core.Common/Security/Authorizing/RoleProvider.cs @@ -43,7 +43,7 @@ namespace ASC.Core.Security.Authorizing { //circ dep private IServiceProvider ServiceProvider { get; } - public RoleProvider(IServiceProvider serviceProvider) => (ServiceProvider) = (serviceProvider); + public RoleProvider(IServiceProvider serviceProvider) => ServiceProvider = serviceProvider; public List<IRole> GetRoles(ISubject account) { diff --git a/common/ASC.Core.Common/Tenants/TenantCookieSettings.cs b/common/ASC.Core.Common/Tenants/TenantCookieSettings.cs index e2ce90f933..d738cdf29d 100644 --- a/common/ASC.Core.Common/Tenants/TenantCookieSettings.cs +++ b/common/ASC.Core.Common/Tenants/TenantCookieSettings.cs @@ -91,7 +91,7 @@ namespace ASC.Core.Tenants public void SetForTenant(int tenantId, TenantCookieSettings settings = null) { if (!IsVisibleSettings) return; - SettingsManager.SaveForTenant((settings ?? TenantCookieSettings.GetInstance()), tenantId); + SettingsManager.SaveForTenant(settings ?? TenantCookieSettings.GetInstance(), tenantId); } public TenantCookieSettings GetForUser(Guid userId) @@ -111,7 +111,7 @@ namespace ASC.Core.Tenants public void SetForUser(Guid userId, TenantCookieSettings settings = null) { if (!IsVisibleSettings) return; - SettingsManager.SaveForUser((settings ?? TenantCookieSettings.GetInstance()), userId); + SettingsManager.SaveForUser(settings ?? TenantCookieSettings.GetInstance(), userId); } public DateTime GetExpiresTime(int tenantId) diff --git a/common/ASC.Data.Backup.Core/Core/DbHelper.cs b/common/ASC.Data.Backup.Core/Core/DbHelper.cs index 8aca730396..64abdee234 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -117,7 +117,7 @@ namespace ASC.Data.Backup tables = connect .GetSchema("Tables") .Select(@"TABLE_TYPE <> 'SYSTEM_TABLE'") - .Select(row => ((string)row["TABLE_NAME"])); + .Select(row => (string)row["TABLE_NAME"]); } return tables diff --git a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs index 6d6a618577..2b03e88768 100644 --- a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs +++ b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs @@ -559,14 +559,14 @@ namespace ASC.Data.Backup.Service tenantManager.SaveTenant(tenant); var columnMapper = new ColumnMapper(); - columnMapper.SetMapping("tenants_tenants", "alias", tenant.TenantAlias, (Guid.Parse(Id)).ToString("N")); + columnMapper.SetMapping("tenants_tenants", "alias", tenant.TenantAlias, Guid.Parse(Id).ToString("N")); columnMapper.Commit(); var restoreTask = restorePortalTask; restoreTask.Init(ConfigPaths[CurrentRegion], tempFile, TenantId, columnMapper, UpgradesPath); restoreTask.ProgressChanged += (sender, args) => { - Percentage = Percentage = (10d + 0.65 * args.Progress); + Percentage = Percentage = 10d + 0.65 * args.Progress; PublishChanges(); }; restoreTask.RunJob(); diff --git a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs index f5ddd47fe4..a952f1b609 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -605,7 +605,7 @@ namespace ASC.Data.Backup.Tasks Logger.DebugFormat("end saving table {0}", table.Name); } - SetCurrentStepProgress((int)((++tablesProcessed * 100) / (double)tablesCount)); + SetCurrentStepProgress((int)(++tablesProcessed * 100 / (double)tablesCount)); } } Logger.DebugFormat("end saving data for module {0}", module.ModuleName); diff --git a/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs index 2888a72d7b..46bcbbbaf2 100644 --- a/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs @@ -75,7 +75,7 @@ namespace ASC.Data.Backup.Tasks var t = (TableInfo)state; module.CreateDeleteCommand(connection.Fix(), TenantId, t).WithTimeout(120).ExecuteNonQuery(); }, table, 5, onFailure: error => { throw ThrowHelper.CantDeleteTable(table.Name, error); }); - SetCurrentStepProgress((int)((++tablesProcessed * 100) / (double)tablesCount)); + SetCurrentStepProgress((int)(++tablesProcessed * 100 / (double)tablesCount)); } } Logger.DebugFormat("end delete data for module ({0})", module.ModuleName); @@ -96,7 +96,7 @@ namespace ASC.Data.Backup.Tasks onFailure: error => Logger.WarnFormat("Can't delete files for domain {0}: \r\n{1}", domain, error)); } storage.DeleteFiles("\\", "*.*", true); - SetCurrentStepProgress((int)((++modulesProcessed * 100) / (double)storageModules.Count)); + SetCurrentStepProgress((int)(++modulesProcessed * 100 / (double)storageModules.Count)); } Logger.Debug("end delete storage"); } diff --git a/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs index 7ff38c2187..1665c36e3f 100644 --- a/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs @@ -230,7 +230,7 @@ namespace ASC.Data.Backup.Tasks $"where alias = '{alias}'"; if (!string.IsNullOrEmpty(whereCondition)) - commandText += (" and " + whereCondition); + commandText += " and " + whereCondition; var command = connection.CreateCommand(); command.CommandText = commandText; command.WithTimeout(120).ExecuteNonQuery(); diff --git a/common/ASC.Data.Storage/S3/S3Storage.cs b/common/ASC.Data.Storage/S3/S3Storage.cs index af7ce40e5d..f0e003ee0c 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -151,12 +151,12 @@ namespace ASC.Data.Storage.S3 foreach (var h in headers) { - if (h.StartsWith("Content-Disposition")) headersOverrides.ContentDisposition = (h.Substring("Content-Disposition".Length + 1)); - else if (h.StartsWith("Cache-Control")) headersOverrides.CacheControl = (h.Substring("Cache-Control".Length + 1)); - else if (h.StartsWith("Content-Encoding")) headersOverrides.ContentEncoding = (h.Substring("Content-Encoding".Length + 1)); - else if (h.StartsWith("Content-Language")) headersOverrides.ContentLanguage = (h.Substring("Content-Language".Length + 1)); - else if (h.StartsWith("Content-Type")) headersOverrides.ContentType = (h.Substring("Content-Type".Length + 1)); - else if (h.StartsWith("Expires")) headersOverrides.Expires = (h.Substring("Expires".Length + 1)); + if (h.StartsWith("Content-Disposition")) headersOverrides.ContentDisposition = h.Substring("Content-Disposition".Length + 1); + else if (h.StartsWith("Cache-Control")) headersOverrides.CacheControl = h.Substring("Cache-Control".Length + 1); + else if (h.StartsWith("Content-Encoding")) headersOverrides.ContentEncoding = h.Substring("Content-Encoding".Length + 1); + else if (h.StartsWith("Content-Language")) headersOverrides.ContentLanguage = h.Substring("Content-Language".Length + 1); + else if (h.StartsWith("Content-Type")) headersOverrides.ContentType = h.Substring("Content-Type".Length + 1); + else if (h.StartsWith("Expires")) headersOverrides.Expires = h.Substring("Expires".Length + 1); else throw new FormatException($"Invalid header: {h}"); } pUrlRequest.ResponseHeaderOverrides = headersOverrides; @@ -951,7 +951,7 @@ namespace ASC.Data.Storage.S3 { using (var client = GetClient()) { - var request = new ListObjectsRequest { BucketName = _bucket, Prefix = (MakePath(domain, path)) }; + var request = new ListObjectsRequest { BucketName = _bucket, Prefix = MakePath(domain, path) }; var response = client.ListObjectsAsync(request).Result; return response.S3Objects.Count > 0; } @@ -965,7 +965,7 @@ namespace ASC.Data.Storage.S3 public override long GetFileSize(string domain, string path) { using var client = GetClient(); - var request = new ListObjectsRequest { BucketName = _bucket, Prefix = (MakePath(domain, path)) }; + var request = new ListObjectsRequest { BucketName = _bucket, Prefix = MakePath(domain, path) }; var response = client.ListObjectsAsync(request).Result; if (response.S3Objects.Count > 0) { @@ -1059,7 +1059,7 @@ namespace ASC.Data.Storage.S3 { BucketName = _bucket, Prefix = path, - MaxKeys = (1000) + MaxKeys = 1000 }; var objects = new List<S3Object>(); diff --git a/common/ASC.Data.Storage/WebPath.cs b/common/ASC.Data.Storage/WebPath.cs index a9e233dba3..40f97243bb 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -96,7 +96,7 @@ namespace ASC.Data.Storage Appender appender; if (avaliableAppendersCount > 1) { - appender = avaliableAppenders[(relativePath.Length % avaliableAppendersCount)]; + appender = avaliableAppenders[relativePath.Length % avaliableAppendersCount]; } else if (avaliableAppendersCount == 1) { diff --git a/common/ASC.Data.Storage/Wildcard.cs b/common/ASC.Data.Storage/Wildcard.cs index a945ed3166..68a297f566 100644 --- a/common/ASC.Data.Storage/Wildcard.cs +++ b/common/ASC.Data.Storage/Wildcard.cs @@ -90,7 +90,7 @@ namespace ASC.Data.Storage } // final evaluation. The index should be pointing at the // end of the string. - return (offsetInput == input.Length); + return offsetInput == input.Length; } } } \ No newline at end of file diff --git a/common/ASC.FederatedLogin/Helpers/HashHelper.cs b/common/ASC.FederatedLogin/Helpers/HashHelper.cs index 6d7d828e38..d4cf589bc3 100644 --- a/common/ASC.FederatedLogin/Helpers/HashHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/HashHelper.cs @@ -34,7 +34,7 @@ namespace ASC.FederatedLogin.Helpers { if (hash2 == 0) return hash1; - return (((hash1 << 5) + hash1) ^ hash2); + return ((hash1 << 5) + hash1) ^ hash2; } //Use this luke!!! diff --git a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs index 9f4b8d006c..6be75592bb 100644 --- a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs @@ -88,8 +88,8 @@ namespace ASC.FederatedLogin.Helpers query = additionalArgs.Keys.Where(additionalArg => additionalArg != null) .Aggregate(query, (current, additionalArg) => additionalArg != null ? current - + ("&" + HttpUtility.UrlEncode((additionalArg).Trim()) - + "=" + HttpUtility.UrlEncode((additionalArgs[additionalArg] ?? "").Trim())) : null); + + "&" + HttpUtility.UrlEncode(additionalArg.Trim()) + + "=" + HttpUtility.UrlEncode((additionalArgs[additionalArg] ?? "").Trim()) : null); } return uriBuilder.Uri + "?" + query; diff --git a/common/ASC.IPSecurity/IPAddressRange.cs b/common/ASC.IPSecurity/IPAddressRange.cs index 8052978b4f..c98dbc9295 100644 --- a/common/ASC.IPSecurity/IPAddressRange.cs +++ b/common/ASC.IPSecurity/IPAddressRange.cs @@ -66,8 +66,8 @@ namespace ASC.IPSecurity return false; } - lowerBoundary &= (addressByte == lowerByte); - upperBoundary &= (addressByte == upperByte); + lowerBoundary &= addressByte == lowerByte; + upperBoundary &= addressByte == upperByte; } return true; diff --git a/common/ASC.Textile/Blocks/BlockAttributesParser.cs b/common/ASC.Textile/Blocks/BlockAttributesParser.cs index 288fa0998a..e0b5e11abf 100644 --- a/common/ASC.Textile/Blocks/BlockAttributesParser.cs +++ b/common/ASC.Textile/Blocks/BlockAttributesParser.cs @@ -52,7 +52,7 @@ namespace Textile.Blocks } if (input.Length == 0) - return (style.Length > 0 ? " style=\"" + style + "\"" : ""); + return style.Length > 0 ? " style=\"" + style + "\"" : ""; Match m; @@ -133,14 +133,14 @@ namespace Textile.Blocks - return ( + return (style.Length > 0 ? " style=\"" + style + "\"" : "") + (cssClass.Length > 0 ? " class=\"" + cssClass + "\"" : "") + (lang.Length > 0 ? " lang=\"" + lang + "\"" : "") + (id.Length > 0 ? " id=\"" + id + "\"" : "") + (colspan.Length > 0 ? " colspan=\"" + colspan + "\"" : "") + (rowspan.Length > 0 ? " rowspan=\"" + rowspan + "\"" : "") - ); + ; } private static string GetStyle(string element, string style) diff --git a/common/ASC.Textile/States/ListFormatterState.cs b/common/ASC.Textile/States/ListFormatterState.cs index 72b8b5510e..b6c660f46c 100644 --- a/common/ASC.Textile/States/ListFormatterState.cs +++ b/common/ASC.Textile/States/ListFormatterState.cs @@ -86,7 +86,7 @@ namespace Textile.States public sealed override bool ShouldNestState(FormatterState other) { var listState = (ListFormatterState)other; - return (listState.NestingDepth > NestingDepth); + return listState.NestingDepth > NestingDepth; } public sealed override bool ShouldExit(string input) diff --git a/common/ASC.Textile/States/SimpleBlockFormatterState.cs b/common/ASC.Textile/States/SimpleBlockFormatterState.cs index 2a494b36e0..b1a0a84905 100644 --- a/common/ASC.Textile/States/SimpleBlockFormatterState.cs +++ b/common/ASC.Textile/States/SimpleBlockFormatterState.cs @@ -35,9 +35,9 @@ namespace Textile.States public override bool ShouldNestState(FormatterState other) { var blockFormatterState = (SimpleBlockFormatterState)other; - return (blockFormatterState.Tag != Tag || + return blockFormatterState.Tag != Tag || blockFormatterState.AlignInfo != AlignInfo || - blockFormatterState.AttInfo != AttInfo); + blockFormatterState.AttInfo != AttInfo; } protected virtual void OnContextAcquired() diff --git a/common/ASC.Textile/States/TableFormatterState.cs b/common/ASC.Textile/States/TableFormatterState.cs index 93dbb96189..ca6aafed00 100644 --- a/common/ASC.Textile/States/TableFormatterState.cs +++ b/common/ASC.Textile/States/TableFormatterState.cs @@ -58,7 +58,7 @@ namespace Textile.States @"(\.\s?)?(?<tag>\|)" + @"(?<content>.*)(?=\|)" ); - return (!m.Success); + return !m.Success; } protected string FormattedStylesAndAlignment() diff --git a/common/services/ASC.ElasticSearch/Core/Selector.cs b/common/services/ASC.ElasticSearch/Core/Selector.cs index 8b0c33fdbc..74dfb147ab 100644 --- a/common/services/ASC.ElasticSearch/Core/Selector.cs +++ b/common/services/ASC.ElasticSearch/Core/Selector.cs @@ -207,7 +207,7 @@ namespace ASC.ElasticSearch { var t = ServiceProvider.GetService<T>(); var searchSettingsHelper = ServiceProvider.GetService<SearchSettingsHelper>(); - return ((NewArrayExpression)(t.GetSearchContentFields(searchSettingsHelper)).Body).Expressions.ToArray(); + return ((NewArrayExpression)t.GetSearchContentFields(searchSettingsHelper).Body).Expressions.ToArray(); }, value); diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs index f3808eff58..140afdde8c 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs @@ -1176,7 +1176,7 @@ namespace ASC.Files.Core.Data public string GetBunchObjectID(int folderID) { return Query(FilesDbContext.BunchObjects) - .Where(r => r.LeftNode == (folderID).ToString()) + .Where(r => r.LeftNode == folderID.ToString()) .Select(r => r.RightNode) .FirstOrDefault(); } diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index 09ded4768a..1aef4898eb 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -317,8 +317,8 @@ namespace ASC.Web.Files.Services.WCFService || parent.RootFolderType == FolderType.Privacy; entries = entries.Where(x => x.FileEntryType == FileEntryType.Folder || - (x is File<string> f1 && !FileConverter.IsConverting(f1) || - x is File<int> f2 && !FileConverter.IsConverting(f2))); + x is File<string> f1 && !FileConverter.IsConverting(f1) || + x is File<int> f2 && !FileConverter.IsConverting(f2)); var result = new DataWrapper<T> { diff --git a/products/ASC.Files/Core/Core/Security/FileSecurity.cs b/products/ASC.Files/Core/Core/Security/FileSecurity.cs index c177c363ae..647d211718 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -712,8 +712,8 @@ namespace ASC.Files.Core.Security var records = securityDao.GetShares(subjects); var result = new List<FileEntry>(); - result.AddRange(GetSharesForMe<int>(records.Where(r => (r.EntryId is int)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); - result.AddRange(GetSharesForMe<string>(records.Where(r => (r.EntryId is string)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); + result.AddRange(GetSharesForMe<int>(records.Where(r => r.EntryId is int), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); + result.AddRange(GetSharesForMe<string>(records.Where(r => r.EntryId is string), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); return result; } @@ -832,8 +832,8 @@ namespace ASC.Files.Core.Security var records = securityDao.GetShares(subjects); var result = new List<FileEntry>(); - result.AddRange(GetPrivacyForMe<int>(records.Where(r => (r.EntryId is int)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); - result.AddRange(GetPrivacyForMe<string>(records.Where(r => (r.EntryId is string)), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); + result.AddRange(GetPrivacyForMe<int>(records.Where(r => r.EntryId is int), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); + result.AddRange(GetPrivacyForMe<string>(records.Where(r => r.EntryId is string), subjects, filterType, subjectGroup, subjectID, searchText, searchInContent, withSubfolders)); return result; } diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs index 1cd4f28b60..a23d86a359 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs @@ -92,9 +92,9 @@ namespace ASC.Files.Thirdparty.OneDrive { return onedriveItem == null || IsRoot(onedriveItem) ? string.Empty - : (OneDriveStorage.MakeOneDrivePath( + : OneDriveStorage.MakeOneDrivePath( new Regex("^" + OneDriveStorage.RootPath).Replace(onedriveItem.ParentReference.Path, ""), - onedriveItem.Name)); + onedriveItem.Name); } protected string MakeItemTitle(Item onedriveItem) diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs index 352d94bffb..bcdb7d7323 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs @@ -165,7 +165,7 @@ namespace ASC.Files.Thirdparty.SharePoint { SharePointProviderInfoHelper.PublishFolder(MakeId(GetParentFolderId(id))); var serverException = (ServerException)ex; - if (serverException.ServerErrorTypeName == (typeof(FileNotFoundException)).ToString()) + if (serverException.ServerErrorTypeName == typeof(FileNotFoundException).ToString()) { return null; } @@ -388,7 +388,7 @@ namespace ASC.Files.Thirdparty.SharePoint { SharePointProviderInfoHelper.PublishFolder(MakeId(GetParentFolderId(id))); var serverException = (ServerException)ex; - if (serverException.ServerErrorTypeName == (typeof(FileNotFoundException)).ToString()) + if (serverException.ServerErrorTypeName == typeof(FileNotFoundException).ToString()) { return null; } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs index a2cb4e3b16..340c8aea65 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs @@ -433,7 +433,7 @@ namespace ASC.Files.Thirdparty.Sharpbox protected IEnumerable<ICloudFileSystemEntry> GetFolderSubfolders(ICloudDirectoryEntry folder) { - return folder.Where(x => (x is ICloudDirectoryEntry)); + return folder.Where(x => x is ICloudDirectoryEntry); } protected string GetAvailableTitle(string requestTitle, ICloudDirectoryEntry parentFolder, Func<string, ICloudDirectoryEntry, bool> isExist) diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs index b9783258ef..965f1c3323 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs @@ -314,7 +314,7 @@ namespace ASC.Files.Thirdparty.Sharpbox var webException = (WebException)e.InnerException; if (webException != null) { - var response = ((HttpWebResponse)webException.Response); + var response = (HttpWebResponse)webException.Response; if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden) diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFolderDao.cs index 96877abb9b..b30b9339f5 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFolderDao.cs @@ -205,7 +205,7 @@ namespace ASC.Files.Thirdparty.Sharpbox var webException = (WebException)e.InnerException; if (webException != null) { - var response = ((HttpWebResponse)webException.Response); + var response = (HttpWebResponse)webException.Response; if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden) diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs index 1e9841d6ee..4070b97190 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -565,7 +565,7 @@ namespace ASC.Web.Files.Services.DocumentService { Logger.Error( string.Format("DocService mailMerge{0} error: userId - {1}, url - {2}", - (fileData.MailMerge == null ? "" : " " + fileData.MailMerge.RecordIndex + "/" + fileData.MailMerge.RecordCount), + fileData.MailMerge == null ? "" : " " + fileData.MailMerge.RecordIndex + "/" + fileData.MailMerge.RecordCount, userId, fileData.Url), ex); saveMessage = ex.Message; diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index d794bc8124..ed90fd22be 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -772,7 +772,7 @@ namespace ASC.Web.Files.Utils { var cmp = 0; if (x.FileEntryType == FileEntryType.File && y.FileEntryType == FileEntryType.File) - cmp = c * (FileUtility.GetFileExtension((x.Title)).CompareTo(FileUtility.GetFileExtension(y.Title))); + cmp = c * FileUtility.GetFileExtension(x.Title).CompareTo(FileUtility.GetFileExtension(y.Title)); return cmp == 0 ? x.Title.EnumerableComparer(y.Title) : cmp; } , diff --git a/products/ASC.Files/Core/Utils/FileMarker.cs b/products/ASC.Files/Core/Utils/FileMarker.cs index 1dd1c569b4..56f45af9dd 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -549,8 +549,8 @@ namespace ASC.Web.Files.Utils .ToList(); //TODO: refactoring - var entryTagsProvider = GetEntryTags<string>(tags.Where(r=> (r.EntryId is string))); - var entryTagsInternal = GetEntryTags<int>(tags.Where(r=> (r.EntryId is int))); + var entryTagsProvider = GetEntryTags<string>(tags.Where(r=> r.EntryId is string)); + var entryTagsInternal = GetEntryTags<int>(tags.Where(r=> r.EntryId is int)); foreach (var entryTag in entryTagsInternal) { diff --git a/products/ASC.Files/Core/Utils/FileSharing.cs b/products/ASC.Files/Core/Utils/FileSharing.cs index ba65129f43..fa34b85c61 100644 --- a/products/ASC.Files/Core/Utils/FileSharing.cs +++ b/products/ASC.Files/Core/Utils/FileSharing.cs @@ -299,7 +299,7 @@ namespace ASC.Web.Files.Utils if (entry == null) throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest); if (!CanSetAccess(entry)) { - Logger.ErrorFormat("User {0} can't get shared info for {1} {2}", AuthContext.CurrentAccount.ID, (entry.FileEntryType == FileEntryType.File ? "file" : "folder"), entry.ID); + Logger.ErrorFormat("User {0} can't get shared info for {1} {2}", AuthContext.CurrentAccount.ID, entry.FileEntryType == FileEntryType.File ? "file" : "folder", entry.ID); throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException); } diff --git a/products/ASC.Files/Core/Utils/FileTracker.cs b/products/ASC.Files/Core/Utils/FileTracker.cs index a4c3dc0d87..0e066dcdf4 100644 --- a/products/ASC.Files/Core/Utils/FileTracker.cs +++ b/products/ASC.Files/Core/Utils/FileTracker.cs @@ -66,7 +66,7 @@ namespace ASC.Web.Files.Utils if (tracker.EditingBy.TryGetValue(tabId, out var trackInfo)) { trackInfo.TrackTime = DateTime.UtcNow; - checkRight = (DateTime.UtcNow - tracker.EditingBy[tabId].CheckRightTime > CheckRightTimeout); + checkRight = DateTime.UtcNow - tracker.EditingBy[tabId].CheckRightTime > CheckRightTimeout; } else { diff --git a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs index bbcec0bd94..04dbcb3d3d 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -248,7 +248,7 @@ namespace ASC.Files.Helpers if (FilesLinkUtility.IsLocalFileUploader) { - var session = FileUploader.InitiateUpload(file.FolderID, (file.ID ?? default), file.Title, file.ContentLength, encrypted); + var session = FileUploader.InitiateUpload(file.FolderID, file.ID ?? default, file.Title, file.ContentLength, encrypted); var responseObject = ChunkedUploadSessionHelper.ToResponseObject(session, true); return new diff --git a/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs b/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs index 0ce47f95d0..2de3ef40fc 100644 --- a/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs +++ b/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs @@ -109,11 +109,11 @@ namespace ASC.Files.ThumbnailBuilder !r.tariff.Comment.Contains("trial") ) ) && - ( + !r.quota.Features.Contains("free") && !r.quota.Features.Contains("non-profit") && !r.quota.Features.Contains("trial") - ) + ) .GroupBy(r => r.tariff.Tenant) .Select(r => new { tenant = r.Key, stamp = r.Max(b => b.tariff.Stamp) }) diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index c6aeefaf99..1906780259 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1168,7 +1168,7 @@ namespace ASC.Api.Settings foreach (var f in HttpContext.Request.Form.Files) { var parts = f.FileName.Split('.'); - var logoType = (WhiteLabelLogoTypeEnum)(Convert.ToInt32(parts[0])); + var logoType = (WhiteLabelLogoTypeEnum)Convert.ToInt32(parts[0]); var fileExt = parts[1]; TenantWhiteLabelSettingsHelper.SetLogoFromStream(settings, logoType, fileExt, f.OpenReadStream(), storage); } @@ -1983,9 +1983,9 @@ namespace ASC.Api.Settings return dueDate >= DateTime.UtcNow.Date ? Resource.LicenseUploaded : string.Format( - (TenantExtra.GetTenantQuota().Update + TenantExtra.GetTenantQuota().Update ? Resource.LicenseUploadedOverdueSupport - : Resource.LicenseUploadedOverdue), + : Resource.LicenseUploadedOverdue, "", "", dueDate.Date.ToLongDateString()); diff --git a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs index e99749ff90..b1d4bdd894 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -120,7 +120,7 @@ namespace ASC.Web.Core.Calendars { get { - return ((Id ?? "").ToLower()) switch + return (Id ?? "").ToLower() switch { "su" => DayOfWeek.Sunday, "mo" => DayOfWeek.Monday, @@ -256,7 +256,7 @@ namespace ASC.Web.Core.Calendars { var dates = new List<DateTime>(); var utcStartDateOffset = isAllDayLong ? TimeSpan.Zero : eventTimeZone.GetUtcOffset(utcStartDate); - var endDate = (this.Until == DateTime.MinValue ? toDate : (toDate > this.Until ? this.Until : toDate)); + var endDate = this.Until == DateTime.MinValue ? toDate : (toDate > this.Until ? this.Until : toDate); //push start date dates.Add(utcStartDate); @@ -381,10 +381,10 @@ namespace ASC.Web.Core.Calendars dateRange.RemoveAll(date => !ByMonth.Contains(date.Month)); if (ByYearDay != null) - dateRange.RemoveAll(date => (!ByYearDay.Contains(date.DayOfYear) && !ByYearDay.Contains(date.DayOfYear - (date.GetDaysInYear() + 1)))); + dateRange.RemoveAll(date => !ByYearDay.Contains(date.DayOfYear) && !ByYearDay.Contains(date.DayOfYear - (date.GetDaysInYear() + 1))); if (ByMonthDay != null) - dateRange.RemoveAll(date => (!ByMonthDay.Contains(date.Day) && !ByMonthDay.Contains(date.Day - (date.GetDaysInMonth() + 1)))); + dateRange.RemoveAll(date => !ByMonthDay.Contains(date.Day) && !ByMonthDay.Contains(date.Day - (date.GetDaysInMonth() + 1))); if (ByDay != null) dateRange.RemoveAll(date => !ByDay.Any(wd => wd.DayOfWeek == date.DayOfWeek)); @@ -392,7 +392,7 @@ namespace ASC.Web.Core.Calendars if (ByDay == null && ByMonthDay == null && ByYearDay == null) dateRange.RemoveAll(date => date.Day != d.Day); - GetDatesWithTime(ref dates, utcStartDate, endDate, (d - utcStartDateOffset), dateRange.Select(item => item - utcStartDateOffset).ToList()); + GetDatesWithTime(ref dates, utcStartDate, endDate, d - utcStartDateOffset, dateRange.Select(item => item - utcStartDateOffset).ToList()); d = d.AddDays(7 * this.Interval); @@ -422,10 +422,10 @@ namespace ASC.Web.Core.Calendars } if (ByYearDay != null) - dateRange.RemoveAll(date => (!ByYearDay.Contains(date.DayOfYear) && !ByYearDay.Contains(date.DayOfYear - (date.GetDaysInYear() + 1)))); + dateRange.RemoveAll(date => !ByYearDay.Contains(date.DayOfYear) && !ByYearDay.Contains(date.DayOfYear - (date.GetDaysInYear() + 1))); if (ByMonthDay != null) - dateRange.RemoveAll(date => (!ByMonthDay.Contains(date.Day) && !ByMonthDay.Contains(date.Day - (date.GetDaysInMonth() + 1)))); + dateRange.RemoveAll(date => !ByMonthDay.Contains(date.Day) && !ByMonthDay.Contains(date.Day - (date.GetDaysInMonth() + 1))); //only for MONTHLY or YEARLY if (ByDay != null) @@ -440,7 +440,7 @@ namespace ASC.Web.Core.Calendars if (ByDay == null && ByMonthDay == null && ByYearDay == null) dateRange.RemoveAll(date => date.Day != d.Day); - GetDatesWithTime(ref dates, utcStartDate, endDate, (d - utcStartDateOffset), dateRange); + GetDatesWithTime(ref dates, utcStartDate, endDate, d - utcStartDateOffset, dateRange); var nextd = d.AddMonths(this.Interval); @@ -527,7 +527,7 @@ namespace ASC.Web.Core.Calendars dateRange.Add(new DateTime(d.Year, 1, 1).AddDays((yearDay > 0 ? yearDay : (d.GetDaysInYear() + yearDay)) - 1)); } else - dateRange.RemoveAll(date => (!ByYearDay.Contains(date.DayOfYear) && !ByYearDay.Contains(date.DayOfYear - (date.GetDaysInYear() + 1)))); + dateRange.RemoveAll(date => !ByYearDay.Contains(date.DayOfYear) && !ByYearDay.Contains(date.DayOfYear - (date.GetDaysInYear() + 1))); isFirst = false; } @@ -547,7 +547,7 @@ namespace ASC.Web.Core.Calendars } } else - dateRange.RemoveAll(date => (!ByMonthDay.Contains(date.Day) && !ByMonthDay.Contains(date.Day - (date.GetDaysInMonth() + 1)))); + dateRange.RemoveAll(date => !ByMonthDay.Contains(date.Day) && !ByMonthDay.Contains(date.Day - (date.GetDaysInMonth() + 1))); isFirst = false; } @@ -576,7 +576,7 @@ namespace ASC.Web.Core.Calendars if (isFirst) dateRange.Add(d); - GetDatesWithTime(ref dates, utcStartDate, endDate, (d - utcStartDateOffset), dateRange); + GetDatesWithTime(ref dates, utcStartDate, endDate, d - utcStartDateOffset, dateRange); d = d.AddYears(this.Interval); @@ -869,7 +869,7 @@ namespace ASC.Web.Core.Calendars public static Frequency ParseFrequency(string frequency) { - return (frequency.ToLower()) switch + return frequency.ToLower() switch { "monthly" => Frequency.Monthly, @@ -963,7 +963,7 @@ namespace ASC.Web.Core.Calendars foreach (var date in val.Split(',')) { if (DateTime.TryParseExact(date.ToUpper(), _dateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var dt)) - rr.ExDates.Add(new ExDate() { Date = dt, IsDateTime = (date.IndexOf('t', StringComparison.InvariantCultureIgnoreCase) >= 0) }); + rr.ExDates.Add(new ExDate() { Date = dt, IsDateTime = date.IndexOf('t', StringComparison.InvariantCultureIgnoreCase) >= 0 }); } break; diff --git a/web/ASC.Web.Core/CommonPhotoManager.cs b/web/ASC.Web.Core/CommonPhotoManager.cs index 05df7623f8..bedb1f67e4 100644 --- a/web/ASC.Web.Core/CommonPhotoManager.cs +++ b/web/ASC.Web.Core/CommonPhotoManager.cs @@ -53,7 +53,7 @@ namespace ASC.Web.Core var alignWidth = crop ? (minSide == realWidth) : (maxSide == realWidth); - var scaleFactor = (alignWidth) ? (realWidth / (1.0 * width)) : (realHeight / (1.0 * height)); + var scaleFactor = alignWidth ? (realWidth / (1.0 * width)) : (realHeight / (1.0 * height)); if (scaleFactor < 1) scaleFactor = 1; diff --git a/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs b/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs index c19fd9e50a..a574a8b5dc 100644 --- a/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs +++ b/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs @@ -38,7 +38,7 @@ namespace ASC.Web.Core.Helpers int[] formsTable = { 2, 0, 1, 1, 1, 2, 2, 2, 2, 2 }; number = Math.Abs(number); - var res = formsTable[((((number % 100) / 10) != 1) ? 1 : 0) * (number % 10)]; + var res = formsTable[(((number % 100 / 10) != 1) ? 1 : 0) * (number % 10)]; return res switch { 0 => nominative, diff --git a/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs b/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs index c83aa94c5e..8a87666a1b 100644 --- a/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs +++ b/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs @@ -106,7 +106,7 @@ namespace ASC.Web.Core.Helpers { 0 => false, 1 => true, - _ => ((value & (value - 1)) == 0), + _ => (value & (value - 1)) == 0, }; } @@ -216,7 +216,7 @@ namespace ASC.Web.Core.Helpers { if (value is string @string) { - var result = (_isFlagEnum) ? + var result = _isFlagEnum ? GetFlagValue(culture, @string) : GetValue(culture, @string); if (result == null) { @@ -242,7 +242,7 @@ namespace ASC.Web.Core.Helpers { if (value != null && destinationType == typeof(string)) { - object result = (_isFlagEnum) ? + object result = _isFlagEnum ? GetFlagValueText(culture, value) : GetValueText(culture, value); return result; } diff --git a/web/ASC.Web.Core/Notify/StudioNotifyService.cs b/web/ASC.Web.Core/Notify/StudioNotifyService.cs index 6039ff24a6..d828bee1c5 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyService.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyService.cs @@ -144,7 +144,7 @@ namespace ASC.Web.Studio.Core.Notify var salesEmail = SettingsManager.LoadForDefaultTenant<AdditionalWhiteLabelSettings>().SalesEmail ?? SetupInfo.SalesEmail; - var recipient = (IRecipient)(new DirectRecipient(AuthContext.CurrentAccount.ID.ToString(), string.Empty, new[] { salesEmail }, false)); + var recipient = (IRecipient)new DirectRecipient(AuthContext.CurrentAccount.ID.ToString(), string.Empty, new[] { salesEmail }, false); client.SendNoticeToAsync(license ? Actions.RequestLicense : Actions.RequestTariff, new[] { recipient }, diff --git a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs index 3cf016e4ca..0c371cf36f 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -502,7 +502,7 @@ namespace ASC.Web.Studio.Core.Notify var quota = tenantManager.GetTenantQuota(tenant.TenantId); var createdDate = tenant.CreatedDateTime.Date; - var actualEndDate = (tariff.DueDate != DateTime.MaxValue ? tariff.DueDate : tariff.LicenseDate); + var actualEndDate = tariff.DueDate != DateTime.MaxValue ? tariff.DueDate : tariff.LicenseDate; var dueDateIsNotMax = actualEndDate != DateTime.MaxValue; var dueDate = actualEndDate.Date; diff --git a/web/ASC.Web.Core/Tfa/TfaManager.cs b/web/ASC.Web.Core/Tfa/TfaManager.cs index fe357f2875..c09ac5f33b 100644 --- a/web/ASC.Web.Core/Tfa/TfaManager.cs +++ b/web/ASC.Web.Core/Tfa/TfaManager.cs @@ -190,7 +190,7 @@ namespace ASC.Web.Studio.Core.TFA var result = new StringBuilder(length); foreach (var b in data) { - result.Append(alphabet[b % (alphabet.Length)]); + result.Append(alphabet[b % alphabet.Length]); } list.Add(new BackupCode(InstanceCrypto, Signature, result.ToString())); diff --git a/web/ASC.Web.Core/Users/UserPhotoManager.cs b/web/ASC.Web.Core/Users/UserPhotoManager.cs index ace0e0c302..9f8c81f955 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -834,7 +834,7 @@ namespace ASC.Web.Core.Users var moduleID = Guid.Empty; var widening = CommonPhotoManager.GetImgFormatName(format); var size = img.Size(); - var fileName = string.Format("{0}{1}_size_{2}-{3}.{4}", (moduleID == Guid.Empty ? "" : moduleID.ToString()), userID, img.Width, img.Height, widening); + var fileName = string.Format("{0}{1}_size_{2}-{3}.{4}", moduleID == Guid.Empty ? "" : moduleID.ToString(), userID, img.Width, img.Height, widening); var store = GetDataStore(); string photoUrl; diff --git a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs index 474b4a4f45..5f778ad637 100644 --- a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs +++ b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs @@ -347,7 +347,7 @@ namespace ASC.Web.Core.WhiteLabel foreach (var currentLogo in logo) { - var currentLogoType = (WhiteLabelLogoTypeEnum)(currentLogo.Key); + var currentLogoType = (WhiteLabelLogoTypeEnum)currentLogo.Key; var currentLogoPath = currentLogo.Value; if (!string.IsNullOrEmpty(currentLogoPath)) From d86085d9f559b05cb74179d4d140fc70b4feed3b Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:57:22 +0300 Subject: [PATCH 092/167] analizators/s2292 --- common/ASC.Textile/Globals.cs | 27 ++++++--------------------- 1 file changed, 6 insertions(+), 21 deletions(-) diff --git a/common/ASC.Textile/Globals.cs b/common/ASC.Textile/Globals.cs index 6a0c0fa422..34dfea0f2d 100644 --- a/common/ASC.Textile/Globals.cs +++ b/common/ASC.Textile/Globals.cs @@ -44,44 +44,29 @@ namespace Textile #endregion - private static Dictionary<string, string> m_imageAlign; /// <summary> /// Image alignment tags, mapped to their HTML meanings. /// </summary> - public static Dictionary<string, string> ImageAlign - { - get { return Globals.m_imageAlign; } - set { Globals.m_imageAlign = value; } - } - private static Dictionary<string, string> m_horizontalAlign; + public static Dictionary<string, string> ImageAlign { get; set; } /// <summary> /// Horizontal text alignment tags, mapped to their HTML meanings. /// </summary> - public static Dictionary<string, string> HorizontalAlign - { - get { return Globals.m_horizontalAlign; } - set { Globals.m_horizontalAlign = value; } - } - private static Dictionary<string, string> m_verticalAlign; + public static Dictionary<string, string> HorizontalAlign { get; set; } /// <summary> /// Vertical text alignment tags, mapped to their HTML meanings. /// </summary> - public static Dictionary<string, string> VerticalAlign - { - get { return Globals.m_verticalAlign; } - set { Globals.m_verticalAlign = value; } - } + public static Dictionary<string, string> VerticalAlign { get; set;} static Globals() { - m_imageAlign = new Dictionary<string, string> + ImageAlign = new Dictionary<string, string> { ["<"] = "left", ["="] = "center", [">"] = "right" }; - m_horizontalAlign = new Dictionary<string, string> + HorizontalAlign = new Dictionary<string, string> { ["<"] = "left", ["="] = "center", @@ -89,7 +74,7 @@ namespace Textile ["<>"] = "justify" }; - m_verticalAlign = new Dictionary<string, string> + VerticalAlign = new Dictionary<string, string> { ["^"] = "top", ["-"] = "middle", From 8d0324ee2a0658abef1b29ad9fb8e9c7e7209da7 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Fri, 21 Jan 2022 16:59:17 +0300 Subject: [PATCH 093/167] analizators/s2326 --- common/ASC.Core.Common/EF/Context/DbContextManager.cs | 2 +- products/ASC.Files/Core/Core/FileStorageService.cs | 4 ++-- products/ASC.Files/Core/HttpHandlers/SearchHandler.cs | 6 +++--- products/ASC.Files/Core/Utils/EntryManager.cs | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/common/ASC.Core.Common/EF/Context/DbContextManager.cs b/common/ASC.Core.Common/EF/Context/DbContextManager.cs index 690367553b..e3252aacc1 100644 --- a/common/ASC.Core.Common/EF/Context/DbContextManager.cs +++ b/common/ASC.Core.Common/EF/Context/DbContextManager.cs @@ -88,7 +88,7 @@ namespace ASC.Core.Common.EF public static class DbContextManagerExtension { - public static DIHelper AddDbContextManagerService<T>(this DIHelper services) where T : BaseDbContext, new() + public static DIHelper AddDbContextManagerService(this DIHelper services) { //TODO //services.TryAddScoped<MultiRegionalDbContextManager<T>>(); diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index 1aef4898eb..be27708c0c 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -1214,7 +1214,7 @@ namespace ASC.Web.Files.Services.WCFService var folders = providersInfo.Select(providerInfo => { - var folder = EntryManager.GetFakeThirdpartyFolder<T>(providerInfo); + var folder = EntryManager.GetFakeThirdpartyFolder(providerInfo); folder.NewForMe = folder.RootFolderType == FolderType.COMMON ? 1 : 0; return folder; }); @@ -1309,7 +1309,7 @@ namespace ASC.Web.Files.Services.WCFService var curProviderId = Convert.ToInt32(providerId); var providerInfo = providerDao.GetProviderInfo(curProviderId); - var folder = EntryManager.GetFakeThirdpartyFolder<T>(providerInfo); + var folder = EntryManager.GetFakeThirdpartyFolder(providerInfo); ErrorIf(!FileSecurity.CanDelete(folder), FilesCommonResource.ErrorMassage_SecurityException_DeleteFolder); if (providerInfo.RootFolderType == FolderType.COMMON) diff --git a/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs b/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs index b14d6a41cd..7ff59c49aa 100644 --- a/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs +++ b/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs @@ -143,7 +143,7 @@ namespace ASC.Web.Files.Configuration Additional = new Dictionary<string, object> { { "Author", file.CreateByString.HtmlEncode() }, - { "Path", FolderPathBuilder<int>(EntryManager.GetBreadCrumbs(file.FolderID, folderDao)) }, + { "Path", FolderPathBuilder(EntryManager.GetBreadCrumbs(file.FolderID, folderDao)) }, { "Size", FileSizeComment.FilesSizeToString(file.ContentLength) } } }; @@ -162,7 +162,7 @@ namespace ASC.Web.Files.Configuration Additional = new Dictionary<string, object> { { "Author", folder.CreateByString.HtmlEncode() }, - { "Path", FolderPathBuilder<int>(EntryManager.GetBreadCrumbs(folder.ID, folderDao)) }, + { "Path", FolderPathBuilder(EntryManager.GetBreadCrumbs(folder.ID, folderDao)) }, { "IsFolder", true } } }; @@ -172,7 +172,7 @@ namespace ASC.Web.Files.Configuration return list.ToArray(); } - private static string FolderPathBuilder<T>(IEnumerable<FileEntry> folders) + private static string FolderPathBuilder(IEnumerable<FileEntry> folders) { var titles = folders.Select(f => f.Title).ToList(); const string separator = " \\ "; diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index ed90fd22be..50ca9904fa 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -589,7 +589,7 @@ namespace ASC.Web.Files.Utils var providers = providerDao.GetProvidersInfo(parent.RootFolderType, searchText); folderList = providers - .Select(providerInfo => GetFakeThirdpartyFolder<T>(providerInfo, parent.ID.ToString())) + .Select(providerInfo => GetFakeThirdpartyFolder(providerInfo, parent.ID.ToString())) .Where(r => fileSecurity.CanRead(r)).ToList(); if (folderList.Count > 0) @@ -829,7 +829,7 @@ namespace ASC.Web.Files.Utils return result; } - public Folder<string> GetFakeThirdpartyFolder<T>(IProviderInfo providerInfo, string parentFolderId = null) + public Folder<string> GetFakeThirdpartyFolder(IProviderInfo providerInfo, string parentFolderId = null) { //Fake folder. Don't send request to third party var folder = ServiceProvider.GetService<Folder<string>>(); From f3cc581047a4f07d2ce72e56074da1138c88b2eb Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 24 Jan 2022 11:41:44 +0300 Subject: [PATCH 094/167] analizators/bugfix --- common/ASC.Core.Common/EF/Context/DbContextManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/ASC.Core.Common/EF/Context/DbContextManager.cs b/common/ASC.Core.Common/EF/Context/DbContextManager.cs index e3252aacc1..690367553b 100644 --- a/common/ASC.Core.Common/EF/Context/DbContextManager.cs +++ b/common/ASC.Core.Common/EF/Context/DbContextManager.cs @@ -88,7 +88,7 @@ namespace ASC.Core.Common.EF public static class DbContextManagerExtension { - public static DIHelper AddDbContextManagerService(this DIHelper services) + public static DIHelper AddDbContextManagerService<T>(this DIHelper services) where T : BaseDbContext, new() { //TODO //services.TryAddScoped<MultiRegionalDbContextManager<T>>(); From 9ad899e72a4eb3ef998787cc8e04104aea6a9e23 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 24 Jan 2022 12:27:43 +0300 Subject: [PATCH 095/167] analizators/s1264 --- common/ASC.Common/Utils/Wildcard.cs | 4 ++-- common/ASC.Data.Storage/Wildcard.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/common/ASC.Common/Utils/Wildcard.cs b/common/ASC.Common/Utils/Wildcard.cs index b0db7e137d..a08b686e7c 100644 --- a/common/ASC.Common/Utils/Wildcard.cs +++ b/common/ASC.Common/Utils/Wildcard.cs @@ -51,8 +51,8 @@ namespace ASC.Common.Utils { var offsetInput = 0; var isAsterix = false; - int i; - for (i = 0; i < pattern.Length;) + int i = 0; + while (i < pattern.Length) { switch (pattern[i]) { diff --git a/common/ASC.Data.Storage/Wildcard.cs b/common/ASC.Data.Storage/Wildcard.cs index 68a297f566..235c47a8b5 100644 --- a/common/ASC.Data.Storage/Wildcard.cs +++ b/common/ASC.Data.Storage/Wildcard.cs @@ -38,8 +38,8 @@ namespace ASC.Data.Storage var offsetInput = 0; var isAsterix = false; - int i; - for (i = 0; i < pattern.Length;) + int i = 0; + while (i < pattern.Length) { switch (pattern[i]) { From 9292ba4eee1733518e7d0e1835436a755913e20f Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 24 Jan 2022 12:28:00 +0300 Subject: [PATCH 096/167] analizators/s2589 --- common/ASC.Common/Threading/DistributedTaskQueue.cs | 4 ++-- common/ASC.Core.Common/BaseCommonLinkUtility.cs | 2 +- common/ASC.Core.Common/Data/DbTenantService.cs | 13 ++++++------- .../ASC.Core.Common/Notify/Engine/NotifyEngine.cs | 2 +- .../Security/Authorizing/AzManager.cs | 2 +- .../ASC.Data.Storage/DiscStorage/DiscDataStore.cs | 2 +- 6 files changed, 12 insertions(+), 13 deletions(-) diff --git a/common/ASC.Common/Threading/DistributedTaskQueue.cs b/common/ASC.Common/Threading/DistributedTaskQueue.cs index 1801ead832..2454e50c28 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -232,7 +232,7 @@ namespace ASC.Common.Threading using var scope = ServiceProvider.CreateScope(); var task = scope.ServiceProvider.GetService<T>(); task.DistributedTaskCache = cache; - if (task != null && task.Publication == null) + if (task.Publication == null) { task.Publication = GetPublication(); } @@ -249,7 +249,7 @@ namespace ASC.Common.Threading { var task = new DistributedTask(); task.DistributedTaskCache = cache; - if (task != null && task.Publication == null) + if (task.Publication == null) { task.Publication = GetPublication(); } diff --git a/common/ASC.Core.Common/BaseCommonLinkUtility.cs b/common/ASC.Core.Common/BaseCommonLinkUtility.cs index 495fc732bb..8ef62e58ef 100644 --- a/common/ASC.Core.Common/BaseCommonLinkUtility.cs +++ b/common/ASC.Core.Common/BaseCommonLinkUtility.cs @@ -185,7 +185,7 @@ namespace ASC.Core.Common virtualPath.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) return virtualPath; - if (string.IsNullOrEmpty(virtualPath) || virtualPath.StartsWith('/')) + if (virtualPath.StartsWith('/')) { return ServerRootPath + virtualPath; } diff --git a/common/ASC.Core.Common/Data/DbTenantService.cs b/common/ASC.Core.Common/Data/DbTenantService.cs index ad2caf1a04..5d8a0f25a2 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -478,16 +478,15 @@ namespace ASC.Core.Data } // forbidden or exists - var exists = false; + var exists = false; + domain = domain.ToLowerInvariant(); - if (!exists) + if (forbiddenDomains == null) { - if (forbiddenDomains == null) - { - forbiddenDomains = TenantDbContext.TenantForbiden.Select(r => r.Address).ToList(); - } - exists = tenantId != 0 && forbiddenDomains.Contains(domain); + forbiddenDomains = TenantDbContext.TenantForbiden.Select(r => r.Address).ToList(); } + exists = tenantId != 0 && forbiddenDomains.Contains(domain); + if (!exists) { exists = TenantDbContext.Tenants.Where(r => r.Alias == domain && r.Id != tenantId).Any(); diff --git a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs index 29b040578a..5687bb7880 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -255,7 +255,7 @@ namespace ASC.Notify.Engine } NotifyResult result; - if (sendResponces == null || sendResponces.Count == 0) + if (sendResponces.Count == 0) { result = new NotifyResult(SendResult.OK, sendResponces); } diff --git a/common/ASC.Core.Common/Security/Authorizing/AzManager.cs b/common/ASC.Core.Common/Security/Authorizing/AzManager.cs index 61283bf637..8705c8d8b0 100644 --- a/common/ASC.Core.Common/Security/Authorizing/AzManager.cs +++ b/common/ASC.Core.Common/Security/Authorizing/AzManager.cs @@ -76,7 +76,7 @@ namespace ASC.Common.Security.Authorizing var aceList = permissionProvider.GetAcl(s, action, objectId, securityObjProvider); foreach (var ace in aceList) { - if (ace.Reaction == AceType.Deny && !exit) + if (ace.Reaction == AceType.Deny) { acl.IsAllow = false; acl.DenySubject = s; diff --git a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs index 6bce910864..bdc6f4d4f8 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -427,7 +427,7 @@ namespace ASC.Data.Storage.DiscStorage if (string.IsNullOrEmpty(targetDir)) throw new Exception("targetDir is null"); - if (!string.IsNullOrEmpty(targetDir) && !targetDir.EndsWith(Path.DirectorySeparatorChar.ToString())) + if (!targetDir.EndsWith(Path.DirectorySeparatorChar.ToString())) { targetDir += Path.DirectorySeparatorChar; } From fb3a61d0d22729bddd47fef312f3072ca324cbb8 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 24 Jan 2022 12:57:01 +0300 Subject: [PATCH 097/167] analizators/s3442 --- common/ASC.Api.Core/Routing/FormatRoute.cs | 2 +- common/ASC.Common/Collections/HttpRequestDictionary.cs | 2 +- common/ASC.Common/DIHelper.cs | 6 +++--- common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs | 2 +- common/ASC.Core.Common/Notify/NotifySource.cs | 4 ++-- common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs | 6 +++--- common/ASC.Data.Backup.Core/Service/BackupWorker.cs | 2 +- .../Tasks/Modules/ModuleSpecificsBase.cs | 2 +- common/ASC.Data.Storage/BaseStorage.cs | 4 ++-- common/ASC.Textile/Blocks/PhraseBlockModifier.cs | 2 +- common/ASC.Textile/FormatterState.cs | 2 +- common/ASC.Textile/States/ListFormatterState.cs | 2 +- common/services/ASC.AuditTrail/AuditEventsRepository.cs | 2 +- common/services/ASC.AuditTrail/LoginEventsRepository.cs | 2 +- common/services/ASC.Feed.Aggregator/Modules/FeedModule.cs | 2 +- common/services/ASC.TelegramService/Core/Core.cs | 2 +- products/ASC.Files/Core/Core/Entries/FileEntry.cs | 2 +- products/ASC.Files/Core/Core/Security/FileSecurity.cs | 2 +- products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs | 2 +- .../Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs | 2 +- .../Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoBase.cs | 2 +- .../Core/Core/Thirdparty/IThirdPartyProviderDao.cs | 2 +- .../Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs | 2 +- .../Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs | 2 +- .../Services/WCFService/FileOperations/FileOperation.cs | 2 +- web/ASC.Web.Core/Calendars/BaseCalendar.cs | 2 +- web/ASC.Web.Core/Calendars/BaseEvent.cs | 2 +- web/ASC.Web.Core/Calendars/BaseTodo.cs | 2 +- 28 files changed, 34 insertions(+), 34 deletions(-) diff --git a/common/ASC.Api.Core/Routing/FormatRoute.cs b/common/ASC.Api.Core/Routing/FormatRoute.cs index c10998e402..d18cc4adbd 100644 --- a/common/ASC.Api.Core/Routing/FormatRoute.cs +++ b/common/ASC.Api.Core/Routing/FormatRoute.cs @@ -10,7 +10,7 @@ namespace ASC.Web.Api.Routing public bool Check { get; set; } public bool DisableFormat { get; set; } - public CustomHttpMethodAttribute(string method, string template = null, bool check = true, int order = 1) + protected CustomHttpMethodAttribute(string method, string template = null, bool check = true, int order = 1) : base(new List<string>() { method }, $"[controller]{(template != null ? $"/{template}" : "")}") { Check = check; diff --git a/common/ASC.Common/Collections/HttpRequestDictionary.cs b/common/ASC.Common/Collections/HttpRequestDictionary.cs index cf8e2b0c4f..9aa3f06475 100644 --- a/common/ASC.Common/Collections/HttpRequestDictionary.cs +++ b/common/ASC.Common/Collections/HttpRequestDictionary.cs @@ -29,7 +29,7 @@ namespace ASC.Collections { public sealed class HttpRequestDictionary<T> : CachedDictionaryBase<T> { - private class CachedItem + private sealed class CachedItem { internal T Value { get; set; } diff --git a/common/ASC.Common/DIHelper.cs b/common/ASC.Common/DIHelper.cs index dbb8dcee3f..f07571420a 100644 --- a/common/ASC.Common/DIHelper.cs +++ b/common/ASC.Common/DIHelper.cs @@ -97,14 +97,14 @@ namespace ASC.Common public Type Service { get; } public Type Additional { get; set; } - public DIAttribute() { } + protected DIAttribute() { } - public DIAttribute(Type service) + protected DIAttribute(Type service) { Service = service; } - public DIAttribute(Type service, Type implementation) + protected DIAttribute(Type service, Type implementation) { Implementation = implementation; Service = service; diff --git a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs index 5687bb7880..df3c0c651b 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -575,7 +575,7 @@ namespace ASC.Notify.Engine } - private class SendMethodWrapper + private sealed class SendMethodWrapper { private readonly object locker = new object(); private readonly CronExpression cronExpression; diff --git a/common/ASC.Core.Common/Notify/NotifySource.cs b/common/ASC.Core.Common/Notify/NotifySource.cs index 76917bcb21..89258ede8f 100644 --- a/common/ASC.Core.Common/Notify/NotifySource.cs +++ b/common/ASC.Core.Common/Notify/NotifySource.cs @@ -67,7 +67,7 @@ namespace ASC.Core.Notify private UserManager UserManager { get; } private SubscriptionManager SubscriptionManager { get; } - public NotifySource(string id, UserManager userManager, IRecipientProvider recipientsProvider, SubscriptionManager subscriptionManager) + protected NotifySource(string id, UserManager userManager, IRecipientProvider recipientsProvider, SubscriptionManager subscriptionManager) { if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); @@ -77,7 +77,7 @@ namespace ASC.Core.Notify SubscriptionManager = subscriptionManager; } - public NotifySource(Guid id, UserManager userManager, IRecipientProvider recipientsProvider, SubscriptionManager subscriptionManager) + protected NotifySource(Guid id, UserManager userManager, IRecipientProvider recipientsProvider, SubscriptionManager subscriptionManager) : this(id.ToString(), userManager, recipientsProvider, subscriptionManager) { } diff --git a/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs b/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs index 40a0d196a6..98a291822e 100644 --- a/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs +++ b/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs @@ -45,16 +45,16 @@ namespace ASC.Notify.Patterns } - public PatternFormatter() + protected PatternFormatter() { } - public PatternFormatter(string tagSearchRegExp) + protected PatternFormatter(string tagSearchRegExp) : this(tagSearchRegExp, false) { } - internal PatternFormatter(string tagSearchRegExp, bool formatMessage) + protected PatternFormatter(string tagSearchRegExp, bool formatMessage) { if (string.IsNullOrEmpty(tagSearchRegExp)) throw new ArgumentException("tagSearchRegExp"); diff --git a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs index 2b03e88768..6ea1eb38d9 100644 --- a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs +++ b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs @@ -334,7 +334,7 @@ namespace ASC.Data.Backup.Service protected IServiceProvider ServiceProvider { get; set; } - public BaseBackupProgressItem(IOptionsMonitor<ILog> options, IServiceProvider serviceProvider) + protected BaseBackupProgressItem(IOptionsMonitor<ILog> options, IServiceProvider serviceProvider) { Log = options.CurrentValue; ServiceProvider = serviceProvider; diff --git a/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs b/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs index 06066c8b1c..8cb6a321a9 100644 --- a/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/Modules/ModuleSpecificsBase.cs @@ -49,7 +49,7 @@ namespace ASC.Data.Backup.Tasks.Modules public abstract IEnumerable<TableInfo> Tables { get; } public abstract IEnumerable<RelationInfo> TableRelations { get; } private readonly Helpers helpers; - public ModuleSpecificsBase(Helpers helpers) + protected ModuleSpecificsBase(Helpers helpers) { this.helpers = helpers; } diff --git a/common/ASC.Data.Storage/BaseStorage.cs b/common/ASC.Data.Storage/BaseStorage.cs index b0c8f49873..2b1ab92397 100644 --- a/common/ASC.Data.Storage/BaseStorage.cs +++ b/common/ASC.Data.Storage/BaseStorage.cs @@ -55,8 +55,8 @@ namespace ASC.Data.Storage protected IHttpContextAccessor HttpContextAccessor { get; } protected IOptionsMonitor<ILog> Options { get; } protected IHttpClientFactory ClientFactory { get; } - - public BaseStorage( + + protected BaseStorage( TempStream tempStream, TenantManager tenantManager, PathUtils pathUtils, diff --git a/common/ASC.Textile/Blocks/PhraseBlockModifier.cs b/common/ASC.Textile/Blocks/PhraseBlockModifier.cs index 985c506815..d77e9993f8 100644 --- a/common/ASC.Textile/Blocks/PhraseBlockModifier.cs +++ b/common/ASC.Textile/Blocks/PhraseBlockModifier.cs @@ -61,7 +61,7 @@ namespace Textile.Blocks return res; } - private class PhraseModifierMatchEvaluator + private sealed class PhraseModifierMatchEvaluator { readonly string m_tag; diff --git a/common/ASC.Textile/FormatterState.cs b/common/ASC.Textile/FormatterState.cs index c51cdb3f7c..b65085b095 100644 --- a/common/ASC.Textile/FormatterState.cs +++ b/common/ASC.Textile/FormatterState.cs @@ -36,7 +36,7 @@ namespace Textile /// Public constructor. /// </summary> /// <param name="f">The parent formatter.</param> - public FormatterState(TextileFormatter formatter) + protected FormatterState(TextileFormatter formatter) { Formatter = formatter; } diff --git a/common/ASC.Textile/States/ListFormatterState.cs b/common/ASC.Textile/States/ListFormatterState.cs index b6c660f46c..fbeaef8518 100644 --- a/common/ASC.Textile/States/ListFormatterState.cs +++ b/common/ASC.Textile/States/ListFormatterState.cs @@ -36,7 +36,7 @@ namespace Textile.States get { return m_tag.Length; } } - public ListFormatterState(TextileFormatter formatter) + protected ListFormatterState(TextileFormatter formatter) : base(formatter) { } diff --git a/common/services/ASC.AuditTrail/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/AuditEventsRepository.cs index 80dcd7049a..ed70d20b3f 100644 --- a/common/services/ASC.AuditTrail/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/AuditEventsRepository.cs @@ -69,7 +69,7 @@ namespace ASC.AuditTrail return Get(tenant, from, to, null); } - private class Query + private sealed class Query { public Core.Common.EF.Model.AuditEvent AuditEvent { get; set; } public User User { get; set; } diff --git a/common/services/ASC.AuditTrail/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/LoginEventsRepository.cs index a364647bfb..edfccf89f0 100644 --- a/common/services/ASC.AuditTrail/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/LoginEventsRepository.cs @@ -61,7 +61,7 @@ namespace ASC.AuditTrail.Data LazyMessagesContext = new Lazy<MessagesContext>(() => dbMessagesContext.Value); } - private class Query + private sealed class Query { public LoginEvents LoginEvents { get; set; } public User User { get; set; } diff --git a/common/services/ASC.Feed.Aggregator/Modules/FeedModule.cs b/common/services/ASC.Feed.Aggregator/Modules/FeedModule.cs index c676c283ee..84964b39c1 100644 --- a/common/services/ASC.Feed.Aggregator/Modules/FeedModule.cs +++ b/common/services/ASC.Feed.Aggregator/Modules/FeedModule.cs @@ -49,7 +49,7 @@ namespace ASC.Feed.Aggregator.Modules protected TenantManager TenantManager { get; } protected WebItemSecurity WebItemSecurity { get; } - public FeedModule(TenantManager tenantManager, WebItemSecurity webItemSecurity) + protected FeedModule(TenantManager tenantManager, WebItemSecurity webItemSecurity) { TenantManager = tenantManager; WebItemSecurity = webItemSecurity; diff --git a/common/services/ASC.TelegramService/Core/Core.cs b/common/services/ASC.TelegramService/Core/Core.cs index 5e4f66b4ca..387a2e1a2f 100644 --- a/common/services/ASC.TelegramService/Core/Core.cs +++ b/common/services/ASC.TelegramService/Core/Core.cs @@ -186,7 +186,7 @@ namespace ASC.TelegramService.Core public abstract class ParamParser<T> : ParamParser { - public ParamParser() : base(typeof(T)) { } + protected ParamParser() : base(typeof(T)) { } public override abstract object FromString(string arg); public override abstract string ToString(object arg); diff --git a/products/ASC.Files/Core/Core/Entries/FileEntry.cs b/products/ASC.Files/Core/Core/Entries/FileEntry.cs index 9a681671e5..67d9016b8d 100644 --- a/products/ASC.Files/Core/Core/Entries/FileEntry.cs +++ b/products/ASC.Files/Core/Core/Entries/FileEntry.cs @@ -46,7 +46,7 @@ namespace ASC.Files.Core } - public FileEntry(FileHelper fileHelper, Global global) + protected FileEntry(FileHelper fileHelper, Global global) { FileHelper = fileHelper; Global = global; diff --git a/products/ASC.Files/Core/Core/Security/FileSecurity.cs b/products/ASC.Files/Core/Core/Security/FileSecurity.cs index 647d211718..0822201e1b 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -942,7 +942,7 @@ namespace ASC.Files.Core.Security return result; } - private class SubjectComparer : IComparer<FileShareRecord> + private sealed class SubjectComparer : IComparer<FileShareRecord> { private readonly List<Guid> _subjects; diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs index 59d16f94b4..be2793b2e0 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxDaoBase.cs @@ -51,7 +51,7 @@ namespace ASC.Files.Thirdparty.Box { protected override string Id { get => "box"; } - public BoxDaoBase( + protected BoxDaoBase( IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs index 6f0bb68169..07bc5d5017 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxDaoBase.cs @@ -51,7 +51,7 @@ namespace ASC.Files.Thirdparty.Dropbox { protected override string Id { get => "dropbox"; } - public DropboxDaoBase(IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, TenantUtil tenantUtil, DbContextManager<FilesDbContext> dbContextManager, SetupInfo setupInfo, IOptionsMonitor<ILog> monitor, FileUtility fileUtility, TempPath tempPath) + protected DropboxDaoBase(IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, TenantUtil tenantUtil, DbContextManager<FilesDbContext> dbContextManager, SetupInfo setupInfo, IOptionsMonitor<ILog> monitor, FileUtility fileUtility, TempPath tempPath) : base(serviceProvider, userManager, tenantManager, tenantUtil, dbContextManager, setupInfo, monitor, fileUtility, tempPath) { } diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoBase.cs index 16e833a95d..566c03555f 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveDaoBase.cs @@ -52,7 +52,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive { protected override string Id { get => "drive"; } - public GoogleDriveDaoBase(IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, TenantUtil tenantUtil, DbContextManager<FilesDbContext> dbContextManager, SetupInfo setupInfo, IOptionsMonitor<ILog> monitor, FileUtility fileUtility, TempPath tempPath) + protected GoogleDriveDaoBase(IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, TenantUtil tenantUtil, DbContextManager<FilesDbContext> dbContextManager, SetupInfo setupInfo, IOptionsMonitor<ILog> monitor, FileUtility fileUtility, TempPath tempPath) : base(serviceProvider, userManager, tenantManager, tenantUtil, dbContextManager, setupInfo, monitor, fileUtility, tempPath) { } diff --git a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs index fe1f4973c0..40f14f0aa7 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs @@ -229,7 +229,7 @@ namespace ASC.Files.Thirdparty protected abstract string Id { get; } - public ThirdPartyProviderDao( + protected ThirdPartyProviderDao( IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs index a23d86a359..399540137f 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveDaoBase.cs @@ -49,7 +49,7 @@ namespace ASC.Files.Thirdparty.OneDrive { protected override string Id { get => "onedrive"; } - public OneDriveDaoBase(IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, TenantUtil tenantUtil, DbContextManager<FilesDbContext> dbContextManager, SetupInfo setupInfo, IOptionsMonitor<ILog> monitor, FileUtility fileUtility, TempPath tempPath) + protected OneDriveDaoBase(IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, TenantUtil tenantUtil, DbContextManager<FilesDbContext> dbContextManager, SetupInfo setupInfo, IOptionsMonitor<ILog> monitor, FileUtility fileUtility, TempPath tempPath) : base(serviceProvider, userManager, tenantManager, tenantUtil, dbContextManager, setupInfo, monitor, fileUtility, tempPath) { } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs index 340c8aea65..a6a4f51077 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxDaoBase.cs @@ -53,7 +53,7 @@ namespace ASC.Files.Thirdparty.Sharpbox { protected override string Id { get => "sbox"; } - public SharpBoxDaoBase(IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, TenantUtil tenantUtil, DbContextManager<FilesDbContext> dbContextManager, SetupInfo setupInfo, IOptionsMonitor<ILog> monitor, FileUtility fileUtility, TempPath tempPath) + protected SharpBoxDaoBase(IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, TenantUtil tenantUtil, DbContextManager<FilesDbContext> dbContextManager, SetupInfo setupInfo, IOptionsMonitor<ILog> monitor, FileUtility fileUtility, TempPath tempPath) : base(serviceProvider, userManager, tenantManager, tenantUtil, dbContextManager, setupInfo, monitor, fileUtility, tempPath) { } diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperation.cs index 982333dbba..12243c63e9 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileOperation.cs @@ -79,7 +79,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations protected DistributedTask TaskInfo { get; set; } - public FileOperation(IServiceProvider serviceProvider) + protected FileOperation(IServiceProvider serviceProvider) { principal = serviceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()?.HttpContext?.User ?? Thread.CurrentPrincipal; culture = Thread.CurrentThread.CurrentCulture.Name; diff --git a/web/ASC.Web.Core/Calendars/BaseCalendar.cs b/web/ASC.Web.Core/Calendars/BaseCalendar.cs index fed61d0588..942991c97c 100644 --- a/web/ASC.Web.Core/Calendars/BaseCalendar.cs +++ b/web/ASC.Web.Core/Calendars/BaseCalendar.cs @@ -35,7 +35,7 @@ namespace ASC.Web.Core.Calendars { public abstract class BaseCalendar : ICalendar, ICloneable { - public BaseCalendar(AuthContext authContext, TimeZoneConverter timeZoneConverter) + protected BaseCalendar(AuthContext authContext, TimeZoneConverter timeZoneConverter) { this.Context = new CalendarContext(); this.SharingOptions = new SharingOptions(); diff --git a/web/ASC.Web.Core/Calendars/BaseEvent.cs b/web/ASC.Web.Core/Calendars/BaseEvent.cs index 17a4a895ff..dca6649370 100644 --- a/web/ASC.Web.Core/Calendars/BaseEvent.cs +++ b/web/ASC.Web.Core/Calendars/BaseEvent.cs @@ -33,7 +33,7 @@ namespace ASC.Web.Core.Calendars { public virtual TimeZoneInfo TimeZone { get; set; } - public BaseEvent() + protected BaseEvent() { this.Context = new EventContext(); this.AlertType = EventAlertType.Never; diff --git a/web/ASC.Web.Core/Calendars/BaseTodo.cs b/web/ASC.Web.Core/Calendars/BaseTodo.cs index 6dce6fff94..e2f81514cb 100644 --- a/web/ASC.Web.Core/Calendars/BaseTodo.cs +++ b/web/ASC.Web.Core/Calendars/BaseTodo.cs @@ -33,7 +33,7 @@ namespace ASC.Web.Core.Calendars { internal TimeZoneInfo TimeZone { get; set; } - public BaseTodo() + protected BaseTodo() { this.Context = new TodoContext(); } From 0fcac4768630beb5213ed50cc4d36a136a7c1eeb Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 24 Jan 2022 13:01:19 +0300 Subject: [PATCH 098/167] analizators/s3604 --- common/ASC.Core.Common/Billing/CouponManager.cs | 2 +- common/services/ASC.Webhooks.Service/WorkerService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/common/ASC.Core.Common/Billing/CouponManager.cs b/common/ASC.Core.Common/Billing/CouponManager.cs index 9fd7056160..27cd20b1a7 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -56,7 +56,7 @@ namespace ASC.Core.Common.Billing private readonly byte[] Secret; private readonly Uri BaseAddress; private readonly string ApiVersion; - private readonly SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1); + private readonly SemaphoreSlim SemaphoreSlim; private readonly ILog Log; diff --git a/common/services/ASC.Webhooks.Service/WorkerService.cs b/common/services/ASC.Webhooks.Service/WorkerService.cs index 402cdab757..3b4c0173f3 100644 --- a/common/services/ASC.Webhooks.Service/WorkerService.cs +++ b/common/services/ASC.Webhooks.Service/WorkerService.cs @@ -13,7 +13,7 @@ namespace ASC.Webhooks.Service [Singletone] public class WorkerService { - private readonly int? threadCount = 10; + private readonly int? threadCount; private readonly WebhookSender webhookSender; private readonly ConcurrentQueue<WebhookRequest> queue; private CancellationToken cancellationToken; From fce8d26cef9aa8f39404d79dd738ac348152b1eb Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 24 Jan 2022 13:49:00 +0300 Subject: [PATCH 099/167] analizators/ca1507 --- common/ASC.Api.Core/Core/ApiDateTime.cs | 2 +- common/ASC.Common/Data/StreamExtension.cs | 4 +- common/ASC.Common/Data/TempStream.cs | 2 +- .../ASC.Core.Common/Billing/BillingClient.cs | 2 +- .../Billing/License/LicenseReader.cs | 2 +- .../ASC.Core.Common/Billing/TariffService.cs | 4 +- .../Caching/CachedAzService.cs | 2 +- .../Caching/CachedQuotaService.cs | 2 +- .../Caching/CachedSubscriptionService.cs | 2 +- .../Caching/CachedTenantService.cs | 2 +- .../Caching/CachedUserService.cs | 2 +- .../Configuration/SmtpSettings.cs | 10 ++--- .../Context/Impl/CoreConfiguration.cs | 4 +- .../Context/Impl/PaymentManager.cs | 2 +- .../Context/Impl/TenantManager.cs | 2 +- .../Context/SecurityContext.cs | 4 +- .../ASC.Core.Common/Core/DBResourceManager.cs | 4 +- common/ASC.Core.Common/Data/DbQuotaService.cs | 4 +- .../ASC.Core.Common/Data/DbSettingsManager.cs | 2 +- .../Data/DbSubscriptionService.cs | 38 ++++++++-------- .../ASC.Core.Common/Data/DbTenantService.cs | 4 +- common/ASC.Core.Common/Data/DbUserService.cs | 4 +- .../Encryption/EncryptionSettings.cs | 4 +- .../Notify/Channels/SenderChannel.cs | 6 +-- .../Notify/DirectSubscriptionProvider.cs | 40 ++++++++--------- .../ASC.Core.Common/Notify/EmailSenderSink.cs | 2 +- .../Notify/Engine/DispatchEngine.cs | 2 +- .../Notify/Engine/InterceptorStorage.cs | 8 ++-- .../Notify/Engine/NotifyEngine.cs | 14 +++--- .../Notify/Engine/NotifyRequest.cs | 8 ++-- .../Notify/Engine/SendInterceptorSkeleton.cs | 4 +- .../Notify/JabberSenderSink.cs | 2 +- .../Notify/Messages/NoticeMessage.cs | 12 ++--- .../Notify/Model/NotifyAction.cs | 2 +- .../Notify/Model/NotifyClientImpl.cs | 10 ++--- common/ASC.Core.Common/Notify/NotifySource.cs | 2 +- .../Notify/Patterns/Pattern.cs | 4 +- .../Notify/Patterns/PatternFormatter.cs | 6 +-- .../Notify/Patterns/TagValue.cs | 2 +- .../Notify/RecipientProviderImpl.cs | 6 +-- .../Notify/Sinks/DispatchSink.cs | 2 +- .../Notify/Telegram/TelegramSenderSink.cs | 2 +- .../Notify/TopSubscriptionProvider.cs | 40 ++++++++--------- .../Security/Authorizing/AzManager.cs | 8 ++-- .../Authorizing/PermissionProvider.cs | 4 +- .../Authorizing/PermissionResolver.cs | 2 +- .../Security/EmailValidationKeyProvider.cs | 8 ++-- common/ASC.Core.Common/Users/UserFormatter.cs | 2 +- common/ASC.Data.Backup.Core/ActionInvoker.cs | 2 +- .../Extensions/EnumerableExtensions.cs | 10 ++--- .../Tasks/BackupPortalTask.cs | 2 +- .../Tasks/PortalTaskBase.cs | 6 +-- .../Tasks/RestoreDbModuleTask.cs | 6 +-- .../Tasks/RestorePortalTask.cs | 2 +- .../Tasks/TransferPortalTask.cs | 2 +- common/ASC.Data.Storage/BaseStorage.cs | 2 +- .../CrossModuleTransferUtility.cs | 12 ++--- .../DiscStorage/DiscDataStore.cs | 44 +++++++++---------- common/ASC.Data.Storage/Extensions.cs | 4 +- common/ASC.Data.Storage/ProgressStream.cs | 2 +- common/ASC.Data.Storage/S3/S3Storage.cs | 2 +- common/ASC.Data.Storage/TenantPath.cs | 2 +- common/ASC.Data.Storage/WebPath.cs | 4 +- .../Helpers/OAuth20TokenHelper.cs | 4 +- .../Helpers/RequestHelper.cs | 2 +- .../LoginProviders/DocuSignLoginProvider.cs | 2 +- .../LoginProviders/ProviderManager.cs | 2 +- .../MultiRegionAccountLinker.cs | 2 +- .../Profile/LoginProfile.cs | 8 ++-- .../ASC.VoipService/Twilio/TwilioProvider.cs | 4 +- .../ASC.ElasticSearch/Engine/BaseIndexer.cs | 2 +- .../Core/Core/Dao/TeamlabDao/FileDao.cs | 12 ++--- .../Core/Core/Dao/TeamlabDao/FolderDao.cs | 12 ++--- .../Core/Core/Dao/TeamlabDao/TagDao.cs | 4 +- .../Core/Core/Entries/EncryptionKeyPair.cs | 4 +- .../ASC.Files/Core/Core/FilesIntegration.cs | 2 +- .../Core/Core/Thirdparty/Box/BoxFileDao.cs | 6 +-- .../Core/Core/Thirdparty/Box/BoxFolderDao.cs | 2 +- .../Core/Core/Thirdparty/Box/BoxStorage.cs | 2 +- .../Core/Thirdparty/Dropbox/DropboxFileDao.cs | 6 +-- .../Thirdparty/Dropbox/DropboxFolderDao.cs | 2 +- .../GoogleDrive/GoogleDriveFileDao.cs | 6 +-- .../GoogleDrive/GoogleDriveFolderDao.cs | 2 +- .../GoogleDrive/GoogleDriveStorage.cs | 6 +-- .../Thirdparty/OneDrive/OneDriveFileDao.cs | 6 +-- .../Thirdparty/OneDrive/OneDriveFolderDao.cs | 2 +- .../Thirdparty/OneDrive/OneDriveStorage.cs | 6 +-- .../Thirdparty/ProviderDao/ProviderFileDao.cs | 12 ++--- .../ProviderDao/ProviderFolderDao.cs | 2 +- .../Core/Thirdparty/RegexDaoSelectorBase.cs | 2 +- .../SharePoint/SharePointFileDao.cs | 4 +- .../Thirdparty/Sharpbox/SharpBoxFileDao.cs | 6 +-- .../ASC.Files/Core/Helpers/DocuSignHelper.cs | 14 +++--- .../ASC.Files/Core/Helpers/PathProvider.cs | 8 ++-- .../ASC.Files/Core/Helpers/WordpressHelper.cs | 4 +- .../HttpHandlers/ChunkedUploaderHandler.cs | 2 +- .../Core/Services/FFmpegService/FFmpeg.cs | 4 +- products/ASC.Files/Core/Utils/EntryManager.cs | 4 +- .../ASC.Files/Core/Utils/FileConverter.cs | 2 +- products/ASC.Files/Core/Utils/FileMarker.cs | 2 +- .../Server/Helpers/FilesControllerHelper.cs | 4 +- .../Controllers/SettingsController.cs | 2 +- .../Controllers/SmtpSettingsController.cs | 2 +- web/ASC.Web.Core/Files/DocumentService.cs | 10 ++--- .../CachedMobileAppInstallRegistrator.cs | 2 +- .../Notify/StudioNotifyService.cs | 16 +++---- web/ASC.Web.Core/Sms/SmsKeyStorage.cs | 2 +- web/ASC.Web.Core/Sms/SmsSender.cs | 4 +- web/ASC.Web.Core/Users/UserManagerWrapper.cs | 6 +-- web/ASC.Web.Core/WebItemSecurity.cs | 2 +- 110 files changed, 315 insertions(+), 315 deletions(-) diff --git a/common/ASC.Api.Core/Core/ApiDateTime.cs b/common/ASC.Api.Core/Core/ApiDateTime.cs index daeddcdd3e..a481eec906 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -88,7 +88,7 @@ namespace ASC.Api.Core public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) { - if (string.IsNullOrEmpty(data)) throw new ArgumentNullException("data"); + if (string.IsNullOrEmpty(data)) throw new ArgumentNullException(nameof(data)); if (data.Length < 7) throw new ArgumentException("invalid date time format"); diff --git a/common/ASC.Common/Data/StreamExtension.cs b/common/ASC.Common/Data/StreamExtension.cs index c27b05eee1..655a7c13a6 100644 --- a/common/ASC.Common/Data/StreamExtension.cs +++ b/common/ASC.Common/Data/StreamExtension.cs @@ -36,8 +36,8 @@ namespace ASC.Common.Data public static void StreamCopyTo(this Stream srcStream, Stream dstStream, int length) { - if (srcStream == null) throw new ArgumentNullException("srcStream"); - if (dstStream == null) throw new ArgumentNullException("dstStream"); + if (srcStream == null) throw new ArgumentNullException(nameof(srcStream)); + if (dstStream == null) throw new ArgumentNullException(nameof(dstStream)); var buffer = new byte[BufferSize]; int totalRead = 0; diff --git a/common/ASC.Common/Data/TempStream.cs b/common/ASC.Common/Data/TempStream.cs index 0b6ee90911..196af2f604 100644 --- a/common/ASC.Common/Data/TempStream.cs +++ b/common/ASC.Common/Data/TempStream.cs @@ -32,7 +32,7 @@ namespace ASC.Common public Stream GetBuffered(Stream srcStream) { - if (srcStream == null) throw new ArgumentNullException("srcStream"); + if (srcStream == null) throw new ArgumentNullException(nameof(srcStream)); if (!srcStream.CanSeek || srcStream.CanTimeout) { //Buffer it diff --git a/common/ASC.Core.Common/Billing/BillingClient.cs b/common/ASC.Core.Common/Billing/BillingClient.cs index f51f9aca6b..f4f4d229e6 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -186,7 +186,7 @@ namespace ASC.Core.Billing { if (productIds == null) { - throw new ArgumentNullException("productIds"); + throw new ArgumentNullException(nameof(productIds)); } var parameters = productIds.Select(pid => Tuple.Create("ProductId", pid)).ToList(); diff --git a/common/ASC.Core.Common/Billing/License/LicenseReader.cs b/common/ASC.Core.Common/Billing/License/LicenseReader.cs index bcb2518b1c..859128a981 100644 --- a/common/ASC.Core.Common/Billing/License/LicenseReader.cs +++ b/common/ASC.Core.Common/Billing/License/LicenseReader.cs @@ -153,7 +153,7 @@ namespace ASC.Core.Billing private static void SaveLicense(Stream licenseStream, string path) { - if (licenseStream == null) throw new ArgumentNullException("licenseStream"); + if (licenseStream == null) throw new ArgumentNullException(nameof(licenseStream)); if (licenseStream.CanSeek) { diff --git a/common/ASC.Core.Common/Billing/TariffService.cs b/common/ASC.Core.Common/Billing/TariffService.cs index aad10a1f67..4e07ccdcad 100644 --- a/common/ASC.Core.Common/Billing/TariffService.cs +++ b/common/ASC.Core.Common/Billing/TariffService.cs @@ -279,7 +279,7 @@ namespace ASC.Core.Billing { if (tariff == null) { - throw new ArgumentNullException("tariff"); + throw new ArgumentNullException(nameof(tariff)); } var q = QuotaService.GetTenantQuota(tariff.QuotaId); @@ -432,7 +432,7 @@ namespace ASC.Core.Billing { if (productIds == null) { - throw new ArgumentNullException("productIds"); + throw new ArgumentNullException(nameof(productIds)); } try { diff --git a/common/ASC.Core.Common/Caching/CachedAzService.cs b/common/ASC.Core.Common/Caching/CachedAzService.cs index 50e9817d2f..2150ebcb76 100644 --- a/common/ASC.Core.Common/Caching/CachedAzService.cs +++ b/common/ASC.Core.Common/Caching/CachedAzService.cs @@ -87,7 +87,7 @@ namespace ASC.Core.Caching public CachedAzService(DbAzService service, AzServiceCache azServiceCache) { - this.service = service ?? throw new ArgumentNullException("service"); + this.service = service ?? throw new ArgumentNullException(nameof(service)); Cache = azServiceCache.Cache; cacheNotify = azServiceCache.CacheNotify; CacheExpiration = TimeSpan.FromMinutes(10); diff --git a/common/ASC.Core.Common/Caching/CachedQuotaService.cs b/common/ASC.Core.Common/Caching/CachedQuotaService.cs index 7a490d5c54..f8ff5be388 100644 --- a/common/ASC.Core.Common/Caching/CachedQuotaService.cs +++ b/common/ASC.Core.Common/Caching/CachedQuotaService.cs @@ -127,7 +127,7 @@ namespace ASC.Core.Caching public CachedQuotaService(DbQuotaService service, QuotaServiceCache quotaServiceCache) : this() { - Service = service ?? throw new ArgumentNullException("service"); + Service = service ?? throw new ArgumentNullException(nameof(service)); QuotaServiceCache = quotaServiceCache; Cache = quotaServiceCache.Cache; CacheNotify = quotaServiceCache.CacheNotify; diff --git a/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs b/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs index e8b4b6a746..9d3448b0a9 100644 --- a/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs +++ b/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs @@ -114,7 +114,7 @@ namespace ASC.Core.Caching public CachedSubscriptionService(DbSubscriptionService service, SubscriptionServiceCache subscriptionServiceCache) { - this.service = service ?? throw new ArgumentNullException("service"); + this.service = service ?? throw new ArgumentNullException(nameof(service)); cache = subscriptionServiceCache.Cache; notifyRecord = subscriptionServiceCache.NotifyRecord; notifyMethod = subscriptionServiceCache.NotifyMethod; diff --git a/common/ASC.Core.Common/Caching/CachedTenantService.cs b/common/ASC.Core.Common/Caching/CachedTenantService.cs index b9dbc6553f..9ff75ae5e4 100644 --- a/common/ASC.Core.Common/Caching/CachedTenantService.cs +++ b/common/ASC.Core.Common/Caching/CachedTenantService.cs @@ -205,7 +205,7 @@ namespace ASC.Core.Caching public CachedTenantService(DbTenantService service, TenantServiceCache tenantServiceCache, ICache cache) : this() { this.cache = cache; - Service = service ?? throw new ArgumentNullException("service"); + Service = service ?? throw new ArgumentNullException(nameof(service)); TenantServiceCache = tenantServiceCache; CacheNotifyItem = tenantServiceCache.CacheNotifyItem; CacheNotifySettings = tenantServiceCache.CacheNotifySettings; diff --git a/common/ASC.Core.Common/Caching/CachedUserService.cs b/common/ASC.Core.Common/Caching/CachedUserService.cs index 4dda7d2354..35dc77a9a3 100644 --- a/common/ASC.Core.Common/Caching/CachedUserService.cs +++ b/common/ASC.Core.Common/Caching/CachedUserService.cs @@ -207,7 +207,7 @@ namespace ASC.Core.Caching UserServiceCache userServiceCache ) : this() { - Service = service ?? throw new ArgumentNullException("service"); + Service = service ?? throw new ArgumentNullException(nameof(service)); CoreBaseSettings = coreBaseSettings; UserServiceCache = userServiceCache; Cache = userServiceCache.Cache; diff --git a/common/ASC.Core.Common/Configuration/SmtpSettings.cs b/common/ASC.Core.Common/Configuration/SmtpSettings.cs index 7348d06ef1..08c1641427 100644 --- a/common/ASC.Core.Common/Configuration/SmtpSettings.cs +++ b/common/ASC.Core.Common/Configuration/SmtpSettings.cs @@ -83,17 +83,17 @@ namespace ASC.Core.Configuration { if (string.IsNullOrEmpty(host)) { - throw new ArgumentException("Empty smtp host.", "host"); + throw new ArgumentException("Empty smtp host.", nameof(host)); } if (string.IsNullOrEmpty(senderAddress)) { - throw new ArgumentException("Empty sender address.", "senderAddress"); + throw new ArgumentException("Empty sender address.", nameof(senderAddress)); } Host = host; Port = port; SenderAddress = senderAddress; - SenderDisplayName = senderDisplayName ?? throw new ArgumentNullException("senderDisplayName"); + SenderDisplayName = senderDisplayName ?? throw new ArgumentNullException(nameof(senderDisplayName)); } public void SetCredentials(string userName, string password) @@ -105,11 +105,11 @@ namespace ASC.Core.Configuration { if (string.IsNullOrEmpty(userName)) { - throw new ArgumentException("Empty user name.", "userName"); + throw new ArgumentException("Empty user name.", nameof(userName)); } if (string.IsNullOrEmpty(password)) { - throw new ArgumentException("Empty password.", "password"); + throw new ArgumentException("Empty password.", nameof(password)); } CredentialsUserName = userName; CredentialsUserPassword = password; diff --git a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs index 153c890ffe..d3f4eb1e7f 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -179,7 +179,7 @@ namespace ASC.Core { if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); } byte[] bytes = null; if (value != null) @@ -193,7 +193,7 @@ namespace ASC.Core { if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); } var bytes = TenantService.GetTenantSettings(tenant, key); diff --git a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs index 07c096202b..d8837644ea 100644 --- a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs +++ b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs @@ -104,7 +104,7 @@ namespace ASC.Core { if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); } var now = DateTime.UtcNow; diff --git a/common/ASC.Core.Common/Context/Impl/TenantManager.cs b/common/ASC.Core.Common/Context/Impl/TenantManager.cs index 5f7315fc56..9b7c6a1c30 100644 --- a/common/ASC.Core.Common/Context/Impl/TenantManager.cs +++ b/common/ASC.Core.Common/Context/Impl/TenantManager.cs @@ -194,7 +194,7 @@ namespace ASC.Core public Tenant SetTenantVersion(Tenant tenant, int version) { - if (tenant == null) throw new ArgumentNullException("tenant"); + if (tenant == null) throw new ArgumentNullException(nameof(tenant)); if (tenant.Version != version) { tenant.Version = version; diff --git a/common/ASC.Core.Common/Context/SecurityContext.cs b/common/ASC.Core.Common/Context/SecurityContext.cs index b602aed346..218702e095 100644 --- a/common/ASC.Core.Common/Context/SecurityContext.cs +++ b/common/ASC.Core.Common/Context/SecurityContext.cs @@ -113,8 +113,8 @@ namespace ASC.Core public string AuthenticateMe(string login, string passwordHash) { - if (login == null) throw new ArgumentNullException("login"); - if (passwordHash == null) throw new ArgumentNullException("passwordHash"); + if (login == null) throw new ArgumentNullException(nameof(login)); + if (passwordHash == null) throw new ArgumentNullException(nameof(passwordHash)); var tenantid = TenantManager.GetCurrentTenant().TenantId; var u = UserManager.GetUsersByPasswordHash(tenantid, login, passwordHash); diff --git a/common/ASC.Core.Common/Core/DBResourceManager.cs b/common/ASC.Core.Common/Core/DBResourceManager.cs index 0ef86e4d58..d44c3375f9 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -174,11 +174,11 @@ namespace TMResourceData { if (culture == null) { - throw new ArgumentNullException("culture"); + throw new ArgumentNullException(nameof(culture)); } if (string.IsNullOrEmpty(filename)) { - throw new ArgumentNullException("filename"); + throw new ArgumentNullException(nameof(filename)); } DbContext = dbContext; diff --git a/common/ASC.Core.Common/Data/DbQuotaService.cs b/common/ASC.Core.Common/Data/DbQuotaService.cs index 0c271f2242..1711343f18 100644 --- a/common/ASC.Core.Common/Data/DbQuotaService.cs +++ b/common/ASC.Core.Common/Data/DbQuotaService.cs @@ -115,7 +115,7 @@ namespace ASC.Core.Data public TenantQuota SaveTenantQuota(TenantQuota quota) { - if (quota == null) throw new ArgumentNullException("quota"); + if (quota == null) throw new ArgumentNullException(nameof(quota)); var dbQuota = new DbQuota { @@ -155,7 +155,7 @@ namespace ASC.Core.Data public void SetTenantQuotaRow(TenantQuotaRow row, bool exchange) { - if (row == null) throw new ArgumentNullException("row"); + if (row == null) throw new ArgumentNullException(nameof(row)); using var tx = CoreDbContext.Database.BeginTransaction(); diff --git a/common/ASC.Core.Common/Data/DbSettingsManager.cs b/common/ASC.Core.Common/Data/DbSettingsManager.cs index 7dd6fdaebc..78561ab5a9 100644 --- a/common/ASC.Core.Common/Data/DbSettingsManager.cs +++ b/common/ASC.Core.Common/Data/DbSettingsManager.cs @@ -185,7 +185,7 @@ namespace ASC.Core.Data public bool SaveSettingsFor<T>(T settings, int tenantId, Guid userId) where T : ISettings { - if (settings == null) throw new ArgumentNullException("settings"); + if (settings == null) throw new ArgumentNullException(nameof(settings)); try { var key = settings.ID.ToString() + tenantId + userId; diff --git a/common/ASC.Core.Common/Data/DbSubscriptionService.cs b/common/ASC.Core.Common/Data/DbSubscriptionService.cs index 563d4a889e..5c15dc0d1c 100644 --- a/common/ASC.Core.Common/Data/DbSubscriptionService.cs +++ b/common/ASC.Core.Common/Data/DbSubscriptionService.cs @@ -69,8 +69,8 @@ namespace ASC.Core.Data public string[] GetRecipients(int tenant, string sourceId, string actionId, string objectId) { - if (sourceId == null) throw new ArgumentNullException("sourceId"); - if (actionId == null) throw new ArgumentNullException("actionId"); + if (sourceId == null) throw new ArgumentNullException(nameof(sourceId)); + if (actionId == null) throw new ArgumentNullException(nameof(actionId)); var q = GetQuery(tenant, sourceId, actionId) .Where(r => r.Object == (objectId ?? string.Empty)) @@ -83,8 +83,8 @@ namespace ASC.Core.Data public IEnumerable<SubscriptionRecord> GetSubscriptions(int tenant, string sourceId, string actionId) { - if (sourceId == null) throw new ArgumentNullException("sourceId"); - if (actionId == null) throw new ArgumentNullException("actionId"); + if (sourceId == null) throw new ArgumentNullException(nameof(sourceId)); + if (actionId == null) throw new ArgumentNullException(nameof(actionId)); var q = GetQuery(tenant, sourceId, actionId); return GetSubscriptions(q, tenant); @@ -108,7 +108,7 @@ namespace ASC.Core.Data public SubscriptionRecord GetSubscription(int tenant, string sourceId, string actionId, string recipientId, string objectId) { - if (recipientId == null) throw new ArgumentNullException("recipientId"); + if (recipientId == null) throw new ArgumentNullException(nameof(recipientId)); var q = GetQuery(tenant, sourceId, actionId) .Where(r => r.Recipient == recipientId) @@ -119,9 +119,9 @@ namespace ASC.Core.Data public bool IsUnsubscribe(int tenant, string sourceId, string actionId, string recipientId, string objectId) { - if (recipientId == null) throw new ArgumentNullException("recipientId"); - if (sourceId == null) throw new ArgumentNullException("sourceId"); - if (actionId == null) throw new ArgumentNullException("actionId"); + if (recipientId == null) throw new ArgumentNullException(nameof(recipientId)); + if (sourceId == null) throw new ArgumentNullException(nameof(sourceId)); + if (actionId == null) throw new ArgumentNullException(nameof(actionId)); var q = UserDbContext.Subscriptions .Where(r => r.Source == sourceId && @@ -144,9 +144,9 @@ namespace ASC.Core.Data public string[] GetSubscriptions(int tenant, string sourceId, string actionId, string recipientId, bool checkSubscribe) { - if (recipientId == null) throw new ArgumentNullException("recipientId"); - if (sourceId == null) throw new ArgumentNullException("sourceId"); - if (actionId == null) throw new ArgumentNullException("actionId"); + if (recipientId == null) throw new ArgumentNullException(nameof(recipientId)); + if (sourceId == null) throw new ArgumentNullException(nameof(sourceId)); + if (actionId == null) throw new ArgumentNullException(nameof(actionId)); var q = GetQuery(tenant, sourceId, actionId) .Where(r=> r.Recipient == recipientId) @@ -163,7 +163,7 @@ namespace ASC.Core.Data public void SaveSubscription(SubscriptionRecord s) { - if (s == null) throw new ArgumentNullException("s"); + if (s == null) throw new ArgumentNullException(nameof(s)); var subs = new Subscription { @@ -186,8 +186,8 @@ namespace ASC.Core.Data public void RemoveSubscriptions(int tenant, string sourceId, string actionId, string objectId) { - if (sourceId == null) throw new ArgumentNullException("sourceId"); - if (actionId == null) throw new ArgumentNullException("actionId"); + if (sourceId == null) throw new ArgumentNullException(nameof(sourceId)); + if (actionId == null) throw new ArgumentNullException(nameof(actionId)); using var tr = UserDbContext.Database.BeginTransaction(); var q = UserDbContext.Subscriptions @@ -213,8 +213,8 @@ namespace ASC.Core.Data public IEnumerable<SubscriptionMethod> GetSubscriptionMethods(int tenant, string sourceId, string actionId, string recipientId) { - if (sourceId == null) throw new ArgumentNullException("sourceId"); - if (actionId == null) throw new ArgumentNullException("actionId"); + if (sourceId == null) throw new ArgumentNullException(nameof(sourceId)); + if (actionId == null) throw new ArgumentNullException(nameof(actionId)); var q = UserDbContext.SubscriptionMethods .Where(r => r.Tenant == -1 || r.Tenant == tenant) @@ -258,7 +258,7 @@ namespace ASC.Core.Data public void SetSubscriptionMethod(SubscriptionMethod m) { - if (m == null) throw new ArgumentNullException("m"); + if (m == null) throw new ArgumentNullException(nameof(m)); using var tr = UserDbContext.Database.BeginTransaction(); @@ -297,8 +297,8 @@ namespace ASC.Core.Data private IQueryable<Subscription> GetQuery(int tenant, string sourceId, string actionId) { - if (sourceId == null) throw new ArgumentNullException("sourceId"); - if (actionId == null) throw new ArgumentNullException("actionId"); + if (sourceId == null) throw new ArgumentNullException(nameof(sourceId)); + if (actionId == null) throw new ArgumentNullException(nameof(actionId)); return UserDbContext.Subscriptions diff --git a/common/ASC.Core.Common/Data/DbTenantService.cs b/common/ASC.Core.Common/Data/DbTenantService.cs index 5d8a0f25a2..7b0ba0de8e 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -158,7 +158,7 @@ namespace ASC.Core.Data public IEnumerable<Tenant> GetTenants(string login, string passwordHash) { - if (string.IsNullOrEmpty(login)) throw new ArgumentNullException("login"); + if (string.IsNullOrEmpty(login)) throw new ArgumentNullException(nameof(login)); IQueryable<TenantUserSecurity> query() => TenantsQuery() .Where(r => r.Status == TenantStatus.Active) @@ -245,7 +245,7 @@ namespace ASC.Core.Data public Tenant GetTenant(string domain) { - if (string.IsNullOrEmpty(domain)) throw new ArgumentNullException("domain"); + if (string.IsNullOrEmpty(domain)) throw new ArgumentNullException(nameof(domain)); domain = domain.ToLowerInvariant(); diff --git a/common/ASC.Core.Common/Data/DbUserService.cs b/common/ASC.Core.Common/Data/DbUserService.cs index c82834bb99..f3250557fd 100644 --- a/common/ASC.Core.Common/Data/DbUserService.cs +++ b/common/ASC.Core.Common/Data/DbUserService.cs @@ -239,7 +239,7 @@ namespace ASC.Core.Data public UserInfo GetUserByPasswordHash(int tenant, string login, string passwordHash) { - if (string.IsNullOrEmpty(login)) throw new ArgumentNullException("login"); + if (string.IsNullOrEmpty(login)) throw new ArgumentNullException(nameof(login)); if (Guid.TryParse(login, out var userId)) { @@ -548,7 +548,7 @@ namespace ASC.Core.Data public UserInfo SaveUser(int tenant, UserInfo user) { - if (user == null) throw new ArgumentNullException("user"); + if (user == null) throw new ArgumentNullException(nameof(user)); if (string.IsNullOrEmpty(user.UserName)) throw new ArgumentOutOfRangeException("Empty username."); if (user.ID == default) user.ID = Guid.NewGuid(); diff --git a/common/ASC.Core.Common/Encryption/EncryptionSettings.cs b/common/ASC.Core.Common/Encryption/EncryptionSettings.cs index 8494e71c41..7764765c15 100644 --- a/common/ASC.Core.Common/Encryption/EncryptionSettings.cs +++ b/common/ASC.Core.Common/Encryption/EncryptionSettings.cs @@ -131,12 +131,12 @@ namespace ASC.Core.Encryption if (length < 1 || length > 128) { - throw new ArgumentException("password_length_incorrect", "length"); + throw new ArgumentException("password_length_incorrect", nameof(length)); } if (numberOfNonAlphanumericCharacters > length || numberOfNonAlphanumericCharacters < 0) { - throw new ArgumentException("min_required_non_alphanumeric_characters_incorrect", "numberOfNonAlphanumericCharacters"); + throw new ArgumentException("min_required_non_alphanumeric_characters_incorrect", nameof(numberOfNonAlphanumericCharacters)); } var array2 = new char[length]; diff --git a/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs b/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs index c000ddf737..92f8b1eda9 100644 --- a/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs +++ b/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs @@ -46,19 +46,19 @@ namespace ASC.Notify.Channels public SenderChannel(Context context, string senderName, ISink decorateSink, ISink senderSink) { - this.SenderName = senderName ?? throw new ArgumentNullException("senderName"); + this.SenderName = senderName ?? throw new ArgumentNullException(nameof(senderName)); this.firstSink = decorateSink; this.senderSink = senderSink ?? throw new ApplicationException($"channel with tag {senderName} not created sender sink"); - context = context ?? throw new ArgumentNullException("context"); + context = context ?? throw new ArgumentNullException(nameof(context)); var dispatcherSink = new DispatchSink(SenderName, context.DispatchEngine); this.firstSink = AddSink(firstSink, dispatcherSink); } public void SendAsync(INoticeMessage message) { - if (message == null) throw new ArgumentNullException("message"); + if (message == null) throw new ArgumentNullException(nameof(message)); firstSink.ProcessMessageAsync(message); } diff --git a/common/ASC.Core.Common/Notify/DirectSubscriptionProvider.cs b/common/ASC.Core.Common/Notify/DirectSubscriptionProvider.cs index 7ae665ae8c..07b0b2088a 100644 --- a/common/ASC.Core.Common/Notify/DirectSubscriptionProvider.cs +++ b/common/ASC.Core.Common/Notify/DirectSubscriptionProvider.cs @@ -41,32 +41,32 @@ namespace ASC.Core.Notify public DirectSubscriptionProvider(string sourceID, SubscriptionManager subscriptionManager, IRecipientProvider recipientProvider) { - if (string.IsNullOrEmpty(sourceID)) throw new ArgumentNullException("sourceID"); + if (string.IsNullOrEmpty(sourceID)) throw new ArgumentNullException(nameof(sourceID)); this.sourceID = sourceID; - this.subscriptionManager = subscriptionManager ?? throw new ArgumentNullException("subscriptionManager"); - this.recipientProvider = recipientProvider ?? throw new ArgumentNullException("recipientProvider"); + this.subscriptionManager = subscriptionManager ?? throw new ArgumentNullException(nameof(subscriptionManager)); + this.recipientProvider = recipientProvider ?? throw new ArgumentNullException(nameof(recipientProvider)); } public object GetSubscriptionRecord(INotifyAction action, IRecipient recipient, string objectID) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); return subscriptionManager.GetSubscriptionRecord(sourceID, action.ID, recipient.ID, objectID); } public string[] GetSubscriptions(INotifyAction action, IRecipient recipient, bool checkSubscribe = true) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); return subscriptionManager.GetSubscriptions(sourceID, action.ID, recipient.ID, checkSubscribe); } public IRecipient[] GetRecipients(INotifyAction action, string objectID) { - if (action == null) throw new ArgumentNullException("action"); + if (action == null) throw new ArgumentNullException(nameof(action)); return subscriptionManager.GetRecipients(sourceID, action.ID, objectID) .Select(r => recipientProvider.GetRecipient(r)) @@ -76,53 +76,53 @@ namespace ASC.Core.Notify public string[] GetSubscriptionMethod(INotifyAction action, IRecipient recipient) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); return subscriptionManager.GetSubscriptionMethod(sourceID, action.ID, recipient.ID); } public void UpdateSubscriptionMethod(INotifyAction action, IRecipient recipient, params string[] senderNames) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); subscriptionManager.UpdateSubscriptionMethod(sourceID, action.ID, recipient.ID, senderNames); } public bool IsUnsubscribe(IDirectRecipient recipient, INotifyAction action, string objectID) { - if (recipient == null) throw new ArgumentNullException("recipient"); - if (action == null) throw new ArgumentNullException("action"); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); + if (action == null) throw new ArgumentNullException(nameof(action)); return subscriptionManager.IsUnsubscribe(sourceID, recipient.ID, action.ID, objectID); } public void Subscribe(INotifyAction action, string objectID, IRecipient recipient) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); subscriptionManager.Subscribe(sourceID, action.ID, objectID, recipient.ID); } public void UnSubscribe(INotifyAction action, string objectID, IRecipient recipient) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); subscriptionManager.Unsubscribe(sourceID, action.ID, objectID, recipient.ID); } public void UnSubscribe(INotifyAction action) { - if (action == null) throw new ArgumentNullException("action"); + if (action == null) throw new ArgumentNullException(nameof(action)); subscriptionManager.UnsubscribeAll(sourceID, action.ID); } public void UnSubscribe(INotifyAction action, string objectID) { - if (action == null) throw new ArgumentNullException("action"); + if (action == null) throw new ArgumentNullException(nameof(action)); subscriptionManager.UnsubscribeAll(sourceID, action.ID, objectID); } diff --git a/common/ASC.Core.Common/Notify/EmailSenderSink.cs b/common/ASC.Core.Common/Notify/EmailSenderSink.cs index 3b99a635fc..abcca2d244 100644 --- a/common/ASC.Core.Common/Notify/EmailSenderSink.cs +++ b/common/ASC.Core.Common/Notify/EmailSenderSink.cs @@ -49,7 +49,7 @@ namespace ASC.Core.Notify public EmailSenderSink(INotifySender sender, IServiceProvider serviceProvider, IOptionsMonitor<ILog> options) { - this.sender = sender ?? throw new ArgumentNullException("sender"); + this.sender = sender ?? throw new ArgumentNullException(nameof(sender)); ServiceProvider = serviceProvider; Log = options.Get("ASC.Notify"); } diff --git a/common/ASC.Core.Common/Notify/Engine/DispatchEngine.cs b/common/ASC.Core.Common/Notify/Engine/DispatchEngine.cs index b9686b7a9b..6f5d6a8d81 100644 --- a/common/ASC.Core.Common/Notify/Engine/DispatchEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/DispatchEngine.cs @@ -47,7 +47,7 @@ namespace ASC.Notify.Engine { log = options.Get("ASC.Notify"); logMessages = options.Get("ASC.Notify.Messages"); - this.context = context ?? throw new ArgumentNullException("context"); + this.context = context ?? throw new ArgumentNullException(nameof(context)); logOnly = "log".Equals(configuration["core:notify:postman"], StringComparison.InvariantCultureIgnoreCase); log.DebugFormat("LogOnly: {0}", logOnly); } diff --git a/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs b/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs index a514d10fb8..89f7136fdc 100644 --- a/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs +++ b/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs @@ -54,8 +54,8 @@ namespace ASC.Notify.Engine public void Add(ISendInterceptor interceptor) { - if (interceptor == null) throw new ArgumentNullException("interceptor"); - if (string.IsNullOrEmpty(interceptor.Name)) throw new ArgumentException("empty name property", "interceptor"); + if (interceptor == null) throw new ArgumentNullException(nameof(interceptor)); + if (string.IsNullOrEmpty(interceptor.Name)) throw new ArgumentException("empty name property", nameof(interceptor)); switch (interceptor.Lifetime) { @@ -72,7 +72,7 @@ namespace ASC.Notify.Engine public ISendInterceptor Get(string name) { - if (string.IsNullOrEmpty(name)) throw new ArgumentException("empty name", "name"); + if (string.IsNullOrEmpty(name)) throw new ArgumentException("empty name", nameof(name)); var result = GetInternal(name, CallInterceptors); if (result == null) result = GetInternal(name, globalInterceptors); return result; @@ -80,7 +80,7 @@ namespace ASC.Notify.Engine public void Remove(string name) { - if (string.IsNullOrEmpty(name)) throw new ArgumentException("empty name", "name"); + if (string.IsNullOrEmpty(name)) throw new ArgumentException("empty name", nameof(name)); RemoveInternal(name, CallInterceptors); RemoveInternal(name, globalInterceptors); diff --git a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs index df3c0c651b..3c13771148 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -76,7 +76,7 @@ namespace ASC.Notify.Engine public NotifyEngine(Context context, IServiceProvider serviceProvider) { - this.context = context ?? throw new ArgumentNullException("context"); + this.context = context ?? throw new ArgumentNullException(nameof(context)); log = serviceProvider.GetService<IOptionsMonitor<ILog>>().Get("ASC.Notify"); ServiceProvider = serviceProvider; notifyScheduler = new Thread(NotifyScheduler) { IsBackground = true, Name = "NotifyScheduler" }; @@ -102,8 +102,8 @@ namespace ASC.Notify.Engine internal void RegisterSendMethod(Action<DateTime> method, string cron) { - if (method == null) throw new ArgumentNullException("method"); - if (string.IsNullOrEmpty(cron)) throw new ArgumentNullException("cron"); + if (method == null) throw new ArgumentNullException(nameof(method)); + if (string.IsNullOrEmpty(cron)) throw new ArgumentNullException(nameof(cron)); var w = new SendMethodWrapper(method, cron, log); lock (sendMethods) @@ -121,7 +121,7 @@ namespace ASC.Notify.Engine internal void UnregisterSendMethod(Action<DateTime> method) { - if (method == null) throw new ArgumentNullException("method"); + if (method == null) throw new ArgumentNullException(nameof(method)); lock (sendMethods) { @@ -346,7 +346,7 @@ namespace ASC.Notify.Engine private List<SendResponse> SendDirectNotify(NotifyRequest request, IServiceScope serviceScope) { - if (!(request.Recipient is IDirectRecipient)) throw new ArgumentException("request.Recipient not IDirectRecipient", "request"); + if (!(request.Recipient is IDirectRecipient)) throw new ArgumentException("request.Recipient not IDirectRecipient", nameof(request)); var responses = new List<SendResponse>(); var response = CheckPreventInterceptors(request, InterceptorPlace.DirectSend, serviceScope, null); @@ -401,7 +401,7 @@ namespace ASC.Notify.Engine private SendResponse SendDirectNotify(NotifyRequest request, ISenderChannel channel, IServiceScope serviceScope) { - if (!(request.Recipient is IDirectRecipient)) throw new ArgumentException("request.Recipient not IDirectRecipient", "request"); + if (!(request.Recipient is IDirectRecipient)) throw new ArgumentException("request.Recipient not IDirectRecipient", nameof(request)); request.CurrentSender = channel.SenderName; @@ -419,7 +419,7 @@ namespace ASC.Notify.Engine private SendResponse CreateNoticeMessageFromNotifyRequest(NotifyRequest request, string sender, IServiceScope serviceScope, out NoticeMessage noticeMessage) { - if (request == null) throw new ArgumentNullException("request"); + if (request == null) throw new ArgumentNullException(nameof(request)); var recipientProvider = request.GetRecipientsProvider(serviceScope); var recipient = request.Recipient as IDirectRecipient; diff --git a/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs b/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs index 1e34ce40cf..b1e4151d1b 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs @@ -75,9 +75,9 @@ namespace ASC.Notify.Engine RequaredTags = new List<string>(); Interceptors = new List<ISendInterceptor>(); - NotifySource = notifySource ?? throw new ArgumentNullException("notifySource"); - Recipient = recipient ?? throw new ArgumentNullException("recipient"); - NotifyAction = action ?? throw new ArgumentNullException("action"); + NotifySource = notifySource ?? throw new ArgumentNullException(nameof(notifySource)); + Recipient = recipient ?? throw new ArgumentNullException(nameof(recipient)); + NotifyAction = action ?? throw new ArgumentNullException(nameof(action)); ObjectID = objectID; IsNeedCheckSubscriptions = true; @@ -125,7 +125,7 @@ namespace ASC.Notify.Engine internal NotifyRequest Split(IRecipient recipient) { - if (recipient == null) throw new ArgumentNullException("recipient"); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); var newRequest = new NotifyRequest(NotifySource, NotifyAction, ObjectID, recipient) { SenderNames = SenderNames, diff --git a/common/ASC.Core.Common/Notify/Engine/SendInterceptorSkeleton.cs b/common/ASC.Core.Common/Notify/Engine/SendInterceptorSkeleton.cs index 25d6104f20..e6b56d6601 100644 --- a/common/ASC.Core.Common/Notify/Engine/SendInterceptorSkeleton.cs +++ b/common/ASC.Core.Common/Notify/Engine/SendInterceptorSkeleton.cs @@ -44,8 +44,8 @@ namespace ASC.Notify.Engine public SendInterceptorSkeleton(string name, InterceptorPlace preventPlace, InterceptorLifetime lifetime, Func<NotifyRequest, InterceptorPlace, IServiceScope, bool> sendInterceptor) { - if (string.IsNullOrEmpty(name)) throw new ArgumentException("Empty name.", "name"); - if (sendInterceptor == null) throw new ArgumentNullException("sendInterceptor"); + if (string.IsNullOrEmpty(name)) throw new ArgumentException("Empty name.", nameof(name)); + if (sendInterceptor == null) throw new ArgumentNullException(nameof(sendInterceptor)); method = sendInterceptor; Name = name; diff --git a/common/ASC.Core.Common/Notify/JabberSenderSink.cs b/common/ASC.Core.Common/Notify/JabberSenderSink.cs index 868d9edd4a..d491898849 100644 --- a/common/ASC.Core.Common/Notify/JabberSenderSink.cs +++ b/common/ASC.Core.Common/Notify/JabberSenderSink.cs @@ -44,7 +44,7 @@ namespace ASC.Core.Notify public JabberSenderSink(INotifySender sender, IServiceProvider serviceProvider) { - this.sender = sender ?? throw new ArgumentNullException("sender"); + this.sender = sender ?? throw new ArgumentNullException(nameof(sender)); ServiceProvider = serviceProvider; } diff --git a/common/ASC.Core.Common/Notify/Messages/NoticeMessage.cs b/common/ASC.Core.Common/Notify/Messages/NoticeMessage.cs index c3b86fa401..a764d5400f 100644 --- a/common/ASC.Core.Common/Notify/Messages/NoticeMessage.cs +++ b/common/ASC.Core.Common/Notify/Messages/NoticeMessage.cs @@ -48,25 +48,25 @@ namespace ASC.Notify.Messages public NoticeMessage(IDirectRecipient recipient, INotifyAction action, string objectID) { - Recipient = recipient ?? throw new ArgumentNullException("recipient"); + Recipient = recipient ?? throw new ArgumentNullException(nameof(recipient)); Action = action; ObjectID = objectID; } public NoticeMessage(IDirectRecipient recipient, INotifyAction action, string objectID, IPattern pattern) { - Recipient = recipient ?? throw new ArgumentNullException("recipient"); + Recipient = recipient ?? throw new ArgumentNullException(nameof(recipient)); Action = action; - Pattern = pattern ?? throw new ArgumentNullException("pattern"); + Pattern = pattern ?? throw new ArgumentNullException(nameof(pattern)); ObjectID = objectID; ContentType = pattern.ContentType; } public NoticeMessage(IDirectRecipient recipient, string subject, string body, string contentType) { - Recipient = recipient ?? throw new ArgumentNullException("recipient"); + Recipient = recipient ?? throw new ArgumentNullException(nameof(recipient)); Subject = subject; - Body = body ?? throw new ArgumentNullException("body"); + Body = body ?? throw new ArgumentNullException(nameof(body)); ContentType = contentType; } @@ -89,7 +89,7 @@ namespace ASC.Notify.Messages public void AddArgument(params ITagValue[] tagValues) { - if (tagValues == null) throw new ArgumentNullException("tagValues"); + if (tagValues == null) throw new ArgumentNullException(nameof(tagValues)); Array.ForEach(tagValues, tagValue => { diff --git a/common/ASC.Core.Common/Notify/Model/NotifyAction.cs b/common/ASC.Core.Common/Notify/Model/NotifyAction.cs index ec0a449c6c..dfd96793b0 100644 --- a/common/ASC.Core.Common/Notify/Model/NotifyAction.cs +++ b/common/ASC.Core.Common/Notify/Model/NotifyAction.cs @@ -43,7 +43,7 @@ namespace ASC.Notify.Model public NotifyAction(string id, string name) { - ID = id ?? throw new ArgumentNullException("id"); + ID = id ?? throw new ArgumentNullException(nameof(id)); Name = name; } diff --git a/common/ASC.Core.Common/Notify/Model/NotifyClientImpl.cs b/common/ASC.Core.Common/Notify/Model/NotifyClientImpl.cs index 25492b9377..34de37863a 100644 --- a/common/ASC.Core.Common/Notify/Model/NotifyClientImpl.cs +++ b/common/ASC.Core.Common/Notify/Model/NotifyClientImpl.cs @@ -43,9 +43,9 @@ namespace ASC.Notify.Model public NotifyClientImpl(Context context, INotifySource notifySource, IServiceScope serviceScope) { - this.notifySource = notifySource ?? throw new ArgumentNullException("notifySource"); + this.notifySource = notifySource ?? throw new ArgumentNullException(nameof(notifySource)); ServiceScope = serviceScope; - ctx = context ?? throw new ArgumentNullException("context"); + ctx = context ?? throw new ArgumentNullException(nameof(context)); } public void SendNoticeToAsync(INotifyAction action, IRecipient[] recipients, string[] senderNames, params ITagValue[] args) @@ -108,7 +108,7 @@ namespace ASC.Notify.Model public void SendNoticeToAsync(INotifyAction action, string objectID, IRecipient[] recipients, string[] senderNames, bool checkSubsciption, params ITagValue[] args) { - if (recipients == null) throw new ArgumentNullException("recipients"); + if (recipients == null) throw new ArgumentNullException(nameof(recipients)); BeginSingleRecipientEvent("__syspreventduplicateinterceptor"); @@ -127,8 +127,8 @@ namespace ASC.Notify.Model private NotifyRequest CreateRequest(INotifyAction action, string objectID, IRecipient recipient, ITagValue[] args, string[] senders, bool checkSubsciption) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); var request = new NotifyRequest(notifySource, action, objectID, recipient) { diff --git a/common/ASC.Core.Common/Notify/NotifySource.cs b/common/ASC.Core.Common/Notify/NotifySource.cs index 89258ede8f..6148488446 100644 --- a/common/ASC.Core.Common/Notify/NotifySource.cs +++ b/common/ASC.Core.Common/Notify/NotifySource.cs @@ -69,7 +69,7 @@ namespace ASC.Core.Notify protected NotifySource(string id, UserManager userManager, IRecipientProvider recipientsProvider, SubscriptionManager subscriptionManager) { - if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id"); + if (string.IsNullOrEmpty(id)) throw new ArgumentNullException(nameof(id)); ID = id; UserManager = userManager; diff --git a/common/ASC.Core.Common/Notify/Patterns/Pattern.cs b/common/ASC.Core.Common/Notify/Patterns/Pattern.cs index 3c2605273c..01398d5e44 100644 --- a/common/ASC.Core.Common/Notify/Patterns/Pattern.cs +++ b/common/ASC.Core.Common/Notify/Patterns/Pattern.cs @@ -52,8 +52,8 @@ namespace ASC.Notify.Patterns { if (string.IsNullOrEmpty(id)) throw new ArgumentException("id"); ID = id; - Subject = subject ?? throw new ArgumentNullException("subject"); - Body = body ?? throw new ArgumentNullException("body"); + Subject = subject ?? throw new ArgumentNullException(nameof(subject)); + Body = body ?? throw new ArgumentNullException(nameof(body)); ContentType = string.IsNullOrEmpty(contentType) ? HTMLContentType : contentType; } diff --git a/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs b/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs index 98a291822e..d9959ba492 100644 --- a/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs +++ b/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs @@ -65,7 +65,7 @@ namespace ASC.Notify.Patterns public string[] GetTags(IPattern pattern) { - if (pattern == null) throw new ArgumentNullException("pattern"); + if (pattern == null) throw new ArgumentNullException(nameof(pattern)); var findedTags = new List<string>(SearchTags(pattern.Body)); Array.ForEach(SearchTags(pattern.Subject), tag => { if (!findedTags.Contains(tag)) findedTags.Add(tag); }); @@ -74,9 +74,9 @@ namespace ASC.Notify.Patterns public void FormatMessage(INoticeMessage message, ITagValue[] tagsValues) { - if (message == null) throw new ArgumentNullException("message"); + if (message == null) throw new ArgumentNullException(nameof(message)); if (message.Pattern == null) throw new ArgumentException("message"); - if (tagsValues == null) throw new ArgumentNullException("tagsValues"); + if (tagsValues == null) throw new ArgumentNullException(nameof(tagsValues)); BeforeFormat(message, tagsValues); diff --git a/common/ASC.Core.Common/Notify/Patterns/TagValue.cs b/common/ASC.Core.Common/Notify/Patterns/TagValue.cs index 77ec54dee7..b1575905a1 100644 --- a/common/ASC.Core.Common/Notify/Patterns/TagValue.cs +++ b/common/ASC.Core.Common/Notify/Patterns/TagValue.cs @@ -46,7 +46,7 @@ namespace ASC.Notify.Patterns public TagValue(string tag, object value) { - if (string.IsNullOrEmpty(tag)) throw new ArgumentNullException("tag"); + if (string.IsNullOrEmpty(tag)) throw new ArgumentNullException(nameof(tag)); Tag = tag; Value = value; diff --git a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs index 77b11a7b07..cc76fa8520 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -54,7 +54,7 @@ namespace ASC.Core.Notify public virtual IRecipient[] GetGroupEntries(IRecipientsGroup group) { - if (group == null) throw new ArgumentNullException("group"); + if (group == null) throw new ArgumentNullException(nameof(group)); var result = new List<IRecipient>(); if (TryParseGuid(group.ID, out var groupID)) @@ -71,7 +71,7 @@ namespace ASC.Core.Notify public virtual IRecipientsGroup[] GetGroups(IRecipient recipient) { - if (recipient == null) throw new ArgumentNullException("recipient"); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); var result = new List<IRecipientsGroup>(); if (TryParseGuid(recipient.ID, out var recID)) @@ -98,7 +98,7 @@ namespace ASC.Core.Notify public virtual string[] GetRecipientAddresses(IDirectRecipient recipient, string senderName) { - if (recipient == null) throw new ArgumentNullException("recipient"); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); if (TryParseGuid(recipient.ID, out var userID)) { diff --git a/common/ASC.Core.Common/Notify/Sinks/DispatchSink.cs b/common/ASC.Core.Common/Notify/Sinks/DispatchSink.cs index 922fe8a09e..bd1fe25939 100644 --- a/common/ASC.Core.Common/Notify/Sinks/DispatchSink.cs +++ b/common/ASC.Core.Common/Notify/Sinks/DispatchSink.cs @@ -38,7 +38,7 @@ namespace ASC.Notify.Sinks public DispatchSink(string senderName, DispatchEngine dispatcher) { - this.dispatcher = dispatcher ?? throw new ArgumentNullException("dispatcher"); + this.dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); this.senderName = senderName; } diff --git a/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs b/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs index b7ac18be60..1f8aa3b886 100644 --- a/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs +++ b/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs @@ -43,7 +43,7 @@ namespace ASC.Core.Notify public TelegramSenderSink(INotifySender sender, IServiceProvider serviceProvider) { - this.sender = sender ?? throw new ArgumentNullException("sender"); + this.sender = sender ?? throw new ArgumentNullException(nameof(sender)); this.serviceProvider = serviceProvider; } diff --git a/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs b/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs index 01351c226d..779aacfb72 100644 --- a/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs +++ b/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs @@ -41,8 +41,8 @@ namespace ASC.Notify.Model public TopSubscriptionProvider(IRecipientProvider recipientProvider, ISubscriptionProvider directSubscriptionProvider) { - this.recipientProvider = recipientProvider ?? throw new ArgumentNullException("recipientProvider"); - subscriptionProvider = directSubscriptionProvider ?? throw new ArgumentNullException("directSubscriptionProvider"); + this.recipientProvider = recipientProvider ?? throw new ArgumentNullException(nameof(recipientProvider)); + subscriptionProvider = directSubscriptionProvider ?? throw new ArgumentNullException(nameof(directSubscriptionProvider)); } public TopSubscriptionProvider(IRecipientProvider recipientProvider, ISubscriptionProvider directSubscriptionProvider, string[] defaultSenderMethods) @@ -54,8 +54,8 @@ namespace ASC.Notify.Model public virtual string[] GetSubscriptionMethod(INotifyAction action, IRecipient recipient) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); var senders = subscriptionProvider.GetSubscriptionMethod(action, recipient); if (senders == null || senders.Length == 0) @@ -73,7 +73,7 @@ namespace ASC.Notify.Model public virtual IRecipient[] GetRecipients(INotifyAction action, string objectID) { - if (action == null) throw new ArgumentNullException("action"); + if (action == null) throw new ArgumentNullException(nameof(action)); var recipents = new List<IRecipient>(5); var directRecipients = subscriptionProvider.GetRecipients(action, objectID) ?? new IRecipient[0]; @@ -83,8 +83,8 @@ namespace ASC.Notify.Model public virtual bool IsUnsubscribe(IDirectRecipient recipient, INotifyAction action, string objectID) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); return subscriptionProvider.IsUnsubscribe(recipient, action, objectID); } @@ -92,30 +92,30 @@ namespace ASC.Notify.Model public virtual void Subscribe(INotifyAction action, string objectID, IRecipient recipient) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); subscriptionProvider.Subscribe(action, objectID, recipient); } public virtual void UnSubscribe(INotifyAction action, string objectID, IRecipient recipient) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); subscriptionProvider.UnSubscribe(action, objectID, recipient); } public void UnSubscribe(INotifyAction action, string objectID) { - if (action == null) throw new ArgumentNullException("action"); + if (action == null) throw new ArgumentNullException(nameof(action)); subscriptionProvider.UnSubscribe(action, objectID); } public void UnSubscribe(INotifyAction action) { - if (action == null) throw new ArgumentNullException("action"); + if (action == null) throw new ArgumentNullException(nameof(action)); subscriptionProvider.UnSubscribe(action); } @@ -131,17 +131,17 @@ namespace ASC.Notify.Model public virtual void UpdateSubscriptionMethod(INotifyAction action, IRecipient recipient, params string[] senderNames) { - if (action == null) throw new ArgumentNullException("action"); - if (recipient == null) throw new ArgumentNullException("recipient"); - if (senderNames == null) throw new ArgumentNullException("senderNames"); + if (action == null) throw new ArgumentNullException(nameof(action)); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); + if (senderNames == null) throw new ArgumentNullException(nameof(senderNames)); subscriptionProvider.UpdateSubscriptionMethod(action, recipient, senderNames); } public virtual object GetSubscriptionRecord(INotifyAction action, IRecipient recipient, string objectID) { - if (recipient == null) throw new ArgumentNullException("recipient"); - if (action == null) throw new ArgumentNullException("action"); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); + if (action == null) throw new ArgumentNullException(nameof(action)); var subscriptionRecord = subscriptionProvider.GetSubscriptionRecord(action, recipient, objectID); @@ -161,8 +161,8 @@ namespace ASC.Notify.Model public virtual string[] GetSubscriptions(INotifyAction action, IRecipient recipient, bool checkSubscription = true) { - if (recipient == null) throw new ArgumentNullException("recipient"); - if (action == null) throw new ArgumentNullException("action"); + if (recipient == null) throw new ArgumentNullException(nameof(recipient)); + if (action == null) throw new ArgumentNullException(nameof(action)); var objects = new List<string>(); var direct = subscriptionProvider.GetSubscriptions(action, recipient, checkSubscription) ?? Array.Empty<string>(); diff --git a/common/ASC.Core.Common/Security/Authorizing/AzManager.cs b/common/ASC.Core.Common/Security/Authorizing/AzManager.cs index 8705c8d8b0..4036462b18 100644 --- a/common/ASC.Core.Common/Security/Authorizing/AzManager.cs +++ b/common/ASC.Core.Common/Security/Authorizing/AzManager.cs @@ -43,8 +43,8 @@ namespace ASC.Common.Security.Authorizing public AzManager(IRoleProvider roleProvider, IPermissionProvider permissionProvider) : this() { - this.roleProvider = roleProvider ?? throw new ArgumentNullException("roleProvider"); - this.permissionProvider = permissionProvider ?? throw new ArgumentNullException("permissionProvider"); + this.roleProvider = roleProvider ?? throw new ArgumentNullException(nameof(roleProvider)); + this.permissionProvider = permissionProvider ?? throw new ArgumentNullException(nameof(permissionProvider)); } @@ -52,8 +52,8 @@ namespace ASC.Common.Security.Authorizing ISecurityObjectProvider securityObjProvider, out ISubject denySubject, out IAction denyAction) { - if (subject == null) throw new ArgumentNullException("subject"); - if (action == null) throw new ArgumentNullException("action"); + if (subject == null) throw new ArgumentNullException(nameof(subject)); + if (action == null) throw new ArgumentNullException(nameof(action)); var acl = GetAzManagerAcl(subject, action, objectId, securityObjProvider); denySubject = acl.DenySubject; diff --git a/common/ASC.Core.Common/Security/Authorizing/PermissionProvider.cs b/common/ASC.Core.Common/Security/Authorizing/PermissionProvider.cs index 878e65d4b8..7ffc4a8410 100644 --- a/common/ASC.Core.Common/Security/Authorizing/PermissionProvider.cs +++ b/common/ASC.Core.Common/Security/Authorizing/PermissionProvider.cs @@ -44,8 +44,8 @@ namespace ASC.Core.Security.Authorizing public IEnumerable<Ace> GetAcl(ISubject subject, IAction action, ISecurityObjectId objectId, ISecurityObjectProvider secObjProvider) { - if (subject == null) throw new ArgumentNullException("subject"); - if (action == null) throw new ArgumentNullException("action"); + if (subject == null) throw new ArgumentNullException(nameof(subject)); + if (action == null) throw new ArgumentNullException(nameof(action)); return AuthorizationManager .GetAcesWithInherits(subject.ID, action.ID, objectId, secObjProvider) diff --git a/common/ASC.Core.Common/Security/Authorizing/PermissionResolver.cs b/common/ASC.Core.Common/Security/Authorizing/PermissionResolver.cs index 4d7cc57b1f..6fe753fc00 100644 --- a/common/ASC.Core.Common/Security/Authorizing/PermissionResolver.cs +++ b/common/ASC.Core.Common/Security/Authorizing/PermissionResolver.cs @@ -45,7 +45,7 @@ namespace ASC.Core.Security.Authorizing public PermissionResolver(AzManager azManager) { - this.azManager = azManager ?? throw new ArgumentNullException("azManager"); + this.azManager = azManager ?? throw new ArgumentNullException(nameof(azManager)); } diff --git a/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs b/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs index 36da33b545..820fbe17e5 100644 --- a/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs +++ b/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs @@ -85,7 +85,7 @@ namespace ASC.Security.Cryptography public string GetEmailKey(int tenantId, string email) { - if (string.IsNullOrEmpty(email)) throw new ArgumentNullException("email"); + if (string.IsNullOrEmpty(email)) throw new ArgumentNullException(nameof(email)); email = FormatEmail(tenantId, email); @@ -96,7 +96,7 @@ namespace ASC.Security.Cryptography private string FormatEmail(int tenantId, string email) { - if (email == null) throw new ArgumentNullException("email"); + if (email == null) throw new ArgumentNullException(nameof(email)); try { return string.Format("{0}|{1}|{2}", email.ToLowerInvariant(), tenantId, Encoding.UTF8.GetString(MachinePseudoKeys.GetMachineConstant())); @@ -123,8 +123,8 @@ namespace ASC.Security.Cryptography private ValidationResult ValidateEmailKeyInternal(string email, string key, TimeSpan validInterval) { - if (string.IsNullOrEmpty(email)) throw new ArgumentNullException("email"); - if (key == null) throw new ArgumentNullException("key"); + if (string.IsNullOrEmpty(email)) throw new ArgumentNullException(nameof(email)); + if (key == null) throw new ArgumentNullException(nameof(key)); email = FormatEmail(TenantManager.GetCurrentTenant().TenantId, email); var parts = key.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); diff --git a/common/ASC.Core.Common/Users/UserFormatter.cs b/common/ASC.Core.Common/Users/UserFormatter.cs index 0936dfb3cb..394f3f8f9b 100644 --- a/common/ASC.Core.Common/Users/UserFormatter.cs +++ b/common/ASC.Core.Common/Users/UserFormatter.cs @@ -51,7 +51,7 @@ namespace ASC.Core.Users public string GetUserName(UserInfo userInfo, DisplayUserNameFormat format) { - if (userInfo == null) throw new ArgumentNullException("userInfo"); + if (userInfo == null) throw new ArgumentNullException(nameof(userInfo)); return string.Format(GetUserDisplayFormat(format), userInfo.FirstName, userInfo.LastName); } diff --git a/common/ASC.Data.Backup.Core/ActionInvoker.cs b/common/ASC.Data.Backup.Core/ActionInvoker.cs index e4ce168963..32c1be95af 100644 --- a/common/ASC.Data.Backup.Core/ActionInvoker.cs +++ b/common/ASC.Data.Backup.Core/ActionInvoker.cs @@ -52,7 +52,7 @@ namespace ASC.Data.Backup bool isSleepExponential = true) { if (action == null) - throw new ArgumentNullException("action"); + throw new ArgumentNullException(nameof(action)); var countAttempts = 0; while (countAttempts++ < maxAttempts) diff --git a/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs b/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs index 23e6934fc4..6fc7aec1dd 100644 --- a/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs +++ b/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs @@ -56,13 +56,13 @@ namespace ASC.Data.Backup.Extensions Func<TEntry, TKey> parentKeySelector) { if (elements == null) - throw new ArgumentNullException("elements"); + throw new ArgumentNullException(nameof(elements)); if (keySelector == null) - throw new ArgumentNullException("keySelector"); + throw new ArgumentNullException(nameof(keySelector)); if (parentKeySelector == null) - throw new ArgumentNullException("parentKeySelector"); + throw new ArgumentNullException(nameof(parentKeySelector)); var dic = elements.ToDictionary(keySelector, x => new TreeNode<TEntry>(x)); foreach (var keyValue in dic) @@ -81,10 +81,10 @@ namespace ASC.Data.Backup.Extensions public static IEnumerable<IEnumerable<TEntry>> MakeParts<TEntry>(this IEnumerable<TEntry> collection, int partLength) { if (collection == null) - throw new ArgumentNullException("collection"); + throw new ArgumentNullException(nameof(collection)); if (partLength <= 0) - throw new ArgumentOutOfRangeException("partLength", partLength, "Length must be positive integer"); + throw new ArgumentOutOfRangeException(nameof(partLength), partLength, "Length must be positive integer"); return MakePartsIterator(collection, partLength); } diff --git a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs index a952f1b609..5a0f1b8b58 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -78,7 +78,7 @@ namespace ASC.Data.Backup.Tasks public void Init(int tenantId, string fromConfigPath, string toFilePath, int limit) { if (string.IsNullOrEmpty(toFilePath)) - throw new ArgumentNullException("toFilePath"); + throw new ArgumentNullException(nameof(toFilePath)); BackupFilePath = toFilePath; Limit = limit; Init(tenantId, fromConfigPath); diff --git a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs index fe6aae0e9e..41c67c5511 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -167,7 +167,7 @@ namespace ASC.Data.Backup.Tasks { if (value <= 0) { - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException(nameof(value)); } stepsCount = value; Logger.Debug("Steps: " + stepsCount); @@ -191,7 +191,7 @@ namespace ASC.Data.Backup.Tasks { if (value < 0 || value > 100) { - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException(nameof(value)); } if (value == 100) { @@ -207,7 +207,7 @@ namespace ASC.Data.Backup.Tasks { if (value < 0 || value > 100) { - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException(nameof(value)); } if (Progress != value) { diff --git a/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs b/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs index 06f36cbb43..22ff841453 100644 --- a/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs @@ -54,9 +54,9 @@ namespace ASC.Data.Backup.Tasks public RestoreDbModuleTask(IOptionsMonitor<ILog> options, IModuleSpecifics module, IDataReadOperator reader, ColumnMapper columnMapper, DbFactory factory, bool replaceDate, bool dump, StorageFactory storageFactory, StorageFactoryConfig storageFactoryConfig, ModuleProvider moduleProvider) : base(factory, options, storageFactory, storageFactoryConfig, moduleProvider) { - Reader = reader ?? throw new ArgumentNullException("reader"); - ColumnMapper = columnMapper ?? throw new ArgumentNullException("columnMapper"); - DbFactory = factory ?? throw new ArgumentNullException("factory"); + Reader = reader ?? throw new ArgumentNullException(nameof(reader)); + ColumnMapper = columnMapper ?? throw new ArgumentNullException(nameof(columnMapper)); + DbFactory = factory ?? throw new ArgumentNullException(nameof(factory)); Module = module; ReplaceDate = replaceDate; Dump = dump; diff --git a/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs index 16d9e1db71..5dc5985a30 100644 --- a/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs @@ -84,7 +84,7 @@ namespace ASC.Data.Backup.Tasks public void Init(string toConfigPath, string fromFilePath, int tenantId = -1, ColumnMapper columnMapper = null, string upgradesPath = null) { if (fromFilePath == null) - throw new ArgumentNullException("fromFilePath"); + throw new ArgumentNullException(nameof(fromFilePath)); if (!File.Exists(fromFilePath)) throw new FileNotFoundException("file not found at given path"); diff --git a/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs index 1665c36e3f..632af50158 100644 --- a/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs @@ -83,7 +83,7 @@ namespace ASC.Data.Backup.Tasks public void Init(int tenantId, string fromConfigPath, string toConfigPath, int limit, string backupDirectory) { Limit = limit; - ToConfigPath = toConfigPath ?? throw new ArgumentNullException("toConfigPath"); + ToConfigPath = toConfigPath ?? throw new ArgumentNullException(nameof(toConfigPath)); Init(tenantId, fromConfigPath); BackupDirectory = backupDirectory; diff --git a/common/ASC.Data.Storage/BaseStorage.cs b/common/ASC.Data.Storage/BaseStorage.cs index 2b1ab92397..b25f4fac77 100644 --- a/common/ASC.Data.Storage/BaseStorage.cs +++ b/common/ASC.Data.Storage/BaseStorage.cs @@ -104,7 +104,7 @@ namespace ASC.Data.Storage { if (path == null) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } if (string.IsNullOrEmpty(_tenant) && IsSupportInternalUri) diff --git a/common/ASC.Data.Storage/CrossModuleTransferUtility.cs b/common/ASC.Data.Storage/CrossModuleTransferUtility.cs index 97abdc3d1b..3bc35eb1de 100644 --- a/common/ASC.Data.Storage/CrossModuleTransferUtility.cs +++ b/common/ASC.Data.Storage/CrossModuleTransferUtility.cs @@ -57,18 +57,18 @@ namespace ASC.Data.Storage Option = option; TempStream = tempStream; TempPath = tempPath; - this.source = source ?? throw new ArgumentNullException("source"); - this.destination = destination ?? throw new ArgumentNullException("destination"); + this.source = source ?? throw new ArgumentNullException(nameof(source)); + this.destination = destination ?? throw new ArgumentNullException(nameof(destination)); maxChunkUploadSize = 10 * 1024 * 1024; chunksize = 5 * 1024 * 1024; } public void CopyFile(string srcDomain, string srcPath, string destDomain, string destPath) { - if (srcDomain == null) throw new ArgumentNullException("srcDomain"); - if (srcPath == null) throw new ArgumentNullException("srcPath"); - if (destDomain == null) throw new ArgumentNullException("destDomain"); - if (destPath == null) throw new ArgumentNullException("destPath"); + if (srcDomain == null) throw new ArgumentNullException(nameof(srcDomain)); + if (srcPath == null) throw new ArgumentNullException(nameof(srcPath)); + if (destDomain == null) throw new ArgumentNullException(nameof(destDomain)); + if (destPath == null) throw new ArgumentNullException(nameof(destPath)); using var stream = source.GetReadStream(srcDomain, srcPath); if (stream.Length < maxChunkUploadSize) diff --git a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs index bdc6f4d4f8..1fe967da00 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -98,7 +98,7 @@ namespace ASC.Data.Storage.DiscStorage { if (path == null) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } var pathMap = GetPath(domain); @@ -118,7 +118,7 @@ namespace ASC.Data.Storage.DiscStorage public Stream GetReadStream(string domain, string path, bool withDecription) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); var target = GetTarget(domain, path); if (File.Exists(target)) @@ -135,7 +135,7 @@ namespace ASC.Data.Storage.DiscStorage public override Stream GetReadStream(string domain, string path, int offset) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); var target = GetTarget(domain, path); if (File.Exists(target)) @@ -172,8 +172,8 @@ namespace ASC.Data.Storage.DiscStorage QuotaController.QuotaUsedCheck(buffered.Length); } - if (path == null) throw new ArgumentNullException("path"); - if (buffered == null) throw new ArgumentNullException("stream"); + if (path == null) throw new ArgumentNullException(nameof(path)); + if (buffered == null) throw new ArgumentNullException(nameof(stream)); //Try seek to start if (buffered.CanSeek) @@ -277,7 +277,7 @@ namespace ASC.Data.Storage.DiscStorage public override void Delete(string domain, string path) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); var target = GetTarget(domain, path); if (File.Exists(target)) @@ -295,7 +295,7 @@ namespace ASC.Data.Storage.DiscStorage public override void DeleteFiles(string domain, List<string> paths) { - if (paths == null) throw new ArgumentNullException("paths"); + if (paths == null) throw new ArgumentNullException(nameof(paths)); foreach (var path in paths) { @@ -313,7 +313,7 @@ namespace ASC.Data.Storage.DiscStorage public override void DeleteFiles(string domain, string folderPath, string pattern, bool recursive) { - if (folderPath == null) throw new ArgumentNullException("folderPath"); + if (folderPath == null) throw new ArgumentNullException(nameof(folderPath)); //Return dirs var targetDir = GetTarget(domain, folderPath); @@ -335,7 +335,7 @@ namespace ASC.Data.Storage.DiscStorage public override void DeleteFiles(string domain, string folderPath, DateTime fromDate, DateTime toDate) { - if (folderPath == null) throw new ArgumentNullException("folderPath"); + if (folderPath == null) throw new ArgumentNullException(nameof(folderPath)); //Return dirs var targetDir = GetTarget(domain, folderPath); @@ -374,8 +374,8 @@ namespace ASC.Data.Storage.DiscStorage public override Uri Move(string srcdomain, string srcpath, string newdomain, string newpath, bool quotaCheckFileSize = true) { - if (srcpath == null) throw new ArgumentNullException("srcpath"); - if (newpath == null) throw new ArgumentNullException("srcpath"); + if (srcpath == null) throw new ArgumentNullException(nameof(srcpath)); + if (newpath == null) throw new ArgumentNullException(nameof(srcpath)); var target = GetTarget(srcdomain, srcpath); var newtarget = GetTarget(newdomain, newpath); @@ -407,7 +407,7 @@ namespace ASC.Data.Storage.DiscStorage public override bool IsDirectory(string domain, string path) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); //Return dirs var targetDir = GetTarget(domain, path); @@ -420,7 +420,7 @@ namespace ASC.Data.Storage.DiscStorage public override void DeleteDirectory(string domain, string path) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); //Return dirs var targetDir = GetTarget(domain, path); @@ -485,7 +485,7 @@ namespace ASC.Data.Storage.DiscStorage public override void DeleteExpired(string domain, string folderPath, TimeSpan oldThreshold) { - if (folderPath == null) throw new ArgumentNullException("folderPath"); + if (folderPath == null) throw new ArgumentNullException(nameof(folderPath)); //Return dirs var targetDir = GetTarget(domain, folderPath); @@ -531,7 +531,7 @@ namespace ASC.Data.Storage.DiscStorage public override string[] ListDirectoriesRelative(string domain, string path, bool recursive) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); //Return dirs var targetDir = GetTarget(domain, path); @@ -548,7 +548,7 @@ namespace ASC.Data.Storage.DiscStorage public override string[] ListFilesRelative(string domain, string path, string pattern, bool recursive) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); //Return dirs var targetDir = GetTarget(domain, path); @@ -565,7 +565,7 @@ namespace ASC.Data.Storage.DiscStorage public override bool IsFile(string domain, string path) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); //Return dirs var target = GetTarget(domain, path); @@ -602,8 +602,8 @@ namespace ASC.Data.Storage.DiscStorage public override Uri Copy(string srcdomain, string srcpath, string newdomain, string newpath) { - if (srcpath == null) throw new ArgumentNullException("srcpath"); - if (newpath == null) throw new ArgumentNullException("srcpath"); + if (srcpath == null) throw new ArgumentNullException(nameof(srcpath)); + if (newpath == null) throw new ArgumentNullException(nameof(srcpath)); var target = GetTarget(srcdomain, srcpath); var newtarget = GetTarget(newdomain, newpath); @@ -680,7 +680,7 @@ namespace ASC.Data.Storage.DiscStorage public Stream GetWriteStream(string domain, string path, FileMode fileMode) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); var target = GetTarget(domain, path); CreateDirectory(target); return File.Open(target, fileMode); @@ -716,7 +716,7 @@ namespace ASC.Data.Storage.DiscStorage public void Encrypt(string domain, string path) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); var target = GetTarget(domain, path); @@ -732,7 +732,7 @@ namespace ASC.Data.Storage.DiscStorage public void Decrypt(string domain, string path) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); var target = GetTarget(domain, path); diff --git a/common/ASC.Data.Storage/Extensions.cs b/common/ASC.Data.Storage/Extensions.cs index b8892a79da..afc368009e 100644 --- a/common/ASC.Data.Storage/Extensions.cs +++ b/common/ASC.Data.Storage/Extensions.cs @@ -46,8 +46,8 @@ namespace ASC.Data.Storage public static void IronReadToStream(this IDataStore store, string domain, string path, int tryCount, Stream readTo) { - if (tryCount < 1) throw new ArgumentOutOfRangeException("tryCount", "Must be greater or equal 1."); - if (!readTo.CanWrite) throw new ArgumentException("stream cannot be written", "readTo"); + if (tryCount < 1) throw new ArgumentOutOfRangeException(nameof(tryCount), "Must be greater or equal 1."); + if (!readTo.CanWrite) throw new ArgumentException("stream cannot be written", nameof(readTo)); var tryCurrent = 0; var offset = 0; diff --git a/common/ASC.Data.Storage/ProgressStream.cs b/common/ASC.Data.Storage/ProgressStream.cs index 7d29302a6d..720d5bbc50 100644 --- a/common/ASC.Data.Storage/ProgressStream.cs +++ b/common/ASC.Data.Storage/ProgressStream.cs @@ -36,7 +36,7 @@ namespace ASC.Data.Storage public ProgressStream(Stream stream) { - this.stream = stream ?? throw new ArgumentNullException("stream"); + this.stream = stream ?? throw new ArgumentNullException(nameof(stream)); try { length = stream.Length; diff --git a/common/ASC.Data.Storage/S3/S3Storage.cs b/common/ASC.Data.Storage/S3/S3Storage.cs index f0e003ee0c..abe306b95a 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -1262,7 +1262,7 @@ namespace ASC.Data.Storage.S3 public ResponseStreamWrapper(GetObjectResponse response) { - _response = response ?? throw new ArgumentNullException("response"); + _response = response ?? throw new ArgumentNullException(nameof(response)); } diff --git a/common/ASC.Data.Storage/TenantPath.cs b/common/ASC.Data.Storage/TenantPath.cs index 36e2fe49a1..0f604fda12 100644 --- a/common/ASC.Data.Storage/TenantPath.cs +++ b/common/ASC.Data.Storage/TenantPath.cs @@ -35,7 +35,7 @@ namespace ASC.Data.Storage { if (tenant == null) { - throw new ArgumentNullException("tenant"); + throw new ArgumentNullException(nameof(tenant)); } if (long.TryParse(tenant, NumberStyles.Integer, CultureInfo.InvariantCulture, out var tenantId)) diff --git a/common/ASC.Data.Storage/WebPath.cs b/common/ASC.Data.Storage/WebPath.cs index 40f97243bb..0752ac206e 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -82,7 +82,7 @@ namespace ASC.Data.Storage { if (!string.IsNullOrEmpty(relativePath) && relativePath.IndexOf('~') == 0) { - throw new ArgumentException($"bad path format {relativePath} remove '~'", "relativePath"); + throw new ArgumentException($"bad path format {relativePath} remove '~'", nameof(relativePath)); } var result = relativePath; @@ -200,7 +200,7 @@ namespace ASC.Data.Storage { if (!string.IsNullOrEmpty(relativePath) && relativePath.IndexOf('~') == 0) { - throw new ArgumentException($"bad path format {relativePath} remove '~'", "relativePath"); + throw new ArgumentException($"bad path format {relativePath} remove '~'", nameof(relativePath)); } if (CoreBaseSettings.Standalone && ServiceProvider.GetService<StaticUploader>().CanUpload()) //hack for skip resolve DistributedTaskQueueOptionsManager diff --git a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs index 6be75592bb..5ed17df780 100644 --- a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs @@ -103,7 +103,7 @@ namespace ASC.FederatedLogin.Helpers var clientSecret = loginProvider.ClientSecret; var redirectUri = loginProvider.RedirectUri; - if (string.IsNullOrEmpty(authCode)) throw new ArgumentNullException("authCode"); + if (string.IsNullOrEmpty(authCode)) throw new ArgumentNullException(nameof(authCode)); if (string.IsNullOrEmpty(clientID)) throw new ArgumentNullException("clientID"); if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret"); @@ -142,7 +142,7 @@ namespace ASC.FederatedLogin.Helpers public static OAuth20Token RefreshToken(string requestUrl, OAuth20Token token) { - if (token == null || !CanRefresh(token)) throw new ArgumentException("Can not refresh given token", "token"); + if (token == null || !CanRefresh(token)) throw new ArgumentException("Can not refresh given token", nameof(token)); var data = $"client_id={HttpUtility.UrlEncode(token.ClientID)}&client_secret={HttpUtility.UrlEncode(token.ClientSecret)}&refresh_token={HttpUtility.UrlEncode(token.RefreshToken)}&grant_type=refresh_token"; diff --git a/common/ASC.FederatedLogin/Helpers/RequestHelper.cs b/common/ASC.FederatedLogin/Helpers/RequestHelper.cs index 1ee9a7d6ea..be5240a859 100644 --- a/common/ASC.FederatedLogin/Helpers/RequestHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/RequestHelper.cs @@ -38,7 +38,7 @@ namespace ASC.FederatedLogin.Helpers public static string PerformRequest(string uri, string contentType = "", string method = "GET", string body = "", Dictionary<string, string> headers = null, int timeout = 30000) { - if (string.IsNullOrEmpty(uri)) throw new ArgumentNullException("uri"); + if (string.IsNullOrEmpty(uri)) throw new ArgumentNullException(nameof(uri)); var request = new HttpRequestMessage(); request.RequestUri = new Uri(uri); diff --git a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs index 21549f2090..42fe66347d 100644 --- a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs @@ -88,7 +88,7 @@ namespace ASC.FederatedLogin.LoginProviders public OAuth20Token GetAccessToken(string authCode) { - if (string.IsNullOrEmpty(authCode)) throw new ArgumentNullException("authCode"); + if (string.IsNullOrEmpty(authCode)) throw new ArgumentNullException(nameof(authCode)); if (string.IsNullOrEmpty(ClientID)) throw new ArgumentException("clientID"); if (string.IsNullOrEmpty(ClientSecret)) throw new ArgumentException("clientSecret"); diff --git a/common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs b/common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs index 85ddffe722..3d1deb91ee 100644 --- a/common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs +++ b/common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs @@ -79,7 +79,7 @@ namespace ASC.FederatedLogin.LoginProviders public LoginProfile GetLoginProfile(string providerType, string accessToken) { var consumer = GetLoginProvider(providerType); - if (consumer == null) throw new ArgumentException("Unknown provider type", "providerType"); + if (consumer == null) throw new ArgumentException("Unknown provider type", nameof(providerType)); try { diff --git a/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs b/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs index cfb901392a..2a38655e77 100644 --- a/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs +++ b/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs @@ -48,7 +48,7 @@ namespace ASC.FederatedLogin databaseId = string.Join(".", new[] { _baseDatabaseId, hostedRegion.Trim() }); if (!_accountLinkers.ContainsKey(databaseId)) - throw new ArgumentException($"Region {databaseId} is not defined", "hostedRegion"); + throw new ArgumentException($"Region {databaseId} is not defined", nameof(hostedRegion)); return databaseId; } diff --git a/common/ASC.FederatedLogin/Profile/LoginProfile.cs b/common/ASC.FederatedLogin/Profile/LoginProfile.cs index bbed67d0df..af7b337aee 100644 --- a/common/ASC.FederatedLogin/Profile/LoginProfile.cs +++ b/common/ASC.FederatedLogin/Profile/LoginProfile.cs @@ -233,7 +233,7 @@ namespace ASC.FederatedLogin.Profile internal void SetField(string name, string value) { - if (name == null) throw new ArgumentNullException("name"); + if (name == null) throw new ArgumentNullException(nameof(name)); if (!string.IsNullOrEmpty(value)) { if (_fields.ContainsKey(name)) @@ -276,7 +276,7 @@ namespace ASC.FederatedLogin.Profile public static bool HasProfile(HttpRequest request) { - if (request == null) throw new ArgumentNullException("request"); + if (request == null) throw new ArgumentNullException(nameof(request)); return new Uri(request.GetDisplayUrl()).HasProfile(); } @@ -361,7 +361,7 @@ namespace ASC.FederatedLogin.Profile internal void FromSerializedString(string serialized) { - if (serialized == null) throw new ArgumentNullException("serialized"); + if (serialized == null) throw new ArgumentNullException(nameof(serialized)); _fields = serialized.Split(PairSeparator).ToDictionary(x => x.Split(KeyValueSeparator)[0], y => y.Split(KeyValueSeparator)[1]); } @@ -386,7 +386,7 @@ namespace ASC.FederatedLogin.Profile protected LoginProfile(Signature signature, InstanceCrypto instanceCrypto, SerializationInfo info) : this(signature, instanceCrypto) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); var transformed = (string)info.GetValue(QueryParamName, typeof(string)); FromTransport(transformed); } diff --git a/common/ASC.VoipService/Twilio/TwilioProvider.cs b/common/ASC.VoipService/Twilio/TwilioProvider.cs index d2ee57c930..533e698b57 100644 --- a/common/ASC.VoipService/Twilio/TwilioProvider.cs +++ b/common/ASC.VoipService/Twilio/TwilioProvider.cs @@ -60,8 +60,8 @@ namespace ASC.VoipService.Twilio public TwilioProvider(string accountSid, string authToken, AuthContext authContext, TenantUtil tenantUtil, SecurityContext securityContext, BaseCommonLinkUtility baseCommonLinkUtility) { - if (string.IsNullOrEmpty(accountSid)) throw new ArgumentNullException("accountSid"); - if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException("authToken"); + if (string.IsNullOrEmpty(accountSid)) throw new ArgumentNullException(nameof(accountSid)); + if (string.IsNullOrEmpty(authToken)) throw new ArgumentNullException(nameof(authToken)); this.authToken = authToken; AuthContext = authContext; diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index febed6aed5..904047c81f 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -611,7 +611,7 @@ namespace ASC.ElasticSearch } break; default: - throw new ArgumentOutOfRangeException("action", action, null); + throw new ArgumentOutOfRangeException(nameof(action), action, null); } } diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index b650ad93a5..10af00d5f3 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -368,7 +368,7 @@ namespace ASC.Files.Core.Data { if (file == null) { - throw new ArgumentNullException("file"); + throw new ArgumentNullException(nameof(file)); } var maxChunkedUploadSize = SetupInfo.MaxChunkedUploadSize(TenantExtra, TenantStatisticProvider); @@ -514,7 +514,7 @@ namespace ASC.Files.Core.Data public File<int> ReplaceFileVersion(File<int> file, Stream fileStream) { - if (file == null) throw new ArgumentNullException("file"); + if (file == null) throw new ArgumentNullException(nameof(file)); if (file.ID == default) throw new ArgumentException("No file id or folder id toFolderId determine provider"); var maxChunkedUploadSize = SetupInfo.MaxChunkedUploadSize(TenantExtra, TenantStatisticProvider); @@ -1171,9 +1171,9 @@ namespace ASC.Files.Core.Data public void SaveEditHistory(File<int> file, string changes, Stream differenceStream) { - if (file == null) throw new ArgumentNullException("file"); - if (string.IsNullOrEmpty(changes)) throw new ArgumentNullException("changes"); - if (differenceStream == null) throw new ArgumentNullException("differenceStream"); + if (file == null) throw new ArgumentNullException(nameof(file)); + if (string.IsNullOrEmpty(changes)) throw new ArgumentNullException(nameof(changes)); + if (differenceStream == null) throw new ArgumentNullException(nameof(differenceStream)); changes = changes.Trim(); @@ -1285,7 +1285,7 @@ namespace ASC.Files.Core.Data public void SaveThumbnail(File<int> file, Stream thumbnail) { - if (file == null) throw new ArgumentNullException("file"); + if (file == null) throw new ArgumentNullException(nameof(file)); var toUpdate = FilesDbContext.Files .FirstOrDefault(r => r.Id == file.ID && r.Version == file.Version && r.TenantId == TenantID); diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs index 140afdde8c..2f99f6ae1c 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs @@ -297,7 +297,7 @@ namespace ASC.Files.Core.Data public int SaveFolder(Folder<int> folder, IDbContextTransaction transaction) { - if (folder == null) throw new ArgumentNullException("folder"); + if (folder == null) throw new ArgumentNullException(nameof(folder)); folder.Title = Global.ReplaceInvalidCharsAndTruncate(folder.Title); @@ -486,7 +486,7 @@ namespace ASC.Files.Core.Data var folder = GetFolder(folderId); if (folder.FolderType != FolderType.DEFAULT) - throw new ArgumentException("It is forbidden to move the System folder.", "folderId"); + throw new ArgumentException("It is forbidden to move the System folder.", nameof(folderId)); var recalcFolders = new List<int> { toFolderId }; var parent = FilesDbContext.Folders @@ -824,8 +824,8 @@ namespace ASC.Files.Core.Data public IEnumerable<int> GetFolderIDs(string module, string bunch, IEnumerable<string> data, bool createIfNotExists) { - if (string.IsNullOrEmpty(module)) throw new ArgumentNullException("module"); - if (string.IsNullOrEmpty(bunch)) throw new ArgumentNullException("bunch"); + if (string.IsNullOrEmpty(module)) throw new ArgumentNullException(nameof(module)); + if (string.IsNullOrEmpty(bunch)) throw new ArgumentNullException(nameof(bunch)); var keys = data.Select(id => $"{module}/{bunch}/{id}").ToArray(); @@ -908,8 +908,8 @@ namespace ASC.Files.Core.Data public int GetFolderID(string module, string bunch, string data, bool createIfNotExists) { - if (string.IsNullOrEmpty(module)) throw new ArgumentNullException("module"); - if (string.IsNullOrEmpty(bunch)) throw new ArgumentNullException("bunch"); + if (string.IsNullOrEmpty(module)) throw new ArgumentNullException(nameof(module)); + if (string.IsNullOrEmpty(bunch)) throw new ArgumentNullException(nameof(bunch)); var key = $"{module}/{bunch}/{data}"; var folderId = Query(FilesDbContext.BunchObjects) diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs index 8766c941a1..05ffb3813f 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs @@ -177,7 +177,7 @@ namespace ASC.Files.Core.Data public IEnumerable<Tag> GetTags(string[] names, TagType tagType) { - if (names == null) throw new ArgumentNullException("names"); + if (names == null) throw new ArgumentNullException(nameof(names)); var q = Query(FilesDbContext.Tag) .Join(FilesDbContext.TagLink, r => r.Id, l => l.TagId, (tag, link) => new TagLinkData { Tag = tag, Link = link }) @@ -191,7 +191,7 @@ namespace ASC.Files.Core.Data public IEnumerable<Tag> GetTags(string name, TagType tagType) { - if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); + if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); return GetTags(new[] { name }, tagType); } diff --git a/products/ASC.Files/Core/Core/Entries/EncryptionKeyPair.cs b/products/ASC.Files/Core/Core/Entries/EncryptionKeyPair.cs index 3cf65ce08e..70aefb7bf8 100644 --- a/products/ASC.Files/Core/Core/Entries/EncryptionKeyPair.cs +++ b/products/ASC.Files/Core/Core/Entries/EncryptionKeyPair.cs @@ -72,8 +72,8 @@ namespace ASC.Web.Files.Core.Entries public void SetKeyPair(string publicKey, string privateKeyEnc) { - if (string.IsNullOrEmpty(publicKey)) throw new ArgumentNullException("publicKey"); - if (string.IsNullOrEmpty(privateKeyEnc)) throw new ArgumentNullException("privateKeyEnc"); + if (string.IsNullOrEmpty(publicKey)) throw new ArgumentNullException(nameof(publicKey)); + if (string.IsNullOrEmpty(privateKeyEnc)) throw new ArgumentNullException(nameof(privateKeyEnc)); var user = UserManager.GetUsers(AuthContext.CurrentAccount.ID); if (!AuthContext.IsAuthenticated || user.IsVisitor(UserManager)) throw new System.Security.SecurityException(); diff --git a/products/ASC.Files/Core/Core/FilesIntegration.cs b/products/ASC.Files/Core/Core/FilesIntegration.cs index 70658a8de8..8ce27d11e9 100644 --- a/products/ASC.Files/Core/Core/FilesIntegration.cs +++ b/products/ASC.Files/Core/Core/FilesIntegration.cs @@ -55,7 +55,7 @@ namespace ASC.Web.Files.Api public IEnumerable<T> RegisterBunchFolders<T>(string module, string bunch, IEnumerable<string> data) { if (data == null) - throw new ArgumentNullException("data"); + throw new ArgumentNullException(nameof(data)); data = data.ToList(); if (!data.Any()) diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs index c7cf70574c..0db8e96994 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFileDao.cs @@ -246,7 +246,7 @@ namespace ASC.Files.Thirdparty.Box ProviderInfo.CacheReset(boxFileId, true); var boxFile = GetBoxFile(file.ID); - if (boxFile == null) throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); + if (boxFile == null) throw new ArgumentNullException(nameof(file), FilesCommonResource.ErrorMassage_FileNotFound); if (boxFile is ErrorFile errorFile) throw new Exception(errorFile.Error); var fileStream = ProviderInfo.Storage.DownloadStream(boxFile, (int)offset); @@ -266,8 +266,8 @@ namespace ASC.Files.Thirdparty.Box public File<string> SaveFile(File<string> file, Stream fileStream) { - if (file == null) throw new ArgumentNullException("file"); - if (fileStream == null) throw new ArgumentNullException("fileStream"); + if (file == null) throw new ArgumentNullException(nameof(file)); + if (fileStream == null) throw new ArgumentNullException(nameof(fileStream)); BoxFile newBoxFile = null; diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFolderDao.cs index 99ee0e9a96..bd13e5738d 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxFolderDao.cs @@ -180,7 +180,7 @@ namespace ASC.Files.Thirdparty.Box public string SaveFolder(Folder<string> folder) { - if (folder == null) throw new ArgumentNullException("folder"); + if (folder == null) throw new ArgumentNullException(nameof(folder)); if (folder.ID != null) { return RenameFolder(folder, folder.Title); diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxStorage.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxStorage.cs index ed3d602c65..66a1959fbe 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxStorage.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxStorage.cs @@ -121,7 +121,7 @@ namespace ASC.Files.Thirdparty.Box public Stream DownloadStream(BoxFile file, int offset = 0) { - if (file == null) throw new ArgumentNullException("file"); + if (file == null) throw new ArgumentNullException(nameof(file)); if (offset > 0 && file.Size.HasValue) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs index 901a2fde36..43f8440ffe 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFileDao.cs @@ -250,7 +250,7 @@ namespace ASC.Files.Thirdparty.Dropbox ProviderInfo.CacheReset(dropboxFilePath, true); var dropboxFile = GetDropboxFile(file.ID); - if (dropboxFile == null) throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); + if (dropboxFile == null) throw new ArgumentNullException(nameof(file), FilesCommonResource.ErrorMassage_FileNotFound); if (dropboxFile is ErrorFile errorFile) throw new Exception(errorFile.Error); var fileStream = ProviderInfo.Storage.DownloadStream(MakeDropboxPath(dropboxFile), (int)offset); @@ -270,8 +270,8 @@ namespace ASC.Files.Thirdparty.Dropbox public File<string> SaveFile(File<string> file, Stream fileStream) { - if (file == null) throw new ArgumentNullException("file"); - if (fileStream == null) throw new ArgumentNullException("fileStream"); + if (file == null) throw new ArgumentNullException(nameof(file)); + if (fileStream == null) throw new ArgumentNullException(nameof(fileStream)); FileMetadata newDropboxFile = null; diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFolderDao.cs index d7751a8ad9..5d793c7846 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxFolderDao.cs @@ -181,7 +181,7 @@ namespace ASC.Files.Thirdparty.Dropbox public string SaveFolder(Folder<string> folder) { - if (folder == null) throw new ArgumentNullException("folder"); + if (folder == null) throw new ArgumentNullException(nameof(folder)); if (folder.ID != null) { return RenameFolder(folder, folder.Title); diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs index 08a92a8074..8f68abf428 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFileDao.cs @@ -246,7 +246,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive var driveId = MakeDriveId(file.ID); ProviderInfo.CacheReset(driveId, true); var driveFile = GetDriveEntry(file.ID); - if (driveFile == null) throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); + if (driveFile == null) throw new ArgumentNullException(nameof(file), FilesCommonResource.ErrorMassage_FileNotFound); if (driveFile is ErrorDriveEntry errorDriveEntry) throw new Exception(errorDriveEntry.Error); var fileStream = ProviderInfo.Storage.DownloadStream(driveFile, (int)offset); @@ -271,8 +271,8 @@ namespace ASC.Files.Thirdparty.GoogleDrive public File<string> SaveFile(File<string> file, Stream fileStream) { - if (file == null) throw new ArgumentNullException("file"); - if (fileStream == null) throw new ArgumentNullException("fileStream"); + if (file == null) throw new ArgumentNullException(nameof(file)); + if (fileStream == null) throw new ArgumentNullException(nameof(fileStream)); DriveFile newDriveFile = null; diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFolderDao.cs index 28b26accd3..e784006a19 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveFolderDao.cs @@ -177,7 +177,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive public string SaveFolder(Folder<string> folder) { - if (folder == null) throw new ArgumentNullException("folder"); + if (folder == null) throw new ArgumentNullException(nameof(folder)); if (folder.ID != null) { return RenameFolder(folder, folder.Title); diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs index 8930f5d4c9..d95b3d25ee 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveStorage.cs @@ -205,7 +205,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive public Stream DownloadStream(DriveFile file, int offset = 0) { - if (file == null) throw new ArgumentNullException("file"); + if (file == null) throw new ArgumentNullException(nameof(file)); var downloadArg = $"{file.Id}?alt=media"; @@ -347,7 +347,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive public ResumableUploadSession CreateResumableSession(DriveFile driveFile, long contentLength) { - if (driveFile == null) throw new ArgumentNullException("driveFile"); + if (driveFile == null) throw new ArgumentNullException(nameof(driveFile)); var fileId = string.Empty; var method = "POST"; @@ -389,7 +389,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive public void Transfer(ResumableUploadSession googleDriveSession, Stream stream, long chunkLength) { if (stream == null) - throw new ArgumentNullException("stream"); + throw new ArgumentNullException(nameof(stream)); if (googleDriveSession.Status != ResumableUploadSessionStatus.Started) throw new InvalidOperationException("Can't upload chunk for given upload session."); diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs index 3c9cd22b84..29a2b63bd0 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFileDao.cs @@ -246,7 +246,7 @@ namespace ASC.Files.Thirdparty.OneDrive ProviderInfo.CacheReset(onedriveFileId); var onedriveFile = GetOneDriveItem(file.ID); - if (onedriveFile == null) throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); + if (onedriveFile == null) throw new ArgumentNullException(nameof(file), FilesCommonResource.ErrorMassage_FileNotFound); if (onedriveFile is ErrorItem errorItem) throw new Exception(errorItem.Error); var fileStream = ProviderInfo.Storage.DownloadStream(onedriveFile, (int)offset); @@ -266,8 +266,8 @@ namespace ASC.Files.Thirdparty.OneDrive public File<string> SaveFile(File<string> file, Stream fileStream) { - if (file == null) throw new ArgumentNullException("file"); - if (fileStream == null) throw new ArgumentNullException("fileStream"); + if (file == null) throw new ArgumentNullException(nameof(file)); + if (fileStream == null) throw new ArgumentNullException(nameof(fileStream)); Item newOneDriveFile = null; diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFolderDao.cs index 7a0bfda7f4..ff81daa728 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveFolderDao.cs @@ -177,7 +177,7 @@ namespace ASC.Files.Thirdparty.OneDrive public string SaveFolder(Folder<string> folder) { - if (folder == null) throw new ArgumentNullException("folder"); + if (folder == null) throw new ArgumentNullException(nameof(folder)); if (folder.ID != null) { return RenameFolder(folder, folder.Title); diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs index fd901dca45..37658b87b9 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveStorage.cs @@ -141,7 +141,7 @@ namespace ASC.Files.Thirdparty.OneDrive public Stream DownloadStream(Item file, int offset = 0) { - if (file == null || file.File == null) throw new ArgumentNullException("file"); + if (file == null || file.File == null) throw new ArgumentNullException(nameof(file)); var fileStream = OnedriveClient .Drive @@ -250,7 +250,7 @@ namespace ASC.Files.Thirdparty.OneDrive public ResumableUploadSession CreateResumableSession(Item onedriveFile, long contentLength) { - if (onedriveFile == null) throw new ArgumentNullException("onedriveFile"); + if (onedriveFile == null) throw new ArgumentNullException(nameof(onedriveFile)); var folderId = onedriveFile.ParentReference.Id; var fileName = onedriveFile.Name; @@ -289,7 +289,7 @@ namespace ASC.Files.Thirdparty.OneDrive public void Transfer(ResumableUploadSession oneDriveSession, Stream stream, long chunkLength) { if (stream == null) - throw new ArgumentNullException("stream"); + throw new ArgumentNullException(nameof(stream)); if (oneDriveSession.Status != ResumableUploadSessionStatus.Started) throw new InvalidOperationException("Can't upload chunk for given upload session."); diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFileDao.cs index 7bb179e8b5..64202e8a5f 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFileDao.cs @@ -208,7 +208,7 @@ namespace ASC.Files.Thirdparty.ProviderDao /// <returns>Stream</returns> public Stream GetFileStream(File<string> file, long offset) { - if (file == null) throw new ArgumentNullException("file"); + if (file == null) throw new ArgumentNullException(nameof(file)); var fileId = file.ID; var selector = GetSelector(fileId); file.ID = selector.ConvertId(fileId); @@ -221,7 +221,7 @@ namespace ASC.Files.Thirdparty.ProviderDao public bool IsSupportedPreSignedUri(File<string> file) { - if (file == null) throw new ArgumentNullException("file"); + if (file == null) throw new ArgumentNullException(nameof(file)); var fileId = file.ID; var selector = GetSelector(fileId); file.ID = selector.ConvertId(fileId); @@ -234,7 +234,7 @@ namespace ASC.Files.Thirdparty.ProviderDao public Uri GetPreSignedUri(File<string> file, TimeSpan expires) { - if (file == null) throw new ArgumentNullException("file"); + if (file == null) throw new ArgumentNullException(nameof(file)); var fileId = file.ID; var selector = GetSelector(fileId); file.ID = selector.ConvertId(fileId); @@ -247,7 +247,7 @@ namespace ASC.Files.Thirdparty.ProviderDao public File<string> SaveFile(File<string> file, Stream fileStream) { - if (file == null) throw new ArgumentNullException("file"); + if (file == null) throw new ArgumentNullException(nameof(file)); var fileId = file.ID; var folderId = file.FolderID; @@ -281,7 +281,7 @@ namespace ASC.Files.Thirdparty.ProviderDao public File<string> ReplaceFileVersion(File<string> file, Stream fileStream) { - if (file == null) throw new ArgumentNullException("file"); + if (file == null) throw new ArgumentNullException(nameof(file)); if (file.ID == null) throw new ArgumentException("No file id or folder id toFolderId determine provider"); var fileId = file.ID; @@ -446,7 +446,7 @@ namespace ASC.Files.Thirdparty.ProviderDao if (file.FolderID != null) return GetSelector(file.FolderID).GetFileDao(file.FolderID); - throw new ArgumentException("Can't create instance of dao for given file.", "file"); + throw new ArgumentException("Can't create instance of dao for given file.", nameof(file)); } private string ConvertId(string id) diff --git a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs index 4a3b3a38b7..9ed97f9094 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderDao/ProviderFolderDao.cs @@ -144,7 +144,7 @@ filterType, subjectGroup, subjectID, searchText, searchSubfolders, checkShare); public string SaveFolder(Folder<string> folder) { - if (folder == null) throw new ArgumentNullException("folder"); + if (folder == null) throw new ArgumentNullException(nameof(folder)); if (folder.ID != null) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs b/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs index f0653fec6c..2e825eb568 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs @@ -130,7 +130,7 @@ namespace ASC.Files.Thirdparty internal BaseProviderInfo<T> GetInfo(string objectId) { - if (objectId == null) throw new ArgumentNullException("objectId"); + if (objectId == null) throw new ArgumentNullException(nameof(objectId)); var id = objectId; var match = Selector.Match(id); if (match.Success) diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs index ff159ff5a9..4c960d0d8f 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointFileDao.cs @@ -236,7 +236,7 @@ namespace ASC.Files.Thirdparty.SharePoint { var fileToDownload = ProviderInfo.GetFileById(file.ID); if (fileToDownload == null) - throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); + throw new ArgumentNullException(nameof(file), FilesCommonResource.ErrorMassage_FileNotFound); var fileStream = ProviderInfo.GetFileStream(fileToDownload.ServerRelativeUrl, (int)offset); @@ -255,7 +255,7 @@ namespace ASC.Files.Thirdparty.SharePoint public File<string> SaveFile(File<string> file, Stream fileStream) { - if (fileStream == null) throw new ArgumentNullException("fileStream"); + if (fileStream == null) throw new ArgumentNullException(nameof(fileStream)); if (file.ID != null) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs index 965f1c3323..7050e13865 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Sharpbox/SharpBoxFileDao.cs @@ -244,7 +244,7 @@ namespace ASC.Files.Thirdparty.Sharpbox var fileToDownload = GetFileById(file.ID); if (fileToDownload == null) - throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); + throw new ArgumentNullException(nameof(file), FilesCommonResource.ErrorMassage_FileNotFound); if (fileToDownload is ErrorEntry errorEntry) throw new Exception(errorEntry.Error); @@ -287,7 +287,7 @@ namespace ASC.Files.Thirdparty.Sharpbox public File<string> SaveFile(File<string> file, Stream fileStream) { - if (fileStream == null) throw new ArgumentNullException("fileStream"); + if (fileStream == null) throw new ArgumentNullException(nameof(fileStream)); ICloudFileSystemEntry entry = null; if (file.ID != null) { @@ -486,7 +486,7 @@ namespace ASC.Files.Thirdparty.Sharpbox var entry = GetFileById(file.ID); if (entry == null) - throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); + throw new ArgumentNullException(nameof(file), FilesCommonResource.ErrorMassage_FileNotFound); var oldFileId = MakeId(entry); var newFileId = oldFileId; diff --git a/products/ASC.Files/Core/Helpers/DocuSignHelper.cs b/products/ASC.Files/Core/Helpers/DocuSignHelper.cs index 75e9d3c991..a54f8ca466 100644 --- a/products/ASC.Files/Core/Helpers/DocuSignHelper.cs +++ b/products/ASC.Files/Core/Helpers/DocuSignHelper.cs @@ -99,7 +99,7 @@ namespace ASC.Web.Files.Helpers public void SaveToken(OAuth20Token token) { - if (token == null) throw new ArgumentNullException("token"); + if (token == null) throw new ArgumentNullException(nameof(token)); TokenHelper.SaveToken(new Token(token, AppAttr)); } @@ -207,7 +207,7 @@ namespace ASC.Web.Files.Helpers public string SendDocuSign<T>(T fileId, DocuSignData docuSignData, IDictionary<string, StringValues> requestHeaders) { - if (docuSignData == null) throw new ArgumentNullException("docuSignData"); + if (docuSignData == null) throw new ArgumentNullException(nameof(docuSignData)); var token = DocuSignToken.GetToken(); var account = GetDocuSignAccount(token); @@ -223,7 +223,7 @@ namespace ASC.Web.Files.Helpers private DocuSignAccount GetDocuSignAccount(OAuth20Token token) { - if (token == null) throw new ArgumentNullException("token"); + if (token == null) throw new ArgumentNullException(nameof(token)); var userInfoString = RequestHelper.PerformRequest(ConsumerFactory.Get<DocuSignLoginProvider>().DocuSignHost + "/oauth/userinfo", headers: new Dictionary<string, string> { { "Authorization", "Bearer " + DocuSignToken.GetRefreshedToken(token) } }); @@ -240,8 +240,8 @@ namespace ASC.Web.Files.Helpers private DocuSign.eSign.Client.Configuration GetConfiguration(DocuSignAccount account, OAuth20Token token) { - if (account == null) throw new ArgumentNullException("account"); - if (token == null) throw new ArgumentNullException("token"); + if (account == null) throw new ArgumentNullException(nameof(account)); + if (token == null) throw new ArgumentNullException(nameof(token)); var apiClient = new ApiClient(account.BaseUri + "/restapi"); @@ -377,8 +377,8 @@ namespace ASC.Web.Files.Helpers public File<T> SaveDocument<T>(string envelopeId, string documentId, string documentName, T folderId) { - if (string.IsNullOrEmpty(envelopeId)) throw new ArgumentNullException("envelopeId"); - if (string.IsNullOrEmpty(documentId)) throw new ArgumentNullException("documentId"); + if (string.IsNullOrEmpty(envelopeId)) throw new ArgumentNullException(nameof(envelopeId)); + if (string.IsNullOrEmpty(documentId)) throw new ArgumentNullException(nameof(documentId)); var token = DocuSignToken.GetToken(); var account = GetDocuSignAccount(token); diff --git a/products/ASC.Files/Core/Helpers/PathProvider.cs b/products/ASC.Files/Core/Helpers/PathProvider.cs index 9ea4dbaf0a..4d1559b971 100644 --- a/products/ASC.Files/Core/Helpers/PathProvider.cs +++ b/products/ASC.Files/Core/Helpers/PathProvider.cs @@ -107,7 +107,7 @@ namespace ASC.Web.Files.Classes public string GetFolderUrl<T>(Folder<T> folder, int projectID = 0) { - if (folder == null) throw new ArgumentNullException("folder", FilesCommonResource.ErrorMassage_FolderNotFound); + if (folder == null) throw new ArgumentNullException(nameof(folder), FilesCommonResource.ErrorMassage_FolderNotFound); var folderDao = DaoFactory.GetFolderDao<T>(); @@ -139,7 +139,7 @@ namespace ASC.Web.Files.Classes public string GetFileStreamUrl<T>(File<T> file, string doc = null, bool lastVersion = false) { - if (file == null) throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); + if (file == null) throw new ArgumentNullException(nameof(file), FilesCommonResource.ErrorMassage_FileNotFound); //NOTE: Always build path to handler! var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath)); @@ -163,7 +163,7 @@ namespace ASC.Web.Files.Classes public string GetFileChangesUrl<T>(File<T> file, string doc = null) { - if (file == null) throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); + if (file == null) throw new ArgumentNullException(nameof(file), FilesCommonResource.ErrorMassage_FileNotFound); var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath)); var query = uriBuilder.Query; @@ -181,7 +181,7 @@ namespace ASC.Web.Files.Classes public string GetTempUrl(Stream stream, string ext) { - if (stream == null) throw new ArgumentNullException("stream"); + if (stream == null) throw new ArgumentNullException(nameof(stream)); var store = GlobalStore.GetStore(); var fileName = string.Format("{0}{1}", Guid.NewGuid(), ext); diff --git a/products/ASC.Files/Core/Helpers/WordpressHelper.cs b/products/ASC.Files/Core/Helpers/WordpressHelper.cs index b0908e05ff..21e1881891 100644 --- a/products/ASC.Files/Core/Helpers/WordpressHelper.cs +++ b/products/ASC.Files/Core/Helpers/WordpressHelper.cs @@ -61,7 +61,7 @@ namespace ASC.Web.Files.Helpers public void SaveToken(OAuth20Token token) { - if (token == null) throw new ArgumentNullException("token"); + if (token == null) throw new ArgumentNullException(nameof(token)); TokenHelper.SaveToken(new Token(token, AppAttr)); } @@ -75,7 +75,7 @@ namespace ASC.Web.Files.Helpers public void DeleteToken(OAuth20Token token) { - if (token == null) throw new ArgumentNullException("token"); + if (token == null) throw new ArgumentNullException(nameof(token)); TokenHelper.DeleteToken(AppAttr); } diff --git a/products/ASC.Files/Core/HttpHandlers/ChunkedUploaderHandler.cs b/products/ASC.Files/Core/HttpHandlers/ChunkedUploaderHandler.cs index 034c211118..136f004666 100644 --- a/products/ASC.Files/Core/HttpHandlers/ChunkedUploaderHandler.cs +++ b/products/ASC.Files/Core/HttpHandlers/ChunkedUploaderHandler.cs @@ -385,7 +385,7 @@ namespace ASC.Web.Files.HttpHandlers public ChunkedRequestHelper(HttpRequest request) { - _request = request ?? throw new ArgumentNullException("request"); + _request = request ?? throw new ArgumentNullException(nameof(request)); } private bool IsAuthDataSet(InstanceCrypto instanceCrypto) diff --git a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs index a69b74d318..0d1c715a44 100644 --- a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs +++ b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs @@ -123,8 +123,8 @@ namespace ASC.Web.Files.Services.FFmpegService private static Task<int> StreamCopyToAsync(Stream srcStream, Stream dstStream, bool closeSrc = false, bool closeDst = false) { - if (srcStream == null) throw new ArgumentNullException("srcStream"); - if (dstStream == null) throw new ArgumentNullException("dstStream"); + if (srcStream == null) throw new ArgumentNullException(nameof(srcStream)); + if (dstStream == null) throw new ArgumentNullException(nameof(dstStream)); return StreamCopyToAsyncInternal(srcStream, dstStream, closeSrc, closeDst); } diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index 50ca9904fa..7ad6c458bd 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -332,7 +332,7 @@ namespace ASC.Web.Files.Utils { total = 0; - if (parent == null) throw new ArgumentNullException("parent", FilesCommonResource.ErrorMassage_FolderNotFound); + if (parent == null) throw new ArgumentNullException(nameof(parent), FilesCommonResource.ErrorMassage_FolderNotFound); if (parent.ProviderEntry && !FilesSettingsHelper.EnableThirdParty) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFolder); if (parent.RootFolderType == FolderType.Privacy && (!PrivacyRoomSettings.IsAvailable(TenantManager) || !PrivacyRoomSettings.GetEnabled(SettingsManager))) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFolder); @@ -1071,7 +1071,7 @@ namespace ASC.Web.Files.Utils public File<T> UpdateToVersionFile<T>(T fileId, int version, string doc = null, bool checkRight = true) { var fileDao = DaoFactory.GetFileDao<T>(); - if (version < 1) throw new ArgumentNullException("version"); + if (version < 1) throw new ArgumentNullException(nameof(version)); var editLink = FileShareLink.Check(doc, false, fileDao, out var fromFile); diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index d382ca9889..323d25ada4 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -697,7 +697,7 @@ namespace ASC.Web.Files.Utils var readLink = FileShareLink.Check(doc, true, fileDao, out file); if (file == null) { - throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); + throw new ArgumentNullException(nameof(file), FilesCommonResource.ErrorMassage_FileNotFound); } if (!readLink) { diff --git a/products/ASC.Files/Core/Utils/FileMarker.cs b/products/ASC.Files/Core/Utils/FileMarker.cs index 56f45af9dd..696b110726 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -513,7 +513,7 @@ namespace ASC.Web.Files.Utils public List<FileEntry> MarkedItems<T>(Folder<T> folder) { - if (folder == null) throw new ArgumentNullException("folder", FilesCommonResource.ErrorMassage_FolderNotFound); + if (folder == null) throw new ArgumentNullException(nameof(folder), FilesCommonResource.ErrorMassage_FolderNotFound); if (!FileSecurity.CanRead(folder)) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ViewFolder); if (folder.RootFolderType == FolderType.TRASH && !Equals(folder.ID, GlobalFolder.GetFolderTrash<T>(DaoFactory))) throw new SecurityException(FilesCommonResource.ErrorMassage_ViewTrashItem); diff --git a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs index 04dbcb3d3d..f9778a3f27 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -281,7 +281,7 @@ namespace ASC.Files.Helpers public FileWrapper<T> CreateTextFile(T folderId, string title, string content) { - if (title == null) throw new ArgumentNullException("title"); + if (title == null) throw new ArgumentNullException(nameof(title)); //Try detect content var extension = ".txt"; if (!string.IsNullOrEmpty(content)) @@ -305,7 +305,7 @@ namespace ASC.Files.Helpers public FileWrapper<T> CreateHtmlFile(T folderId, string title, string content) { - if (title == null) throw new ArgumentNullException("title"); + if (title == null) throw new ArgumentNullException(nameof(title)); return CreateFile(folderId, title, content, ".html"); } diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index 1906780259..686e08ad7c 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -2743,7 +2743,7 @@ namespace ASC.Api.Settings private bool SaveMailWhiteLabelSettings(MailWhiteLabelSettings settings) { - if (settings == null) throw new ArgumentNullException("settings"); + if (settings == null) throw new ArgumentNullException(nameof(settings)); DemandRebrandingPermission(); diff --git a/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs b/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs index 1476025ca0..980c88b456 100644 --- a/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs @@ -100,7 +100,7 @@ namespace ASC.Api.Settings //TODO: Add validation check if (smtpSettings == null) - throw new ArgumentNullException("smtpSettings"); + throw new ArgumentNullException(nameof(smtpSettings)); PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings); diff --git a/web/ASC.Web.Core/Files/DocumentService.cs b/web/ASC.Web.Core/Files/DocumentService.cs index 1b5e8d3357..c12d257489 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -114,8 +114,8 @@ namespace ASC.Web.Core.Files out string convertedDocumentUri) { fromExtension = string.IsNullOrEmpty(fromExtension) ? Path.GetExtension(documentUri) : fromExtension; - if (string.IsNullOrEmpty(fromExtension)) throw new ArgumentNullException("fromExtension", "Document's extension for conversion is not known"); - if (string.IsNullOrEmpty(toExtension)) throw new ArgumentNullException("toExtension", "Extension for conversion is not known"); + if (string.IsNullOrEmpty(fromExtension)) throw new ArgumentNullException(nameof(fromExtension), "Document's extension for conversion is not known"); + if (string.IsNullOrEmpty(toExtension)) throw new ArgumentNullException(nameof(toExtension), "Extension for conversion is not known"); var title = Path.GetFileName(documentUri ?? ""); title = string.IsNullOrEmpty(title) || title.Contains('?') ? Guid.NewGuid().ToString() : title; @@ -310,7 +310,7 @@ namespace ASC.Web.Core.Files out Dictionary<string, string> urls) { if (string.IsNullOrEmpty(docbuilderUrl)) - throw new ArgumentNullException("docbuilderUrl"); + throw new ArgumentNullException(nameof(docbuilderUrl)); if (string.IsNullOrEmpty(requestKey) && string.IsNullOrEmpty(scriptUrl)) throw new ArgumentException("requestKey or inputScript is empty"); @@ -391,7 +391,7 @@ namespace ASC.Web.Core.Files public static bool HealthcheckRequest(string healthcheckUrl, IHttpClientFactory clientFactory) { if (string.IsNullOrEmpty(healthcheckUrl)) - throw new ArgumentNullException("healthcheckUrl"); + throw new ArgumentNullException(nameof(healthcheckUrl)); var request = new HttpRequestMessage(); request.RequestUri = new Uri(healthcheckUrl); @@ -694,7 +694,7 @@ namespace ASC.Web.Core.Files /// <returns>The percentage of completion of conversion</returns> private static int GetResponseUri(string jsonDocumentResponse, out string responseUri) { - if (string.IsNullOrEmpty(jsonDocumentResponse)) throw new ArgumentException("Invalid param", "jsonDocumentResponse"); + if (string.IsNullOrEmpty(jsonDocumentResponse)) throw new ArgumentException("Invalid param", nameof(jsonDocumentResponse)); var responseFromService = JObject.Parse(jsonDocumentResponse); if (responseFromService == null) throw new WebException("Invalid answer format"); diff --git a/web/ASC.Web.Core/Mobile/CachedMobileAppInstallRegistrator.cs b/web/ASC.Web.Core/Mobile/CachedMobileAppInstallRegistrator.cs index 64bebf52ec..db8693d74c 100644 --- a/web/ASC.Web.Core/Mobile/CachedMobileAppInstallRegistrator.cs +++ b/web/ASC.Web.Core/Mobile/CachedMobileAppInstallRegistrator.cs @@ -49,7 +49,7 @@ namespace ASC.Web.Core.Mobile { Cache = cache; TenantManager = tenantManager; - this.registrator = registrator ?? throw new ArgumentNullException("registrator"); + this.registrator = registrator ?? throw new ArgumentNullException(nameof(registrator)); this.cacheExpiration = cacheExpiration; } diff --git a/web/ASC.Web.Core/Notify/StudioNotifyService.cs b/web/ASC.Web.Core/Notify/StudioNotifyService.cs index d828bee1c5..be375daafc 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyService.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyService.cs @@ -125,22 +125,22 @@ namespace ASC.Web.Studio.Core.Notify public void SendRequestTariff(bool license, string fname, string lname, string title, string email, string phone, string ctitle, string csize, string site, string message) { fname = (fname ?? "").Trim(); - if (string.IsNullOrEmpty(fname)) throw new ArgumentNullException("fname"); + if (string.IsNullOrEmpty(fname)) throw new ArgumentNullException(nameof(fname)); lname = (lname ?? "").Trim(); - if (string.IsNullOrEmpty(lname)) throw new ArgumentNullException("lname"); + if (string.IsNullOrEmpty(lname)) throw new ArgumentNullException(nameof(lname)); title = (title ?? "").Trim(); email = (email ?? "").Trim(); - if (string.IsNullOrEmpty(email)) throw new ArgumentNullException("email"); + if (string.IsNullOrEmpty(email)) throw new ArgumentNullException(nameof(email)); phone = (phone ?? "").Trim(); - if (string.IsNullOrEmpty(phone)) throw new ArgumentNullException("phone"); + if (string.IsNullOrEmpty(phone)) throw new ArgumentNullException(nameof(phone)); ctitle = (ctitle ?? "").Trim(); - if (string.IsNullOrEmpty(ctitle)) throw new ArgumentNullException("ctitle"); + if (string.IsNullOrEmpty(ctitle)) throw new ArgumentNullException(nameof(ctitle)); csize = (csize ?? "").Trim(); - if (string.IsNullOrEmpty(csize)) throw new ArgumentNullException("csize"); + if (string.IsNullOrEmpty(csize)) throw new ArgumentNullException(nameof(csize)); site = (site ?? "").Trim(); - if (string.IsNullOrEmpty(site) && !CoreBaseSettings.CustomMode) throw new ArgumentNullException("site"); + if (string.IsNullOrEmpty(site) && !CoreBaseSettings.CustomMode) throw new ArgumentNullException(nameof(site)); message = (message ?? "").Trim(); - if (string.IsNullOrEmpty(message) && !CoreBaseSettings.CustomMode) throw new ArgumentNullException("message"); + if (string.IsNullOrEmpty(message) && !CoreBaseSettings.CustomMode) throw new ArgumentNullException(nameof(message)); var salesEmail = SettingsManager.LoadForDefaultTenant<AdditionalWhiteLabelSettings>().SalesEmail ?? SetupInfo.SalesEmail; diff --git a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs index 11d094284c..bb0f3c0f84 100644 --- a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs +++ b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs @@ -108,7 +108,7 @@ namespace ASC.Web.Core.Sms { if (string.IsNullOrEmpty(phone)) { - throw new ArgumentNullException("phone"); + throw new ArgumentNullException(nameof(phone)); } lock (KeyLocker) diff --git a/web/ASC.Web.Core/Sms/SmsSender.cs b/web/ASC.Web.Core/Sms/SmsSender.cs index e903983ab9..3f6a3adde9 100644 --- a/web/ASC.Web.Core/Sms/SmsSender.cs +++ b/web/ASC.Web.Core/Sms/SmsSender.cs @@ -62,11 +62,11 @@ namespace ASC.Web.Core.Sms { if (string.IsNullOrEmpty(number)) { - throw new ArgumentNullException("number"); + throw new ArgumentNullException(nameof(number)); } if (string.IsNullOrEmpty(message)) { - throw new ArgumentNullException("message"); + throw new ArgumentNullException(nameof(message)); } if (!SmsProviderManager.Enabled()) { diff --git a/web/ASC.Web.Core/Users/UserManagerWrapper.cs b/web/ASC.Web.Core/Users/UserManagerWrapper.cs index d30b2f968a..ba9c0fee41 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -98,7 +98,7 @@ namespace ASC.Web.Core.Users private string MakeUniqueName(UserInfo userInfo) { if (string.IsNullOrEmpty(userInfo.Email)) - throw new ArgumentException(Resource.ErrorEmailEmpty, "userInfo"); + throw new ArgumentException(Resource.ErrorEmailEmpty, nameof(userInfo)); var uniqueName = new MailAddress(userInfo.Email).User; var startUniqueName = uniqueName; @@ -118,7 +118,7 @@ namespace ASC.Web.Core.Users public UserInfo AddUser(UserInfo userInfo, string passwordHash, bool afterInvite = false, bool notify = true, bool isVisitor = false, bool fromInviteLink = false, bool makeUniqueName = true) { - if (userInfo == null) throw new ArgumentNullException("userInfo"); + if (userInfo == null) throw new ArgumentNullException(nameof(userInfo)); if (!UserFormatter.IsValidUserName(userInfo.FirstName, userInfo.LastName)) throw new Exception(Resource.ErrorIncorrectUserName); @@ -257,7 +257,7 @@ namespace ASC.Web.Core.Users public string SendUserPassword(string email) { email = (email ?? "").Trim(); - if (!email.TestEmailRegex()) throw new ArgumentNullException("email", Resource.ErrorNotCorrectEmail); + if (!email.TestEmailRegex()) throw new ArgumentNullException(nameof(email), Resource.ErrorNotCorrectEmail); if (!IPSecurity.Verify()) { diff --git a/web/ASC.Web.Core/WebItemSecurity.cs b/web/ASC.Web.Core/WebItemSecurity.cs index bc143a935a..3dce5b757d 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -399,7 +399,7 @@ namespace ASC.Web.Core { if (string.IsNullOrEmpty(id)) { - throw new ArgumentNullException("id"); + throw new ArgumentNullException(nameof(id)); } var itemId = Guid.Empty; From b4334b8947e057c69ceed7e66349487ae9825a8e Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 25 Jan 2022 13:47:36 +0300 Subject: [PATCH 100/167] analizators/Add HttpClient service --- common/ASC.Api.Core/Core/BaseStartup.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index 48404e7fdc..a85e1a99ea 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -64,6 +64,7 @@ namespace ASC.Api.Core services.AddCustomHealthCheck(Configuration); services.AddHttpContextAccessor(); services.AddMemoryCache(); + services.AddHttpClient(); if (AddAndUseSession) services.AddSession(); From 17cb4a647ba375805ca23e595c9abe994beae20b Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 31 Jan 2022 14:35:59 +0300 Subject: [PATCH 101/167] analizators: bugfix --- web/ASC.Web.Core/Files/DocumentServiceLicense.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/web/ASC.Web.Core/Files/DocumentServiceLicense.cs b/web/ASC.Web.Core/Files/DocumentServiceLicense.cs index 64b87e0386..cb034a9633 100644 --- a/web/ASC.Web.Core/Files/DocumentServiceLicense.cs +++ b/web/ASC.Web.Core/Files/DocumentServiceLicense.cs @@ -16,6 +16,7 @@ using System; using System.Collections.Generic; +using System.Net.Http; using ASC.Common; using ASC.Common.Caching; @@ -35,17 +36,21 @@ namespace ASC.Web.Core.Files public CoreBaseSettings CoreBaseSettings { get; } private FilesLinkUtility FilesLinkUtility { get; } private FileUtility FileUtility { get; } + private IHttpClientFactory ClientFactory { get; } + public DocumentServiceLicense( ICache cache, CoreBaseSettings coreBaseSettings, FilesLinkUtility filesLinkUtility, - FileUtility fileUtility) + FileUtility fileUtility, + IHttpClientFactory clientFactory) { Cache = cache; CoreBaseSettings = coreBaseSettings; FilesLinkUtility = filesLinkUtility; FileUtility = fileUtility; + ClientFactory = clientFactory; } private CommandResponse GetDocumentServiceLicense() @@ -65,7 +70,9 @@ namespace ASC.Web.Core.Files null, null, null, - FileUtility.SignatureSecret); + FileUtility.SignatureSecret, + ClientFactory + ); Cache.Insert(cacheKey, commandResponse, DateTime.UtcNow.Add(CACHE_EXPIRATION)); } From ad78c464958660b53fa6909dfcc0889256ea4652 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Mon, 31 Jan 2022 19:36:51 +0300 Subject: [PATCH 102/167] Api: priveate properties replaced with fields, used single line expressions, cosmetic --- .../ASC.Api.Core/Auth/ConfirmAuthHandler.cs | 55 +++--- common/ASC.Api.Core/Auth/CookieAuthHandler.cs | 34 ++-- .../ControllerNameAttributeConvention.cs | 7 +- common/ASC.Api.Core/Core/ApiContext.cs | 158 ++++++++--------- common/ASC.Api.Core/Core/ApiDateTime.cs | 162 ++++++++---------- common/ASC.Api.Core/Core/BaseStartup.cs | 18 +- .../Core/CustomEndpointDataSource.cs | 13 +- common/ASC.Api.Core/Core/CustomHealthCheck.cs | 16 +- common/ASC.Api.Core/Core/ItemDictionary.cs | 8 +- common/ASC.Api.Core/Core/ItemKeyValuePair.cs | 2 - common/ASC.Api.Core/Core/Module.cs | 3 - common/ASC.Api.Core/Core/Update.cs | 12 +- common/ASC.Api.Core/Core/Validate.cs | 36 ++-- .../ASC.Api.Core/Core/XmlOutputFormatter.cs | 7 +- .../Middleware/CommonApiResponse.cs | 54 ++---- .../Middleware/CultureMiddleware.cs | 25 +-- .../Middleware/DisposeMiddleware.cs | 15 +- .../Middleware/IpSecurityFilter.cs | 24 ++- .../ASC.Api.Core/Middleware/PaymentFilter.cs | 23 ++- .../Middleware/ProductSecurityFilter.cs | 47 ++--- .../Middleware/ResponseWrapper.cs | 5 +- .../Middleware/TenantStatusFilter.cs | 21 ++- .../WebhooksGlobalFilterAttribute.cs | 22 +-- common/ASC.Api.Core/Model/Contact.cs | 12 +- common/ASC.Api.Core/Model/EmployeeWraper.cs | 47 ++--- .../ASC.Api.Core/Model/EmployeeWraperFull.cs | 89 ++-------- .../ASC.Api.Core/Model/GroupWrapperSummary.cs | 23 +-- common/ASC.Api.Core/Routing/DefaultRoute.cs | 9 +- common/ASC.Api.Core/Routing/FormatRoute.cs | 3 + 29 files changed, 351 insertions(+), 599 deletions(-) diff --git a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs index 9b4d611e27..0401004f15 100644 --- a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs @@ -20,9 +20,18 @@ namespace ASC.Api.Core.Auth [Scope(Additional = typeof(ConfirmAuthHandlerExtension))] public class ConfirmAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions> { - public ConfirmAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) - { - } + private readonly SecurityContext _securityContext; + private readonly UserManager _userManager; + private readonly IServiceProvider _serviceProvider; + + public ConfirmAuthHandler( + IOptionsMonitor<AuthenticationSchemeOptions> options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock) : + base(options, logger, encoder, clock) + { } + public ConfirmAuthHandler( IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, @@ -33,25 +42,21 @@ namespace ASC.Api.Core.Auth IServiceProvider serviceProvider) : base(options, logger, encoder, clock) { - SecurityContext = securityContext; - UserManager = userManager; - ServiceProvider = serviceProvider; + _securityContext = securityContext; + _userManager = userManager; + _serviceProvider = serviceProvider; } - private SecurityContext SecurityContext { get; } - private UserManager UserManager { get; } - private IServiceProvider ServiceProvider { get; } - protected override Task<AuthenticateResult> HandleAuthenticateAsync() { - using var scope = ServiceProvider.CreateScope(); + using var scope = _serviceProvider.CreateScope(); var emailValidationKeyHelper = scope.ServiceProvider.GetService<EmailValidationKeyModelHelper>(); var emailValidationKeyModel = emailValidationKeyHelper.GetModel(); if (!emailValidationKeyModel.Type.HasValue) { - return SecurityContext.IsAuthenticated + return _securityContext.IsAuthenticated ? Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name))) : Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString()))); } @@ -74,32 +79,24 @@ namespace ASC.Api.Core.Auth if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Ok) { Guid userId; - if (!SecurityContext.IsAuthenticated) + if (!_securityContext.IsAuthenticated) { if (emailValidationKeyModel.UiD.HasValue && !emailValidationKeyModel.UiD.Equals(Guid.Empty)) - { userId = emailValidationKeyModel.UiD.Value; - } else { - if(emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmailActivation || - emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmpInvite || - emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.LinkInvite) - { + if(emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmailActivation + || emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmpInvite + || emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.LinkInvite) userId = ASC.Core.Configuration.Constants.CoreSystem.ID; - } else - { - userId = UserManager.GetUserByEmail(emailValidationKeyModel.Email).ID; - } + userId = _userManager.GetUserByEmail(emailValidationKeyModel.Email).ID; } } else - { - userId = SecurityContext.CurrentAccount.ID; - } + userId = _securityContext.CurrentAccount.ID; - SecurityContext.AuthenticateMeWithoutCookie(userId, claims); + _securityContext.AuthenticateMeWithoutCookie(userId, claims); } var result = checkKeyResult switch @@ -114,9 +111,7 @@ namespace ASC.Api.Core.Auth public class ConfirmAuthHandlerExtension { - public static void Register(DIHelper services) - { + public static void Register(DIHelper services) => services.TryAdd<EmailValidationKeyModelHelper>(); - } } } diff --git a/common/ASC.Api.Core/Auth/CookieAuthHandler.cs b/common/ASC.Api.Core/Auth/CookieAuthHandler.cs index 1316ab3185..53332f8806 100644 --- a/common/ASC.Api.Core/Auth/CookieAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/CookieAuthHandler.cs @@ -17,34 +17,38 @@ namespace ASC.Api.Core.Auth [Scope] public class CookieAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions> { - private AuthorizationHelper AuthorizationHelper { get; } - private SecurityContext SecurityContext { get; } - private CookiesManager CookiesManager { get; } + private readonly AuthorizationHelper _authorizationHelper; + private readonly SecurityContext _securityContext; + private readonly CookiesManager _cookiesManager; - public CookieAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) - { - } - // - public CookieAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, + public CookieAuthHandler( + IOptionsMonitor<AuthenticationSchemeOptions> options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock) + : base(options, logger, encoder, clock) { } + + public CookieAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, + ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, AuthorizationHelper authorizationHelper, SecurityContext securityContext, CookiesManager cookiesManager) : this(options, logger, encoder, clock) { - AuthorizationHelper = authorizationHelper; - SecurityContext = securityContext; - CookiesManager = cookiesManager; + _authorizationHelper = authorizationHelper; + _securityContext = securityContext; + _cookiesManager = cookiesManager; } protected override Task<AuthenticateResult> HandleAuthenticateAsync() { - var result = AuthorizationHelper.ProcessBasicAuthorization(out _); + var result = _authorizationHelper.ProcessBasicAuthorization(out _); if (!result) { - SecurityContext.Logout(); - CookiesManager.ClearCookies(CookiesType.AuthKey); - CookiesManager.ClearCookies(CookiesType.SocketIO); + _securityContext.Logout(); + _cookiesManager.ClearCookies(CookiesType.AuthKey); + _cookiesManager.ClearCookies(CookiesType.SocketIO); } return Task.FromResult( diff --git a/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs b/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs index 65af908c8b..60e9075879 100644 --- a/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs +++ b/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs @@ -10,10 +10,7 @@ namespace ASC.Api.Core.Convention { public string Name { get; } - public ControllerNameAttribute(string name) - { - Name = name; - } + public ControllerNameAttribute(string name) => Name = name; } public class ControllerNameAttributeConvention : IControllerModelConvention @@ -22,9 +19,7 @@ namespace ASC.Api.Core.Convention { var controllerNameAttribute = controller.Attributes.OfType<ControllerNameAttribute>().SingleOrDefault(); if (controllerNameAttribute != null) - { controller.ControllerName = controllerNameAttribute.Name; - } } } } diff --git a/common/ASC.Api.Core/Core/ApiContext.cs b/common/ASC.Api.Core/Core/ApiContext.cs index 62f61ba1ba..f1fa26e7cc 100644 --- a/common/ASC.Api.Core/Core/ApiContext.cs +++ b/common/ASC.Api.Core/Core/ApiContext.cs @@ -39,60 +39,22 @@ namespace ASC.Api.Core [Scope] public class ApiContext : ICloneable { - private static int MaxCount = 1000; public IHttpContextAccessor HttpContextAccessor { get; set; } - public Tenant tenant; - public Tenant Tenant { get { return tenant ??= TenantManager.GetCurrentTenant(HttpContextAccessor?.HttpContext); } } - - public ApiContext(IHttpContextAccessor httpContextAccessor, SecurityContext securityContext, TenantManager tenantManager) + public string[] Fields { get; set; } + public string[] FilterValues { get; set; } + public bool FromCache { get; set; } + public Tenant Tenant => _tenant ??= _tenantManager.GetCurrentTenant(HttpContextAccessor?.HttpContext); + public long? TotalCount { - SecurityContext = securityContext; - TenantManager = tenantManager; - HttpContextAccessor = httpContextAccessor; - if (httpContextAccessor.HttpContext == null) return; - - Count = MaxCount; - var query = HttpContextAccessor.HttpContext.Request.Query; - //Try parse values - var count = query.GetRequestValue("count"); - if (!string.IsNullOrEmpty(count) && ulong.TryParse(count, out var countParsed)) + set { - //Count specified and valid - Count = Math.Min((long)countParsed, MaxCount); - } - - var startIndex = query.GetRequestValue("startIndex"); - if (startIndex != null && long.TryParse(startIndex, out var startIndexParsed)) - { - StartIndex = Math.Max(0, startIndexParsed); - SpecifiedStartIndex = StartIndex; - } - - var sortOrder = query.GetRequestValue("sortOrder"); - if ("descending".Equals(sortOrder)) - { - SortDescending = true; - } - - FilterToType = query.GetRequestValue("type"); - SortBy = query.GetRequestValue("sortBy"); - FilterBy = query.GetRequestValue("filterBy"); - FilterOp = query.GetRequestValue("filterOp"); - FilterValue = query.GetRequestValue("filterValue"); - FilterValues = query.GetRequestArray("filterValue"); - Fields = query.GetRequestArray("fields"); - - var updatedSince = query.GetRequestValue("updatedSince"); - if (updatedSince != null) - { - UpdatedSince = Convert.ToDateTime(updatedSince); + if (HttpContextAccessor.HttpContext.Items.ContainsKey(nameof(TotalCount))) + HttpContextAccessor.HttpContext.Items[nameof(TotalCount)] = value; + else + HttpContextAccessor.HttpContext.Items.Add(nameof(TotalCount), value); } } - public string[] Fields { get; set; } - - public string[] FilterValues { get; set; } - /// <summary> /// Filters responce to specific type from request parameter "type" /// </summary> @@ -116,9 +78,7 @@ namespace ASC.Api.Core /// Don't forget to call _context.SetDataPaginated() to prevent SmartList from filtering response if you fetch data from DB with TOP & COUNT /// </remarks> public long StartIndex { get; set; } - - internal long SpecifiedStartIndex { get; set; } - + /// <summary> /// Gets field to sort by from request parameter "sortBy" /// </summary> @@ -150,10 +110,50 @@ namespace ASC.Api.Core /// Gets value to filter from request parameter "updatedSince" /// </summary> public DateTime UpdatedSince { get; set; } - - public bool FromCache { get; set; } - + internal long SpecifiedCount { get; private set; } + internal long SpecifiedStartIndex { get; set; } + + private Tenant _tenant; + private static int s_maxCount = 1000; + private readonly SecurityContext _securityContext; + private readonly TenantManager _tenantManager; + + public ApiContext(IHttpContextAccessor httpContextAccessor, SecurityContext securityContext, TenantManager tenantManager) + { + _securityContext = securityContext; + _tenantManager = tenantManager; + HttpContextAccessor = httpContextAccessor; + if (httpContextAccessor.HttpContext == null) return; + + Count = s_maxCount; + var query = HttpContextAccessor.HttpContext.Request.Query; + //Try parse values + var count = query.GetRequestValue("count"); + if (!string.IsNullOrEmpty(count) && ulong.TryParse(count, out var countParsed)) + Count = Math.Min((long)countParsed, s_maxCount); //Count specified and valid + + var startIndex = query.GetRequestValue("startIndex"); + if (startIndex != null && long.TryParse(startIndex, out var startIndexParsed)) + { + StartIndex = Math.Max(0, startIndexParsed); + SpecifiedStartIndex = StartIndex; + } + + var sortOrder = query.GetRequestValue("sortOrder"); + if ("descending".Equals(sortOrder)) SortDescending = true; + + FilterToType = query.GetRequestValue("type"); + SortBy = query.GetRequestValue("sortBy"); + FilterBy = query.GetRequestValue("filterBy"); + FilterOp = query.GetRequestValue("filterOp"); + FilterValue = query.GetRequestValue("filterValue"); + FilterValues = query.GetRequestArray("filterValue"); + Fields = query.GetRequestArray("fields"); + + var updatedSince = query.GetRequestValue("updatedSince"); + if (updatedSince != null) UpdatedSince = Convert.ToDateTime(updatedSince); + } /// <summary> /// Set mark that data is already paginated and additional filtering is not needed @@ -162,12 +162,14 @@ namespace ASC.Api.Core { //Count = 0;//We always ask for +1 count so smart list should cut it StartIndex = 0; + return this; } public ApiContext SetDataSorted() { SortBy = string.Empty; + return this; } @@ -176,57 +178,33 @@ namespace ASC.Api.Core FilterBy = string.Empty; FilterOp = string.Empty; FilterValue = string.Empty; + return this; } public ApiContext SetTotalCount(long totalCollectionCount) { TotalCount = totalCollectionCount; + return this; } - public long? TotalCount - { - set - { - if (HttpContextAccessor.HttpContext.Items.ContainsKey(nameof(TotalCount))) - { - HttpContextAccessor.HttpContext.Items[nameof(TotalCount)] = value; - } - else - { - HttpContextAccessor.HttpContext.Items.Add(nameof(TotalCount), value); - } - } - } - - private SecurityContext SecurityContext { get; } - private TenantManager TenantManager { get; } - public ApiContext SetCount(int count) { HttpContextAccessor.HttpContext.Items[nameof(Count)] = count; + return this; } - public object Clone() - { - return MemberwiseClone(); - } + public object Clone() => MemberwiseClone(); - public override string ToString() - { - return string.Format("C:{0},S:{1},So:{2},Sd:{3},Fb;{4},Fo:{5},Fv:{6},Us:{7},Ftt:{8}", Count, StartIndex, + public override string ToString() => string.Format("C:{0},S:{1},So:{2},Sd:{3},Fb;{4},Fo:{5},Fv:{6},Us:{7},Ftt:{8}", Count, StartIndex, SortBy, SortDescending, FilterBy, FilterOp, FilterValue, UpdatedSince.Ticks, FilterToType); - } public void AuthByClaim() { var id = HttpContextAccessor.HttpContext.User.Claims.FirstOrDefault(r => r.Type == ClaimTypes.Sid); - if (Guid.TryParse(id?.Value, out var userId)) - { - SecurityContext.AuthenticateMeWithoutCookie(userId); - } + if (Guid.TryParse(id?.Value, out var userId)) _securityContext.AuthenticateMeWithoutCookie(userId); } } @@ -237,8 +215,7 @@ namespace ASC.Api.Core if (query != null) { var values = query[key + "[]"]; - if (values.Count > 0) - return values; + if (values.Count > 0) return values; values = query[key]; if (values.Count > 0) @@ -249,24 +226,25 @@ namespace ASC.Api.Core if (!string.IsNullOrEmpty(values[0])) return values[0].Split(','); } + return values; } } + return null; } public static string GetRequestValue(this IQueryCollection query, string key) { var reqArray = query.GetRequestArray(key); + return reqArray?.FirstOrDefault(); } } public static class ApiContextExtension { - public static bool Check(this ApiContext context, string field) - { - return context?.Fields == null || (context.Fields != null && context.Fields.Contains(field, StringComparer.InvariantCultureIgnoreCase)); - } + public static bool Check(this ApiContext context, string field) => + context?.Fields == null || (context.Fields != null && context.Fields.Contains(field, StringComparer.InvariantCultureIgnoreCase)); } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/ApiDateTime.cs b/common/ASC.Api.Core/Core/ApiDateTime.cs index 8a4e79495e..f839e4ce0b 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -39,33 +39,41 @@ namespace ASC.Api.Core [TypeConverter(typeof(ApiDateTimeTypeConverter))] public class ApiDateTime : IComparable<ApiDateTime>, IComparable { + public DateTime UtcTime { get; private set; } + public TimeSpan TimeZoneOffset { get; private set; } + internal static readonly string[] Formats = new[] - { - "o", - "yyyy'-'MM'-'dd'T'HH'-'mm'-'ss'.'fffffffK", - "yyyy'-'MM'-'dd'T'HH'-'mm'-'ss'.'fffK", - "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", - "yyyy'-'MM'-'dd'T'HH'-'mm'-'ssK", - "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd" - }; - - public ApiDateTime() - : this(null, null, null) { - } + "o", + "yyyy'-'MM'-'dd'T'HH'-'mm'-'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH'-'mm'-'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH'-'mm'-'ssK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyy'-'MM'-'dd" + }; - public ApiDateTime(TenantManager tenantManager, TimeZoneConverter timeZoneConverter, DateTime? dateTime) - : this(tenantManager, dateTime, null, timeZoneConverter) - { - } + private readonly TenantManager _tenantManager; + private readonly TimeZoneConverter _timeZoneConverter; - public ApiDateTime(TenantManager tenantManager, DateTime? dateTime, TimeZoneInfo timeZone, TimeZoneConverter timeZoneConverter) + public ApiDateTime() : this(null, null, null) { } + + public ApiDateTime( + TenantManager tenantManager, + TimeZoneConverter timeZoneConverter, + DateTime? dateTime) + : this(tenantManager, dateTime, null, timeZoneConverter) { } + + public ApiDateTime( + TenantManager tenantManager, + DateTime? dateTime, + TimeZoneInfo timeZone, + TimeZoneConverter timeZoneConverter) { if (dateTime.HasValue && dateTime.Value > DateTime.MinValue && dateTime.Value < DateTime.MaxValue) { - TenantManager = tenantManager; - TimeZoneConverter = timeZoneConverter; + _tenantManager = tenantManager; + _timeZoneConverter = timeZoneConverter; SetDate(dateTime.Value, timeZone); } else @@ -81,14 +89,12 @@ namespace ASC.Api.Core TimeZoneOffset = offset; } - public static ApiDateTime Parse(string data, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) - { - return Parse(data, null, tenantManager, timeZoneConverter); - } + public static ApiDateTime Parse(string data, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) => + Parse(data, null, tenantManager, timeZoneConverter); public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) { - if (string.IsNullOrEmpty(data)) throw new ArgumentNullException("data"); + if (string.IsNullOrEmpty(data)) throw new ArgumentNullException(nameof(data)); if (data.Length < 7) throw new ArgumentException("invalid date time format"); @@ -97,22 +103,21 @@ namespace ASC.Api.Core { //Parse time var tzOffset = TimeSpan.Zero; - if (offsetPart.Contains(":") && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset)) - { + if (offsetPart.Contains(':') && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset)) return new ApiDateTime(dateTime, tzOffset); - } + if (!data.EndsWith("Z", true, CultureInfo.InvariantCulture)) { - if (tz == null) - { - tz = GetTimeZoneInfo(tenantManager, timeZoneConverter); - } + if (tz == null) tz = GetTimeZoneInfo(tenantManager, timeZoneConverter); + tzOffset = tz.GetUtcOffset(dateTime); dateTime = dateTime.Subtract(tzOffset); } + return new ApiDateTime(dateTime, tzOffset); } + throw new ArgumentException("invalid date time format: " + data); } @@ -123,32 +128,23 @@ namespace ASC.Api.Core UtcTime = DateTime.MinValue; if (timeZone == null) - { - timeZone = GetTimeZoneInfo(TenantManager, TimeZoneConverter); - } + timeZone = GetTimeZoneInfo(_tenantManager, _timeZoneConverter); //Hack if (timeZone.IsInvalidTime(new DateTime(value.Ticks, DateTimeKind.Unspecified))) - { value = value.AddHours(1); - } if (value.Kind == DateTimeKind.Local) - { value = TimeZoneInfo.ConvertTimeToUtc(new DateTime(value.Ticks, DateTimeKind.Unspecified), timeZone); - } + if (value.Kind == DateTimeKind.Unspecified) - { - //Assume it's utc - value = new DateTime(value.Ticks, DateTimeKind.Utc); - } + value = new DateTime(value.Ticks, DateTimeKind.Utc); //Assume it's utc if (value.Kind == DateTimeKind.Utc) { UtcTime = value; //Set UTC time TimeZoneOffset = timeZone.GetUtcOffset(value); } - } private static TimeZoneInfo GetTimeZoneInfo(TenantManager tenantManager, TimeZoneConverter timeZoneConverter) @@ -162,6 +158,7 @@ namespace ASC.Api.Core { //Tenant failed } + return timeZone; } @@ -169,12 +166,14 @@ namespace ASC.Api.Core { var dateString = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff", CultureInfo.InvariantCulture); var offsetString = offset.Ticks == 0 ? "Z" : ((offset < TimeSpan.Zero) ? "-" : "+") + offset.ToString("hh\\:mm", CultureInfo.InvariantCulture); + return dateString + offsetString; } public static ApiDateTime FromDate(TenantManager tenantManager, TimeZoneConverter timeZoneConverter, DateTime d) { var date = new ApiDateTime(tenantManager, timeZoneConverter, d); + return date; } @@ -183,12 +182,13 @@ namespace ASC.Api.Core if (d.HasValue) { var date = new ApiDateTime(tenantManager, timeZoneConverter, d); + return date; } + return null; } - public static bool operator >(ApiDateTime left, ApiDateTime right) { if (ReferenceEquals(left, right)) return false; @@ -196,6 +196,7 @@ namespace ASC.Api.Core return left.CompareTo(right) > 0; } + public static bool operator >=(ApiDateTime left, ApiDateTime right) { if (ReferenceEquals(left, right)) return false; @@ -204,46 +205,34 @@ namespace ASC.Api.Core return left.CompareTo(right) >= 0; } - public static bool operator <=(ApiDateTime left, ApiDateTime right) - { - return !(left >= right); - } + public static bool operator <=(ApiDateTime left, ApiDateTime right) => !(left >= right); - public static bool operator <(ApiDateTime left, ApiDateTime right) - { - return !(left > right); - } + public static bool operator <(ApiDateTime left, ApiDateTime right) => !(left > right); - public static bool operator ==(ApiDateTime left, ApiDateTime right) - { - return Equals(left, right); - } + public static bool operator ==(ApiDateTime left, ApiDateTime right) => Equals(left, right); - public static bool operator !=(ApiDateTime left, ApiDateTime right) - { - return !(left == right); - } + public static bool operator !=(ApiDateTime left, ApiDateTime right) => !(left == right); public static implicit operator DateTime(ApiDateTime d) { if (d == null) return DateTime.MinValue; + return d.UtcTime; } public static implicit operator DateTime?(ApiDateTime d) { if (d == null) return null; + return d.UtcTime; } - public int CompareTo(DateTime other) - { - return CompareTo(new ApiDateTime(TenantManager, TimeZoneConverter, other)); - } + public int CompareTo(DateTime other) => CompareTo(new ApiDateTime(_tenantManager, _timeZoneConverter, other)); public int CompareTo(ApiDateTime other) { if (other == null) return 1; + return UtcTime.CompareTo(other.UtcTime); } @@ -252,6 +241,7 @@ namespace ASC.Api.Core if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(ApiDateTime)) return false; + return Equals((ApiDateTime)obj); } @@ -259,6 +249,7 @@ namespace ASC.Api.Core { if (other is null) return false; if (ReferenceEquals(this, other)) return true; + return UtcTime.Equals(other.UtcTime) && TimeZoneOffset.Equals(other.TimeZoneOffset); } @@ -274,6 +265,7 @@ namespace ASC.Api.Core { if (obj is DateTime dateTime) return CompareTo(dateTime); + return obj is ApiDateTime apiDateTime ? CompareTo(apiDateTime) : 0; } @@ -287,15 +279,7 @@ namespace ASC.Api.Core return ToRoundTripString(localUtcTime, TimeZoneOffset); } - public DateTime UtcTime { get; private set; } - public TimeSpan TimeZoneOffset { get; private set; } - private TenantManager TenantManager { get; } - private TimeZoneConverter TimeZoneConverter { get; } - - public static ApiDateTime GetSample() - { - return new ApiDateTime(DateTime.UtcNow, TimeSpan.Zero); - } + public static ApiDateTime GetSample() => new ApiDateTime(DateTime.UtcNow, TimeSpan.Zero); } public class ApiDateTimeTypeConverter : DateTimeConverter @@ -304,19 +288,18 @@ namespace ASC.Api.Core { if (destinationType == typeof(string)) return value.ToString(); + return base.ConvertTo(context, culture, value, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string @string) - { return ApiDateTime.Parse(@string, null, null); - } + if (value is DateTime time) - { return new ApiDateTime(null, null, time); - } + return base.ConvertFrom(context, culture, value); } } @@ -326,43 +309,32 @@ namespace ASC.Api.Core public override ApiDateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TryGetDateTime(out var result)) - { return new ApiDateTime(result, TimeSpan.Zero); - } else { if (DateTime.TryParseExact(reader.GetString(), ApiDateTime.Formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var dateTime)) - { return new ApiDateTime(dateTime, TimeSpan.Zero); - } else - { return new ApiDateTime(); - } } } - public override void Write(Utf8JsonWriter writer, ApiDateTime value, JsonSerializerOptions options) - { + public override void Write(Utf8JsonWriter writer, ApiDateTime value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString()); - } } [Scope] public class ApiDateTimeHelper { - private TenantManager TenantManager { get; } - private TimeZoneConverter TimeZoneConverter { get; } + private readonly TenantManager _tenantManager; + private readonly TimeZoneConverter _timeZoneConverter; public ApiDateTimeHelper(TenantManager tenantManager, TimeZoneConverter timeZoneConverter) { - TenantManager = tenantManager; - TimeZoneConverter = timeZoneConverter; + _tenantManager = tenantManager; + _timeZoneConverter = timeZoneConverter; } - public ApiDateTime Get(DateTime? from) - { - return ApiDateTime.FromDate(TenantManager, TimeZoneConverter, from); - } + public ApiDateTime Get(DateTime? from) => ApiDateTime.FromDate(_tenantManager, _timeZoneConverter, from); } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index 165fdf11ea..6a536f9e4a 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -23,7 +23,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Authorization; @@ -56,11 +55,10 @@ namespace ASC.Api.Core { Configuration = configuration; HostEnvironment = hostEnvironment; - DIHelper = new DIHelper(); + DIHelper = new DIHelper(); + if (bool.TryParse(Configuration["core:products"], out var loadProducts)) - { LoadProducts = loadProducts; - } } public virtual void ConfigureServices(IServiceCollection services) @@ -109,9 +107,8 @@ namespace ASC.Api.Core var kafkaConfiguration = Configuration.GetSection("kafka").Get<KafkaSettings>(); if (kafkaConfiguration != null) - { DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); - } + else if (redisConfiguration != null) { DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); @@ -119,17 +116,12 @@ namespace ASC.Api.Core services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else - { DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); - } - DIHelper.TryAdd(typeof(IWebhookPublisher), typeof(WebhookPublisher)); if (LoadProducts) - { DIHelper.RegisterProducts(Configuration, HostEnvironment.ContentRootPath); - } var builder = services.AddMvcCore(config => { @@ -155,10 +147,8 @@ namespace ASC.Api.Core var authBuilder = services.AddAuthentication("cookie") .AddScheme<AuthenticationSchemeOptions, CookieAuthHandler>("cookie", a => { }); - if (ConfirmAddScheme) - { + if (ConfirmAddScheme) authBuilder.AddScheme<AuthenticationSchemeOptions, ConfirmAuthHandler>("confirm", a => { }); - } services.AddAutoMapper(Assembly.GetAssembly(typeof(MappingProfile))); } diff --git a/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs b/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs index 89c84f2ddd..44ab6de8d3 100644 --- a/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs +++ b/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs @@ -13,8 +13,8 @@ namespace ASC.Api.Core.Core public class CustomEndpointDataSource : EndpointDataSource { public EndpointDataSource Source { get; } - public override IReadOnlyList<Endpoint> Endpoints { get; } + public CustomEndpointDataSource(EndpointDataSource source) { Source = source; @@ -28,9 +28,7 @@ namespace ASC.Api.Core.Core var enableFormat = attr == null || !attr.DisableFormat; if (enableFormat) - { endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".{format}"), r.Order, r.Metadata, r.DisplayName)); - } else { endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".json"), r.Order - 1, r.Metadata, r.DisplayName)); @@ -38,14 +36,10 @@ namespace ASC.Api.Core.Core } return endpoints; - }) - .ToList(); + }).ToList(); } - public override IChangeToken GetChangeToken() - { - return Source.GetChangeToken(); - } + public override IChangeToken GetChangeToken() => Source.GetChangeToken(); } public static class EndpointExtension @@ -53,6 +47,7 @@ namespace ASC.Api.Core.Core public static IEndpointRouteBuilder MapCustom(this IEndpointRouteBuilder endpoints) { endpoints.DataSources.Add(new CustomEndpointDataSource(endpoints.DataSources.First())); + return endpoints; } } diff --git a/common/ASC.Api.Core/Core/CustomHealthCheck.cs b/common/ASC.Api.Core/Core/CustomHealthCheck.cs index 57a8990396..eaf5cd2b62 100644 --- a/common/ASC.Api.Core/Core/CustomHealthCheck.cs +++ b/common/ASC.Api.Core/Core/CustomHealthCheck.cs @@ -24,21 +24,15 @@ namespace ASC.Api.Core.Core var connectionString = configurationExtension.GetConnectionStrings("default"); - if (String.Compare(connectionString.ProviderName, "MySql.Data.MySqlClient") == 0) - { + if (string.Compare(connectionString.ProviderName, "MySql.Data.MySqlClient") == 0) hcBuilder.AddMySql(connectionString.ConnectionString, name: "mysqldb", - tags: new string[] { "mysqldb" } - ); - } + tags: new string[] { "mysqldb" }); - if (String.Compare(connectionString.ProviderName, "Npgsql") == 0) - { + if (string.Compare(connectionString.ProviderName, "Npgsql") == 0) hcBuilder.AddNpgSql(connectionString.ConnectionString, name: "postgredb", - tags: new string[] { "postgredb" } - ); - } + tags: new string[] { "postgredb" }); var kafkaSettings = configurationExtension.GetSetting<KafkaSettings>("kafka"); @@ -63,11 +57,9 @@ namespace ASC.Api.Core.Core var elasticSearchUri = $"{scheme}://{host}:{port}"; if (Uri.IsWellFormedUriString(elasticSearchUri, UriKind.Absolute)) - { hcBuilder.AddElasticsearch(elasticSearchUri, name: "elasticsearch", tags: new string[] { "elasticsearch" }); - } } return services; diff --git a/common/ASC.Api.Core/Core/ItemDictionary.cs b/common/ASC.Api.Core/Core/ItemDictionary.cs index a5a9028f78..9382b82739 100644 --- a/common/ASC.Api.Core/Core/ItemDictionary.cs +++ b/common/ASC.Api.Core/Core/ItemDictionary.cs @@ -36,13 +36,9 @@ namespace ASC.Api.Collections [CollectionDataContract(Name = "hash", Namespace = "", ItemName = "entry", KeyName = "key", ValueName = "value")] public class ItemDictionary<TKey, TValue> : Dictionary<TKey, TValue> { - public ItemDictionary() - { - } + public ItemDictionary() { } public ItemDictionary(IDictionary<TKey, TValue> items) - : base(items) - { - } + : base(items) { } } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/ItemKeyValuePair.cs b/common/ASC.Api.Core/Core/ItemKeyValuePair.cs index f3613b068c..a36461fe63 100644 --- a/common/ASC.Api.Core/Core/ItemKeyValuePair.cs +++ b/common/ASC.Api.Core/Core/ItemKeyValuePair.cs @@ -29,8 +29,6 @@ namespace ASC.Api.Collections public class ItemKeyValuePair<TKey, TValue> { public TKey Key { get; set; } - - public TValue Value { get; set; } } diff --git a/common/ASC.Api.Core/Core/Module.cs b/common/ASC.Api.Core/Core/Module.cs index 49f43074f8..0d308ddcca 100644 --- a/common/ASC.Api.Core/Core/Module.cs +++ b/common/ASC.Api.Core/Core/Module.cs @@ -7,14 +7,11 @@ namespace ASC.Api.Core public class Module { public Guid Id { get; set; } - public string AppName { get; set; } public string Title { get; set; } public string Link { get; set; } - public string IconUrl { get; set; } public string ImageUrl { get; set; } - public string HelpUrl { get; set; } public string Description { get; set; } public bool IsPrimary { get; set; } diff --git a/common/ASC.Api.Core/Core/Update.cs b/common/ASC.Api.Core/Core/Update.cs index 6107cd184f..88799b1012 100644 --- a/common/ASC.Api.Core/Core/Update.cs +++ b/common/ASC.Api.Core/Core/Update.cs @@ -30,10 +30,8 @@ namespace ASC.Api.Utils { public static T IfNotEquals<T>(T current, T @new) { - if (!Equals(current, @new)) - { - return @new; - } + if (!Equals(current, @new)) return @new; + return current; } @@ -41,10 +39,8 @@ namespace ASC.Api.Utils { if (Equals(@new, default(T))) return current; - if (!Equals(current, @new)) - { - return @new; - } + if (!Equals(current, @new)) return @new; + return current; } } diff --git a/common/ASC.Api.Core/Core/Validate.cs b/common/ASC.Api.Core/Core/Validate.cs index f7d8a4b4ba..ff8d9e145f 100644 --- a/common/ASC.Api.Core/Core/Validate.cs +++ b/common/ASC.Api.Core/Core/Validate.cs @@ -33,34 +33,22 @@ namespace ASC.Api.Utils { public static class Validate { - public static T If<T>(this T item, Func<T, bool> @if, Func<T> then) where T : class - { - return @if(item) ? then() : item; - } + public static T If<T>(this T item, Func<T, bool> @if, Func<T> then) where T : class => + @if(item) ? then() : item; - public static T IfNull<T>(this T item, Func<T> func) where T : class - { - return item.If((x) => x == default(T), func); - } + public static T IfNull<T>(this T item, Func<T> func) where T : class => item.If((x) => + x == default(T), func); - public static T ThrowIfNull<T>(this T item, Exception e) where T : class - { - return item.IfNull(() => { throw e; }); - } + public static T ThrowIfNull<T>(this T item, Exception e) where T : class => + item.IfNull(() => { throw e; }); - public static T NotFoundIfNull<T>(this T item) where T : class - { - return NotFoundIfNull(item, "Item not found"); - } + public static T NotFoundIfNull<T>(this T item) where T : class => + NotFoundIfNull(item, "Item not found"); - public static T NotFoundIfNull<T>(this T item, string message) where T : class - { - return item.IfNull(() => { throw new ItemNotFoundException(message); }); - } + public static T NotFoundIfNull<T>(this T item, string message) where T : class => + item.IfNull(() => { throw new ItemNotFoundException(message); }); - public static T? NullIfDefault<T>(this T item) where T : struct -{ - return EqualityComparer<T>.Default.Equals(item, default(T)) ? default(T?) : item; - } + public static T? NullIfDefault<T>(this T item) where T : struct => + EqualityComparer<T>.Default.Equals(item, default(T)) ? default(T?) : item; } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/XmlOutputFormatter.cs b/common/ASC.Api.Core/Core/XmlOutputFormatter.cs index 906e228b33..c75b87fc8a 100644 --- a/common/ASC.Api.Core/Core/XmlOutputFormatter.cs +++ b/common/ASC.Api.Core/Core/XmlOutputFormatter.cs @@ -13,10 +13,8 @@ namespace ASC.Api.Core.Core { public class XmlOutputFormatter : IOutputFormatter { - public bool CanWriteResult(OutputFormatterCanWriteContext context) - { - return context.ContentType == MimeMapping.GetMimeMapping(".xml"); - } + public bool CanWriteResult(OutputFormatterCanWriteContext context) => + context.ContentType == MimeMapping.GetMimeMapping(".xml"); public Task WriteAsync(OutputFormatterWriteContext context) { @@ -28,6 +26,7 @@ namespace ASC.Api.Core.Core var responseJson = JsonConvert.SerializeObject(context.Object, Formatting.Indented, settings); responseJson = JsonConvert.DeserializeObject<XDocument>("{\"result\":" + responseJson + "}", settings).ToString(SaveOptions.None); + return context.HttpContext.Response.WriteAsync(responseJson); } } diff --git a/common/ASC.Api.Core/Middleware/CommonApiResponse.cs b/common/ASC.Api.Core/Middleware/CommonApiResponse.cs index 05cbad8e4c..5c056f0605 100644 --- a/common/ASC.Api.Core/Middleware/CommonApiResponse.cs +++ b/common/ASC.Api.Core/Middleware/CommonApiResponse.cs @@ -8,23 +8,15 @@ namespace ASC.Api.Core.Middleware public abstract class CommonApiResponse { public int Status { get; set; } - public HttpStatusCode StatusCode { get; set; } - protected CommonApiResponse(HttpStatusCode statusCode) - { - StatusCode = statusCode; - } + protected CommonApiResponse(HttpStatusCode statusCode) => StatusCode = statusCode; - public static SuccessApiResponse Create(HttpStatusCode statusCode, object response) - { - return new SuccessApiResponse(statusCode, response); - } + public static SuccessApiResponse Create(HttpStatusCode statusCode, object response) => + new SuccessApiResponse(statusCode, response); - public static ErrorApiResponse CreateError(HttpStatusCode statusCode, Exception error) - { - return new ErrorApiResponse(statusCode, error); - } + public static ErrorApiResponse CreateError(HttpStatusCode statusCode, Exception error) => + new ErrorApiResponse(statusCode, error); } public class ErrorApiResponse : CommonApiResponse @@ -41,9 +33,7 @@ namespace ASC.Api.Core.Middleware public class SuccessApiResponse : CommonApiResponse { public int? Count { get; set; } - public long? Total { get; set; } - public object Response { get; set; } protected internal SuccessApiResponse(HttpStatusCode statusCode, object response, long? total = null, int? count = null) : base(statusCode) @@ -52,28 +42,13 @@ namespace ASC.Api.Core.Middleware Response = response; Total = total; - if (count.HasValue) - { - Count = count; - } + if (count.HasValue) Count = count; else { - if (response is List<object> list) - { - Count = list.Count; - } - else if (response is IEnumerable<object> collection) - { - Count = collection.Count(); - } - else if (response == null) - { - Count = 0; - } - else - { - Count = 1; - } + if (response is List<object> list) Count = list.Count; + else if (response is IEnumerable<object> collection) Count = collection.Count(); + else if (response == null) Count = 0; + else Count = 1; } } } @@ -81,22 +56,17 @@ namespace ASC.Api.Core.Middleware public class CommonApiError { public string Message { get; set; } - public string Type { get; set; } - public string Stack { get; set; } - public int Hresult { get; set; } - public static CommonApiError FromException(Exception exception, string message = null) - { - return new CommonApiError() + public static CommonApiError FromException(Exception exception, string message = null) => + new CommonApiError() { Message = message ?? exception.Message, Type = exception.GetType().ToString(), Stack = exception.StackTrace, Hresult = exception.HResult }; - } } } diff --git a/common/ASC.Api.Core/Middleware/CultureMiddleware.cs b/common/ASC.Api.Core/Middleware/CultureMiddleware.cs index 146cef9d44..09fb69c207 100644 --- a/common/ASC.Api.Core/Middleware/CultureMiddleware.cs +++ b/common/ASC.Api.Core/Middleware/CultureMiddleware.cs @@ -11,12 +11,9 @@ namespace ASC.Api.Core.Middleware { public class CultureMiddleware { - private readonly RequestDelegate next; + private readonly RequestDelegate _next; - public CultureMiddleware(RequestDelegate next) - { - this.next = next; - } + public CultureMiddleware(RequestDelegate next) => _next = next; public async Task Invoke(HttpContext context, UserManager userManager, TenantManager tenantManager, AuthContext authContext) { @@ -26,29 +23,21 @@ namespace ASC.Api.Core.Middleware { var user = userManager.GetUsers(authContext.CurrentAccount.ID); - if (!string.IsNullOrEmpty(user.CultureName)) - { - culture = user.GetCulture(); - } + if (!string.IsNullOrEmpty(user.CultureName)) culture = user.GetCulture(); } - if (culture == null) - { - culture = tenantManager.GetCurrentTenant().GetCulture(); - } + if (culture == null) culture = tenantManager.GetCurrentTenant().GetCulture(); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; - await next.Invoke(context); + await _next.Invoke(context); } } public static class CultureMiddlewareExtensions { - public static IApplicationBuilder UseCultureMiddleware(this IApplicationBuilder builder) - { - return builder.UseMiddleware<CultureMiddleware>(); - } + public static IApplicationBuilder UseCultureMiddleware(this IApplicationBuilder builder) => + builder.UseMiddleware<CultureMiddleware>(); } } diff --git a/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs b/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs index e26a746d03..de512b8c6c 100644 --- a/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs +++ b/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs @@ -9,26 +9,21 @@ namespace ASC.Api.Core.Middleware { public class DisposeMiddleware { - private readonly RequestDelegate next; + private readonly RequestDelegate _next; - public DisposeMiddleware(RequestDelegate next) - { - this.next = next; - } + public DisposeMiddleware(RequestDelegate next) => _next = next; public async Task Invoke(HttpContext context) { context.Response.RegisterForDispose(new DisposableHttpContext(context)); - await next.Invoke(context); + await _next.Invoke(context); } } public static class DisposeMiddlewareExtensions { - public static IApplicationBuilder UseDisposeMiddleware(this IApplicationBuilder builder) - { - return builder.UseMiddleware<DisposeMiddleware>(); - } + public static IApplicationBuilder UseDisposeMiddleware(this IApplicationBuilder builder) => + builder.UseMiddleware<DisposeMiddleware>(); } } diff --git a/common/ASC.Api.Core/Middleware/IpSecurityFilter.cs b/common/ASC.Api.Core/Middleware/IpSecurityFilter.cs index 0b8741c2e5..655f5ca68e 100644 --- a/common/ASC.Api.Core/Middleware/IpSecurityFilter.cs +++ b/common/ASC.Api.Core/Middleware/IpSecurityFilter.cs @@ -3,7 +3,6 @@ using ASC.Common; using ASC.Common.Logging; using ASC.Core; -using ASC.IPSecurity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; @@ -14,32 +13,29 @@ namespace ASC.Api.Core.Middleware [Scope] public class IpSecurityFilter : IResourceFilter { - private readonly ILog log; + private readonly AuthContext _authContext; + private readonly IPSecurity.IPSecurity _iPSecurity; + private readonly ILog _logger; public IpSecurityFilter( IOptionsMonitor<ILog> options, AuthContext authContext, IPSecurity.IPSecurity IPSecurity) { - log = options.CurrentValue; - AuthContext = authContext; - this.IPSecurity = IPSecurity; + _logger = options.CurrentValue; + _authContext = authContext; + _iPSecurity = IPSecurity; } - private AuthContext AuthContext { get; } - public IPRestrictionsSettings IPRestrictionsSettings { get; } - private IPSecurity.IPSecurity IPSecurity { get; } - - public void OnResourceExecuted(ResourceExecutedContext context) - { - } + public void OnResourceExecuted(ResourceExecutedContext context) { } public void OnResourceExecuting(ResourceExecutingContext context) { - if (AuthContext.IsAuthenticated && !IPSecurity.Verify()) + if (_authContext.IsAuthenticated && !_iPSecurity.Verify()) { context.Result = new StatusCodeResult((int)HttpStatusCode.Forbidden); - log.WarnFormat("IPSecurity: user {0}", AuthContext.CurrentAccount.ID); + _logger.WarnFormat("IPSecurity: user {0}", _authContext.CurrentAccount.ID); + return; } } diff --git a/common/ASC.Api.Core/Middleware/PaymentFilter.cs b/common/ASC.Api.Core/Middleware/PaymentFilter.cs index 284a04ae59..f72b793583 100644 --- a/common/ASC.Api.Core/Middleware/PaymentFilter.cs +++ b/common/ASC.Api.Core/Middleware/PaymentFilter.cs @@ -17,35 +17,34 @@ namespace ASC.Api.Core.Middleware [Scope] public class PaymentFilter : IResourceFilter { - private readonly ILog log; + private readonly TenantExtra _tenantExtra; + private readonly ILog _logger; public PaymentFilter(IOptionsMonitor<ILog> options, TenantExtra tenantExtra) { - log = options.CurrentValue; - TenantExtra = tenantExtra; + _logger = options.CurrentValue; + _tenantExtra = tenantExtra; } - private TenantExtra TenantExtra { get; } - - public void OnResourceExecuted(ResourceExecutedContext context) - { - } + public void OnResourceExecuted(ResourceExecutedContext context) { } public void OnResourceExecuting(ResourceExecutingContext context) { - if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor && !controllerActionDescriptor.EndpointMetadata.OfType<CustomHttpMethodAttribute>().FirstOrDefault().Check) + if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor + && !controllerActionDescriptor.EndpointMetadata.OfType<CustomHttpMethodAttribute>().FirstOrDefault().Check) { - log.Debug("Payment is not required"); + _logger.Debug("Payment is not required"); + return; } var header = context.HttpContext.Request.Headers["Payment-Info"]; if (string.IsNullOrEmpty(header) || (bool.TryParse(header, out var flag) && flag)) { - if (TenantExtra.IsNotPaid()) + if (_tenantExtra.IsNotPaid()) { context.Result = new StatusCodeResult((int)HttpStatusCode.PaymentRequired); - log.WarnFormat("Payment Required {0}.", context.HttpContext.Request.Url()); + _logger.WarnFormat("Payment Required {0}.", context.HttpContext.Request.Url()); } } } diff --git a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs index cbc2cd13b1..7b5b96a306 100644 --- a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs +++ b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs @@ -20,11 +20,10 @@ namespace ASC.Api.Core.Middleware [Scope] public class ProductSecurityFilter : IResourceFilter { - private static readonly IDictionary<string, Guid> products; - private readonly ILog log; - - private WebItemSecurity WebItemSecurity { get; } - private AuthContext AuthContext { get; } + private static readonly IDictionary<string, Guid> _products; + private readonly ILog _logger; + private readonly WebItemSecurity _webItemSecurity; + private readonly AuthContext _authContext; static ProductSecurityFilter() { @@ -35,7 +34,7 @@ namespace ASC.Api.Core.Middleware var wiki = new Guid("742cf945-cbbc-4a57-82d6-1600a12cf8ca"); var photo = new Guid("9d51954f-db9b-4aed-94e3-ed70b914e101"); - products = new Dictionary<string, Guid> + _products = new Dictionary<string, Guid> { { "blog", blog }, { "bookmark", bookmark }, @@ -59,18 +58,16 @@ namespace ASC.Api.Core.Middleware WebItemSecurity webItemSecurity, AuthContext authContext) { - log = options.CurrentValue; - WebItemSecurity = webItemSecurity; - AuthContext = authContext; + _logger = options.CurrentValue; + _webItemSecurity = webItemSecurity; + _authContext = authContext; } - public void OnResourceExecuted(ResourceExecutedContext context) - { - } + public void OnResourceExecuted(ResourceExecutedContext context) { } public void OnResourceExecuting(ResourceExecutingContext context) { - if (!AuthContext.IsAuthenticated) return; + if (!_authContext.IsAuthenticated) return; if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor) { @@ -78,13 +75,12 @@ namespace ASC.Api.Core.Middleware if (pid != Guid.Empty) { if (CallContext.GetData("asc.web.product_id") == null) - { CallContext.SetData("asc.web.product_id", pid); - } - if (!WebItemSecurity.IsAvailableForMe(pid)) + + if (!_webItemSecurity.IsAvailableForMe(pid)) { context.Result = new StatusCodeResult((int)HttpStatusCode.Forbidden); - log.WarnFormat("Product {0} denied for user {1}", controllerActionDescriptor.ControllerName, AuthContext.CurrentAccount); + _logger.WarnFormat("Product {0} denied for user {1}", controllerActionDescriptor.ControllerName, _authContext.CurrentAccount); } } } @@ -92,10 +88,8 @@ namespace ASC.Api.Core.Middleware private static Guid FindProduct(ControllerActionDescriptor method) { - if (method == null || string.IsNullOrEmpty(method.ControllerName)) - { - return default; - } + if (method == null || string.IsNullOrEmpty(method.ControllerName)) return default; + var name = method.ControllerName.ToLower(); if (name == "community") { @@ -103,17 +97,12 @@ namespace ASC.Api.Core.Middleware if (!string.IsNullOrEmpty(url)) { var module = url.Split('/')[0]; - if (products.ContainsKey(module)) - { - return products[module]; - } + if (_products.ContainsKey(module)) return _products[module]; } } - if (products.ContainsKey(name)) - { - return products[name]; - } + if (_products.ContainsKey(name)) return _products[name]; + return default; } } diff --git a/common/ASC.Api.Core/Middleware/ResponseWrapper.cs b/common/ASC.Api.Core/Middleware/ResponseWrapper.cs index fe249af62f..f1414d658f 100644 --- a/common/ASC.Api.Core/Middleware/ResponseWrapper.cs +++ b/common/ASC.Api.Core/Middleware/ResponseWrapper.cs @@ -16,10 +16,7 @@ namespace ASC.Api.Core.Middleware var status = (HttpStatusCode)context.HttpContext.Response.StatusCode; string message = null; - if (status == HttpStatusCode.OK) - { - status = HttpStatusCode.InternalServerError; - } + if (status == HttpStatusCode.OK) status = HttpStatusCode.InternalServerError; switch (context.Exception) { diff --git a/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs b/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs index 8eda940670..ebeb8bb6a3 100644 --- a/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs +++ b/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs @@ -14,34 +14,33 @@ namespace ASC.Api.Core.Middleware [Scope] public class TenantStatusFilter : IResourceFilter { - private readonly ILog log; + private readonly TenantManager _tenantManager; + private readonly ILog _logger; public TenantStatusFilter(IOptionsMonitor<ILog> options, TenantManager tenantManager) { - log = options.CurrentValue; - TenantManager = tenantManager; + _logger = options.CurrentValue; + _tenantManager = tenantManager; } - private TenantManager TenantManager { get; } - - public void OnResourceExecuted(ResourceExecutedContext context) - { - } + public void OnResourceExecuted(ResourceExecutedContext context) { } public void OnResourceExecuting(ResourceExecutingContext context) { - var tenant = TenantManager.GetCurrentTenant(false); + var tenant = _tenantManager.GetCurrentTenant(false); if (tenant == null) { context.Result = new StatusCodeResult((int)HttpStatusCode.NotFound); - log.WarnFormat("Tenant {0} not found", tenant.TenantId); + _logger.WarnFormat("Tenant {0} not found", tenant.TenantId); + return; } if (tenant.Status == TenantStatus.RemovePending || tenant.Status == TenantStatus.Suspended) { context.Result = new StatusCodeResult((int)HttpStatusCode.NotFound); - log.WarnFormat("Tenant {0} is not removed or suspended", tenant.TenantId); + _logger.WarnFormat("Tenant {0} is not removed or suspended", tenant.TenantId); + return; } } diff --git a/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs b/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs index 6ed151b8fa..ff37cb3c3a 100644 --- a/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs +++ b/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs @@ -15,26 +15,27 @@ namespace ASC.Api.Core.Middleware [Scope] public class WebhooksGlobalFilterAttribute : ResultFilterAttribute { - private IWebhookPublisher WebhookPublisher { get; } - private static List<string> methodList = new List<string> { "POST", "UPDATE", "DELETE" }; - private JsonSerializerOptions jsonSerializerOptions; + private readonly IWebhookPublisher _webhookPublisher; + private readonly JsonSerializerOptions _jsonSerializerOptions; + private static List<string> _methodList = new List<string> { "POST", "UPDATE", "DELETE" }; public WebhooksGlobalFilterAttribute(IWebhookPublisher webhookPublisher, Action<JsonOptions> projectJsonOptions) { - WebhookPublisher = webhookPublisher; + _webhookPublisher = webhookPublisher; var jsonOptions = new JsonOptions(); projectJsonOptions.Invoke(jsonOptions); - jsonSerializerOptions = jsonOptions.JsonSerializerOptions; + _jsonSerializerOptions = jsonOptions.JsonSerializerOptions; } public override void OnResultExecuted(ResultExecutedContext context) { var method = context.HttpContext.Request.Method; - if (!methodList.Contains(method) || context.Canceled) + if (!_methodList.Contains(method) || context.Canceled) { - base.OnResultExecuted(context); + base.OnResultExecuted(context); + return; } @@ -43,17 +44,18 @@ namespace ASC.Api.Core.Middleware if (routePattern == null) { - base.OnResultExecuted(context); + base.OnResultExecuted(context); + return; } if (context.Result is ObjectResult objectResult) { - var resultContent = JsonSerializer.Serialize(objectResult.Value, jsonSerializerOptions); + var resultContent = JsonSerializer.Serialize(objectResult.Value, _jsonSerializerOptions); var eventName = $"method: {method}, route: {routePattern}"; - WebhookPublisher.Publish(eventName, resultContent); + _webhookPublisher.Publish(eventName, resultContent); } base.OnResultExecuted(context); diff --git a/common/ASC.Api.Core/Model/Contact.cs b/common/ASC.Api.Core/Model/Contact.cs index 123900c7c5..e82c789edb 100644 --- a/common/ASC.Api.Core/Model/Contact.cs +++ b/common/ASC.Api.Core/Model/Contact.cs @@ -28,13 +28,10 @@ namespace ASC.Web.Api.Models public class Contact { public string Type { get; set; } - public string Value { get; set; } - public Contact() - { - //For binder - } + //For binder + public Contact() { } public Contact(string type, string value) { @@ -42,9 +39,6 @@ namespace ASC.Web.Api.Models Value = value; } - public static Contact GetSample() - { - return new Contact("GTalk", "my@gmail.com"); - } + public static Contact GetSample() => new Contact("GTalk", "my@gmail.com"); } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Model/EmployeeWraper.cs b/common/ASC.Api.Core/Model/EmployeeWraper.cs index 781275a0e2..b795f2d647 100644 --- a/common/ASC.Api.Core/Model/EmployeeWraper.cs +++ b/common/ASC.Api.Core/Model/EmployeeWraper.cs @@ -39,36 +39,31 @@ namespace ASC.Web.Api.Models public class EmployeeWraper { public Guid Id { get; set; } - public string DisplayName { get; set; } - public string Title { get; set; } - public string AvatarSmall { get; set; } - public string ProfileUrl { get; set; } - public static EmployeeWraper GetSample() - { - return new EmployeeWraper + public static EmployeeWraper GetSample() => + new EmployeeWraper { Id = Guid.Empty, DisplayName = "Mike Zanyatski", Title = "Manager", AvatarSmall = "url to small avatar", }; - } } [Scope] public class EmployeeWraperHelper { - private ApiContext HttpContext { get; } - private DisplayUserSettingsHelper DisplayUserSettingsHelper { get; } - protected UserPhotoManager UserPhotoManager { get; } - private CommonLinkUtility CommonLinkUtility { get; } + protected UserPhotoManager UserPhotoManager { get; } protected UserManager UserManager { get; } + private readonly ApiContext _httpContext; + private readonly DisplayUserSettingsHelper _displayUserSettingsHelper; + private readonly CommonLinkUtility _commonLinkUtility; + public EmployeeWraperHelper( ApiContext httpContext, DisplayUserSettingsHelper displayUserSettingsHelper, @@ -76,17 +71,15 @@ namespace ASC.Web.Api.Models CommonLinkUtility commonLinkUtility, UserManager userManager) { - HttpContext = httpContext; - DisplayUserSettingsHelper = displayUserSettingsHelper; UserPhotoManager = userPhotoManager; - CommonLinkUtility = commonLinkUtility; UserManager = userManager; + _httpContext = httpContext; + _displayUserSettingsHelper = displayUserSettingsHelper; + _commonLinkUtility = commonLinkUtility; + } - public EmployeeWraper Get(UserInfo userInfo) - { - return Init(new EmployeeWraper(), userInfo); - } + public EmployeeWraper Get(UserInfo userInfo) => Init(new EmployeeWraper(), userInfo); public EmployeeWraper Get(Guid userId) { @@ -103,23 +96,19 @@ namespace ASC.Web.Api.Models protected EmployeeWraper Init(EmployeeWraper result, UserInfo userInfo) { result.Id = userInfo.ID; - result.DisplayName = DisplayUserSettingsHelper.GetFullUserName(userInfo); - if (!string.IsNullOrEmpty(userInfo.Title)) - { - result.Title = userInfo.Title; - } + result.DisplayName = _displayUserSettingsHelper.GetFullUserName(userInfo); + + if (!string.IsNullOrEmpty(userInfo.Title)) result.Title = userInfo.Title; var userInfoLM = userInfo.LastModified.GetHashCode(); - if (HttpContext.Check("avatarSmall")) - { + if (_httpContext.Check("avatarSmall")) result.AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); - } if (result.Id != Guid.Empty) { - var profileUrl = CommonLinkUtility.GetUserProfile(userInfo, false); - result.ProfileUrl = CommonLinkUtility.GetFullAbsolutePath(profileUrl); + var profileUrl = _commonLinkUtility.GetUserProfile(userInfo, false); + result.ProfileUrl = _commonLinkUtility.GetFullAbsolutePath(profileUrl); } return result; diff --git a/common/ASC.Api.Core/Model/EmployeeWraperFull.cs b/common/ASC.Api.Core/Model/EmployeeWraperFull.cs index aafc1dd727..15eb3cbbba 100644 --- a/common/ASC.Api.Core/Model/EmployeeWraperFull.cs +++ b/common/ASC.Api.Core/Model/EmployeeWraperFull.cs @@ -44,58 +44,31 @@ namespace ASC.Web.Api.Models public class EmployeeWraperFull : EmployeeWraper { public string FirstName { get; set; } - public string LastName { get; set; } - public string UserName { get; set; } - public string Email { get; set; } - public List<Contact> Contacts { get; set; } - public ApiDateTime Birthday { get; set; } - public string Sex { get; set; } - public EmployeeStatus Status { get; set; } - public EmployeeActivationStatus ActivationStatus { get; set; } - public ApiDateTime Terminated { get; set; } - public string Department { get; set; } - public ApiDateTime WorkFrom { get; set; } - public List<GroupWrapperSummary> Groups { get; set; } - public string Location { get; set; } - public string Notes { get; set; } - public string AvatarMax { get; set; } - public string AvatarMedium { get; set; } - public string Avatar { get; set; } - public bool IsAdmin { get; set; } - public bool IsLDAP { get; set; } - public List<string> ListAdminModules { get; set; } - public bool IsOwner { get; set; } - public bool IsVisitor { get; set; } - public string CultureName { get; set; } - - public string MobilePhone { get; set; } - public MobilePhoneActivationStatus MobilePhoneActivationStatus { get; set; } - public bool IsSSO { get; set; } public new static EmployeeWraperFull GetSample() @@ -134,9 +107,9 @@ namespace ASC.Web.Api.Models [Scope] public class EmployeeWraperFullHelper : EmployeeWraperHelper { - private ApiContext Context { get; } - private WebItemSecurity WebItemSecurity { get; } - private ApiDateTimeHelper ApiDateTimeHelper { get; } + private readonly ApiContext _context; + private readonly WebItemSecurity _webItemSecurity; + private readonly ApiDateTimeHelper _apiDateTimeHelper; public EmployeeWraperFullHelper( ApiContext context, @@ -148,9 +121,9 @@ namespace ASC.Web.Api.Models ApiDateTimeHelper apiDateTimeHelper) : base(context, displayUserSettingsHelper, userPhotoManager, commonLinkUtility, userManager) { - Context = context; - WebItemSecurity = webItemSecurity; - ApiDateTimeHelper = apiDateTimeHelper; + _context = context; + _webItemSecurity = webItemSecurity; + _apiDateTimeHelper = apiDateTimeHelper; } public static Expression<Func<User, UserInfo>> GetExpression(ApiContext apiContext) @@ -163,9 +136,7 @@ namespace ASC.Web.Api.Models var bindExprs = new List<MemberAssignment>(); if (apiContext.Check("Id")) - { bindExprs.Add(Expression.Bind(typeof(UserInfo).GetProperty("ID"), Expression.Property(parameter, typeof(User).GetProperty("Id")))); - } var body = Expression.MemberInit(newExpr, bindExprs); var lambda = Expression.Lambda<Func<User, UserInfo>>(body, parameter); @@ -180,15 +151,15 @@ namespace ASC.Web.Api.Models UserName = userInfo.UserName, FirstName = userInfo.FirstName, LastName = userInfo.LastName, - Birthday = ApiDateTimeHelper.Get(userInfo.BirthDate), + Birthday = _apiDateTimeHelper.Get(userInfo.BirthDate), Status = userInfo.Status, ActivationStatus = userInfo.ActivationStatus & ~EmployeeActivationStatus.AutoGenerated, - Terminated = ApiDateTimeHelper.Get(userInfo.TerminatedDate), - WorkFrom = ApiDateTimeHelper.Get(userInfo.WorkFromDate), + Terminated = _apiDateTimeHelper.Get(userInfo.TerminatedDate), + WorkFrom = _apiDateTimeHelper.Get(userInfo.WorkFromDate), Email = userInfo.Email, IsVisitor = userInfo.IsVisitor(UserManager), IsAdmin = userInfo.IsAdmin(UserManager), - IsOwner = userInfo.IsOwner(Context.Tenant), + IsOwner = userInfo.IsOwner(_context.Tenant), IsLDAP = userInfo.IsLDAP(), IsSSO = userInfo.IsSSO() }; @@ -196,35 +167,25 @@ namespace ASC.Web.Api.Models Init(result, userInfo); if (userInfo.Sex.HasValue) - { result.Sex = userInfo.Sex.Value ? "male" : "female"; - } if (!string.IsNullOrEmpty(userInfo.Location)) - { result.Location = userInfo.Location; - } if (!string.IsNullOrEmpty(userInfo.Notes)) - { result.Notes = userInfo.Notes; - } if (!string.IsNullOrEmpty(userInfo.MobilePhone)) - { result.MobilePhone = userInfo.MobilePhone; - } result.MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus; if (!string.IsNullOrEmpty(userInfo.CultureName)) - { result.CultureName = userInfo.CultureName; - } FillConacts(result, userInfo); - if (Context.Check("groups") || Context.Check("department")) + if (_context.Check("groups") || _context.Check("department")) { var groups = UserManager.GetUserGroups(userInfo.ID) .Select(x => new GroupWrapperSummary(x, UserManager)) @@ -235,35 +196,25 @@ namespace ASC.Web.Api.Models result.Groups = groups; result.Department = string.Join(", ", result.Groups.Select(d => d.Name.HtmlEncode())); } - else - { - result.Department = ""; - } + else result.Department = ""; } var userInfoLM = userInfo.LastModified.GetHashCode(); - if (Context.Check("avatarMax")) - { + if (_context.Check("avatarMax")) result.AvatarMax = UserPhotoManager.GetMaxPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); - } - if (Context.Check("avatarMedium")) - { + if (_context.Check("avatarMedium")) result.AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); - } - if (Context.Check("avatar")) - { + if (_context.Check("avatar")) result.Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); - } - if (Context.Check("listAdminModules")) + if (_context.Check("listAdminModules")) { - var listAdminModules = userInfo.GetListAdminModules(WebItemSecurity); + var listAdminModules = userInfo.GetListAdminModules(_webItemSecurity); - if (listAdminModules.Any()) - result.ListAdminModules = listAdminModules; + if (listAdminModules.Any()) result.ListAdminModules = listAdminModules; } return result; @@ -278,15 +229,11 @@ namespace ASC.Web.Api.Models for (var i = 0; i < userInfo.ContactsList.Count; i += 2) { if (i + 1 < userInfo.ContactsList.Count) - { contacts.Add(new Contact(userInfo.ContactsList[i], userInfo.ContactsList[i + 1])); - } } if (contacts.Any()) - { employeeWraperFull.Contacts = contacts; - } } } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Model/GroupWrapperSummary.cs b/common/ASC.Api.Core/Model/GroupWrapperSummary.cs index 4c34c035d4..872eefd9ef 100644 --- a/common/ASC.Api.Core/Model/GroupWrapperSummary.cs +++ b/common/ASC.Api.Core/Model/GroupWrapperSummary.cs @@ -33,6 +33,12 @@ namespace ASC.Web.Api.Models { public class GroupWrapperSummary { + public Guid Id { get; set; } + public string Name { get; set; } + public string Manager { get; set; } + + protected GroupWrapperSummary() { } + public GroupWrapperSummary(GroupInfo group, UserManager userManager) { Id = group.ID; @@ -40,20 +46,7 @@ namespace ASC.Web.Api.Models Manager = userManager.GetUsers(userManager.GetDepartmentManager(group.ID)).UserName; } - protected GroupWrapperSummary() - { - } - - - public string Name { get; set; } - - public Guid Id { get; set; } - - public string Manager { get; set; } - - public static GroupWrapperSummary GetSample() - { - return new GroupWrapperSummary { Id = Guid.Empty, Manager = "Jake.Zazhitski", Name = "Group Name" }; - } + public static GroupWrapperSummary GetSample() => + new GroupWrapperSummary { Id = Guid.Empty, Manager = "Jake.Zazhitski", Name = "Group Name" }; } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Routing/DefaultRoute.cs b/common/ASC.Api.Core/Routing/DefaultRoute.cs index e14b3c4cc5..5945e3df2a 100644 --- a/common/ASC.Api.Core/Routing/DefaultRoute.cs +++ b/common/ASC.Api.Core/Routing/DefaultRoute.cs @@ -6,13 +6,8 @@ namespace ASC.Web.Api.Routing { public static string BaseUrl { get; set; } - static DefaultRouteAttribute() - { - BaseUrl = "api/2.0"; - } + static DefaultRouteAttribute() => BaseUrl = "api/2.0"; - public DefaultRouteAttribute() : base(BaseUrl) - { - } + public DefaultRouteAttribute() : base(BaseUrl) { } } } diff --git a/common/ASC.Api.Core/Routing/FormatRoute.cs b/common/ASC.Api.Core/Routing/FormatRoute.cs index c10998e402..319fb397f6 100644 --- a/common/ASC.Api.Core/Routing/FormatRoute.cs +++ b/common/ASC.Api.Core/Routing/FormatRoute.cs @@ -33,6 +33,7 @@ namespace ASC.Web.Api.Routing public CreateAttribute(bool check = true, int order = 1) : this(null, check, order) { } + public CreateAttribute(string template, bool check = true, int order = 1) : base(HttpMethod.Post.Method, template, check, order) { } @@ -42,6 +43,7 @@ namespace ASC.Web.Api.Routing public UpdateAttribute(bool check = true, int order = 1) : this(null, check, order) { } + public UpdateAttribute(string template, bool check = true, int order = 1) : base(HttpMethod.Put.Method, template, check, order) { } @@ -51,6 +53,7 @@ namespace ASC.Web.Api.Routing public DeleteAttribute(bool check = true, int order = 1) : this(null, check, order) { } + public DeleteAttribute(string template, bool check = true, int order = 1) : base(HttpMethod.Delete.Method, template, check, order) { } From 724065389f3a901e18d961392f9fb389479a8cea Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 11:35:28 +0300 Subject: [PATCH 103/167] AuditTrail: private properties replaced with fields, used single line expressions, cosmetic --- .../ASC.AuditTrail/AuditEventsRepository.cs | 260 +++++++++--------- .../ASC.AuditTrail/AuditReportCreator.cs | 61 ++-- common/services/ASC.AuditTrail/BaseEvent.cs | 6 +- common/services/ASC.AuditTrail/LoginEvent.cs | 1 - .../ASC.AuditTrail/LoginEventsRepository.cs | 59 ++-- .../Mappers/AuditActionMapper.cs | 45 +-- .../ASC.AuditTrail/Mappers/CrmActionMapper.cs | 10 +- .../Mappers/DocumentsActionMapper.cs | 21 +- .../Mappers/LoginActionMapper.cs | 64 +++-- .../Mappers/OthersActionMapper.cs | 10 +- .../Mappers/PeopleActionMapper.cs | 148 +++++----- .../Mappers/ProjectsActionMapper.cs | 242 ++++++++-------- .../Mappers/SettingsActionMapper.cs | 208 +++++++------- 13 files changed, 554 insertions(+), 581 deletions(-) diff --git a/common/services/ASC.AuditTrail/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/AuditEventsRepository.cs index 5ea5616469..877bde344c 100644 --- a/common/services/ASC.AuditTrail/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/AuditEventsRepository.cs @@ -1,121 +1,107 @@ -/* - * - * (c) Copyright Ascensio System Limited 2010-2018 - * - * This program is freeware. You can redistribute it and/or modify it under the terms of the GNU - * General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html). - * In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that - * Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights. - * - * THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR - * FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html - * - * You can contact Ascensio System SIA by email at sales@onlyoffice.com - * - * The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display - * Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3. - * - * Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains - * relevant author attributions when distributing the software. If the display of the logo in its graphic - * form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE" - * in every copy of the program you distribute. - * Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks. - * -*/ - - -using System; -using System.Collections.Generic; -using System.Linq; +/* + * + * (c) Copyright Ascensio System Limited 2010-2018 + * + * This program is freeware. You can redistribute it and/or modify it under the terms of the GNU + * General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html). + * In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that + * Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights. + * + * THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR + * FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html + * + * You can contact Ascensio System SIA by email at sales@onlyoffice.com + * + * The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display + * Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3. + * + * Pursuant to Section 7 � 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains + * relevant author attributions when distributing the software. If the display of the logo in its graphic + * form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE" + * in every copy of the program you distribute. + * Pursuant to Section 7 � 3(e) we decline to grant you any rights under trademark law for use of our trademarks. + * +*/ -using ASC.AuditTrail.Mappers; -using ASC.Common; -using ASC.Core.Common.EF; -using ASC.Core.Common.EF.Context; -using ASC.Core.Users; -using ASC.MessagingSystem; -using Newtonsoft.Json; - -namespace ASC.AuditTrail +using System; +using System.Collections.Generic; +using System.Linq; + +using ASC.AuditTrail.Mappers; +using ASC.Common; +using ASC.Core.Common.EF; +using ASC.Core.Common.EF.Context; +using ASC.Core.Users; +using ASC.MessagingSystem; + +using Newtonsoft.Json; + +namespace ASC.AuditTrail { - [Scope] - public class AuditEventsRepository - { - private MessageTarget MessageTarget { get; set; } - private UserFormatter UserFormatter { get; set; } - private Lazy<AuditTrailContext> LazyAuditTrailContext { get; } - private AuditTrailContext AuditTrailContext { get => LazyAuditTrailContext.Value; } - private AuditActionMapper AuditActionMapper { get; } - - public AuditEventsRepository(MessageTarget messageTarget, UserFormatter userFormatter, DbContextManager<AuditTrailContext> dbContextManager, AuditActionMapper auditActionMapper) - { - MessageTarget = messageTarget; - UserFormatter = userFormatter; - LazyAuditTrailContext = new Lazy<AuditTrailContext>(() => dbContextManager.Value ); - AuditActionMapper = auditActionMapper; - } - - public IEnumerable<AuditEvent> GetLast(int tenant, int chunk) - { - return Get(tenant, null, null, chunk); - } - - public IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) - { - return Get(tenant, from, to, null); - } - - private class Query - { - public Core.Common.EF.Model.AuditEvent AuditEvent { get; set; } - public User User { get; set; } - } - - private IEnumerable<AuditEvent> Get(int tenant, DateTime? fromDate, DateTime? to, int? limit) + [Scope] + public class AuditEventsRepository + { + private AuditTrailContext AuditTrailContext => _lazyAuditTrailContext.Value; + + private readonly MessageTarget _messageTarget; + private readonly UserFormatter _userFormatter; + private readonly Lazy<AuditTrailContext> _lazyAuditTrailContext; + private readonly AuditActionMapper _auditActionMapper; + + public AuditEventsRepository( + MessageTarget messageTarget, + UserFormatter userFormatter, + DbContextManager<AuditTrailContext> dbContextManager, + AuditActionMapper auditActionMapper) + { + _messageTarget = messageTarget; + _userFormatter = userFormatter; + _lazyAuditTrailContext = new Lazy<AuditTrailContext>(() => dbContextManager.Value ); + _auditActionMapper = auditActionMapper; + } + + public IEnumerable<AuditEvent> GetLast(int tenant, int chunk) => Get(tenant, null, null, chunk); + + public IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) => Get(tenant, from, to, null); + + private IEnumerable<AuditEvent> Get(int tenant, DateTime? fromDate, DateTime? to, int? limit) { var query = from q in AuditTrailContext.AuditEvents from p in AuditTrailContext.Users.Where(p => q.UserId == p.Id).DefaultIfEmpty() where q.TenantId == tenant orderby q.Date descending - select new Query { AuditEvent = q, User = p }; - - if (fromDate.HasValue && to.HasValue) - { - query = query.Where(q => q.AuditEvent.Date >= fromDate & q.AuditEvent.Date <= to); - } - - if (limit.HasValue) - { - query = query.Take((int)limit); - } - - return query.AsEnumerable().Select(ToAuditEvent).ToList(); - } - - public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) - { - IQueryable<Core.Common.EF.Model.AuditEvent> query = AuditTrailContext.AuditEvents - .Where(a => a.TenantId == tenant) - .OrderByDescending(a => a.Date); - - if (from.HasValue && to.HasValue) - { - query = query.Where(a => a.Date >= from & a.Date <= to); - } - - return query.Count(); - } - - private AuditEvent ToAuditEvent(Query query) - { - try - { + select new Query { AuditEvent = q, User = p }; + + if (fromDate.HasValue && to.HasValue) + query = query.Where(q => q.AuditEvent.Date >= fromDate & q.AuditEvent.Date <= to); + + if (limit.HasValue) query = query.Take((int)limit); + + return query.AsEnumerable().Select(ToAuditEvent).ToList(); + } + + public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) + { + IQueryable<Core.Common.EF.Model.AuditEvent> query = AuditTrailContext.AuditEvents + .Where(a => a.TenantId == tenant) + .OrderByDescending(a => a.Date); + + if (from.HasValue && to.HasValue) + query = query.Where(a => a.Date >= from & a.Date <= to); + + return query.Count(); + } + + private AuditEvent ToAuditEvent(Query query) + { + try + { var evt = new AuditEvent { Id = query.AuditEvent.Id, - IP = query.AuditEvent.Ip, + Ip = query.AuditEvent.Ip, Initiator = query.AuditEvent.Initiator, Browser = query.AuditEvent.Browser, Platform = query.AuditEvent.Platform, @@ -124,34 +110,38 @@ namespace ASC.AuditTrail UserId = query.AuditEvent.UserId, Page = query.AuditEvent.Page, Action = query.AuditEvent.Action - }; - - if (query.AuditEvent.Description != null) - { - evt.Description = JsonConvert.DeserializeObject<IList<string>>( - Convert.ToString(query.AuditEvent.Description), - new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); - } - - evt.Target = MessageTarget.Parse(query.AuditEvent.Target); - - evt.UserName = (query.User.FirstName != null && query.User.LastName != null) ? UserFormatter.GetUserName(query.User.FirstName, query.User.LastName) : - evt.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : - evt.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : - evt.Initiator ?? AuditReportResource.UnknownAccount; - - evt.ActionText = AuditActionMapper.GetActionText(evt); - evt.ActionTypeText = AuditActionMapper.GetActionTypeText(evt); - evt.Product = AuditActionMapper.GetProductText(evt); - evt.Module = AuditActionMapper.GetModuleText(evt); - - return evt; - } - catch (Exception) - { - } + }; - return null; - } - } + if (query.AuditEvent.Description != null) + { + evt.Description = JsonConvert.DeserializeObject<IList<string>>( + Convert.ToString(query.AuditEvent.Description), + new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); + } + + evt.Target = _messageTarget.Parse(query.AuditEvent.Target); + + evt.UserName = (query.User.FirstName != null && query.User.LastName != null) ? _userFormatter.GetUserName(query.User.FirstName, query.User.LastName) : + evt.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : + evt.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : + evt.Initiator ?? AuditReportResource.UnknownAccount; + + evt.ActionText = _auditActionMapper.GetActionText(evt); + evt.ActionTypeText = _auditActionMapper.GetActionTypeText(evt); + evt.Product = _auditActionMapper.GetProductText(evt); + evt.Module = _auditActionMapper.GetModuleText(evt); + + return evt; + } + catch (Exception) { } + + return null; + } + + private class Query + { + public Core.Common.EF.Model.AuditEvent AuditEvent { get; set; } + public User User { get; set; } + } + } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/AuditReportCreator.cs b/common/services/ASC.AuditTrail/AuditReportCreator.cs index 10214d5a89..94315157e1 100644 --- a/common/services/ASC.AuditTrail/AuditReportCreator.cs +++ b/common/services/ASC.AuditTrail/AuditReportCreator.cs @@ -47,46 +47,51 @@ namespace ASC.AuditTrail [Scope] public class AuditReportCreator { - private ILog Log { get; } - private GlobalFolderHelper GlobalFolderHelper { get; } - private FileUploader FileUploader { get; } - private FilesLinkUtility FilesLinkUtility { get; } - private CommonLinkUtility CommonLinkUtility { get; } + private readonly GlobalFolderHelper _globalFolderHelper; + private readonly FileUploader _fileUploader; + private readonly FilesLinkUtility _filesLinkUtility; + private readonly CommonLinkUtility _commonLinkUtility; + private readonly ILog _logger; - public AuditReportCreator(GlobalFolderHelper globalFolderHelper, IOptionsMonitor<ILog> options, FileUploader fileUploader, FilesLinkUtility filesLinkUtility, CommonLinkUtility commonLinkUtility) + public AuditReportCreator( + GlobalFolderHelper globalFolderHelper, + IOptionsMonitor<ILog> options, + FileUploader fileUploader, + FilesLinkUtility filesLinkUtility, + CommonLinkUtility commonLinkUtility) { - GlobalFolderHelper = globalFolderHelper; - Log = options.CurrentValue; - FileUploader = fileUploader; - FilesLinkUtility = filesLinkUtility; - CommonLinkUtility = commonLinkUtility; + _globalFolderHelper = globalFolderHelper; + _logger = options.CurrentValue; + _fileUploader = fileUploader; + _filesLinkUtility = filesLinkUtility; + _commonLinkUtility = commonLinkUtility; } public string CreateCsvReport<TEvent>(IEnumerable<TEvent> events, string reportName) where TEvent : BaseEvent { try { - using (var stream = new MemoryStream()) - using (var writer = new StreamWriter(stream, Encoding.UTF8)) - using (var csv = new CsvWriter(writer, CultureInfo.CurrentCulture)) - { - csv.Configuration.RegisterClassMap(new BaseEventMap<TEvent>()); - - csv.WriteHeader<TEvent>(); - csv.NextRecord(); - csv.WriteRecords(events); - writer.Flush(); - - var file = FileUploader.Exec(GlobalFolderHelper.FolderMy, reportName, stream.Length, stream, true); - var fileUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID)); + using var stream = new MemoryStream(); + using var writer = new StreamWriter(stream, Encoding.UTF8); + using var csv = new CsvWriter(writer, CultureInfo.CurrentCulture); - fileUrl += string.Format("&options={{\"codePage\":{0}}}", Encoding.UTF8.CodePage); - return fileUrl; - } + csv.Configuration.RegisterClassMap(new BaseEventMap<TEvent>()); + + csv.WriteHeader<TEvent>(); + csv.NextRecord(); + csv.WriteRecords(events); + writer.Flush(); + + var file = _fileUploader.Exec(_globalFolderHelper.FolderMy, reportName, stream.Length, stream, true); + var fileUrl = _commonLinkUtility.GetFullAbsolutePath(_filesLinkUtility.GetFileWebEditorUrl(file.ID)); + + fileUrl += string.Format("&options={{\"codePage\":{0}}}", Encoding.UTF8.CodePage); + + return fileUrl; } catch (Exception ex) { - Log.Error("Error while generating login report: " + ex); + _logger.Error("Error while generating login report: " + ex); throw; } } diff --git a/common/services/ASC.AuditTrail/BaseEvent.cs b/common/services/ASC.AuditTrail/BaseEvent.cs index deee1948a5..29994afe13 100644 --- a/common/services/ASC.AuditTrail/BaseEvent.cs +++ b/common/services/ASC.AuditTrail/BaseEvent.cs @@ -38,17 +38,13 @@ namespace ASC.AuditTrail public class BaseEvent { public int Id { get; set; } - public int TenantId { get; set; } - public Guid UserId { get; set; } - public bool Mobile { get; set; } - public IList<string> Description { get; set; } [Event("IpCol")] - public string IP { get; set; } + public string Ip { get; set; } [Event("BrowserCol")] public string Browser { get; set; } diff --git a/common/services/ASC.AuditTrail/LoginEvent.cs b/common/services/ASC.AuditTrail/LoginEvent.cs index 542a772ae1..bf95bd1139 100644 --- a/common/services/ASC.AuditTrail/LoginEvent.cs +++ b/common/services/ASC.AuditTrail/LoginEvent.cs @@ -31,7 +31,6 @@ namespace ASC.AuditTrail public class LoginEvent : BaseEvent { public string Login { get; set; } - public int Action { get; set; } } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/LoginEventsRepository.cs index fa829e8688..eb62f8d9e5 100644 --- a/common/services/ASC.AuditTrail/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/LoginEventsRepository.cs @@ -42,23 +42,21 @@ namespace ASC.AuditTrail.Data { [Scope] public class LoginEventsRepository - { - private UserFormatter UserFormatter { get; } - private AuditActionMapper AuditActionMapper { get; } - private MessagesContext MessagesContext { get => LazyMessagesContext.Value; } - private Lazy<MessagesContext> LazyMessagesContext { get; } + { + private MessagesContext MessagesContext => _lazyMessagesContext.Value; - public LoginEventsRepository(UserFormatter userFormatter, AuditActionMapper auditActionMapper, DbContextManager<MessagesContext> dbMessagesContext) - { - UserFormatter = userFormatter; - AuditActionMapper = auditActionMapper; - LazyMessagesContext = new Lazy<MessagesContext>(() => dbMessagesContext.Value); - } + private readonly UserFormatter _userFormatter; + private readonly AuditActionMapper _auditActionMapper; + private readonly Lazy<MessagesContext> _lazyMessagesContext; - private class Query + public LoginEventsRepository( + UserFormatter userFormatter, + AuditActionMapper auditActionMapper, + DbContextManager<MessagesContext> dbMessagesContext) { - public LoginEvents LoginEvents { get; set; } - public User User { get; set; } + _userFormatter = userFormatter; + _auditActionMapper = auditActionMapper; + _lazyMessagesContext = new Lazy<MessagesContext>(() => dbMessagesContext.Value); } public IEnumerable<LoginEvent> GetLast(int tenant, int chunk) @@ -68,7 +66,7 @@ namespace ASC.AuditTrail.Data from p in MessagesContext.Users.Where(p => b.UserId == p.Id).DefaultIfEmpty() where b.TenantId == tenant orderby b.Date descending - select new Query { LoginEvents = b, User = p }) + select new LoginEventQuery { LoginEvents = b, User = p }) .Take(chunk); return query.AsEnumerable().Select(ToLoginEvent).ToList(); @@ -83,7 +81,7 @@ namespace ASC.AuditTrail.Data where q.Date >= fromDate where q.Date <= to orderby q.Date descending - select new Query { LoginEvents = q, User = p }; + select new LoginEventQuery { LoginEvents = q, User = p }; return query.AsEnumerable().Select(ToLoginEvent).ToList(); } @@ -93,20 +91,17 @@ namespace ASC.AuditTrail.Data var query = MessagesContext.LoginEvents .Where(l => l.TenantId == tenant); - if (from.HasValue && to.HasValue) - { - query = query.Where(l => l.Date >= from & l.Date <= to); - } + if (from.HasValue && to.HasValue) query = query.Where(l => l.Date >= from & l.Date <= to); return query.Count(); } - private LoginEvent ToLoginEvent(Query query) + private LoginEvent ToLoginEvent(LoginEventQuery query) { var evt = new LoginEvent { Id = query.LoginEvents.Id, - IP = query.LoginEvents.Ip, + Ip = query.LoginEvents.Ip, Login = query.LoginEvents.Login, Browser = query.LoginEvents.Browser, Platform = query.LoginEvents.Platform, @@ -117,25 +112,31 @@ namespace ASC.AuditTrail.Data Action = query.LoginEvents.Action }; - if (query.LoginEvents.Description != null) - { + if (query.LoginEvents.Description != null) evt.Description = JsonConvert.DeserializeObject<IList<string>>( query.LoginEvents.Description, new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc - }); - } + }); + evt.UserName = (!string.IsNullOrEmpty(query.User?.FirstName) && !string.IsNullOrEmpty(query.User?.LastName)) - ? UserFormatter.GetUserName(query.User.FirstName, query.User.LastName) + ? _userFormatter.GetUserName(query.User.FirstName, query.User.LastName) : !string.IsNullOrWhiteSpace(evt.Login) ? evt.Login : evt.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : AuditReportResource.UnknownAccount; - evt.ActionText = AuditActionMapper.GetActionText(evt); + evt.ActionText = _auditActionMapper.GetActionText(evt); + return evt; - } + } + } + + public class LoginEventQuery + { + public LoginEvents LoginEvents { get; set; } + public User User { get; set; } } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs index d6d6be2612..2fde7b959c 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -39,15 +39,15 @@ namespace ASC.AuditTrail.Mappers [Singletone] public class AuditActionMapper { - private Dictionary<MessageAction, MessageMaps> Actions { get; } - private ILog Log { get; } + private readonly Dictionary<MessageAction, MessageMaps> _actions; + private readonly ILog _logger; public AuditActionMapper(IOptionsMonitor<ILog> options) { - Actions = new Dictionary<MessageAction, MessageMaps>(); - Log = options.CurrentValue; + _actions = new Dictionary<MessageAction, MessageMaps>(); + _logger = options.CurrentValue; - Actions = Actions + _actions = _actions .Union(LoginActionsMapper.GetMaps()) .Union(ProjectsActionsMapper.GetMaps()) .Union(CrmActionMapper.GetMaps()) @@ -61,15 +61,16 @@ namespace ASC.AuditTrail.Mappers public string GetActionText(AuditEvent evt) { var action = (MessageAction)evt.Action; - if (!Actions.ContainsKey(action)) + if (!_actions.ContainsKey(action)) { - Log.Error(string.Format("There is no action text for \"{0}\" type of event", action)); + _logger.Error(string.Format("There is no action text for \"{0}\" type of event", action)); + return string.Empty; } try { - var actionText = Actions[(MessageAction)evt.Action].GetActionText(); + var actionText = _actions[(MessageAction)evt.Action].GetActionText(); if (evt.Description == null || !evt.Description.Any()) return actionText; @@ -90,7 +91,7 @@ namespace ASC.AuditTrail.Mappers public string GetActionText(LoginEvent evt) { var action = (MessageAction)evt.Action; - if (!Actions.ContainsKey(action)) + if (!_actions.ContainsKey(action)) { //log.Error(string.Format("There is no action text for \"{0}\" type of event", action)); return string.Empty; @@ -98,7 +99,7 @@ namespace ASC.AuditTrail.Mappers try { - var actionText = Actions[(MessageAction)evt.Action].GetActionText(); + var actionText = _actions[(MessageAction)evt.Action].GetActionText(); if (evt.Description == null || !evt.Description.Any()) return actionText; @@ -117,31 +118,35 @@ namespace ASC.AuditTrail.Mappers public string GetActionTypeText(AuditEvent evt) { - var action = (MessageAction)evt.Action; - return !Actions.ContainsKey(action) + var action = (MessageAction)evt.Action; + + return !_actions.ContainsKey(action) ? string.Empty - : Actions[(MessageAction)evt.Action].GetActionTypeText(); + : _actions[(MessageAction)evt.Action].GetActionTypeText(); } public string GetProductText(AuditEvent evt) { - var action = (MessageAction)evt.Action; - return !Actions.ContainsKey(action) + var action = (MessageAction)evt.Action; + + return !_actions.ContainsKey(action) ? string.Empty - : Actions[(MessageAction)evt.Action].GetProduct(); + : _actions[(MessageAction)evt.Action].GetProduct(); } public string GetModuleText(AuditEvent evt) { - var action = (MessageAction)evt.Action; - return !Actions.ContainsKey(action) + var action = (MessageAction)evt.Action; + + return !_actions.ContainsKey(action) ? string.Empty - : Actions[(MessageAction)evt.Action].GetModule(); + : _actions[(MessageAction)evt.Action].GetModule(); } private string ToLimitedText(string text) { - if (text == null) return null; + if (text == null) return null; + return text.Length < 50 ? text : string.Format("{0}...", text.Substring(0, 47)); } } diff --git a/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs index 6f0a9170fe..27401f3b2b 100644 --- a/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs @@ -34,10 +34,9 @@ namespace ASC.AuditTrail.Mappers { internal class CrmActionMapper { - public static Dictionary<MessageAction, MessageMaps> GetMaps() - { - return new Dictionary<MessageAction, MessageMaps> - { + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { #region companies { @@ -1622,7 +1621,6 @@ namespace ASC.AuditTrail.Mappers }, #endregion - }; - } + }; } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs index 0189838e04..05c3cd6dd0 100644 --- a/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs @@ -33,19 +33,9 @@ namespace ASC.AuditTrail.Mappers { internal class DocumentsActionMapper { - public static Dictionary<MessageAction, MessageMaps> GetMaps() - { - return new Dictionary<MessageAction, MessageMaps> - { - { - MessageAction.FileCreated, new MessageMaps - { - ActionTypeTextResourceName = "CreateActionType", - ActionTextResourceName = "FileCreated", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { { MessageAction.FileRenamed, new MessageMaps { @@ -63,7 +53,7 @@ namespace ASC.AuditTrail.Mappers ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } - }, + }, { MessageAction.UserFileUpdated, new MessageMaps { @@ -424,7 +414,6 @@ namespace ASC.AuditTrail.Mappers ModuleResourceName = "FilesModule" } }, - }; - } + }; } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs index 0ad37f1fd2..877faf6fa1 100644 --- a/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs @@ -34,38 +34,36 @@ namespace ASC.AuditTrail.Mappers { internal class LoginActionsMapper { - public static Dictionary<MessageAction, MessageMaps> GetMaps() - { - return new Dictionary<MessageAction, MessageMaps> - { - {MessageAction.LoginSuccess, new MessageMaps {ActionTextResourceName = "LoginSuccess"}}, - {MessageAction.LoginSuccessViaSocialAccount, new MessageMaps {ActionTextResourceName = "LoginSuccessSocialAccount"}}, - {MessageAction.LoginSuccessViaSocialApp, new MessageMaps {ActionTextResourceName = "LoginSuccessSocialApp"}}, - {MessageAction.LoginSuccessViaSms, new MessageMaps {ActionTextResourceName = "LoginSuccessViaSms"}}, - {MessageAction.LoginSuccessViaApi, new MessageMaps {ActionTextResourceName = "LoginSuccessViaApi"}}, - {MessageAction.LoginSuccessViaApiSms, new MessageMaps {ActionTextResourceName = "LoginSuccessViaApiSms"}}, - {MessageAction.LoginSuccessViaApiTfa, new MessageMaps {ActionTextResourceName = "LoginSuccessViaApiTfa"}}, - {MessageAction.LoginSuccessViaApiSocialAccount, new MessageMaps {ActionTextResourceName = "LoginSuccessViaSocialAccount"}}, - {MessageAction.LoginSuccessViaSSO, new MessageMaps {ActionTextResourceName = "LoginSuccessViaSSO"}}, - {MessageAction.LoginSuccesViaTfaApp, new MessageMaps {ActionTextResourceName = "LoginSuccesViaTfaApp"}}, - {MessageAction.LoginFailInvalidCombination, new MessageMaps {ActionTextResourceName = "LoginFailInvalidCombination"}}, - {MessageAction.LoginFailSocialAccountNotFound, new MessageMaps {ActionTextResourceName = "LoginFailSocialAccountNotFound"}}, - {MessageAction.LoginFailDisabledProfile, new MessageMaps {ActionTextResourceName = "LoginFailDisabledProfile"}}, - {MessageAction.LoginFail, new MessageMaps {ActionTextResourceName = "LoginFail"}}, - {MessageAction.LoginFailViaSms, new MessageMaps {ActionTextResourceName = "LoginFailViaSms"}}, - {MessageAction.LoginFailViaApi, new MessageMaps {ActionTextResourceName = "LoginFailViaApi"}}, - {MessageAction.LoginFailViaApiSms, new MessageMaps {ActionTextResourceName = "LoginFailViaApiSms"}}, - {MessageAction.LoginFailViaApiTfa, new MessageMaps {ActionTextResourceName = "LoginFailViaApiTfa"}}, - {MessageAction.LoginFailViaApiSocialAccount, new MessageMaps {ActionTextResourceName = "LoginFailViaApiSocialAccount"}}, - {MessageAction.LoginFailViaTfaApp, new MessageMaps {ActionTextResourceName = "LoginFailViaTfaApp"}}, - {MessageAction.LoginFailIpSecurity, new MessageMaps {ActionTextResourceName = "LoginFailIpSecurity"}}, - {MessageAction.LoginFailViaSSO, new MessageMaps {ActionTextResourceName = "LoginFailViaSSO"}}, - {MessageAction.LoginFailBruteForce, new MessageMaps {ActionTextResourceName = "LoginFailBruteForce"}}, - {MessageAction.LoginFailRecaptcha, new MessageMaps {ActionTextResourceName = "LoginFailRecaptcha"}}, - {MessageAction.Logout, new MessageMaps {ActionTextResourceName = "Logout"}}, - {MessageAction.SessionStarted, new MessageMaps {ActionTextResourceName = "SessionStarted"}}, - {MessageAction.SessionCompleted, new MessageMaps {ActionTextResourceName = "SessionCompleted"}} - }; - } + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { + { MessageAction.LoginSuccess, new MessageMaps { ActionTextResourceName = "LoginSuccess"} }, + { MessageAction.LoginSuccessViaSocialAccount, new MessageMaps { ActionTextResourceName = "LoginSuccessSocialAccount"} }, + { MessageAction.LoginSuccessViaSocialApp, new MessageMaps { ActionTextResourceName = "LoginSuccessSocialApp"} }, + { MessageAction.LoginSuccessViaSms, new MessageMaps { ActionTextResourceName = "LoginSuccessViaSms"} }, + { MessageAction.LoginSuccessViaApi, new MessageMaps { ActionTextResourceName = "LoginSuccessViaApi"} }, + { MessageAction.LoginSuccessViaApiSms, new MessageMaps { ActionTextResourceName = "LoginSuccessViaApiSms"} }, + { MessageAction.LoginSuccessViaApiTfa, new MessageMaps { ActionTextResourceName = "LoginSuccessViaApiTfa"} }, + { MessageAction.LoginSuccessViaApiSocialAccount, new MessageMaps { ActionTextResourceName = "LoginSuccessViaSocialAccount"} }, + { MessageAction.LoginSuccessViaSSO, new MessageMaps { ActionTextResourceName = "LoginSuccessViaSSO"} }, + { MessageAction.LoginSuccesViaTfaApp, new MessageMaps { ActionTextResourceName = "LoginSuccesViaTfaApp"} }, + { MessageAction.LoginFailInvalidCombination, new MessageMaps { ActionTextResourceName = "LoginFailInvalidCombination" } }, + { MessageAction.LoginFailSocialAccountNotFound, new MessageMaps { ActionTextResourceName = "LoginFailSocialAccountNotFound" } }, + { MessageAction.LoginFailDisabledProfile, new MessageMaps { ActionTextResourceName = "LoginFailDisabledProfile" } }, + { MessageAction.LoginFail, new MessageMaps { ActionTextResourceName = "LoginFail" } }, + { MessageAction.LoginFailViaSms, new MessageMaps { ActionTextResourceName = "LoginFailViaSms" } }, + { MessageAction.LoginFailViaApi, new MessageMaps { ActionTextResourceName = "LoginFailViaApi" } }, + { MessageAction.LoginFailViaApiSms, new MessageMaps { ActionTextResourceName = "LoginFailViaApiSms" } }, + { MessageAction.LoginFailViaApiTfa, new MessageMaps { ActionTextResourceName = "LoginFailViaApiTfa" } }, + { MessageAction.LoginFailViaApiSocialAccount, new MessageMaps { ActionTextResourceName = "LoginFailViaApiSocialAccount" } }, + { MessageAction.LoginFailViaTfaApp, new MessageMaps { ActionTextResourceName = "LoginFailViaTfaApp" } }, + { MessageAction.LoginFailIpSecurity, new MessageMaps { ActionTextResourceName = "LoginFailIpSecurity" } }, + { MessageAction.LoginFailViaSSO, new MessageMaps { ActionTextResourceName = "LoginFailViaSSO"}}, + { MessageAction.LoginFailBruteForce, new MessageMaps { ActionTextResourceName = "LoginFailBruteForce" } }, + { MessageAction.LoginFailRecaptcha, new MessageMaps { ActionTextResourceName = "LoginFailRecaptcha" } }, + { MessageAction.Logout, new MessageMaps { ActionTextResourceName = "Logout" } }, + { MessageAction.SessionStarted, new MessageMaps { ActionTextResourceName = "SessionStarted" } }, + { MessageAction.SessionCompleted, new MessageMaps { ActionTextResourceName = "SessionCompleted" } } + }; } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs index 572e0644a1..6e4524f42d 100644 --- a/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs @@ -34,10 +34,9 @@ namespace ASC.AuditTrail.Mappers { internal class OthersActionsMapper { - public static Dictionary<MessageAction, MessageMaps> GetMaps() - { - return new Dictionary<MessageAction, MessageMaps> - { + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { { MessageAction.ContactAdminMailSent, new MessageMaps { @@ -46,7 +45,6 @@ namespace ASC.AuditTrail.Mappers ProductResourceName = "OthersProduct" } } - }; - } + }; } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs index a67feacb0d..286b6367e3 100644 --- a/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs @@ -34,171 +34,170 @@ namespace ASC.AuditTrail.Mappers { internal class PeopleActionMapper { - public static Dictionary<MessageAction, MessageMaps> GetMaps() - { - return new Dictionary<MessageAction, MessageMaps> - { + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { { MessageAction.UserCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "UserCreated", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.GuestCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "GuestCreated", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserCreatedViaInvite, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "UserCreatedViaInvite", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.GuestCreatedViaInvite, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "GuestCreatedViaInvite", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserActivated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserActivated", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.GuestActivated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "GuestActivated", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdated", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } - }, + } + }, { MessageAction.UserUpdatedMobileNumber, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdatedMobileNumber", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserUpdatedLanguage, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdatedLanguage", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserAddedAvatar, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserAddedAvatar", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserDeletedAvatar, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "UserDeletedAvatar", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserUpdatedAvatarThumbnails, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdatedAvatarThumbnails", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserLinkedSocialAccount, new MessageMaps - { + { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "UserLinkedSocialAccount", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserUnlinkedSocialAccount, new MessageMaps - { + { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "UserUnlinkedSocialAccount", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserSentActivationInstructions, new MessageMaps - { + { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "UserSentActivationInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserSentEmailChangeInstructions, new MessageMaps - { + { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "UserSentEmailInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserSentPasswordChangeInstructions, new MessageMaps - { + { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "UserSentPasswordInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserSentDeleteInstructions, new MessageMaps - { + { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "UserSentDeleteInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserUpdatedEmail, new MessageMaps @@ -211,149 +210,148 @@ namespace ASC.AuditTrail.Mappers }, { MessageAction.UserUpdatedPassword, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserUpdatedPassword", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "UserDeleted", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UsersUpdatedType, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UsersUpdatedType", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UsersUpdatedStatus, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UsersUpdatedStatus", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UsersSentActivationInstructions, new MessageMaps - { + { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "UsersSentActivationInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UsersDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "UsersDeleted", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.SentInviteInstructions, new MessageMaps - { + { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "SentInviteInstructions", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserImported, new MessageMaps - { + { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "UserImported", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.GuestImported, new MessageMaps - { + { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "GuestImported", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.GroupCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "GroupCreated", ProductResourceName = "PeopleProduct", ModuleResourceName = "GroupsModule" - } + } }, { MessageAction.GroupUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "GroupUpdated", ProductResourceName = "PeopleProduct", ModuleResourceName = "GroupsModule" - } + } }, { MessageAction.GroupDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "GroupDeleted", ProductResourceName = "PeopleProduct", ModuleResourceName = "GroupsModule" - } + } }, { MessageAction.UserDataReassigns, new MessageMaps - { + { ActionTypeTextResourceName = "ReassignsActionType", ActionTextResourceName = "UserDataReassigns", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserDataRemoving, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "UserDataRemoving", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserConnectedTfaApp, new MessageMaps - { + { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "UserTfaGenerateCodes", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } }, { MessageAction.UserDisconnectedTfaApp, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "UserTfaDisconnected", ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" - } + } } - }; - } + }; } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs index ac3de67f0f..97ba08b181 100644 --- a/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs @@ -33,74 +33,73 @@ namespace ASC.AuditTrail.Mappers { internal class ProjectsActionsMapper { - public static Dictionary<MessageAction, MessageMaps> GetMaps() - { - return new Dictionary<MessageAction, MessageMaps> - { + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { #region projects { MessageAction.ProjectCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ProjectCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectCreatedFromTemplate, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ProjectCreatedFromTemplate", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ProjectUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectUpdatedStatus, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ProjectUpdatedStatus", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectFollowed, new MessageMaps - { + { ActionTypeTextResourceName = "FollowActionType", ActionTextResourceName = "ProjectFollowed", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectUnfollowed, new MessageMaps - { + { ActionTypeTextResourceName = "UnfollowActionType", ActionTextResourceName = "ProjectUnfollowed", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ProjectDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, #endregion @@ -109,30 +108,30 @@ namespace ASC.AuditTrail.Mappers { MessageAction.ProjectDeletedMember, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ProjectDeletedMember", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectUpdatedTeam, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ProjectUpdatedTeam", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectUpdatedMemberRights, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "ProjectUpdatedMemberRights", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, #endregion @@ -141,48 +140,48 @@ namespace ASC.AuditTrail.Mappers { MessageAction.ProjectLinkedCompany, new MessageMaps - { + { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "ProjectLinkedCompany", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectUnlinkedCompany, new MessageMaps - { + { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "ProjectUnlinkedCompany", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectLinkedPerson, new MessageMaps - { + { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "ProjectLinkedPerson", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectUnlinkedPerson, new MessageMaps - { + { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "ProjectUnlinkedPerson", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, { MessageAction.ProjectLinkedContacts, new MessageMaps - { + { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "ProjectLinkedContacts", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, #endregion @@ -191,39 +190,39 @@ namespace ASC.AuditTrail.Mappers { MessageAction.MilestoneCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "MilestoneCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "MilestonesModule" - } + } }, { MessageAction.MilestoneUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "MilestoneUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "MilestonesModule" - } + } }, { MessageAction.MilestoneUpdatedStatus, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "MilestoneUpdatedStatus", ProductResourceName = "ProjectsProduct", ModuleResourceName = "MilestonesModule" - } + } }, { MessageAction.MilestoneDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "MilestoneDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "MilestonesModule" - } + } }, #endregion @@ -232,138 +231,138 @@ namespace ASC.AuditTrail.Mappers { MessageAction.TaskCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "TaskCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskCreatedFromDiscussion, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "TaskCreatedFromDiscussion", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskUpdatedStatus, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskUpdatedStatus", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskMovedToMilestone, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskMovedToMilestone", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskUnlinkedMilestone, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskUnlinkedMilestone", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskUpdatedFollowing, new MessageMaps - { + { ActionTypeTextResourceName = "FollowActionType", ActionTextResourceName = "TaskUpdatedFollowing", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskAttachedFiles, new MessageMaps - { + { ActionTypeTextResourceName = "AttachActionType", ActionTextResourceName = "TaskAttachedFiles", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskDetachedFile, new MessageMaps - { + { ActionTypeTextResourceName = "DetachActionType", ActionTextResourceName = "TaskDetachedFile", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TasksLinked, new MessageMaps - { + { ActionTypeTextResourceName = "LinkActionType", ActionTextResourceName = "TasksLinked", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TasksUnlinked, new MessageMaps - { + { ActionTypeTextResourceName = "UnlinkActionType", ActionTextResourceName = "TasksUnlinked", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "TaskDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskCommentCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "TaskCommentCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskCommentUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskCommentUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.TaskCommentDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "TaskCommentDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, #endregion @@ -372,39 +371,39 @@ namespace ASC.AuditTrail.Mappers { MessageAction.SubtaskCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "SubtaskCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.SubtaskUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "SubtaskUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.SubtaskUpdatedStatus, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "SubtaskUpdatedStatus", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, { MessageAction.SubtaskDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "SubtaskDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TasksModule" - } + } }, #endregion @@ -413,84 +412,84 @@ namespace ASC.AuditTrail.Mappers { MessageAction.DiscussionCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "DiscussionCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" - } + } }, { MessageAction.DiscussionUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DiscussionUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" - } + } }, { MessageAction.DiscussionUpdatedFollowing, new MessageMaps - { + { ActionTypeTextResourceName = "FollowActionType", ActionTextResourceName = "DiscussionUpdatedFollowing", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" - } + } }, { MessageAction.DiscussionAttachedFiles, new MessageMaps - { + { ActionTypeTextResourceName = "AttachActionType", ActionTextResourceName = "DiscussionAttachedFiles", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" - } + } }, { MessageAction.DiscussionDetachedFile, new MessageMaps - { + { ActionTypeTextResourceName = "DetachActionType", ActionTextResourceName = "DiscussionDetachedFile", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" - } + } }, { MessageAction.DiscussionDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "DiscussionDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" - } + } }, { MessageAction.DiscussionCommentCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "DiscussionCommentCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" - } + } }, { MessageAction.DiscussionCommentUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DiscussionCommentUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" - } + } }, { MessageAction.DiscussionCommentDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "DiscussionCommentDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "DiscussionsModule" - } + } }, #endregion @@ -499,39 +498,39 @@ namespace ASC.AuditTrail.Mappers { MessageAction.TaskTimeCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "TaskTimeCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TimeTrackingModule" - } + } }, { MessageAction.TaskTimeUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskTimeUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TimeTrackingModule" - } + } }, { MessageAction.TaskTimesUpdatedStatus, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TaskTimesUpdatedStatus", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TimeTrackingModule" - } + } }, { MessageAction.TaskTimesDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "TaskTimesDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "TimeTrackingModule" - } + } }, #endregion @@ -540,30 +539,30 @@ namespace ASC.AuditTrail.Mappers { MessageAction.ReportTemplateCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ReportTemplateCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ReportsModule" - } + } }, { MessageAction.ReportTemplateUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ReportTemplateUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ReportsModule" - } + } }, { MessageAction.ReportTemplateDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ReportTemplateDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ReportsModule" - } + } }, #endregion @@ -572,43 +571,42 @@ namespace ASC.AuditTrail.Mappers { MessageAction.ProjectTemplateCreated, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ProjectTemplateCreated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsSettingsModule" - } + } }, { MessageAction.ProjectTemplateUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ProjectTemplateUpdated", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsSettingsModule" - } + } }, { MessageAction.ProjectTemplateDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ProjectTemplateDeleted", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsSettingsModule" - } + } }, { MessageAction.ProjectsImportedFromBasecamp, new MessageMaps - { + { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "ProjectsImportedFromBasecamp", ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" - } + } }, #endregion - }; - } + }; } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs index 74904ef51f..e347d8ba7f 100644 --- a/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs @@ -33,452 +33,450 @@ namespace ASC.AuditTrail.Mappers { internal class SettingsActionsMapper { - public static Dictionary<MessageAction, MessageMaps> GetMaps() - { - return new Dictionary<MessageAction, MessageMaps> - { + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { { MessageAction.LanguageSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "LanguageSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.TimeZoneSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TimeZoneSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.DnsSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DnsSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.TrustedMailDomainSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TrustedMailDomainSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.PasswordStrengthSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PasswordStrengthSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.TwoFactorAuthenticationSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TwoFactorAuthenticationSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.TwoFactorAuthenticationDisabled, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TwoFactorAuthenticationSettingsDisabled", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.TwoFactorAuthenticationEnabledBySms, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TwoFactorAuthenticationSettingsEnabledBySms", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.TwoFactorAuthenticationEnabledByTfaApp, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TwoFactorAuthenticationSettingsEnabledByTfaApp", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.AdministratorMessageSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "AdministratorMessageSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.DefaultStartPageSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DefaultStartPageSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "GeneralModule" - } + } }, { MessageAction.ProductsListUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ProductsListUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.OwnerUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "OwnerChanged", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.AdministratorAdded, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "AdministratorAdded", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.UsersOpenedProductAccess, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "ProductAccessOpenedForUsers", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.GroupsOpenedProductAccess, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "ProductAccessOpenedForGroups", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.ProductAccessOpened, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "ProductAccessOpened", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.ProductAccessRestricted, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "ProductAccessRestricted", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.ProductAddedAdministrator, new MessageMaps - { + { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ProductAddedAdministrator", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.ProductDeletedAdministrator, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ProductDeletedAdministrator", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.AdministratorDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "AdministratorDeleted", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.AdministratorOpenedFullAccess, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "AdministratorOpenedFullAccess", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.GreetingSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "GreetingSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.TeamTemplateChanged, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "TeamTemplateChanged", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.ColorThemeChanged, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ColorThemeChanged", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.OwnerSentPortalDeactivationInstructions, new MessageMaps - { + { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "OwnerSentPortalDeactivationInstructions", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.OwnerSentPortalDeleteInstructions, new MessageMaps - { + { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "OwnerSentPortalDeleteInstructions", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.LoginHistoryReportDownloaded, new MessageMaps - { + { ActionTypeTextResourceName = "DownloadActionType", ActionTextResourceName = "LoginHistoryReportDownloaded", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.AuditTrailReportDownloaded, new MessageMaps - { + { ActionTypeTextResourceName = "DownloadActionType", ActionTextResourceName = "AuditTrailReportDownloaded", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.PortalDeactivated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PortalDeactivated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.PortalDeleted, new MessageMaps - { + { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "PortalDeleted", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.OwnerSentChangeOwnerInstructions, new MessageMaps - { + { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "OwnerSentChangeOwnerInstructions", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.SSOEnabled, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "SSOEnabled", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.SSODisabled, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "SSODisabled", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } - }, + } + }, { MessageAction.PortalAccessSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PortalAccessSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.DocumentServiceLocationSetting, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentServiceLocationSetting", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.AuthorizationKeysSetting, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "AuthorizationKeysSetting", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.FullTextSearchSetting, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FullTextSearchSetting", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.StartTransferSetting, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "StartTransferSetting", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.StartBackupSetting, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "StartBackupSetting", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.LicenseKeyUploaded, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "LicenseKeyUploaded", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.StartStorageEncryption, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "StartStorageEncryption", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.StartStorageDecryption, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "StartStorageDecryption", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.CookieSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CookieSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.MailServiceSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "MailServiceSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.CustomNavigationSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "CustomNavigationSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.AuditSettingsUpdated, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "AuditSettingsUpdated", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.PrivacyRoomEnable, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PrivacyRoomEnable", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } }, { MessageAction.PrivacyRoomDisable, new MessageMaps - { + { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "PrivacyRoomDisable", ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" - } + } } - }; - } + }; } } \ No newline at end of file From 200b8a02120fb7bc73e8913a4230c4595b75e3fb Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 12:11:19 +0300 Subject: [PATCH 104/167] AuditTrail: project reconstruction --- .../Attributes/EventAttribute.cs | 17 ++ .../Mappers/AuditActionMapper.cs | 3 +- .../ASC.AuditTrail/{ => Models}/AuditEvent.cs | 3 +- .../ASC.AuditTrail/Models/AuditEventQuery.cs | 10 + .../ASC.AuditTrail/{ => Models}/BaseEvent.cs | 22 +- .../ASC.AuditTrail/{ => Models}/LoginEvent.cs | 2 +- .../ASC.AuditTrail/Models/LoginEventQuery.cs | 11 + .../Models/Profiles/AuditEventProfile.cs | 7 + .../Models/Profiles/LoginEventProfile.cs | 14 + .../AuditEventsRepository.cs | 287 +++++++++--------- .../LoginEventsRepository.cs | 107 +++---- 11 files changed, 264 insertions(+), 219 deletions(-) create mode 100644 common/services/ASC.AuditTrail/Attributes/EventAttribute.cs rename common/services/ASC.AuditTrail/{ => Models}/AuditEvent.cs (96%) create mode 100644 common/services/ASC.AuditTrail/Models/AuditEventQuery.cs rename common/services/ASC.AuditTrail/{ => Models}/BaseEvent.cs (88%) rename common/services/ASC.AuditTrail/{ => Models}/LoginEvent.cs (98%) create mode 100644 common/services/ASC.AuditTrail/Models/LoginEventQuery.cs create mode 100644 common/services/ASC.AuditTrail/Models/Profiles/AuditEventProfile.cs create mode 100644 common/services/ASC.AuditTrail/Models/Profiles/LoginEventProfile.cs rename common/services/ASC.AuditTrail/{ => Repositories}/AuditEventsRepository.cs (92%) rename common/services/ASC.AuditTrail/{ => Repositories}/LoginEventsRepository.cs (98%) diff --git a/common/services/ASC.AuditTrail/Attributes/EventAttribute.cs b/common/services/ASC.AuditTrail/Attributes/EventAttribute.cs new file mode 100644 index 0000000000..a805f832fd --- /dev/null +++ b/common/services/ASC.AuditTrail/Attributes/EventAttribute.cs @@ -0,0 +1,17 @@ +using System; + +namespace ASC.AuditTrail.Attributes +{ + [AttributeUsage(AttributeTargets.Property)] + public class EventAttribute : Attribute + { + public string Resource { get; private set; } + public int Order { get; private set; } + + public EventAttribute(string resource, int order = 0) + { + Resource = resource; + Order = order; + } + } +} diff --git a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs index 2fde7b959c..bd76781d76 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -26,8 +26,9 @@ using System; using System.Collections.Generic; -using System.Linq; +using System.Linq; +using ASC.AuditTrail.Models; using ASC.Common; using ASC.Common.Logging; using ASC.MessagingSystem; diff --git a/common/services/ASC.AuditTrail/AuditEvent.cs b/common/services/ASC.AuditTrail/Models/AuditEvent.cs similarity index 96% rename from common/services/ASC.AuditTrail/AuditEvent.cs rename to common/services/ASC.AuditTrail/Models/AuditEvent.cs index 27b1910bd1..f0bf43361f 100644 --- a/common/services/ASC.AuditTrail/AuditEvent.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEvent.cs @@ -25,8 +25,9 @@ using ASC.MessagingSystem; +using ASC.AuditTrail.Attributes; -namespace ASC.AuditTrail +namespace ASC.AuditTrail.Models { public class AuditEvent : BaseEvent { diff --git a/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs b/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs new file mode 100644 index 0000000000..766d771bed --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs @@ -0,0 +1,10 @@ +using ASC.Core.Common.EF; + +namespace ASC.AuditTrail.Models +{ + public class AuditEventQuery + { + public Core.Common.EF.Model.AuditEvent AuditEvent { get; set; } + public User User { get; set; } + } +} diff --git a/common/services/ASC.AuditTrail/BaseEvent.cs b/common/services/ASC.AuditTrail/Models/BaseEvent.cs similarity index 88% rename from common/services/ASC.AuditTrail/BaseEvent.cs rename to common/services/ASC.AuditTrail/Models/BaseEvent.cs index 29994afe13..98f8e441ba 100644 --- a/common/services/ASC.AuditTrail/BaseEvent.cs +++ b/common/services/ASC.AuditTrail/Models/BaseEvent.cs @@ -29,11 +29,13 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Reflection; - +using System.Reflection; + +using ASC.AuditTrail.Attributes; + using CsvHelper.Configuration; -namespace ASC.AuditTrail +namespace ASC.AuditTrail.Models { public class BaseEvent { @@ -82,18 +84,4 @@ namespace ASC.AuditTrail } } } - - [AttributeUsage(AttributeTargets.Property)] - internal class EventAttribute : Attribute - { - public string Resource { get; private set; } - - public int Order { get; private set; } - - public EventAttribute(string resource, int order = 0) - { - Resource = resource; - Order = order; - } - } } diff --git a/common/services/ASC.AuditTrail/LoginEvent.cs b/common/services/ASC.AuditTrail/Models/LoginEvent.cs similarity index 98% rename from common/services/ASC.AuditTrail/LoginEvent.cs rename to common/services/ASC.AuditTrail/Models/LoginEvent.cs index bf95bd1139..0529014c02 100644 --- a/common/services/ASC.AuditTrail/LoginEvent.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEvent.cs @@ -26,7 +26,7 @@ -namespace ASC.AuditTrail +namespace ASC.AuditTrail.Models { public class LoginEvent : BaseEvent { diff --git a/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs b/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs new file mode 100644 index 0000000000..778d35e93b --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs @@ -0,0 +1,11 @@ +using ASC.Core.Common.EF; +using ASC.Core.Common.EF.Model; + +namespace ASC.AuditTrail.Models +{ + public class LoginEventQuery + { + public LoginEvents LoginEvents { get; set; } + public User User { get; set; } + } +} diff --git a/common/services/ASC.AuditTrail/Models/Profiles/AuditEventProfile.cs b/common/services/ASC.AuditTrail/Models/Profiles/AuditEventProfile.cs new file mode 100644 index 0000000000..6f6a379df3 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Profiles/AuditEventProfile.cs @@ -0,0 +1,7 @@ +namespace ASC.AuditTrail.Models.Profiles +{ + public class AuditEventProfile + { + + } +} diff --git a/common/services/ASC.AuditTrail/Models/Profiles/LoginEventProfile.cs b/common/services/ASC.AuditTrail/Models/Profiles/LoginEventProfile.cs new file mode 100644 index 0000000000..90970bf863 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Profiles/LoginEventProfile.cs @@ -0,0 +1,14 @@ +using ASC.AuditTrail.Data; + +using AutoMapper; + +namespace ASC.AuditTrail.Models.Profiles +{ + public class LoginEventProfile : Profile + { + public LoginEventProfile() + { + CreateMap<LoginEvent, LoginEventQuery>(); + } + } +} diff --git a/common/services/ASC.AuditTrail/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs similarity index 92% rename from common/services/ASC.AuditTrail/AuditEventsRepository.cs rename to common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs index 877bde344c..0f6076f5ff 100644 --- a/common/services/ASC.AuditTrail/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs @@ -1,147 +1,142 @@ -/* - * - * (c) Copyright Ascensio System Limited 2010-2018 - * - * This program is freeware. You can redistribute it and/or modify it under the terms of the GNU - * General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html). - * In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that - * Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights. - * - * THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR - * FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html - * - * You can contact Ascensio System SIA by email at sales@onlyoffice.com - * - * The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display - * Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3. - * - * Pursuant to Section 7 � 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains - * relevant author attributions when distributing the software. If the display of the logo in its graphic - * form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE" - * in every copy of the program you distribute. - * Pursuant to Section 7 � 3(e) we decline to grant you any rights under trademark law for use of our trademarks. - * -*/ - - -using System; -using System.Collections.Generic; -using System.Linq; - -using ASC.AuditTrail.Mappers; -using ASC.Common; -using ASC.Core.Common.EF; -using ASC.Core.Common.EF.Context; -using ASC.Core.Users; -using ASC.MessagingSystem; - -using Newtonsoft.Json; - -namespace ASC.AuditTrail -{ - [Scope] - public class AuditEventsRepository - { - private AuditTrailContext AuditTrailContext => _lazyAuditTrailContext.Value; - - private readonly MessageTarget _messageTarget; - private readonly UserFormatter _userFormatter; - private readonly Lazy<AuditTrailContext> _lazyAuditTrailContext; - private readonly AuditActionMapper _auditActionMapper; - - public AuditEventsRepository( - MessageTarget messageTarget, - UserFormatter userFormatter, - DbContextManager<AuditTrailContext> dbContextManager, - AuditActionMapper auditActionMapper) - { - _messageTarget = messageTarget; - _userFormatter = userFormatter; - _lazyAuditTrailContext = new Lazy<AuditTrailContext>(() => dbContextManager.Value ); - _auditActionMapper = auditActionMapper; - } - - public IEnumerable<AuditEvent> GetLast(int tenant, int chunk) => Get(tenant, null, null, chunk); - - public IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) => Get(tenant, from, to, null); - - private IEnumerable<AuditEvent> Get(int tenant, DateTime? fromDate, DateTime? to, int? limit) - { - var query = - from q in AuditTrailContext.AuditEvents - from p in AuditTrailContext.Users.Where(p => q.UserId == p.Id).DefaultIfEmpty() - where q.TenantId == tenant - orderby q.Date descending - select new Query { AuditEvent = q, User = p }; - - if (fromDate.HasValue && to.HasValue) - query = query.Where(q => q.AuditEvent.Date >= fromDate & q.AuditEvent.Date <= to); - - if (limit.HasValue) query = query.Take((int)limit); - - return query.AsEnumerable().Select(ToAuditEvent).ToList(); - } - - public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) - { - IQueryable<Core.Common.EF.Model.AuditEvent> query = AuditTrailContext.AuditEvents - .Where(a => a.TenantId == tenant) - .OrderByDescending(a => a.Date); - - if (from.HasValue && to.HasValue) - query = query.Where(a => a.Date >= from & a.Date <= to); - - return query.Count(); - } - - private AuditEvent ToAuditEvent(Query query) - { - try - { - var evt = new AuditEvent - { - Id = query.AuditEvent.Id, - Ip = query.AuditEvent.Ip, - Initiator = query.AuditEvent.Initiator, - Browser = query.AuditEvent.Browser, - Platform = query.AuditEvent.Platform, - Date = query.AuditEvent.Date, - TenantId = query.AuditEvent.TenantId, - UserId = query.AuditEvent.UserId, - Page = query.AuditEvent.Page, - Action = query.AuditEvent.Action - }; - - if (query.AuditEvent.Description != null) - { - evt.Description = JsonConvert.DeserializeObject<IList<string>>( - Convert.ToString(query.AuditEvent.Description), - new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); - } - - evt.Target = _messageTarget.Parse(query.AuditEvent.Target); - - evt.UserName = (query.User.FirstName != null && query.User.LastName != null) ? _userFormatter.GetUserName(query.User.FirstName, query.User.LastName) : - evt.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : - evt.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : - evt.Initiator ?? AuditReportResource.UnknownAccount; - - evt.ActionText = _auditActionMapper.GetActionText(evt); - evt.ActionTypeText = _auditActionMapper.GetActionTypeText(evt); - evt.Product = _auditActionMapper.GetProductText(evt); - evt.Module = _auditActionMapper.GetModuleText(evt); - - return evt; - } - catch (Exception) { } - - return null; - } - - private class Query - { - public Core.Common.EF.Model.AuditEvent AuditEvent { get; set; } - public User User { get; set; } - } - } +/* + * + * (c) Copyright Ascensio System Limited 2010-2018 + * + * This program is freeware. You can redistribute it and/or modify it under the terms of the GNU + * General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html). + * In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that + * Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights. + * + * THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR + * FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html + * + * You can contact Ascensio System SIA by email at sales@onlyoffice.com + * + * The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display + * Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3. + * + * Pursuant to Section 7 � 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains + * relevant author attributions when distributing the software. If the display of the logo in its graphic + * form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE" + * in every copy of the program you distribute. + * Pursuant to Section 7 � 3(e) we decline to grant you any rights under trademark law for use of our trademarks. + * +*/ + + +using System; +using System.Collections.Generic; +using System.Linq; + +using ASC.AuditTrail.Mappers; +using ASC.AuditTrail.Models; +using ASC.Common; +using ASC.Core.Common.EF; +using ASC.Core.Common.EF.Context; +using ASC.Core.Users; +using ASC.MessagingSystem; + +using Newtonsoft.Json; + +namespace ASC.AuditTrail.Repositories +{ + [Scope] + public class AuditEventsRepository + { + private AuditTrailContext AuditTrailContext => _lazyAuditTrailContext.Value; + + private readonly MessageTarget _messageTarget; + private readonly UserFormatter _userFormatter; + private readonly Lazy<AuditTrailContext> _lazyAuditTrailContext; + private readonly AuditActionMapper _auditActionMapper; + + public AuditEventsRepository( + MessageTarget messageTarget, + UserFormatter userFormatter, + DbContextManager<AuditTrailContext> dbContextManager, + AuditActionMapper auditActionMapper) + { + _messageTarget = messageTarget; + _userFormatter = userFormatter; + _lazyAuditTrailContext = new Lazy<AuditTrailContext>(() => dbContextManager.Value ); + _auditActionMapper = auditActionMapper; + } + + public IEnumerable<AuditEvent> GetLast(int tenant, int chunk) => Get(tenant, null, null, chunk); + + public IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) => Get(tenant, from, to, null); + + private IEnumerable<AuditEvent> Get(int tenant, DateTime? fromDate, DateTime? to, int? limit) + { + var query = + from q in AuditTrailContext.AuditEvents + from p in AuditTrailContext.Users.Where(p => q.UserId == p.Id).DefaultIfEmpty() + where q.TenantId == tenant + orderby q.Date descending + select new AuditEventQuery { AuditEvent = q, User = p }; + + if (fromDate.HasValue && to.HasValue) + query = query.Where(q => q.AuditEvent.Date >= fromDate & q.AuditEvent.Date <= to); + + if (limit.HasValue) query = query.Take((int)limit); + + return query.AsEnumerable().Select(ToAuditEvent).ToList(); + } + + public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) + { + IQueryable<Core.Common.EF.Model.AuditEvent> query = AuditTrailContext.AuditEvents + .Where(a => a.TenantId == tenant) + .OrderByDescending(a => a.Date); + + if (from.HasValue && to.HasValue) + query = query.Where(a => a.Date >= from & a.Date <= to); + + return query.Count(); + } + + private AuditEvent ToAuditEvent(AuditEventQuery query) + { + try + { + var evt = new AuditEvent + { + Id = query.AuditEvent.Id, + Ip = query.AuditEvent.Ip, + Initiator = query.AuditEvent.Initiator, + Browser = query.AuditEvent.Browser, + Platform = query.AuditEvent.Platform, + Date = query.AuditEvent.Date, + TenantId = query.AuditEvent.TenantId, + UserId = query.AuditEvent.UserId, + Page = query.AuditEvent.Page, + Action = query.AuditEvent.Action + }; + + if (query.AuditEvent.Description != null) + { + evt.Description = JsonConvert.DeserializeObject<IList<string>>( + Convert.ToString(query.AuditEvent.Description), + new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); + } + + evt.Target = _messageTarget.Parse(query.AuditEvent.Target); + + evt.UserName = (query.User.FirstName != null && query.User.LastName != null) ? _userFormatter.GetUserName(query.User.FirstName, query.User.LastName) : + evt.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : + evt.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : + evt.Initiator ?? AuditReportResource.UnknownAccount; + + evt.ActionText = _auditActionMapper.GetActionText(evt); + evt.ActionTypeText = _auditActionMapper.GetActionTypeText(evt); + evt.Product = _auditActionMapper.GetProductText(evt); + evt.Module = _auditActionMapper.GetModuleText(evt); + + return evt; + } + catch (Exception) { } + + return null; + } + } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs similarity index 98% rename from common/services/ASC.AuditTrail/LoginEventsRepository.cs rename to common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs index eb62f8d9e5..b9fe4dac71 100644 --- a/common/services/ASC.AuditTrail/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs @@ -28,59 +28,60 @@ using System; using System.Collections.Generic; using System.Linq; - + using ASC.AuditTrail.Mappers; +using ASC.AuditTrail.Models; using ASC.Common; using ASC.Core.Common.EF; using ASC.Core.Common.EF.Context; using ASC.Core.Common.EF.Model; using ASC.Core.Users; - + using Newtonsoft.Json; -namespace ASC.AuditTrail.Data -{ +namespace ASC.AuditTrail.Data.Repositories +{ [Scope] public class LoginEventsRepository - { - private MessagesContext MessagesContext => _lazyMessagesContext.Value; + { + private MessagesContext MessagesContext => _lazyMessagesContext.Value; - private readonly UserFormatter _userFormatter; - private readonly AuditActionMapper _auditActionMapper; + private readonly UserFormatter _userFormatter; + private readonly AuditActionMapper _auditActionMapper; private readonly Lazy<MessagesContext> _lazyMessagesContext; - public LoginEventsRepository( - UserFormatter userFormatter, - AuditActionMapper auditActionMapper, + public LoginEventsRepository( + UserFormatter userFormatter, + AuditActionMapper auditActionMapper, DbContextManager<MessagesContext> dbMessagesContext) { _userFormatter = userFormatter; - _auditActionMapper = auditActionMapper; + _auditActionMapper = auditActionMapper; _lazyMessagesContext = new Lazy<MessagesContext>(() => dbMessagesContext.Value); } public IEnumerable<LoginEvent> GetLast(int tenant, int chunk) - { - var query = - (from b in MessagesContext.LoginEvents - from p in MessagesContext.Users.Where(p => b.UserId == p.Id).DefaultIfEmpty() - where b.TenantId == tenant - orderby b.Date descending - select new LoginEventQuery { LoginEvents = b, User = p }) - .Take(chunk); - + { + var query = + (from b in MessagesContext.LoginEvents + from p in MessagesContext.Users.Where(p => b.UserId == p.Id).DefaultIfEmpty() + where b.TenantId == tenant + orderby b.Date descending + select new LoginEventQuery { LoginEvents = b, User = p }) + .Take(chunk); + return query.AsEnumerable().Select(ToLoginEvent).ToList(); } public IEnumerable<LoginEvent> Get(int tenant, DateTime fromDate, DateTime to) { - var query = - from q in MessagesContext.LoginEvents - from p in MessagesContext.Users.Where(p => q.UserId == p.Id).DefaultIfEmpty() - where q.TenantId == tenant - where q.Date >= fromDate - where q.Date <= to - orderby q.Date descending + var query = + from q in MessagesContext.LoginEvents + from p in MessagesContext.Users.Where(p => q.UserId == p.Id).DefaultIfEmpty() + where q.TenantId == tenant + where q.Date >= fromDate + where q.Date <= to + orderby q.Date descending select new LoginEventQuery { LoginEvents = q, User = p }; return query.AsEnumerable().Select(ToLoginEvent).ToList(); @@ -98,27 +99,27 @@ namespace ASC.AuditTrail.Data private LoginEvent ToLoginEvent(LoginEventQuery query) { - var evt = new LoginEvent - { - Id = query.LoginEvents.Id, - Ip = query.LoginEvents.Ip, - Login = query.LoginEvents.Login, - Browser = query.LoginEvents.Browser, - Platform = query.LoginEvents.Platform, - Date = query.LoginEvents.Date, - TenantId = query.LoginEvents.TenantId, - UserId = query.LoginEvents.UserId, - Page = query.LoginEvents.Page, - Action = query.LoginEvents.Action + var evt = new LoginEvent + { + Id = query.LoginEvents.Id, + Ip = query.LoginEvents.Ip, + Login = query.LoginEvents.Login, + Browser = query.LoginEvents.Browser, + Platform = query.LoginEvents.Platform, + Date = query.LoginEvents.Date, + TenantId = query.LoginEvents.TenantId, + UserId = query.LoginEvents.UserId, + Page = query.LoginEvents.Page, + Action = query.LoginEvents.Action }; - if (query.LoginEvents.Description != null) + if (query.LoginEvents.Description != null) evt.Description = JsonConvert.DeserializeObject<IList<string>>( query.LoginEvents.Description, - new JsonSerializerSettings - { - DateTimeZoneHandling = DateTimeZoneHandling.Utc - }); + new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.Utc + }); evt.UserName = (!string.IsNullOrEmpty(query.User?.FirstName) && !string.IsNullOrEmpty(query.User?.LastName)) ? _userFormatter.GetUserName(query.User.FirstName, query.User.LastName) @@ -128,15 +129,15 @@ namespace ASC.AuditTrail.Data ? AuditReportResource.GuestAccount : AuditReportResource.UnknownAccount; - evt.ActionText = _auditActionMapper.GetActionText(evt); - + evt.ActionText = _auditActionMapper.GetActionText(evt); + return evt; } - } - - public class LoginEventQuery - { - public LoginEvents LoginEvents { get; set; } - public User User { get; set; } + } + + public class LoginEventQuery + { + public LoginEvents LoginEvents { get; set; } + public User User { get; set; } } } \ No newline at end of file From 6cb8f0a0ec14ce42ba50ec298fd9b746f35e748d Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 13:21:26 +0300 Subject: [PATCH 105/167] AuditTrail: add mapping --- .../Mapping/Profiles/AuditEventProfile.cs | 29 ++++++++ .../Mapping/Profiles/LoginEventProfile.cs | 26 +++++++ .../Resolvers/ActionTextValueResolver.cs | 30 +++++++++ .../Resolvers/ActionTypeTextValueResolver.cs | 27 ++++++++ .../Resolvers/DescriptionValueResolver.cs | 30 +++++++++ .../Mapping/Resolvers/ModuleValueResolver.cs | 16 +++++ .../Mapping/Resolvers/ProductValueResolver.cs | 17 +++++ .../Mapping/Resolvers/TargetValueResolver.cs | 16 +++++ .../Resolvers/UserNameValueResolver.cs | 35 ++++++++++ .../Models/Profiles/AuditEventProfile.cs | 7 -- .../Models/Profiles/LoginEventProfile.cs | 14 ---- .../Repositories/AuditEventsRepository.cs | 67 ++----------------- .../Repositories/LoginEventsRepository.cs | 63 ++--------------- 13 files changed, 240 insertions(+), 137 deletions(-) create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Profiles/AuditEventProfile.cs create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Profiles/LoginEventProfile.cs create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTextValueResolver.cs create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTypeTextValueResolver.cs create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/DescriptionValueResolver.cs create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ModuleValueResolver.cs create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ProductValueResolver.cs create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/TargetValueResolver.cs create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/UserNameValueResolver.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Profiles/AuditEventProfile.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Profiles/LoginEventProfile.cs diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Profiles/AuditEventProfile.cs b/common/services/ASC.AuditTrail/Models/Mapping/Profiles/AuditEventProfile.cs new file mode 100644 index 0000000000..ec83f3fc29 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/Profiles/AuditEventProfile.cs @@ -0,0 +1,29 @@ +using ASC.AuditTrail.Models.Mapping.Resolvers; +using ASC.Common.Mapping; + +namespace ASC.AuditTrail.Models.Profiles +{ + public class AuditEventProfile : MappingProfile + { + public AuditEventProfile() + { + CreateMap<AuditEventQuery, AuditEvent>() + .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.AuditEvent.Id)) + .ForMember(dest => dest.Ip, opt => opt.MapFrom(src => src.AuditEvent.Ip)) + .ForMember(dest => dest.Initiator, opt => opt.MapFrom(src => src.AuditEvent.Initiator)) + .ForMember(dest => dest.Browser, opt => opt.MapFrom(src => src.AuditEvent.Browser)) + .ForMember(dest => dest.Platform, opt => opt.MapFrom(src => src.AuditEvent.Platform)) + .ForMember(dest => dest.Date, opt => opt.MapFrom(src => src.AuditEvent.Date)) + .ForMember(dest => dest.TenantId, opt => opt.MapFrom(src => src.AuditEvent.TenantId)) + .ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.AuditEvent.UserId)) + .ForMember(dest => dest.Page, opt => opt.MapFrom(src => src.AuditEvent.Page)) + .ForMember(dest => dest.Action, opt => opt.MapFrom(src => src.AuditEvent.Action)) + .ForMember(dest => dest.Description, opt => opt.MapFrom<AuditEventDescriptionValueResolver>()) + .ForMember(dest => dest.UserName, opt => opt.MapFrom<AuditEventUserNameValueResolver>()) + .ForMember(dest => dest.ActionText, opt => opt.MapFrom<AuditEventActionTextValueResolver>()) + .ForMember(dest => dest.ActionTypeText, opt => opt.MapFrom<AuditEventActionTypeValueResolver>()) + .ForMember(dest => dest.Product, opt => opt.MapFrom<ProductValueResolver>()) + .ForMember(dest => dest.Module, opt => opt.MapFrom<ModuleValueResolver>()); + } + } +} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Profiles/LoginEventProfile.cs b/common/services/ASC.AuditTrail/Models/Mapping/Profiles/LoginEventProfile.cs new file mode 100644 index 0000000000..3940aa3982 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/Profiles/LoginEventProfile.cs @@ -0,0 +1,26 @@ +using ASC.AuditTrail.Models.Mapping.Resolvers; +using ASC.Common.Mapping; + +namespace ASC.AuditTrail.Models.Mapping.Profiles +{ + public class LoginEventProfile : MappingProfile + { + public LoginEventProfile() + { + CreateMap<LoginEventQuery, LoginEvent>() + .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.LoginEvents.Id)) + .ForMember(dest => dest.Ip, opt => opt.MapFrom(src => src.LoginEvents.Ip)) + .ForMember(dest => dest.Login, opt => opt.MapFrom(src => src.LoginEvents.Login)) + .ForMember(dest => dest.Browser, opt => opt.MapFrom(src => src.LoginEvents.Browser)) + .ForMember(dest => dest.Platform, opt => opt.MapFrom(src => src.LoginEvents.Platform)) + .ForMember(dest => dest.Date, opt => opt.MapFrom(src => src.LoginEvents.Date)) + .ForMember(dest => dest.TenantId, opt => opt.MapFrom(src => src.LoginEvents.TenantId)) + .ForMember(dest => dest.Page, opt => opt.MapFrom(src => src.LoginEvents.Page)) + .ForMember(dest => dest.Action, opt => opt.MapFrom(src => src.LoginEvents.Action)) + .ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.LoginEvents.UserId)) + .ForMember(dest => dest.Description, opt => opt.MapFrom<LoginEventDescriptionValueResolver>()) + .ForMember(dest => dest.UserName, opt => opt.MapFrom<LoginEventUserNameValueResolver>()) + .ForMember(dest => dest.ActionText, opt => opt.MapFrom<ActionTextValueResolver>()); + } + } +} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTextValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTextValueResolver.cs new file mode 100644 index 0000000000..63772a83d9 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTextValueResolver.cs @@ -0,0 +1,30 @@ +using ASC.AuditTrail.Mappers; + +using AutoMapper; + +namespace ASC.AuditTrail.Models.Mapping.Resolvers +{ + public class ActionTextValueResolver : IValueResolver<LoginEventQuery, LoginEvent, string> + { + private readonly AuditActionMapper _actionMapper; + + public ActionTextValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; + + public string Resolve(LoginEventQuery source, LoginEvent destination, string destMember, ResolutionContext context) + { + return _actionMapper.GetActionText(destination); + } + } + + public class AuditEventActionTextValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> + { + private readonly AuditActionMapper _actionMapper; + + public AuditEventActionTextValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; + + public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) + { + return _actionMapper.GetActionText(destination); + } + } +} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTypeTextValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTypeTextValueResolver.cs new file mode 100644 index 0000000000..95e6f3c1e9 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTypeTextValueResolver.cs @@ -0,0 +1,27 @@ + +using ASC.AuditTrail.Mappers; + +using AutoMapper; + +namespace ASC.AuditTrail.Models.Mapping.Resolvers +{ + public class LoginEventActionTypeTextValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> + { + private readonly AuditActionMapper _actionMapper; + + public LoginEventActionTypeTextValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; + + public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) => + _actionMapper.GetActionTypeText(destination); + } + + public class AuditEventActionTypeValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> + { + private readonly AuditActionMapper _actionMapper; + + public AuditEventActionTypeValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; + + public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) => + _actionMapper.GetActionTypeText(destination); + } +} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/DescriptionValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/DescriptionValueResolver.cs new file mode 100644 index 0000000000..f3d446e5a2 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/DescriptionValueResolver.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; + +using AutoMapper; + +using Newtonsoft.Json; + +namespace ASC.AuditTrail.Models.Mapping.Resolvers +{ + public class LoginEventDescriptionValueResolver : IValueResolver<LoginEventQuery, LoginEvent, IList<string>> + { + public IList<string> Resolve(LoginEventQuery source, LoginEvent destination, IList<string> destMember, ResolutionContext context) + { + if (source.LoginEvents.Description == null) return null; + + return JsonConvert.DeserializeObject<IList<string>>(source.LoginEvents.Description, + new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); + } + } + + public class AuditEventDescriptionValueResolver : IValueResolver<AuditEventQuery, AuditEvent, IList<string>> + { + public IList<string> Resolve(AuditEventQuery source, AuditEvent destination, IList<string> destMember, ResolutionContext context) + { + if (source.AuditEvent.Description == null) return null; + + return JsonConvert.DeserializeObject<IList<string>>(source.AuditEvent.Description, + new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); + } + } +} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ModuleValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ModuleValueResolver.cs new file mode 100644 index 0000000000..290ec1721c --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ModuleValueResolver.cs @@ -0,0 +1,16 @@ +using ASC.AuditTrail.Mappers; + +using AutoMapper; + +namespace ASC.AuditTrail.Models.Mapping.Resolvers +{ + public class ModuleValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> + { + private readonly AuditActionMapper _actionMapper; + + public ModuleValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; + + public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) => + _actionMapper.GetModuleText(destination); + } +} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ProductValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ProductValueResolver.cs new file mode 100644 index 0000000000..d6afe4ed24 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ProductValueResolver.cs @@ -0,0 +1,17 @@ + +using ASC.AuditTrail.Mappers; + +using AutoMapper; + +namespace ASC.AuditTrail.Models.Mapping.Resolvers +{ + public class ProductValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> + { + private readonly AuditActionMapper _actionMapper; + + public ProductValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; + + public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) => + _actionMapper.GetProductText(destination); + } +} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/TargetValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/TargetValueResolver.cs new file mode 100644 index 0000000000..65153b6b16 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/TargetValueResolver.cs @@ -0,0 +1,16 @@ +using ASC.MessagingSystem; + +using AutoMapper; + +namespace ASC.AuditTrail.Models.Mapping.Resolvers +{ + public class TargetValueResolver : IValueResolver<AuditEventQuery, AuditEvent, MessageTarget> + { + private readonly MessageTarget _target; + + public TargetValueResolver(MessageTarget messageTarget) => _target = messageTarget; + + public MessageTarget Resolve(AuditEventQuery source, AuditEvent destination, MessageTarget destMember, ResolutionContext context) => + _target.Parse(source.AuditEvent.Target); + } +} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/UserNameValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/UserNameValueResolver.cs new file mode 100644 index 0000000000..17341ec4f1 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/UserNameValueResolver.cs @@ -0,0 +1,35 @@ +using ASC.Core.Users; + +using AutoMapper; + +namespace ASC.AuditTrail.Models.Mapping.Resolvers +{ + public class LoginEventUserNameValueResolver : IValueResolver<LoginEventQuery, LoginEvent, string> + { + private readonly UserFormatter _formatter; + + public LoginEventUserNameValueResolver(UserFormatter userFormatter) => _formatter = userFormatter; + + public string Resolve(LoginEventQuery source, LoginEvent destination, string destMember, ResolutionContext context) => + (!string.IsNullOrEmpty(source.User?.FirstName) && !string.IsNullOrEmpty(source.User?.LastName)) + ? _formatter.GetUserName(source.User.FirstName, source.User.LastName) + : !string.IsNullOrWhiteSpace(source.LoginEvents.Login) + ? source.LoginEvents.Login + : source.LoginEvents.UserId == Core.Configuration.Constants.Guest.ID + ? AuditReportResource.GuestAccount + : AuditReportResource.UnknownAccount; + } + + public class AuditEventUserNameValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> + { + private readonly UserFormatter _formatter; + + public AuditEventUserNameValueResolver(UserFormatter userFormatter) => _formatter = userFormatter; + + public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) => + (source.User.FirstName != null && source.User.LastName != null) ? _formatter.GetUserName(source.User.FirstName, source.User.LastName) : + source.AuditEvent.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : + source.AuditEvent.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : + source.AuditEvent.Initiator ?? AuditReportResource.UnknownAccount; + } +} diff --git a/common/services/ASC.AuditTrail/Models/Profiles/AuditEventProfile.cs b/common/services/ASC.AuditTrail/Models/Profiles/AuditEventProfile.cs deleted file mode 100644 index 6f6a379df3..0000000000 --- a/common/services/ASC.AuditTrail/Models/Profiles/AuditEventProfile.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ASC.AuditTrail.Models.Profiles -{ - public class AuditEventProfile - { - - } -} diff --git a/common/services/ASC.AuditTrail/Models/Profiles/LoginEventProfile.cs b/common/services/ASC.AuditTrail/Models/Profiles/LoginEventProfile.cs deleted file mode 100644 index 90970bf863..0000000000 --- a/common/services/ASC.AuditTrail/Models/Profiles/LoginEventProfile.cs +++ /dev/null @@ -1,14 +0,0 @@ -using ASC.AuditTrail.Data; - -using AutoMapper; - -namespace ASC.AuditTrail.Models.Profiles -{ - public class LoginEventProfile : Profile - { - public LoginEventProfile() - { - CreateMap<LoginEvent, LoginEventQuery>(); - } - } -} diff --git a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs index 0f6076f5ff..7924193de8 100644 --- a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs @@ -28,15 +28,12 @@ using System; using System.Collections.Generic; using System.Linq; -using ASC.AuditTrail.Mappers; using ASC.AuditTrail.Models; using ASC.Common; using ASC.Core.Common.EF; using ASC.Core.Common.EF.Context; -using ASC.Core.Users; -using ASC.MessagingSystem; -using Newtonsoft.Json; +using AutoMapper; namespace ASC.AuditTrail.Repositories { @@ -45,21 +42,15 @@ namespace ASC.AuditTrail.Repositories { private AuditTrailContext AuditTrailContext => _lazyAuditTrailContext.Value; - private readonly MessageTarget _messageTarget; - private readonly UserFormatter _userFormatter; private readonly Lazy<AuditTrailContext> _lazyAuditTrailContext; - private readonly AuditActionMapper _auditActionMapper; + private readonly IMapper _mapper; public AuditEventsRepository( - MessageTarget messageTarget, - UserFormatter userFormatter, - DbContextManager<AuditTrailContext> dbContextManager, - AuditActionMapper auditActionMapper) + DbContextManager<AuditTrailContext> dbContextManager, + IMapper mapper) { - _messageTarget = messageTarget; - _userFormatter = userFormatter; - _lazyAuditTrailContext = new Lazy<AuditTrailContext>(() => dbContextManager.Value ); - _auditActionMapper = auditActionMapper; + _lazyAuditTrailContext = new Lazy<AuditTrailContext>(() => dbContextManager.Value); + _mapper = mapper; } public IEnumerable<AuditEvent> GetLast(int tenant, int chunk) => Get(tenant, null, null, chunk); @@ -80,7 +71,7 @@ namespace ASC.AuditTrail.Repositories if (limit.HasValue) query = query.Take((int)limit); - return query.AsEnumerable().Select(ToAuditEvent).ToList(); + return query.AsEnumerable().Select(_mapper.Map<AuditEvent>).ToList(); } public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) @@ -94,49 +85,5 @@ namespace ASC.AuditTrail.Repositories return query.Count(); } - - private AuditEvent ToAuditEvent(AuditEventQuery query) - { - try - { - var evt = new AuditEvent - { - Id = query.AuditEvent.Id, - Ip = query.AuditEvent.Ip, - Initiator = query.AuditEvent.Initiator, - Browser = query.AuditEvent.Browser, - Platform = query.AuditEvent.Platform, - Date = query.AuditEvent.Date, - TenantId = query.AuditEvent.TenantId, - UserId = query.AuditEvent.UserId, - Page = query.AuditEvent.Page, - Action = query.AuditEvent.Action - }; - - if (query.AuditEvent.Description != null) - { - evt.Description = JsonConvert.DeserializeObject<IList<string>>( - Convert.ToString(query.AuditEvent.Description), - new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); - } - - evt.Target = _messageTarget.Parse(query.AuditEvent.Target); - - evt.UserName = (query.User.FirstName != null && query.User.LastName != null) ? _userFormatter.GetUserName(query.User.FirstName, query.User.LastName) : - evt.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : - evt.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : - evt.Initiator ?? AuditReportResource.UnknownAccount; - - evt.ActionText = _auditActionMapper.GetActionText(evt); - evt.ActionTypeText = _auditActionMapper.GetActionTypeText(evt); - evt.Product = _auditActionMapper.GetProductText(evt); - evt.Module = _auditActionMapper.GetModuleText(evt); - - return evt; - } - catch (Exception) { } - - return null; - } } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs index b9fe4dac71..c276542802 100644 --- a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs @@ -29,15 +29,12 @@ using System; using System.Collections.Generic; using System.Linq; -using ASC.AuditTrail.Mappers; using ASC.AuditTrail.Models; using ASC.Common; using ASC.Core.Common.EF; using ASC.Core.Common.EF.Context; -using ASC.Core.Common.EF.Model; -using ASC.Core.Users; -using Newtonsoft.Json; +using AutoMapper; namespace ASC.AuditTrail.Data.Repositories { @@ -46,18 +43,15 @@ namespace ASC.AuditTrail.Data.Repositories { private MessagesContext MessagesContext => _lazyMessagesContext.Value; - private readonly UserFormatter _userFormatter; - private readonly AuditActionMapper _auditActionMapper; private readonly Lazy<MessagesContext> _lazyMessagesContext; + private readonly IMapper _mapper; public LoginEventsRepository( - UserFormatter userFormatter, - AuditActionMapper auditActionMapper, - DbContextManager<MessagesContext> dbMessagesContext) + DbContextManager<MessagesContext> dbMessagesContext, + IMapper mapper) { - _userFormatter = userFormatter; - _auditActionMapper = auditActionMapper; _lazyMessagesContext = new Lazy<MessagesContext>(() => dbMessagesContext.Value); + _mapper = mapper; } public IEnumerable<LoginEvent> GetLast(int tenant, int chunk) @@ -70,7 +64,7 @@ namespace ASC.AuditTrail.Data.Repositories select new LoginEventQuery { LoginEvents = b, User = p }) .Take(chunk); - return query.AsEnumerable().Select(ToLoginEvent).ToList(); + return query.AsEnumerable().Select(_mapper.Map<LoginEvent>).ToList(); } public IEnumerable<LoginEvent> Get(int tenant, DateTime fromDate, DateTime to) @@ -84,7 +78,7 @@ namespace ASC.AuditTrail.Data.Repositories orderby q.Date descending select new LoginEventQuery { LoginEvents = q, User = p }; - return query.AsEnumerable().Select(ToLoginEvent).ToList(); + return query.AsEnumerable().Select(_mapper.Map<LoginEvent>).ToList(); } public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) @@ -96,48 +90,5 @@ namespace ASC.AuditTrail.Data.Repositories return query.Count(); } - - private LoginEvent ToLoginEvent(LoginEventQuery query) - { - var evt = new LoginEvent - { - Id = query.LoginEvents.Id, - Ip = query.LoginEvents.Ip, - Login = query.LoginEvents.Login, - Browser = query.LoginEvents.Browser, - Platform = query.LoginEvents.Platform, - Date = query.LoginEvents.Date, - TenantId = query.LoginEvents.TenantId, - UserId = query.LoginEvents.UserId, - Page = query.LoginEvents.Page, - Action = query.LoginEvents.Action - }; - - if (query.LoginEvents.Description != null) - evt.Description = JsonConvert.DeserializeObject<IList<string>>( - query.LoginEvents.Description, - new JsonSerializerSettings - { - DateTimeZoneHandling = DateTimeZoneHandling.Utc - }); - - evt.UserName = (!string.IsNullOrEmpty(query.User?.FirstName) && !string.IsNullOrEmpty(query.User?.LastName)) - ? _userFormatter.GetUserName(query.User.FirstName, query.User.LastName) - : !string.IsNullOrWhiteSpace(evt.Login) - ? evt.Login - : evt.UserId == Core.Configuration.Constants.Guest.ID - ? AuditReportResource.GuestAccount - : AuditReportResource.UnknownAccount; - - evt.ActionText = _auditActionMapper.GetActionText(evt); - - return evt; - } - } - - public class LoginEventQuery - { - public LoginEvents LoginEvents { get; set; } - public User User { get; set; } } } \ No newline at end of file From 1b32b993b6ee520a0fbd557d7467fff544104fc5 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 14:10:50 +0300 Subject: [PATCH 106/167] ClearEvents: used TimedHostedService template --- .../TimedClearEventsService.cs} | 44 ++++++++++--------- 1 file changed, 23 insertions(+), 21 deletions(-) rename common/services/ASC.ClearEvents/{ClearEventsServiceLauncher.cs => Services/TimedClearEventsService.cs} (80%) diff --git a/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs b/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs similarity index 80% rename from common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs rename to common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs index b006aeafe9..d9148c7d8d 100644 --- a/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs +++ b/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs @@ -43,37 +43,42 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; -namespace ASC.Thumbnails.Svc +namespace ASC.ClearEvents.Services { [Scope(Additional = typeof(MessagesRepositoryExtension))] - public class ClearEventsServiceLauncher : IHostedService + public class TimedClearEventsService : IHostedService, IDisposable { - private ILog Log { get; set; } - private IServiceProvider ServiceProvider { get; } - private Timer ClearTimer; + private readonly ILog _logger; + private readonly IServiceProvider _serviceProvider; + private Timer _timer = null!; - public ClearEventsServiceLauncher(IOptionsMonitor<ILog> options, IServiceProvider serviceProvider) + public TimedClearEventsService(IOptionsMonitor<ILog> options, IServiceProvider serviceProvider) { - Log = options.CurrentValue; - ServiceProvider = serviceProvider; + _logger = options.CurrentValue; + _serviceProvider = serviceProvider; } public Task StartAsync(CancellationToken cancellationToken) { - ClearTimer = new Timer(DeleteOldEvents); - ClearTimer.Change(new TimeSpan(0), TimeSpan.FromDays(1)); + _logger.Debug("Timer Clear Events Service running."); + + _timer = new Timer(DeleteOldEvents, null, TimeSpan.Zero, + TimeSpan.FromDays(1)); + return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { - if (ClearTimer != null) - { - ClearTimer.Dispose(); - } + _logger.Debug("Timed Clear Events Service is stopping."); + + _timer?.Change(Timeout.Infinite, 0); + return Task.CompletedTask; } + public void Dispose() => _timer?.Dispose(); + private void DeleteOldEvents(object state) { try @@ -83,7 +88,7 @@ namespace ASC.Thumbnails.Svc } catch (Exception ex) { - Log.Error(ex.Message, ex); + _logger.Error(ex.Message, ex); } } @@ -93,7 +98,7 @@ namespace ASC.Thumbnails.Svc var compile = func.Compile(); do { - using var scope = ServiceProvider.CreateScope(); + using var scope = _serviceProvider.CreateScope(); using var ef = scope.ServiceProvider.GetService<DbContextManager<Messages>>().Get("messages"); var table = compile.Invoke(ef); @@ -131,12 +136,9 @@ namespace ASC.Thumbnails.Svc public DbSet<DbWebstudioSettings> WebstudioSettings { get; } } -public class MessagesRepositoryExtension + public class MessagesRepositoryExtension { - public static void Register(DIHelper services) - { - services.TryAdd<DbContextManager<MessagesContext>>(); - } + public static void Register(DIHelper services) => services.TryAdd<DbContextManager<MessagesContext>>(); } } \ No newline at end of file From 7f74aa544c46b5c4a1221dd0041d4de17d895491 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 14:16:48 +0300 Subject: [PATCH 107/167] ClearEvents: CreateHostBuilder replcaed with WebApplicationBuilder --- common/services/ASC.ClearEvents/Program.cs | 127 ++++++++++----------- 1 file changed, 60 insertions(+), 67 deletions(-) diff --git a/common/services/ASC.ClearEvents/Program.cs b/common/services/ASC.ClearEvents/Program.cs index 8110acd843..c0e7d30b9b 100644 --- a/common/services/ASC.ClearEvents/Program.cs +++ b/common/services/ASC.ClearEvents/Program.cs @@ -24,89 +24,82 @@ */ +using System; using System.Collections.Generic; using System.IO; -using System.Threading.Tasks; using ASC.Api.Core; +using ASC.ClearEvents.Services; using ASC.Common; using ASC.Common.Caching; using ASC.Common.DependencyInjection; using ASC.Common.Utils; using Autofac; -using Autofac.Extensions.DependencyInjection; - +using Autofac.Extensions.DependencyInjection; + +using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Hosting.WindowsServices; using StackExchange.Redis.Extensions.Core.Configuration; -namespace ASC.Thumbnails.Svc +var options = new WebApplicationOptions { -public class Program - { - public async static Task Main(string[] args) - { - var host = CreateHostBuilder(args).Build(); - - await host.RunAsync(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .UseSystemd() - .UseWindowsService() - .UseServiceProviderFactory(new AutofacServiceProviderFactory()) - .ConfigureAppConfiguration((hostContext, config) => - { - var buided = config.Build(); - var path = buided["pathToConf"]; - if (!Path.IsPathRooted(path)) - { - path = Path.GetFullPath(CrossPlatform.PathCombine(hostContext.HostingEnvironment.ContentRootPath, path)); - } - config.SetBasePath(path); - var env = hostContext.Configuration.GetValue("ENVIRONMENT", "Production"); - config - .AddJsonFile("appsettings.json") - .AddEnvironmentVariables() - .AddCommandLine(args) - .AddInMemoryCollection(new Dictionary<string, string> - { - {"pathToConf", path } - } - ); - }) - .ConfigureServices((hostContext, services) => - { - services.AddMemoryCache(); - var diHelper = new DIHelper(services); + Args = args, + ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default +}; - var redisConfiguration = hostContext.Configuration.GetSection("Redis").Get<RedisConfiguration>(); - var kafkaConfiguration = hostContext.Configuration.GetSection("kafka").Get<KafkaSettings>(); +var builder = WebApplication.CreateBuilder(options); - if (kafkaConfiguration != null) - { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); - } - else if (redisConfiguration != null) - { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); - } - else - { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); - } - - services.AddHostedService<ClearEventsServiceLauncher>(); - diHelper.TryAdd<ClearEventsServiceLauncher>(); - }) - .ConfigureContainer<ContainerBuilder>((context, builder) => - { - builder.Register(context.Configuration, false, false); - }) - .ConfigureNLogLogging(); - } -} +builder.Host.UseSystemd(); +builder.Host.UseWindowsService(); +builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); + +builder.Host.ConfigureAppConfiguration((hostContext, config) => +{ + var configRoot = config.Build(); + var path = configRoot["pathToConf"]; + + if (!Path.IsPathRooted(path)) + path = Path.GetFullPath(CrossPlatform.PathCombine(hostContext.HostingEnvironment.ContentRootPath, path)); + + config.SetBasePath(path); + + var env = hostContext.Configuration.GetValue("ENVIRONMENT", "Production"); + + config.AddJsonFile("appsettings.json") + .AddEnvironmentVariables() + .AddCommandLine(args) + .AddInMemoryCollection(new Dictionary<string, string> { { "pathToConf", path } }); +}); + +builder.Host.ConfigureServices((hostContext, services) => +{ + services.AddMemoryCache(); + + var diHelper = new DIHelper(services); + + var redisConfiguration = hostContext.Configuration.GetSection("Redis").Get<RedisConfiguration>(); + var kafkaConfiguration = hostContext.Configuration.GetSection("kafka").Get<KafkaSettings>(); + + if (kafkaConfiguration != null) diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); + + else if (redisConfiguration != null) diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); + + else diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + + services.AddHostedService<TimedClearEventsService>(); + diHelper.TryAdd<TimedClearEventsService>(); +}); + +builder.Host.ConfigureContainer<ContainerBuilder>((context, builder) => + builder.Register(context.Configuration, false, false)); + +builder.Host.ConfigureNLogLogging(); + +var app = builder.Build(); + +await app.RunAsync(); \ No newline at end of file From 29a2ec96b59e6e1b118a1f677015d239595f9a81 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 14:27:40 +0300 Subject: [PATCH 108/167] ClearEvents: change log level --- .../ASC.ClearEvents/Services/TimedClearEventsService.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs b/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs index d9148c7d8d..d78715986b 100644 --- a/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs +++ b/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs @@ -60,7 +60,7 @@ namespace ASC.ClearEvents.Services public Task StartAsync(CancellationToken cancellationToken) { - _logger.Debug("Timer Clear Events Service running."); + _logger.Info("Timer Clear Events Service running."); _timer = new Timer(DeleteOldEvents, null, TimeSpan.Zero, TimeSpan.FromDays(1)); @@ -70,7 +70,7 @@ namespace ASC.ClearEvents.Services public Task StopAsync(CancellationToken cancellationToken) { - _logger.Debug("Timed Clear Events Service is stopping."); + _logger.Info("Timed Clear Events Service is stopping."); _timer?.Change(Timeout.Infinite, 0); @@ -138,7 +138,7 @@ namespace ASC.ClearEvents.Services public class MessagesRepositoryExtension { - public static void Register(DIHelper services) => services.TryAdd<DbContextManager<MessagesContext>>(); + public static void Register(DIHelper services) => services.TryAdd<DbContextManager<Messages>>(); } } \ No newline at end of file From f2c0f3ec77db428ae448d3ec6815531b507783b8 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 14:38:03 +0300 Subject: [PATCH 109/167] Common: ICahcheNotify is reduced to IEventBus --- common/ASC.Api.Core/Core/BaseStartup.cs | 6 +-- common/ASC.Common/Caching/AscCache.cs | 10 ++-- .../{CacheNotifyAction.cs => EventType.cs} | 4 +- .../Caching/{ICacheNotify.cs => IEventBus.cs} | 26 +++++----- common/ASC.Common/Caching/KafkaCache.cs | 10 ++-- .../ASC.Common/Caching/MemoryCacheNotify.cs | 10 ++-- common/ASC.Common/Caching/RedisCache.cs | 12 ++--- .../Threading/DistributedTaskQueue.cs | 20 ++++---- .../ASC.Core.Common/Billing/TariffService.cs | 10 ++-- .../Caching/CachedAzService.cs | 14 +++--- .../Caching/CachedQuotaService.cs | 12 ++--- .../Caching/CachedSubscriptionService.cs | 24 +++++----- .../Caching/CachedTenantService.cs | 22 ++++----- .../Caching/CachedUserService.cs | 48 +++++++++---------- .../ASC.Core.Common/Configuration/Consumer.cs | 16 +++---- common/ASC.Core.Common/Context/WorkContext.cs | 4 +- .../ASC.Core.Common/Data/DbSettingsManager.cs | 8 ++-- .../Notify/NotifyServiceClient.cs | 10 ++-- .../Notify/Senders/NotifyServiceSender.cs | 2 +- .../Notify/Telegram/TelegramServiceClient.cs | 24 +++++----- .../Service/BackupWorker.cs | 4 +- .../Configuration/StorageSettings.cs | 14 +++--- .../Encryption/EncryptionServiceClient.cs | 10 ++-- .../Migration/MigrateServiceClient.cs | 20 ++++---- common/ASC.Data.Storage/StorageUploader.cs | 10 ++-- common/ASC.FederatedLogin/AccountLinker.cs | 8 ++-- .../LoginProviders/BaseLoginProvider.cs | 2 +- .../LoginProviders/BitlyLoginProvider.cs | 2 +- .../LoginProviders/BoxLoginProvider.cs | 2 +- .../LoginProviders/DocuSignLoginProvider.cs | 2 +- .../LoginProviders/DropboxLoginProvider.cs | 2 +- .../LoginProviders/FacebookLoginProvider.cs | 2 +- .../LoginProviders/GoogleLoginProvider.cs | 2 +- .../LoginProviders/GosUslugiLoginProvider.cs | 2 +- .../LoginProviders/LinkedInLoginProvider.cs | 2 +- .../LoginProviders/MailRuLoginProvider.cs | 2 +- .../LoginProviders/OneDriveLoginProvider.cs | 2 +- .../LoginProviders/TelegramLoginProvider.cs | 2 +- .../LoginProviders/VKLoginProvider.cs | 2 +- .../LoginProviders/WordpressLoginProvider.cs | 2 +- .../LoginProviders/YahooLoginProvider.cs | 2 +- .../LoginProviders/YandexLoginProvider.cs | 2 +- .../ASC.IPSecurity/IPRestrictionsService.cs | 10 ++-- common/ASC.VoipService/Dao/CachedVoipDao.cs | 8 ++-- common/ASC.Webhooks.Core/WebhookPublisher.cs | 6 +-- common/services/ASC.ClearEvents/Program.cs | 6 +-- .../Services/BackupListenerService.cs | 8 ++-- .../ASC.ElasticSearch/Core/SearchSettings.cs | 6 +-- .../ASC.ElasticSearch/Engine/BaseIndexer.cs | 10 ++-- .../Engine/FactoryIndexer.cs | 6 +-- .../ASC.ElasticSearch/Service/Launcher.cs | 14 +++--- .../ASC.ElasticSearch/Service/Service.cs | 6 +-- common/services/ASC.Notify/NotifyService.cs | 16 +++---- common/services/ASC.Notify/Program.cs | 6 +-- common/services/ASC.Studio.Notify/Program.cs | 6 +-- .../ASC.TelegramService/TelegramListener.cs | 32 ++++++------- .../ASC.Webhooks.Service/BuildQueueService.cs | 8 ++-- .../services/ASC.Webhooks.Service/Program.cs | 6 +-- .../ASC.Files/Core/Core/FileStorageService.cs | 6 +-- .../Core/Thirdparty/Box/BoxProviderInfo.cs | 12 ++--- .../Thirdparty/Dropbox/DropboxProviderInfo.cs | 12 ++--- .../GoogleDrive/GoogleDriveProviderInfo.cs | 14 +++--- .../OneDrive/OneDriveProviderInfo.cs | 10 ++-- .../SharePoint/SharePointProviderInfo.cs | 12 ++--- .../ASC.Files/Core/Helpers/EasyBibHelper.cs | 2 +- products/ASC.Files/Core/Helpers/Global.cs | 6 +-- .../ASC.Files/Core/ThirdPartyApp/BoxApp.cs | 2 +- .../Core/ThirdPartyApp/GoogleDriveApp.cs | 2 +- products/ASC.Files/Service/Program.cs | 6 +-- .../ASC.Files/Service/Thumbnail/Service.cs | 8 ++-- .../Controllers/SettingsController.cs | 6 +-- web/ASC.Web.Core/Jabber/FireBase.cs | 2 +- web/ASC.Web.Core/Mail/MailServiceHelper.cs | 8 ++-- .../Notify/StudioNotifyServiceHelper.cs | 6 +-- .../Notify/StudioNotifyServiceSender.cs | 4 +- web/ASC.Web.Core/Sms/SmsKeyStorage.cs | 8 ++-- web/ASC.Web.Core/Sms/SmsProvider.cs | 12 ++--- web/ASC.Web.Core/Users/UserPhotoManager.cs | 12 ++--- web/ASC.Web.Core/WebItemSecurity.cs | 8 ++-- .../WhiteLabel/TenantLogoManager.cs | 6 +-- 80 files changed, 353 insertions(+), 355 deletions(-) rename common/ASC.Common/Caching/{CacheNotifyAction.cs => EventType.cs} (97%) rename common/ASC.Common/Caching/{ICacheNotify.cs => IEventBus.cs} (86%) diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index 165fdf11ea..ce7ed950bf 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -110,17 +110,17 @@ namespace ASC.Api.Core if (kafkaConfiguration != null) { - DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); + DIHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); } else if (redisConfiguration != null) { - DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); + DIHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + DIHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); } diff --git a/common/ASC.Common/Caching/AscCache.cs b/common/ASC.Common/Caching/AscCache.cs index 2a62898ad2..779b6d8630 100644 --- a/common/ASC.Common/Caching/AscCache.cs +++ b/common/ASC.Common/Caching/AscCache.cs @@ -30,8 +30,6 @@ using System.Linq; using System.Runtime.Caching; using System.Text.RegularExpressions; -using Google.Protobuf; - using Microsoft.Extensions.Caching.Memory; namespace ASC.Common.Caching @@ -39,18 +37,18 @@ namespace ASC.Common.Caching [Singletone] public class AscCacheNotify { - private ICacheNotify<AscCacheItem> CacheNotify { get; } + private IEventBus<AscCacheItem> CacheNotify { get; } - public AscCacheNotify(ICacheNotify<AscCacheItem> cacheNotify) + public AscCacheNotify(IEventBus<AscCacheItem> cacheNotify) { CacheNotify = cacheNotify; - CacheNotify.Subscribe((item) => { OnClearCache(); }, CacheNotifyAction.Any); + CacheNotify.Subscribe((item) => { OnClearCache(); }, EventType.Any); } public void ClearCache() { - CacheNotify.Publish(new AscCacheItem { Id = Guid.NewGuid().ToString() }, CacheNotifyAction.Any); + CacheNotify.Publish(new AscCacheItem { Id = Guid.NewGuid().ToString() }, EventType.Any); } public static void OnClearCache() diff --git a/common/ASC.Common/Caching/CacheNotifyAction.cs b/common/ASC.Common/Caching/EventType.cs similarity index 97% rename from common/ASC.Common/Caching/CacheNotifyAction.cs rename to common/ASC.Common/Caching/EventType.cs index 9173d00d76..e0b879cfe7 100644 --- a/common/ASC.Common/Caching/CacheNotifyAction.cs +++ b/common/ASC.Common/Caching/EventType.cs @@ -30,8 +30,8 @@ using System; namespace ASC.Common.Caching { [Flags] - public enum CacheNotifyAction - { + public enum EventType + { Insert = 1, Update = 2, Remove = 4, diff --git a/common/ASC.Common/Caching/ICacheNotify.cs b/common/ASC.Common/Caching/IEventBus.cs similarity index 86% rename from common/ASC.Common/Caching/ICacheNotify.cs rename to common/ASC.Common/Caching/IEventBus.cs index a8ac77606f..e905ed408b 100644 --- a/common/ASC.Common/Caching/ICacheNotify.cs +++ b/common/ASC.Common/Caching/IEventBus.cs @@ -24,19 +24,19 @@ */ -using System; - -using Google.Protobuf; - -namespace ASC.Common.Caching -{ - [Singletone] - public interface ICacheNotify<T> where T : IMessage<T>, new() - { - void Publish(T obj, CacheNotifyAction action); +using System; - void Subscribe(Action<T> onchange, CacheNotifyAction action); - - void Unsubscribe(CacheNotifyAction action); +using Google.Protobuf; + +namespace ASC.Common.Caching +{ + [Singletone] + public interface IEventBus<T> where T : IMessage<T>, new() + { + void Publish(T obj, EventType action); + + void Subscribe(Action<T> onchange, EventType action); + + void Unsubscribe(EventType action); } } diff --git a/common/ASC.Common/Caching/KafkaCache.cs b/common/ASC.Common/Caching/KafkaCache.cs index f452a33f73..1ff6629d16 100644 --- a/common/ASC.Common/Caching/KafkaCache.cs +++ b/common/ASC.Common/Caching/KafkaCache.cs @@ -16,7 +16,7 @@ using Microsoft.Extensions.Options; namespace ASC.Common.Caching { [Singletone] - public class KafkaCache<T> : IDisposable, ICacheNotify<T> where T : IMessage<T>, new() + public class KafkaCache<T> : IDisposable, IEventBus<T> where T : IMessage<T>, new() { private ClientConfig ClientConfig { get; set; } private AdminClientConfig AdminClientConfig { get; set; } @@ -43,7 +43,7 @@ namespace ASC.Common.Caching AdminClientConfig = new AdminClientConfig { BootstrapServers = settings.BootstrapServers }; } - public void Publish(T obj, CacheNotifyAction cacheNotifyAction) + public void Publish(T obj, EventType cacheNotifyAction) { try { @@ -84,7 +84,7 @@ namespace ASC.Common.Caching } } - public void Subscribe(Action<T> onchange, CacheNotifyAction cacheNotifyAction) + public void Subscribe(Action<T> onchange, EventType cacheNotifyAction) { var channelName = GetChannelName(cacheNotifyAction); @@ -167,12 +167,12 @@ namespace ASC.Common.Caching task.Start(); } - private string GetChannelName(CacheNotifyAction cacheNotifyAction) + private string GetChannelName(EventType cacheNotifyAction) { return $"ascchannel{cacheNotifyAction}{typeof(T).FullName}".ToLower(); } - public void Unsubscribe(CacheNotifyAction action) + public void Unsubscribe(EventType action) { Cts.TryGetValue(GetChannelName(action), out var source); if (source != null) diff --git a/common/ASC.Common/Caching/MemoryCacheNotify.cs b/common/ASC.Common/Caching/MemoryCacheNotify.cs index 989b4a205a..88525250b2 100644 --- a/common/ASC.Common/Caching/MemoryCacheNotify.cs +++ b/common/ASC.Common/Caching/MemoryCacheNotify.cs @@ -8,7 +8,7 @@ using Google.Protobuf; namespace ASC.Common.Caching { [Singletone] - public class MemoryCacheNotify<T> : ICacheNotify<T> where T : IMessage<T>, new() + public class MemoryCacheNotify<T> : IEventBus<T> where T : IMessage<T>, new() { private readonly ConcurrentDictionary<string, List<Action<T>>> _actions; @@ -17,7 +17,7 @@ namespace ASC.Common.Caching _actions = new ConcurrentDictionary<string, List<Action<T>>>(); } - public void Publish(T obj, CacheNotifyAction action) + public void Publish(T obj, EventType action) { if (_actions.TryGetValue(GetKey(action), out var onchange) && onchange != null) { @@ -25,7 +25,7 @@ namespace ASC.Common.Caching } } - public void Subscribe(Action<T> onchange, CacheNotifyAction notifyAction) + public void Subscribe(Action<T> onchange, EventType notifyAction) { if (onchange != null) { @@ -34,12 +34,12 @@ namespace ASC.Common.Caching } } - public void Unsubscribe(CacheNotifyAction action) + public void Unsubscribe(EventType action) { _actions.TryRemove(GetKey(action), out _); } - private string GetKey(CacheNotifyAction cacheNotifyAction) + private string GetKey(EventType cacheNotifyAction) { return $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); } diff --git a/common/ASC.Common/Caching/RedisCache.cs b/common/ASC.Common/Caching/RedisCache.cs index 611831a7be..a11c5f4fe7 100644 --- a/common/ASC.Common/Caching/RedisCache.cs +++ b/common/ASC.Common/Caching/RedisCache.cs @@ -25,7 +25,7 @@ using StackExchange.Redis.Extensions.Core.Abstractions; namespace ASC.Common.Caching; [Singletone] -public class RedisCache<T> : ICacheNotify<T> where T : IMessage<T>, new() +public class RedisCache<T> : IEventBus<T> where T : IMessage<T>, new() { private readonly IRedisDatabase _redis; @@ -34,14 +34,14 @@ public class RedisCache<T> : ICacheNotify<T> where T : IMessage<T>, new() _redis = redisCacheClient.GetDbFromConfiguration(); } - public void Publish(T obj, CacheNotifyAction action) + public void Publish(T obj, EventType action) { Task.Run(() => _redis.PublishAsync(GetChannelName(action), new RedisCachePubSubItem<T>() { Object = obj, Action = action })) .GetAwaiter() .GetResult(); } - public void Subscribe(Action<T> onchange, CacheNotifyAction action) + public void Subscribe(Action<T> onchange, EventType action) { Task.Run(() => _redis.SubscribeAsync<RedisCachePubSubItem<T>>(GetChannelName(action), (i) => { @@ -52,7 +52,7 @@ public class RedisCache<T> : ICacheNotify<T> where T : IMessage<T>, new() .GetResult(); } - public void Unsubscribe(CacheNotifyAction action) + public void Unsubscribe(EventType action) { Task.Run(() => _redis.UnsubscribeAsync<RedisCachePubSubItem<T>>(GetChannelName(action), (i) => { @@ -61,7 +61,7 @@ public class RedisCache<T> : ICacheNotify<T> where T : IMessage<T>, new() .GetResult(); } - private string GetChannelName(CacheNotifyAction cacheNotifyAction) + private string GetChannelName(EventType cacheNotifyAction) { return $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); } @@ -70,7 +70,7 @@ public class RedisCache<T> : ICacheNotify<T> where T : IMessage<T>, new() { public T0 Object { get; set; } - public CacheNotifyAction Action { get; set; } + public EventType Action { get; set; } } } diff --git a/common/ASC.Common/Threading/DistributedTaskQueue.cs b/common/ASC.Common/Threading/DistributedTaskQueue.cs index dbe2954ada..5627dcf827 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -44,12 +44,12 @@ namespace ASC.Common.Threading { public ConcurrentDictionary<string, CancellationTokenSource> Cancelations { get; } public ICache Cache { get; } - private readonly ICacheNotify<DistributedTaskCancelation> notify; - private readonly ICacheNotify<DistributedTaskCache> notifyCache; + private readonly IEventBus<DistributedTaskCancelation> notify; + private readonly IEventBus<DistributedTaskCache> notifyCache; public DistributedTaskCacheNotify( - ICacheNotify<DistributedTaskCancelation> notify, - ICacheNotify<DistributedTaskCache> notifyCache, + IEventBus<DistributedTaskCancelation> notify, + IEventBus<DistributedTaskCache> notifyCache, ICache cache) { Cancelations = new ConcurrentDictionary<string, CancellationTokenSource>(); @@ -64,34 +64,34 @@ namespace ASC.Common.Threading { s.Cancel(); } - }, CacheNotifyAction.Remove); + }, Caching.EventType.Remove); this.notifyCache = notifyCache; notifyCache.Subscribe((c) => { Cache.HashSet(c.Key, c.Id, (DistributedTaskCache)null); - }, CacheNotifyAction.Remove); + }, Caching.EventType.Remove); notifyCache.Subscribe((c) => { Cache.HashSet(c.Key, c.Id, c); - }, CacheNotifyAction.InsertOrUpdate); + }, Caching.EventType.InsertOrUpdate); } public void CancelTask(string id) { - notify.Publish(new DistributedTaskCancelation() { Id = id }, CacheNotifyAction.Remove); + notify.Publish(new DistributedTaskCancelation() { Id = id }, Caching.EventType.Remove); } public void SetTask(DistributedTask task) { - notifyCache.Publish(task.DistributedTaskCache, CacheNotifyAction.InsertOrUpdate); + notifyCache.Publish(task.DistributedTaskCache, Caching.EventType.InsertOrUpdate); } public void RemoveTask(string id, string key) { - notifyCache.Publish(new DistributedTaskCache() { Id = id, Key = key }, CacheNotifyAction.Remove); + notifyCache.Publish(new DistributedTaskCache() { Id = id, Key = key }, Caching.EventType.Remove); } } diff --git a/common/ASC.Core.Common/Billing/TariffService.cs b/common/ASC.Core.Common/Billing/TariffService.cs index 5deee5f5c1..d98a48b1c4 100644 --- a/common/ASC.Core.Common/Billing/TariffService.cs +++ b/common/ASC.Core.Common/Billing/TariffService.cs @@ -49,9 +49,9 @@ namespace ASC.Core.Billing public class TariffServiceStorage { public ICache Cache { get; } - internal ICacheNotify<TariffCacheItem> Notify { get; } + internal IEventBus<TariffCacheItem> Notify { get; } - public TariffServiceStorage(ICacheNotify<TariffCacheItem> notify, ICache cache) + public TariffServiceStorage(IEventBus<TariffCacheItem> notify, ICache cache) { Cache = cache; Notify = notify; @@ -60,7 +60,7 @@ namespace ASC.Core.Billing Cache.Remove(TariffService.GetTariffCacheKey(i.TenantId)); Cache.Remove(TariffService.GetBillingUrlCacheKey(i.TenantId)); Cache.Remove(TariffService.GetBillingPaymentCacheKey(i.TenantId)); // clear all payments - }, CacheNotifyAction.Remove); + }, ASC.Common.Caching.EventType.Remove); //TODO: Change code of WCF -> not supported in .NET standard/.Net Core /*try @@ -146,7 +146,7 @@ namespace ASC.Core.Billing private static readonly TimeSpan STANDALONE_CACHE_EXPIRATION = TimeSpan.FromMinutes(15); internal ICache Cache { get; set; } - internal ICacheNotify<TariffCacheItem> Notify { get; set; } + internal IEventBus<TariffCacheItem> Notify { get; set; } internal ILog Log { get; set; } internal IQuotaService QuotaService { get; set; } internal ITenantService TenantService { get; set; } @@ -317,7 +317,7 @@ namespace ASC.Core.Billing public void ClearCache(int tenantId) { - Notify.Publish(new TariffCacheItem { TenantId = tenantId }, CacheNotifyAction.Remove); + Notify.Publish(new TariffCacheItem { TenantId = tenantId }, ASC.Common.Caching.EventType.Remove); } public IEnumerable<PaymentInfo> GetPayments(int tenantId) diff --git a/common/ASC.Core.Common/Caching/CachedAzService.cs b/common/ASC.Core.Common/Caching/CachedAzService.cs index 9aecec13d9..dc5d0f11a2 100644 --- a/common/ASC.Core.Common/Caching/CachedAzService.cs +++ b/common/ASC.Core.Common/Caching/CachedAzService.cs @@ -37,15 +37,15 @@ namespace ASC.Core.Caching class AzServiceCache { internal ICache Cache { get; } - internal ICacheNotify<AzRecordCache> CacheNotify { get; } + internal IEventBus<AzRecordCache> CacheNotify { get; } - public AzServiceCache(ICacheNotify<AzRecordCache> cacheNotify, ICache cache) + public AzServiceCache(IEventBus<AzRecordCache> cacheNotify, ICache cache) { CacheNotify = cacheNotify; Cache = cache; - cacheNotify.Subscribe((r) => UpdateCache(r, true), CacheNotifyAction.Remove); - cacheNotify.Subscribe((r) => UpdateCache(r, false), CacheNotifyAction.InsertOrUpdate); + cacheNotify.Subscribe((r) => UpdateCache(r, true), ASC.Common.Caching.EventType.Remove); + cacheNotify.Subscribe((r) => UpdateCache(r, false), ASC.Common.Caching.EventType.InsertOrUpdate); } private void UpdateCache(AzRecord r, bool remove) @@ -78,7 +78,7 @@ namespace ASC.Core.Caching { private readonly IAzService service; - private readonly ICacheNotify<AzRecordCache> cacheNotify; + private readonly IEventBus<AzRecordCache> cacheNotify; private ICache Cache { get; } @@ -109,14 +109,14 @@ namespace ASC.Core.Caching public AzRecord SaveAce(int tenant, AzRecord r) { r = service.SaveAce(tenant, r); - cacheNotify.Publish(r, CacheNotifyAction.InsertOrUpdate); + cacheNotify.Publish(r, ASC.Common.Caching.EventType.InsertOrUpdate); return r; } public void RemoveAce(int tenant, AzRecord r) { service.RemoveAce(tenant, r); - cacheNotify.Publish(r, CacheNotifyAction.Remove); + cacheNotify.Publish(r, ASC.Common.Caching.EventType.Remove); } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Caching/CachedQuotaService.cs b/common/ASC.Core.Common/Caching/CachedQuotaService.cs index 7a490d5c54..8ab75282ed 100644 --- a/common/ASC.Core.Common/Caching/CachedQuotaService.cs +++ b/common/ASC.Core.Common/Caching/CachedQuotaService.cs @@ -46,11 +46,11 @@ namespace ASC.Core.Caching internal TrustInterval Interval { get; set; } internal ICache Cache { get; } - internal ICacheNotify<QuotaCacheItem> CacheNotify { get; } + internal IEventBus<QuotaCacheItem> CacheNotify { get; } internal bool QuotaCacheEnabled { get; } - public QuotaServiceCache(IConfiguration Configuration, ICacheNotify<QuotaCacheItem> cacheNotify, ICache cache) + public QuotaServiceCache(IConfiguration Configuration, IEventBus<QuotaCacheItem> cacheNotify, ICache cache) { if (Configuration["core:enable-quota-cache"] == null) { @@ -75,7 +75,7 @@ namespace ASC.Core.Caching { Cache.Remove(i.Key); } - }, CacheNotifyAction.Any); + }, ASC.Common.Caching.EventType.Any); } } @@ -113,7 +113,7 @@ namespace ASC.Core.Caching { internal IQuotaService Service { get; set; } internal ICache Cache { get; set; } - internal ICacheNotify<QuotaCacheItem> CacheNotify { get; set; } + internal IEventBus<QuotaCacheItem> CacheNotify { get; set; } internal TrustInterval Interval { get; set; } internal TimeSpan CacheExpiration { get; set; } @@ -155,7 +155,7 @@ namespace ASC.Core.Caching public TenantQuota SaveTenantQuota(TenantQuota quota) { var q = Service.SaveTenantQuota(quota); - CacheNotify.Publish(new QuotaCacheItem { Key = QuotaServiceCache.KEY_QUOTA }, CacheNotifyAction.Any); + CacheNotify.Publish(new QuotaCacheItem { Key = QuotaServiceCache.KEY_QUOTA }, ASC.Common.Caching.EventType.Any); return q; } @@ -168,7 +168,7 @@ namespace ASC.Core.Caching public void SetTenantQuotaRow(TenantQuotaRow row, bool exchange) { Service.SetTenantQuotaRow(row, exchange); - CacheNotify.Publish(new QuotaCacheItem { Key = GetKey(row.Tenant) }, CacheNotifyAction.InsertOrUpdate); + CacheNotify.Publish(new QuotaCacheItem { Key = GetKey(row.Tenant) }, ASC.Common.Caching.EventType.InsertOrUpdate); } public IEnumerable<TenantQuotaRow> FindTenantQuotaRows(int tenantId) diff --git a/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs b/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs index fbe6d7bc15..713015accf 100644 --- a/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs +++ b/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs @@ -38,10 +38,10 @@ namespace ASC.Core.Caching class SubscriptionServiceCache { internal ICache Cache { get; } - internal ICacheNotify<SubscriptionRecord> NotifyRecord { get; } - internal ICacheNotify<SubscriptionMethodCache> NotifyMethod { get; } + internal IEventBus<SubscriptionRecord> NotifyRecord { get; } + internal IEventBus<SubscriptionMethodCache> NotifyMethod { get; } - public SubscriptionServiceCache(ICacheNotify<SubscriptionRecord> notifyRecord, ICacheNotify<SubscriptionMethodCache> notifyMethod, ICache cache) + public SubscriptionServiceCache(IEventBus<SubscriptionRecord> notifyRecord, IEventBus<SubscriptionMethodCache> notifyMethod, ICache cache) { Cache = cache; NotifyRecord = notifyRecord; @@ -57,7 +57,7 @@ namespace ASC.Core.Caching store.SaveSubscription(s); } } - }, CacheNotifyAction.InsertOrUpdate); + }, ASC.Common.Caching.EventType.InsertOrUpdate); notifyRecord.Subscribe((s) => { @@ -76,7 +76,7 @@ namespace ASC.Core.Caching } } } - }, CacheNotifyAction.Remove); + }, ASC.Common.Caching.EventType.Remove); notifyMethod.Subscribe((m) => { @@ -88,7 +88,7 @@ namespace ASC.Core.Caching store.SetSubscriptionMethod(m); } } - }, CacheNotifyAction.Any); + }, ASC.Common.Caching.EventType.Any); } private SubsciptionsStore GetSubsciptionsStore(int tenant, string sourceId, string actionId) @@ -107,8 +107,8 @@ namespace ASC.Core.Caching { private readonly ISubscriptionService service; private readonly ICache cache; - private readonly ICacheNotify<SubscriptionRecord> notifyRecord; - private readonly ICacheNotify<SubscriptionMethodCache> notifyMethod; + private readonly IEventBus<SubscriptionRecord> notifyRecord; + private readonly IEventBus<SubscriptionMethodCache> notifyMethod; private TimeSpan CacheExpiration { get; set; } @@ -162,19 +162,19 @@ namespace ASC.Core.Caching public void SaveSubscription(SubscriptionRecord s) { service.SaveSubscription(s); - notifyRecord.Publish(s, CacheNotifyAction.InsertOrUpdate); + notifyRecord.Publish(s, ASC.Common.Caching.EventType.InsertOrUpdate); } public void RemoveSubscriptions(int tenant, string sourceId, string actionId) { service.RemoveSubscriptions(tenant, sourceId, actionId); - notifyRecord.Publish(new SubscriptionRecord { Tenant = tenant, SourceId = sourceId, ActionId = actionId }, CacheNotifyAction.Remove); + notifyRecord.Publish(new SubscriptionRecord { Tenant = tenant, SourceId = sourceId, ActionId = actionId }, ASC.Common.Caching.EventType.Remove); } public void RemoveSubscriptions(int tenant, string sourceId, string actionId, string objectId) { service.RemoveSubscriptions(tenant, sourceId, actionId, objectId); - notifyRecord.Publish(new SubscriptionRecord { Tenant = tenant, SourceId = sourceId, ActionId = actionId, ObjectId = objectId }, CacheNotifyAction.Remove); + notifyRecord.Publish(new SubscriptionRecord { Tenant = tenant, SourceId = sourceId, ActionId = actionId, ObjectId = objectId }, ASC.Common.Caching.EventType.Remove); } public IEnumerable<SubscriptionMethod> GetSubscriptionMethods(int tenant, string sourceId, string actionId, string recipientId) @@ -189,7 +189,7 @@ namespace ASC.Core.Caching public void SetSubscriptionMethod(SubscriptionMethod m) { service.SetSubscriptionMethod(m); - notifyMethod.Publish(m, CacheNotifyAction.Any); + notifyMethod.Publish(m, ASC.Common.Caching.EventType.Any); } diff --git a/common/ASC.Core.Common/Caching/CachedTenantService.cs b/common/ASC.Core.Common/Caching/CachedTenantService.cs index 1aa26b16da..64d794649f 100644 --- a/common/ASC.Core.Common/Caching/CachedTenantService.cs +++ b/common/ASC.Core.Common/Caching/CachedTenantService.cs @@ -42,13 +42,13 @@ namespace ASC.Core.Caching private const string KEY = "tenants"; private TimeSpan CacheExpiration { get; set; } internal ICache Cache { get; } - internal ICacheNotify<TenantCacheItem> CacheNotifyItem { get; } - internal ICacheNotify<TenantSetting> CacheNotifySettings { get; } + internal IEventBus<TenantCacheItem> CacheNotifyItem { get; } + internal IEventBus<TenantSetting> CacheNotifySettings { get; } public TenantServiceCache( CoreBaseSettings coreBaseSettings, - ICacheNotify<TenantCacheItem> cacheNotifyItem, - ICacheNotify<TenantSetting> cacheNotifySettings, + IEventBus<TenantCacheItem> cacheNotifyItem, + IEventBus<TenantSetting> cacheNotifySettings, ICache cache) { CacheNotifyItem = cacheNotifyItem; @@ -61,12 +61,12 @@ namespace ASC.Core.Caching var tenants = GetTenantStore(); tenants.Remove(t.TenantId); tenants.Clear(coreBaseSettings); - }, CacheNotifyAction.InsertOrUpdate); + }, ASC.Common.Caching.EventType.InsertOrUpdate); cacheNotifySettings.Subscribe((s) => { Cache.Remove(s.Key); - }, CacheNotifyAction.Remove); + }, ASC.Common.Caching.EventType.Remove); } internal TenantStore GetTenantStore() @@ -190,8 +190,8 @@ namespace ASC.Core.Caching internal ITenantService Service { get; set; } private readonly ICache cache; - internal ICacheNotify<TenantSetting> CacheNotifySettings { get; set; } - internal ICacheNotify<TenantCacheItem> CacheNotifyItem { get; set; } + internal IEventBus<TenantSetting> CacheNotifySettings { get; set; } + internal IEventBus<TenantCacheItem> CacheNotifyItem { get; set; } private TimeSpan SettingsExpiration { get; set; } internal TenantServiceCache TenantServiceCache { get; set; } @@ -277,14 +277,14 @@ namespace ASC.Core.Caching public Tenant SaveTenant(CoreSettings coreSettings, Tenant tenant) { tenant = Service.SaveTenant(coreSettings, tenant); - CacheNotifyItem.Publish(new TenantCacheItem() { TenantId = tenant.TenantId }, CacheNotifyAction.InsertOrUpdate); + CacheNotifyItem.Publish(new TenantCacheItem() { TenantId = tenant.TenantId }, ASC.Common.Caching.EventType.InsertOrUpdate); return tenant; } public void RemoveTenant(int id, bool auto = false) { Service.RemoveTenant(id, auto); - CacheNotifyItem.Publish(new TenantCacheItem() { TenantId = id }, CacheNotifyAction.InsertOrUpdate); + CacheNotifyItem.Publish(new TenantCacheItem() { TenantId = id }, ASC.Common.Caching.EventType.InsertOrUpdate); } public IEnumerable<TenantVersion> GetTenantVersions() @@ -308,7 +308,7 @@ namespace ASC.Core.Caching { Service.SetTenantSettings(tenant, key, data); var cacheKey = string.Format("settings/{0}/{1}", tenant, key); - CacheNotifySettings.Publish(new TenantSetting { Key = cacheKey }, CacheNotifyAction.Remove); + CacheNotifySettings.Publish(new TenantSetting { Key = cacheKey }, ASC.Common.Caching.EventType.Remove); } } } diff --git a/common/ASC.Core.Common/Caching/CachedUserService.cs b/common/ASC.Core.Common/Caching/CachedUserService.cs index ce07a463b3..6190dac39a 100644 --- a/common/ASC.Core.Common/Caching/CachedUserService.cs +++ b/common/ASC.Core.Common/Caching/CachedUserService.cs @@ -48,17 +48,17 @@ namespace ASC.Core.Caching internal ICache Cache { get; } internal CoreBaseSettings CoreBaseSettings { get; } - internal ICacheNotify<UserInfoCacheItem> CacheUserInfoItem { get; } - internal ICacheNotify<UserPhotoCacheItem> CacheUserPhotoItem { get; } - internal ICacheNotify<GroupCacheItem> CacheGroupCacheItem { get; } - internal ICacheNotify<UserGroupRefCacheItem> CacheUserGroupRefItem { get; } + internal IEventBus<UserInfoCacheItem> CacheUserInfoItem { get; } + internal IEventBus<UserPhotoCacheItem> CacheUserPhotoItem { get; } + internal IEventBus<GroupCacheItem> CacheGroupCacheItem { get; } + internal IEventBus<UserGroupRefCacheItem> CacheUserGroupRefItem { get; } public UserServiceCache( CoreBaseSettings coreBaseSettings, - ICacheNotify<UserInfoCacheItem> cacheUserInfoItem, - ICacheNotify<UserPhotoCacheItem> cacheUserPhotoItem, - ICacheNotify<GroupCacheItem> cacheGroupCacheItem, - ICacheNotify<UserGroupRefCacheItem> cacheUserGroupRefItem, + IEventBus<UserInfoCacheItem> cacheUserInfoItem, + IEventBus<UserPhotoCacheItem> cacheUserPhotoItem, + IEventBus<GroupCacheItem> cacheGroupCacheItem, + IEventBus<UserGroupRefCacheItem> cacheUserGroupRefItem, ICache cache) { Cache = cache; @@ -68,12 +68,12 @@ namespace ASC.Core.Caching CacheGroupCacheItem = cacheGroupCacheItem; CacheUserGroupRefItem = cacheUserGroupRefItem; - cacheUserInfoItem.Subscribe((u) => InvalidateCache(u), CacheNotifyAction.Any); - cacheUserPhotoItem.Subscribe((p) => Cache.Remove(p.Key), CacheNotifyAction.Remove); - cacheGroupCacheItem.Subscribe((g) => InvalidateCache(), CacheNotifyAction.Any); + cacheUserInfoItem.Subscribe((u) => InvalidateCache(u), ASC.Common.Caching.EventType.Any); + cacheUserPhotoItem.Subscribe((p) => Cache.Remove(p.Key), ASC.Common.Caching.EventType.Remove); + cacheGroupCacheItem.Subscribe((g) => InvalidateCache(), ASC.Common.Caching.EventType.Any); - cacheUserGroupRefItem.Subscribe((r) => UpdateUserGroupRefCache(r, true), CacheNotifyAction.Remove); - cacheUserGroupRefItem.Subscribe((r) => UpdateUserGroupRefCache(r, false), CacheNotifyAction.InsertOrUpdate); + cacheUserGroupRefItem.Subscribe((r) => UpdateUserGroupRefCache(r, true), ASC.Common.Caching.EventType.Remove); + cacheUserGroupRefItem.Subscribe((r) => UpdateUserGroupRefCache(r, false), ASC.Common.Caching.EventType.InsertOrUpdate); } public void InvalidateCache() @@ -190,10 +190,10 @@ namespace ASC.Core.Caching private TimeSpan PhotoExpiration { get; set; } internal CoreBaseSettings CoreBaseSettings { get; set; } internal UserServiceCache UserServiceCache { get; set; } - internal ICacheNotify<UserInfoCacheItem> CacheUserInfoItem { get; set; } - internal ICacheNotify<UserPhotoCacheItem> CacheUserPhotoItem { get; set; } - internal ICacheNotify<GroupCacheItem> CacheGroupCacheItem { get; set; } - internal ICacheNotify<UserGroupRefCacheItem> CacheUserGroupRefItem { get; set; } + internal IEventBus<UserInfoCacheItem> CacheUserInfoItem { get; set; } + internal IEventBus<UserPhotoCacheItem> CacheUserPhotoItem { get; set; } + internal IEventBus<GroupCacheItem> CacheGroupCacheItem { get; set; } + internal IEventBus<UserGroupRefCacheItem> CacheUserGroupRefItem { get; set; } public CachedUserService() { @@ -275,14 +275,14 @@ namespace ASC.Core.Caching public UserInfo SaveUser(int tenant, UserInfo user) { user = Service.SaveUser(tenant, user); - CacheUserInfoItem.Publish(new UserInfoCacheItem { Id = user.ID.ToString(), Tenant = tenant }, CacheNotifyAction.Any); + CacheUserInfoItem.Publish(new UserInfoCacheItem { Id = user.ID.ToString(), Tenant = tenant }, ASC.Common.Caching.EventType.Any); return user; } public void RemoveUser(int tenant, Guid id) { Service.RemoveUser(tenant, id); - CacheUserInfoItem.Publish(new UserInfoCacheItem { Tenant = tenant, Id = id.ToString() }, CacheNotifyAction.Any); + CacheUserInfoItem.Publish(new UserInfoCacheItem { Tenant = tenant, Id = id.ToString() }, ASC.Common.Caching.EventType.Any); } public byte[] GetUserPhoto(int tenant, Guid id) @@ -299,7 +299,7 @@ namespace ASC.Core.Caching public void SetUserPhoto(int tenant, Guid id, byte[] photo) { Service.SetUserPhoto(tenant, id, photo); - CacheUserPhotoItem.Publish(new UserPhotoCacheItem { Key = UserServiceCache.GetUserPhotoCacheKey(tenant, id) }, CacheNotifyAction.Remove); + CacheUserPhotoItem.Publish(new UserPhotoCacheItem { Key = UserServiceCache.GetUserPhotoCacheKey(tenant, id) }, ASC.Common.Caching.EventType.Remove); } public DateTime GetUserPasswordStamp(int tenant, Guid id) @@ -330,14 +330,14 @@ namespace ASC.Core.Caching public Group SaveGroup(int tenant, Group group) { group = Service.SaveGroup(tenant, group); - CacheGroupCacheItem.Publish(new GroupCacheItem { Id = group.Id.ToString() }, CacheNotifyAction.Any); + CacheGroupCacheItem.Publish(new GroupCacheItem { Id = group.Id.ToString() }, ASC.Common.Caching.EventType.Any); return group; } public void RemoveGroup(int tenant, Guid id) { Service.RemoveGroup(tenant, id); - CacheGroupCacheItem.Publish(new GroupCacheItem { Id = id.ToString() }, CacheNotifyAction.Any); + CacheGroupCacheItem.Publish(new GroupCacheItem { Id = id.ToString() }, ASC.Common.Caching.EventType.Any); } @@ -371,7 +371,7 @@ namespace ASC.Core.Caching public UserGroupRef SaveUserGroupRef(int tenant, UserGroupRef r) { r = Service.SaveUserGroupRef(tenant, r); - CacheUserGroupRefItem.Publish(r, CacheNotifyAction.InsertOrUpdate); + CacheUserGroupRefItem.Publish(r, ASC.Common.Caching.EventType.InsertOrUpdate); return r; } @@ -380,7 +380,7 @@ namespace ASC.Core.Caching Service.RemoveUserGroupRef(tenant, userId, groupId, refType); var r = new UserGroupRef(userId, groupId, refType) { Tenant = tenant }; - CacheUserGroupRefItem.Publish(r, CacheNotifyAction.Remove); + CacheUserGroupRefItem.Publish(r, ASC.Common.Caching.EventType.Remove); } diff --git a/common/ASC.Core.Common/Configuration/Consumer.cs b/common/ASC.Core.Common/Configuration/Consumer.cs index 6ff6375c34..69d831c53f 100644 --- a/common/ASC.Core.Common/Configuration/Consumer.cs +++ b/common/ASC.Core.Common/Configuration/Consumer.cs @@ -84,7 +84,7 @@ namespace ASC.Core.Common.Configuration internal protected CoreSettings CoreSettings { get; set; } internal protected ConsumerFactory ConsumerFactory { get; set; } internal protected IConfiguration Configuration { get; } - internal protected ICacheNotify<ConsumerCacheItem> Cache { get; } + internal protected IEventBus<ConsumerCacheItem> Cache { get; } public bool IsSet { @@ -107,7 +107,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory) : this() { TenantManager = tenantManager; @@ -126,7 +126,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> additional) : this(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory) @@ -142,7 +142,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : this(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory) @@ -184,7 +184,7 @@ namespace ASC.Core.Common.Configuration this[providerProp.Key] = null; } - Cache.Publish(new ConsumerCacheItem() { Name = this.Name }, CacheNotifyAction.Remove); + Cache.Publish(new ConsumerCacheItem() { Name = this.Name }, ASC.Common.Caching.EventType.Remove); } public bool Contains(KeyValuePair<string, string> item) @@ -304,7 +304,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory) { @@ -316,7 +316,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) @@ -329,7 +329,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.Core.Common/Context/WorkContext.cs b/common/ASC.Core.Common/Context/WorkContext.cs index c9d5f1f75a..6069c6232a 100644 --- a/common/ASC.Core.Common/Context/WorkContext.cs +++ b/common/ASC.Core.Common/Context/WorkContext.cs @@ -102,8 +102,8 @@ namespace ASC.Core if (notifyStarted) return; var configuration = serviceProvider.GetService<IConfiguration>(); - var cacheNotify = serviceProvider.GetService<ICacheNotify<NotifyMessage>>(); - var cacheInvoke = serviceProvider.GetService<ICacheNotify<NotifyInvoke>>(); + var cacheNotify = serviceProvider.GetService<IEventBus<NotifyMessage>>(); + var cacheInvoke = serviceProvider.GetService<IEventBus<NotifyInvoke>>(); var options = serviceProvider.GetService<IOptionsMonitor<ILog>>(); NotifyContext = new NotifyContext(serviceProvider); diff --git a/common/ASC.Core.Common/Data/DbSettingsManager.cs b/common/ASC.Core.Common/Data/DbSettingsManager.cs index d83a3c85d7..e0c2f1191d 100644 --- a/common/ASC.Core.Common/Data/DbSettingsManager.cs +++ b/common/ASC.Core.Common/Data/DbSettingsManager.cs @@ -46,18 +46,18 @@ namespace ASC.Core.Data public class DbSettingsManagerCache { public ICache Cache { get; } - private ICacheNotify<SettingsCacheItem> Notify { get; } + private IEventBus<SettingsCacheItem> Notify { get; } - public DbSettingsManagerCache(ICacheNotify<SettingsCacheItem> notify, ICache cache) + public DbSettingsManagerCache(IEventBus<SettingsCacheItem> notify, ICache cache) { Cache = cache; Notify = notify; - Notify.Subscribe((i) => Cache.Remove(i.Key), CacheNotifyAction.Remove); + Notify.Subscribe((i) => Cache.Remove(i.Key), ASC.Common.Caching.EventType.Remove); } public void Remove(string key) { - Notify.Publish(new SettingsCacheItem { Key = key }, CacheNotifyAction.Remove); + Notify.Publish(new SettingsCacheItem { Key = key }, ASC.Common.Caching.EventType.Remove); } } diff --git a/common/ASC.Core.Common/Notify/NotifyServiceClient.cs b/common/ASC.Core.Common/Notify/NotifyServiceClient.cs index f14c39a7b5..c11b220f23 100644 --- a/common/ASC.Core.Common/Notify/NotifyServiceClient.cs +++ b/common/ASC.Core.Common/Notify/NotifyServiceClient.cs @@ -34,9 +34,9 @@ namespace ASC.Core.Notify [Scope] public class NotifyServiceClient : INotifyService { - private readonly ICacheNotify<NotifyMessage> СacheNotify; - private readonly ICacheNotify<NotifyInvoke> NotifyInvoke; - public NotifyServiceClient(ICacheNotify<NotifyMessage> cacheNotify, ICacheNotify<NotifyInvoke> notifyInvoke) + private readonly IEventBus<NotifyMessage> СacheNotify; + private readonly IEventBus<NotifyInvoke> NotifyInvoke; + public NotifyServiceClient(IEventBus<NotifyMessage> cacheNotify, IEventBus<NotifyInvoke> notifyInvoke) { СacheNotify = cacheNotify; NotifyInvoke = notifyInvoke; @@ -44,12 +44,12 @@ namespace ASC.Core.Notify public void SendNotifyMessage(NotifyMessage m) { - СacheNotify.Publish(m, CacheNotifyAction.InsertOrUpdate); + СacheNotify.Publish(m, EventType.InsertOrUpdate); } public void InvokeSendMethod(NotifyInvoke notifyInvoke) { - NotifyInvoke.Publish(notifyInvoke, CacheNotifyAction.InsertOrUpdate); + NotifyInvoke.Publish(notifyInvoke, EventType.InsertOrUpdate); } } } diff --git a/common/ASC.Core.Common/Notify/Senders/NotifyServiceSender.cs b/common/ASC.Core.Common/Notify/Senders/NotifyServiceSender.cs index a4f90e3d3c..3cdbd4038f 100644 --- a/common/ASC.Core.Common/Notify/Senders/NotifyServiceSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/NotifyServiceSender.cs @@ -34,7 +34,7 @@ namespace ASC.Core.Notify.Senders public class NotifyServiceSender : INotifySender { public NotifyServiceClient NotifyServiceClient { get; } - public NotifyServiceSender(ICacheNotify<NotifyMessage> cacheNotify, ICacheNotify<NotifyInvoke> notifyInvoke) + public NotifyServiceSender(IEventBus<NotifyMessage> cacheNotify, IEventBus<NotifyInvoke> notifyInvoke) { NotifyServiceClient = new NotifyServiceClient(cacheNotify, notifyInvoke); } diff --git a/common/ASC.Core.Common/Notify/Telegram/TelegramServiceClient.cs b/common/ASC.Core.Common/Notify/Telegram/TelegramServiceClient.cs index 7792f6db62..427253d8c7 100644 --- a/common/ASC.Core.Common/Notify/Telegram/TelegramServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Telegram/TelegramServiceClient.cs @@ -35,17 +35,17 @@ namespace ASC.Core.Common.Notify [Singletone] public class TelegramServiceClient : ITelegramService { - private ICacheNotify<NotifyMessage> CacheMessage { get; } - private ICacheNotify<RegisterUserProto> CacheRegisterUser { get; } - private ICacheNotify<CreateClientProto> CacheCreateClient { get; } - private ICacheNotify<DisableClientProto> CacheDisableClient { get; } + private IEventBus<NotifyMessage> CacheMessage { get; } + private IEventBus<RegisterUserProto> CacheRegisterUser { get; } + private IEventBus<CreateClientProto> CacheCreateClient { get; } + private IEventBus<DisableClientProto> CacheDisableClient { get; } private ICache Cache { get; } - public TelegramServiceClient(ICacheNotify<NotifyMessage> cacheMessage, - ICacheNotify<RegisterUserProto> cacheRegisterUser, - ICacheNotify<CreateClientProto> cacheCreateClient, - ICacheNotify<DisableClientProto> cacheDisableClient, + public TelegramServiceClient(IEventBus<NotifyMessage> cacheMessage, + IEventBus<RegisterUserProto> cacheRegisterUser, + IEventBus<CreateClientProto> cacheCreateClient, + IEventBus<DisableClientProto> cacheDisableClient, ICache cache) { CacheMessage = cacheMessage; @@ -57,7 +57,7 @@ namespace ASC.Core.Common.Notify public void SendMessage(NotifyMessage m) { - CacheMessage.Publish(m, CacheNotifyAction.Insert); + CacheMessage.Publish(m, ASC.Common.Caching.EventType.Insert); } public void RegisterUser(string userId, int tenantId, string token) @@ -68,7 +68,7 @@ namespace ASC.Core.Common.Notify UserId = userId, TenantId = tenantId, Token = token - }, CacheNotifyAction.Insert); + }, ASC.Common.Caching.EventType.Insert); } public void CreateOrUpdateClient(int tenantId, string token, int tokenLifespan, string proxy) @@ -79,12 +79,12 @@ namespace ASC.Core.Common.Notify Token = token, TokenLifespan = tokenLifespan, Proxy = proxy - }, CacheNotifyAction.Insert); + }, ASC.Common.Caching.EventType.Insert); } public void DisableClient(int tenantId) { - CacheDisableClient.Publish(new DisableClientProto() { TenantId = tenantId }, CacheNotifyAction.Insert); + CacheDisableClient.Publish(new DisableClientProto() { TenantId = tenantId }, ASC.Common.Caching.EventType.Insert); } public string RegistrationToken(string userId, int tenantId) diff --git a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs index ff32c687e0..c5a4e9be68 100644 --- a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs +++ b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs @@ -63,7 +63,7 @@ namespace ASC.Data.Backup.Services private Dictionary<string, string> ConfigPaths { get; set; } private int Limit { get; set; } private string UpgradesPath { get; set; } - private ICacheNotify<BackupProgress> CacheBackupProgress { get; } + private IEventBus<BackupProgress> CacheBackupProgress { get; } private FactoryProgressItem FactoryProgressItem { get; set; } private TempPath TempPath { get; } @@ -71,7 +71,7 @@ namespace ASC.Data.Backup.Services public BackupWorker( IOptionsMonitor<ILog> options, - ICacheNotify<BackupProgress> cacheBackupProgress, + IEventBus<BackupProgress> cacheBackupProgress, DistributedTaskQueueOptionsManager progressQueue, FactoryProgressItem factoryProgressItem, TempPath tempPath) diff --git a/common/ASC.Data.Storage/Configuration/StorageSettings.cs b/common/ASC.Data.Storage/Configuration/StorageSettings.cs index c533a93760..36d4832da9 100644 --- a/common/ASC.Data.Storage/Configuration/StorageSettings.cs +++ b/common/ASC.Data.Storage/Configuration/StorageSettings.cs @@ -63,7 +63,7 @@ namespace ASC.Data.Storage.Configuration Subscribed = true; - ServiceProvider.GetService<ICacheNotify<ConsumerCacheItem>>().Subscribe((i) => + ServiceProvider.GetService<IEventBus<ConsumerCacheItem>>().Subscribe((i) => { using var scope = ServiceProvider.CreateScope(); @@ -80,7 +80,7 @@ namespace ASC.Data.Storage.Configuration { storageSettingsHelper.Clear(cdnSettings); } - }, CacheNotifyAction.Remove); + }, Common.Caching.EventType.Remove); } } } @@ -99,7 +99,7 @@ namespace ASC.Data.Storage.Configuration public virtual Func<DataStoreConsumer, DataStoreConsumer> Switch { get { return d => d; } } - internal ICacheNotify<DataStoreCacheItem> Cache { get; set; } + internal IEventBus<DataStoreCacheItem> Cache { get; set; } public abstract Guid ID { get; } } @@ -130,7 +130,7 @@ namespace ASC.Data.Storage.Configuration { private StorageFactoryConfig StorageFactoryConfig { get; } private PathUtils PathUtils { get; } - private ICacheNotify<DataStoreCacheItem> Cache { get; } + private IEventBus<DataStoreCacheItem> Cache { get; } private IOptionsMonitor<ILog> Options { get; } private TenantManager TenantManager { get; } private SettingsManager SettingsManager { get; } @@ -141,7 +141,7 @@ namespace ASC.Data.Storage.Configuration BaseStorageSettingsListener baseStorageSettingsListener, StorageFactoryConfig storageFactoryConfig, PathUtils pathUtils, - ICacheNotify<DataStoreCacheItem> cache, + IEventBus<DataStoreCacheItem> cache, IOptionsMonitor<ILog> options, TenantManager tenantManager, SettingsManager settingsManager, @@ -160,7 +160,7 @@ namespace ASC.Data.Storage.Configuration BaseStorageSettingsListener baseStorageSettingsListener, StorageFactoryConfig storageFactoryConfig, PathUtils pathUtils, - ICacheNotify<DataStoreCacheItem> cache, + IEventBus<DataStoreCacheItem> cache, IOptionsMonitor<ILog> options, TenantManager tenantManager, SettingsManager settingsManager, @@ -184,7 +184,7 @@ namespace ASC.Data.Storage.Configuration var path = TenantPath.CreatePath(tenantId); foreach (var module in StorageFactoryConfig.GetModuleList("", true)) { - Cache.Publish(new DataStoreCacheItem() { TenantId = path, Module = module }, CacheNotifyAction.Remove); + Cache.Publish(new DataStoreCacheItem() { TenantId = path, Module = module }, Common.Caching.EventType.Remove); } } diff --git a/common/ASC.Data.Storage/Encryption/EncryptionServiceClient.cs b/common/ASC.Data.Storage/Encryption/EncryptionServiceClient.cs index 55af732fbc..88c452ea76 100644 --- a/common/ASC.Data.Storage/Encryption/EncryptionServiceClient.cs +++ b/common/ASC.Data.Storage/Encryption/EncryptionServiceClient.cs @@ -34,11 +34,11 @@ namespace ASC.Data.Storage.Encryption public class EncryptionServiceClient : IEncryptionService { - private ICacheNotify<EncryptionSettingsProto> NotifySetting { get; } - private ICacheNotify<EncryptionStop> NotifyStop { get; } + private IEventBus<EncryptionSettingsProto> NotifySetting { get; } + private IEventBus<EncryptionStop> NotifyStop { get; } public EncryptionServiceClient( - ICacheNotify<EncryptionSettingsProto> notifySetting, ICacheNotify<EncryptionStop> notifyStop) + IEventBus<EncryptionSettingsProto> notifySetting, IEventBus<EncryptionStop> notifyStop) { NotifySetting = notifySetting; NotifyStop = notifyStop; @@ -46,12 +46,12 @@ namespace ASC.Data.Storage.Encryption public void Start(EncryptionSettingsProto encryptionSettingsProto) { - NotifySetting.Publish(encryptionSettingsProto, CacheNotifyAction.Insert); + NotifySetting.Publish(encryptionSettingsProto, EventType.Insert); } public void Stop() { - NotifyStop.Publish(new EncryptionStop(), CacheNotifyAction.Insert); + NotifyStop.Publish(new EncryptionStop(), EventType.Insert); } } diff --git a/common/ASC.Data.Storage/Migration/MigrateServiceClient.cs b/common/ASC.Data.Storage/Migration/MigrateServiceClient.cs index 4ee2df0216..241907b558 100644 --- a/common/ASC.Data.Storage/Migration/MigrateServiceClient.cs +++ b/common/ASC.Data.Storage/Migration/MigrateServiceClient.cs @@ -36,12 +36,12 @@ namespace ASC.Data.Storage.Migration [Singletone] public class ServiceClientListener { - private ICacheNotify<MigrationProgress> ProgressMigrationNotify { get; } + private IEventBus<MigrationProgress> ProgressMigrationNotify { get; } private IServiceProvider ServiceProvider { get; } private ICache Cache { get; } public ServiceClientListener( - ICacheNotify<MigrationProgress> progressMigrationNotify, + IEventBus<MigrationProgress> progressMigrationNotify, IServiceProvider serviceProvider, ICache cache) { @@ -71,7 +71,7 @@ namespace ASC.Data.Storage.Migration Cache.Insert(GetCacheKey(n.TenantId), migrationProgress, DateTime.MaxValue); }, - CacheNotifyAction.Insert); + Common.Caching.EventType.Insert); } private string GetCacheKey(int tenantId) @@ -84,14 +84,14 @@ namespace ASC.Data.Storage.Migration public class ServiceClient : IService { public ServiceClientListener ServiceClientListener { get; } - public ICacheNotify<MigrationCache> CacheMigrationNotify { get; } - public ICacheNotify<MigrationUploadCdn> UploadCdnMigrationNotify { get; } + public IEventBus<MigrationCache> CacheMigrationNotify { get; } + public IEventBus<MigrationUploadCdn> UploadCdnMigrationNotify { get; } public IServiceProvider ServiceProvider { get; } public ServiceClient( ServiceClientListener serviceClientListener, - ICacheNotify<MigrationCache> cacheMigrationNotify, - ICacheNotify<MigrationUploadCdn> uploadCdnMigrationNotify, + IEventBus<MigrationCache> cacheMigrationNotify, + IEventBus<MigrationUploadCdn> uploadCdnMigrationNotify, IServiceProvider serviceProvider) { ServiceClientListener = serviceClientListener; @@ -109,7 +109,7 @@ namespace ASC.Data.Storage.Migration TenantId = tenant, StorSettings = storSettings }, - CacheNotifyAction.Insert); + Common.Caching.EventType.Insert); } public void UploadCdn(int tenantId, string relativePath, string mappedPath, CdnStorageSettings settings = null) @@ -123,7 +123,7 @@ namespace ASC.Data.Storage.Migration MappedPath = mappedPath, CdnStorSettings = cdnStorSettings }, - CacheNotifyAction.Insert); + Common.Caching.EventType.Insert); } public double GetProgress(int tenant) @@ -135,7 +135,7 @@ namespace ASC.Data.Storage.Migration public void StopMigrate() { - CacheMigrationNotify.Publish(new MigrationCache(), CacheNotifyAction.InsertOrUpdate); + CacheMigrationNotify.Publish(new MigrationCache(), Common.Caching.EventType.InsertOrUpdate); } } } diff --git a/common/ASC.Data.Storage/StorageUploader.cs b/common/ASC.Data.Storage/StorageUploader.cs index 9b091dc177..2358afafa8 100644 --- a/common/ASC.Data.Storage/StorageUploader.cs +++ b/common/ASC.Data.Storage/StorageUploader.cs @@ -53,14 +53,14 @@ namespace ASC.Data.Storage private IServiceProvider ServiceProvider { get; } private TempStream TempStream { get; } - private ICacheNotify<MigrationProgress> CacheMigrationNotify { get; } + private IEventBus<MigrationProgress> CacheMigrationNotify { get; } static StorageUploader() { Locker = new object(); } - public StorageUploader(IServiceProvider serviceProvider, TempStream tempStream, ICacheNotify<MigrationProgress> cacheMigrationNotify, DistributedTaskQueueOptionsManager options) + public StorageUploader(IServiceProvider serviceProvider, TempStream tempStream, IEventBus<MigrationProgress> cacheMigrationNotify, DistributedTaskQueueOptionsManager options) { ServiceProvider = serviceProvider; TempStream = tempStream; @@ -119,7 +119,7 @@ namespace ASC.Data.Storage public MigrateOperation( IServiceProvider serviceProvider, - ICacheNotify<MigrationProgress> cacheMigrationNotify, + IEventBus<MigrationProgress> cacheMigrationNotify, string id, int tenantId, StorageSettings settings, @@ -143,7 +143,7 @@ namespace ASC.Data.Storage private IServiceProvider ServiceProvider { get; } private StorageFactoryConfig StorageFactoryConfig { get; } private TempStream TempStream { get; } - private ICacheNotify<MigrationProgress> CacheMigrationNotify { get; } + private IEventBus<MigrationProgress> CacheMigrationNotify { get; } protected override void DoJob() { @@ -230,7 +230,7 @@ namespace ASC.Data.Storage Error = Exception.ToString(), IsCompleted = IsCompleted }, - CacheNotifyAction.Insert); + Common.Caching.EventType.Insert); } } diff --git a/common/ASC.FederatedLogin/AccountLinker.cs b/common/ASC.FederatedLogin/AccountLinker.cs index 946609794d..d0d7f1800e 100644 --- a/common/ASC.FederatedLogin/AccountLinker.cs +++ b/common/ASC.FederatedLogin/AccountLinker.cs @@ -47,18 +47,18 @@ namespace ASC.FederatedLogin public class AccountLinkerStorage { private readonly ICache cache; - private readonly ICacheNotify<LinkerCacheItem> notify; + private readonly IEventBus<LinkerCacheItem> notify; - public AccountLinkerStorage(ICacheNotify<LinkerCacheItem> notify, ICache cache) + public AccountLinkerStorage(IEventBus<LinkerCacheItem> notify, ICache cache) { this.cache = cache; this.notify = notify; - notify.Subscribe((c) => cache.Remove(c.Obj), CacheNotifyAction.Remove); + notify.Subscribe((c) => cache.Remove(c.Obj), Common.Caching.EventType.Remove); } public void RemoveFromCache(string obj) { - notify.Publish(new LinkerCacheItem { Obj = obj }, CacheNotifyAction.Remove); + notify.Publish(new LinkerCacheItem { Obj = obj }, Common.Caching.EventType.Remove); } public List<LoginProfile> GetFromCache(string obj, Func<string, List<LoginProfile>> fromDb) { diff --git a/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs index 89cefcaaed..b71d06556d 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs @@ -101,7 +101,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/BitlyLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/BitlyLoginProvider.cs index 2ed9d6ecc7..e1ffeb10f2 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BitlyLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BitlyLoginProvider.cs @@ -65,7 +65,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/BoxLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/BoxLoginProvider.cs index f29e3f3b7b..da9dba5598 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BoxLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BoxLoginProvider.cs @@ -62,7 +62,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs index a5822378a3..af17d0dae7 100644 --- a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs @@ -67,7 +67,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/DropboxLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/DropboxLoginProvider.cs index 301ec6b6a4..ac26e1c4dd 100644 --- a/common/ASC.FederatedLogin/LoginProviders/DropboxLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/DropboxLoginProvider.cs @@ -62,7 +62,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs index 8586df0b38..76af52b7bb 100644 --- a/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs @@ -61,7 +61,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs index d52237aaaf..a1ee204667 100644 --- a/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs @@ -76,7 +76,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs index a9e477a798..7a477d097e 100644 --- a/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs @@ -104,7 +104,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/LinkedInLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/LinkedInLoginProvider.cs index def8917ae4..0d4fa2135b 100644 --- a/common/ASC.FederatedLogin/LoginProviders/LinkedInLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/LinkedInLoginProvider.cs @@ -85,7 +85,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs index 6f73b71e5d..976dffa311 100644 --- a/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs @@ -88,7 +88,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/OneDriveLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/OneDriveLoginProvider.cs index aa85fb4abd..e7afb42a28 100644 --- a/common/ASC.FederatedLogin/LoginProviders/OneDriveLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/OneDriveLoginProvider.cs @@ -66,7 +66,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs index 3a86305340..bcdb7cf63e 100644 --- a/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs @@ -73,7 +73,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs index 1a4f6b9516..6e425df910 100644 --- a/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs @@ -92,7 +92,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/WordpressLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/WordpressLoginProvider.cs index acb1d048b2..c062b3f77e 100644 --- a/common/ASC.FederatedLogin/LoginProviders/WordpressLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/WordpressLoginProvider.cs @@ -57,7 +57,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/YahooLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/YahooLoginProvider.cs index b670abb4bd..fb449ce4f0 100644 --- a/common/ASC.FederatedLogin/LoginProviders/YahooLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/YahooLoginProvider.cs @@ -61,7 +61,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs index 96a96c4840..5c2aaee898 100644 --- a/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs @@ -85,7 +85,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.IPSecurity/IPRestrictionsService.cs b/common/ASC.IPSecurity/IPRestrictionsService.cs index aa4d5483d1..78e8e087d0 100644 --- a/common/ASC.IPSecurity/IPRestrictionsService.cs +++ b/common/ASC.IPSecurity/IPRestrictionsService.cs @@ -38,12 +38,12 @@ namespace ASC.IPSecurity private const string cacheKey = "iprestrictions"; public ICache Cache { get; set; } - internal ICacheNotify<IPRestrictionItem> Notify { get; } + internal IEventBus<IPRestrictionItem> Notify { get; } - public IPRestrictionsServiceCache(ICacheNotify<IPRestrictionItem> notify, ICache cache) + public IPRestrictionsServiceCache(IEventBus<IPRestrictionItem> notify, ICache cache) { Cache = cache; - notify.Subscribe((r) => Cache.Remove(GetCacheKey(r.TenantId)), CacheNotifyAction.Any); + notify.Subscribe((r) => Cache.Remove(GetCacheKey(r.TenantId)), Common.Caching.EventType.Any); Notify = notify; } @@ -57,7 +57,7 @@ namespace ASC.IPSecurity public class IPRestrictionsService { private readonly ICache cache; - private readonly ICacheNotify<IPRestrictionItem> notify; + private readonly IEventBus<IPRestrictionItem> notify; private static readonly TimeSpan timeout = TimeSpan.FromMinutes(5); private IPRestrictionsRepository IPRestrictionsRepository { get; } @@ -85,7 +85,7 @@ namespace ASC.IPSecurity public IEnumerable<string> Save(IEnumerable<string> ips, int tenant) { var restrictions = IPRestrictionsRepository.Save(ips, tenant); - notify.Publish(new IPRestrictionItem { TenantId = tenant }, CacheNotifyAction.InsertOrUpdate); + notify.Publish(new IPRestrictionItem { TenantId = tenant }, Common.Caching.EventType.InsertOrUpdate); return restrictions; } } diff --git a/common/ASC.VoipService/Dao/CachedVoipDao.cs b/common/ASC.VoipService/Dao/CachedVoipDao.cs index 0a39bf0031..7eb1754b75 100644 --- a/common/ASC.VoipService/Dao/CachedVoipDao.cs +++ b/common/ASC.VoipService/Dao/CachedVoipDao.cs @@ -44,18 +44,18 @@ namespace ASC.VoipService.Dao public class VoipDaoCache { internal ICache Cache { get; } - private ICacheNotify<CachedVoipItem> Notify { get; } + private IEventBus<CachedVoipItem> Notify { get; } - public VoipDaoCache(ICacheNotify<CachedVoipItem> notify, ICache cache) + public VoipDaoCache(IEventBus<CachedVoipItem> notify, ICache cache) { Cache = cache; Notify = notify; - Notify.Subscribe((c) => Cache.Remove(CachedVoipDao.GetCacheKey(c.Tenant)), CacheNotifyAction.Any); + Notify.Subscribe((c) => Cache.Remove(CachedVoipDao.GetCacheKey(c.Tenant)), Common.Caching.EventType.Any); } public void ResetCache(int tenant) { - Notify.Publish(new CachedVoipItem { Tenant = tenant }, CacheNotifyAction.Any); + Notify.Publish(new CachedVoipItem { Tenant = tenant }, Common.Caching.EventType.Any); } } diff --git a/common/ASC.Webhooks.Core/WebhookPublisher.cs b/common/ASC.Webhooks.Core/WebhookPublisher.cs index eaa4f7b325..16b4b8d8d9 100644 --- a/common/ASC.Webhooks.Core/WebhookPublisher.cs +++ b/common/ASC.Webhooks.Core/WebhookPublisher.cs @@ -16,13 +16,13 @@ namespace ASC.Webhooks.Core { private DbWorker DbWorker { get; } private TenantManager TenantManager { get; } - private ICacheNotify<WebhookRequest> WebhookNotify { get; } + private IEventBus<WebhookRequest> WebhookNotify { get; } public WebhookPublisher( DbWorker dbWorker, TenantManager tenantManager, IOptionsMonitor<ILog> options, - ICacheNotify<WebhookRequest> webhookNotify) + IEventBus<WebhookRequest> webhookNotify) { DbWorker = dbWorker; TenantManager = tenantManager; @@ -53,7 +53,7 @@ namespace ASC.Webhooks.Core Id = DbId }; - WebhookNotify.Publish(request, CacheNotifyAction.Update); + WebhookNotify.Publish(request, Common.Caching.EventType.Update); } } } diff --git a/common/services/ASC.ClearEvents/Program.cs b/common/services/ASC.ClearEvents/Program.cs index 8110acd843..354049b7b9 100644 --- a/common/services/ASC.ClearEvents/Program.cs +++ b/common/services/ASC.ClearEvents/Program.cs @@ -89,15 +89,15 @@ public class Program if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); } else { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); } services.AddHostedService<ClearEventsServiceLauncher>(); diff --git a/common/services/ASC.Data.Backup/Services/BackupListenerService.cs b/common/services/ASC.Data.Backup/Services/BackupListenerService.cs index 14c765424d..6a36d9e686 100644 --- a/common/services/ASC.Data.Backup/Services/BackupListenerService.cs +++ b/common/services/ASC.Data.Backup/Services/BackupListenerService.cs @@ -3,10 +3,10 @@ [Singletone] internal sealed class BackupListenerService : IHostedService { - private readonly ICacheNotify<DeleteSchedule> _cacheDeleteSchedule; + private readonly IEventBus<DeleteSchedule> _cacheDeleteSchedule; private readonly IServiceScopeFactory _scopeFactory; - public BackupListenerService(ICacheNotify<DeleteSchedule> cacheDeleteSchedule, + public BackupListenerService(IEventBus<DeleteSchedule> cacheDeleteSchedule, IServiceScopeFactory scopeFactory) { _cacheDeleteSchedule = cacheDeleteSchedule; @@ -25,14 +25,14 @@ internal sealed class BackupListenerService : IHostedService public Task StartAsync(CancellationToken cancellationToken) { - _cacheDeleteSchedule.Subscribe((n) => DeleteScheldure(n), CacheNotifyAction.Insert); + _cacheDeleteSchedule.Subscribe((n) => DeleteScheldure(n), Common.Caching.EventType.Insert); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { - _cacheDeleteSchedule.Unsubscribe(CacheNotifyAction.Insert); + _cacheDeleteSchedule.Unsubscribe(Common.Caching.EventType.Insert); return Task.CompletedTask; } diff --git a/common/services/ASC.ElasticSearch/Core/SearchSettings.cs b/common/services/ASC.ElasticSearch/Core/SearchSettings.cs index cc049827d4..d8658d837e 100644 --- a/common/services/ASC.ElasticSearch/Core/SearchSettings.cs +++ b/common/services/ASC.ElasticSearch/Core/SearchSettings.cs @@ -86,7 +86,7 @@ namespace ASC.ElasticSearch.Core private TenantManager TenantManager { get; } private SettingsManager SettingsManager { get; } private CoreBaseSettings CoreBaseSettings { get; } - private ICacheNotify<ReIndexAction> CacheNotify { get; } + private IEventBus<ReIndexAction> CacheNotify { get; } private IServiceProvider ServiceProvider { get; } public IConfiguration Configuration { get; } @@ -94,7 +94,7 @@ namespace ASC.ElasticSearch.Core TenantManager tenantManager, SettingsManager settingsManager, CoreBaseSettings coreBaseSettings, - ICacheNotify<ReIndexAction> cacheNotify, + IEventBus<ReIndexAction> cacheNotify, IServiceProvider serviceProvider, IConfiguration configuration) { @@ -145,7 +145,7 @@ namespace ASC.ElasticSearch.Core var action = new ReIndexAction() { Tenant = TenantManager.GetCurrentTenant().TenantId }; action.Names.AddRange(toReIndex.Select(r => r.ID).ToList()); - CacheNotify.Publish(action, CacheNotifyAction.Any); + CacheNotify.Publish(action, Common.Caching.EventType.Any); } public bool CanIndexByContent<T>(int tenantId) where T : class, ISearchItem diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index 2cff58569f..219091861f 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -57,21 +57,21 @@ namespace ASC.ElasticSearch public class BaseIndexerHelper { public ConcurrentDictionary<string, bool> IsExist { get; set; } - private readonly ICacheNotify<ClearIndexAction> Notify; + private readonly IEventBus<ClearIndexAction> Notify; - public BaseIndexerHelper(ICacheNotify<ClearIndexAction> cacheNotify) + public BaseIndexerHelper(IEventBus<ClearIndexAction> cacheNotify) { IsExist = new ConcurrentDictionary<string, bool>(); Notify = cacheNotify; Notify.Subscribe((a) => { - IsExist.AddOrUpdate(a.Id, false, (q, w) => false); - }, CacheNotifyAction.Any); + IsExist.AddOrUpdate(a.Id, false, (string q, bool w) => false); + }, Common.Caching.EventType.Any); } public void Clear<T>(T t) where T : class, ISearchItem { - Notify.Publish(new ClearIndexAction() { Id = t.IndexName }, CacheNotifyAction.Any); + Notify.Publish(new ClearIndexAction() { Id = t.IndexName }, Common.Caching.EventType.Any); } } diff --git a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs index 2c79d0b214..74fc14518d 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -56,7 +56,7 @@ namespace ASC.ElasticSearch public DateTime LastIndexed { get; set; } public string Indexing { get; set; } - public FactoryIndexerHelper(ICacheNotify<IndexAction> cacheNotify) + public FactoryIndexerHelper(IEventBus<IndexAction> cacheNotify) { cacheNotify.Subscribe((a) => { @@ -65,7 +65,7 @@ namespace ASC.ElasticSearch LastIndexed = new DateTime(a.LastIndexed); } Indexing = a.Indexing; - }, CacheNotifyAction.Any); + }, Common.Caching.EventType.Any); } } @@ -480,7 +480,7 @@ namespace ASC.ElasticSearch Indexer.Refresh(); } - private Task<bool> Queue(Action actionData) + private Task<bool> Queue(System.Action actionData) { var task = new Task<bool>(() => { diff --git a/common/services/ASC.ElasticSearch/Service/Launcher.cs b/common/services/ASC.ElasticSearch/Service/Launcher.cs index d8d5f61b8f..4d6c130cde 100644 --- a/common/services/ASC.ElasticSearch/Service/Launcher.cs +++ b/common/services/ASC.ElasticSearch/Service/Launcher.cs @@ -44,8 +44,8 @@ namespace ASC.ElasticSearch public class ServiceLauncher : IHostedService { private ILog Log { get; } - private ICacheNotify<AscCacheItem> Notify { get; } - private ICacheNotify<IndexAction> IndexNotify { get; } + private IEventBus<AscCacheItem> Notify { get; } + private IEventBus<IndexAction> IndexNotify { get; } private IServiceProvider ServiceProvider { get; } private bool IsStarted { get; set; } private CancellationTokenSource CancellationTokenSource { get; set; } @@ -54,8 +54,8 @@ namespace ASC.ElasticSearch public ServiceLauncher( IOptionsMonitor<ILog> options, - ICacheNotify<AscCacheItem> notify, - ICacheNotify<IndexAction> indexNotify, + IEventBus<AscCacheItem> notify, + IEventBus<IndexAction> indexNotify, IServiceProvider serviceProvider, Settings settings) { @@ -78,7 +78,7 @@ namespace ASC.ElasticSearch await Task.Delay(10000); } IndexAll(true); - }, CacheNotifyAction.Any); + }, Common.Caching.EventType.Any); } catch (Exception e) { @@ -147,7 +147,7 @@ namespace ASC.ElasticSearch } Timer.Change(Period, Period); - IndexNotify.Publish(new IndexAction() { Indexing = "", LastIndexed = DateTime.Now.Ticks }, CacheNotifyAction.Any); + IndexNotify.Publish(new IndexAction() { Indexing = "", LastIndexed = DateTime.Now.Ticks }, Common.Caching.EventType.Any); IsStarted = false; } catch (Exception e) @@ -180,7 +180,7 @@ namespace ASC.ElasticSearch if (!IsStarted) return; Log.DebugFormat("Product {0}", product.IndexName); - IndexNotify.Publish(new IndexAction() { Indexing = product.IndexName, LastIndexed = 0 }, CacheNotifyAction.Any); + IndexNotify.Publish(new IndexAction() { Indexing = product.IndexName, LastIndexed = 0 }, Common.Caching.EventType.Any); product.IndexAll(); } catch (Exception e) diff --git a/common/services/ASC.ElasticSearch/Service/Service.cs b/common/services/ASC.ElasticSearch/Service/Service.cs index 12a2b4462e..ef27f48581 100644 --- a/common/services/ASC.ElasticSearch/Service/Service.cs +++ b/common/services/ASC.ElasticSearch/Service/Service.cs @@ -43,9 +43,9 @@ namespace ASC.ElasticSearch.Service public class Service { private IServiceProvider ServiceProvider { get; } - private ICacheNotify<ReIndexAction> CacheNotify { get; } + private IEventBus<ReIndexAction> CacheNotify { get; } - public Service(IServiceProvider serviceProvider, ICacheNotify<ReIndexAction> cacheNotify) + public Service(IServiceProvider serviceProvider, IEventBus<ReIndexAction> cacheNotify) { ServiceProvider = serviceProvider; CacheNotify = cacheNotify; @@ -56,7 +56,7 @@ namespace ASC.ElasticSearch.Service CacheNotify.Subscribe((a) => { ReIndex(a.Names.ToList(), a.Tenant); - }, CacheNotifyAction.Any); + }, Common.Caching.EventType.Any); } public bool Support(string table) diff --git a/common/services/ASC.Notify/NotifyService.cs b/common/services/ASC.Notify/NotifyService.cs index 7507390e16..1e2988153b 100644 --- a/common/services/ASC.Notify/NotifyService.cs +++ b/common/services/ASC.Notify/NotifyService.cs @@ -45,12 +45,12 @@ namespace ASC.Notify { private ILog Log { get; } - private ICacheNotify<NotifyMessage> CacheNotify { get; } - private ICacheNotify<NotifyInvoke> CacheInvoke { get; } + private IEventBus<NotifyMessage> CacheNotify { get; } + private IEventBus<NotifyInvoke> CacheInvoke { get; } private DbWorker Db { get; } private IServiceProvider ServiceProvider { get; } - public NotifyService(DbWorker db, IServiceProvider serviceProvider, ICacheNotify<NotifyMessage> cacheNotify, ICacheNotify<NotifyInvoke> cacheInvoke, IOptionsMonitor<ILog> options) + public NotifyService(DbWorker db, IServiceProvider serviceProvider, IEventBus<NotifyMessage> cacheNotify, IEventBus<NotifyInvoke> cacheInvoke, IOptionsMonitor<ILog> options) { Db = db; ServiceProvider = serviceProvider; @@ -61,13 +61,13 @@ namespace ASC.Notify public void Start() { - CacheNotify.Subscribe((n) => SendNotifyMessage(n), CacheNotifyAction.InsertOrUpdate); - CacheInvoke.Subscribe((n) => InvokeSendMethod(n), CacheNotifyAction.InsertOrUpdate); + CacheNotify.Subscribe((n) => SendNotifyMessage(n), Common.Caching.EventType.InsertOrUpdate); + CacheInvoke.Subscribe((n) => InvokeSendMethod(n), Common.Caching.EventType.InsertOrUpdate); } public void Stop() { - CacheNotify.Unsubscribe(CacheNotifyAction.InsertOrUpdate); + CacheNotify.Unsubscribe(Common.Caching.EventType.InsertOrUpdate); } public void SendNotifyMessage(NotifyMessage notifyMessage) @@ -115,8 +115,8 @@ namespace ASC.Notify public void Dispose() { - CacheNotify.Unsubscribe(CacheNotifyAction.InsertOrUpdate); - CacheInvoke.Unsubscribe(CacheNotifyAction.InsertOrUpdate); + CacheNotify.Unsubscribe(Common.Caching.EventType.InsertOrUpdate); + CacheInvoke.Unsubscribe(Common.Caching.EventType.InsertOrUpdate); } } diff --git a/common/services/ASC.Notify/Program.cs b/common/services/ASC.Notify/Program.cs index 9adc227e03..883c239755 100644 --- a/common/services/ASC.Notify/Program.cs +++ b/common/services/ASC.Notify/Program.cs @@ -77,17 +77,17 @@ namespace ASC.Notify if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); } diHelper.RegisterProducts(hostContext.Configuration, hostContext.HostingEnvironment.ContentRootPath); diff --git a/common/services/ASC.Studio.Notify/Program.cs b/common/services/ASC.Studio.Notify/Program.cs index b3810aa522..7a178cf58c 100644 --- a/common/services/ASC.Studio.Notify/Program.cs +++ b/common/services/ASC.Studio.Notify/Program.cs @@ -78,17 +78,17 @@ namespace ASC.Studio.Notify if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); } diHelper.RegisterProducts(hostContext.Configuration, hostContext.HostingEnvironment.ContentRootPath); diff --git a/common/services/ASC.TelegramService/TelegramListener.cs b/common/services/ASC.TelegramService/TelegramListener.cs index 344e5d13ce..a600ab5734 100644 --- a/common/services/ASC.TelegramService/TelegramListener.cs +++ b/common/services/ASC.TelegramService/TelegramListener.cs @@ -35,18 +35,18 @@ namespace ASC.TelegramService [Singletone] public class TelegramListener { - private ICacheNotify<NotifyMessage> CacheMessage { get; } - private ICacheNotify<RegisterUserProto> CacheRegisterUser { get; } - private ICacheNotify<CreateClientProto> CacheCreateClient { get; } - private ICacheNotify<DisableClientProto> CacheDisableClient { get; } + private IEventBus<NotifyMessage> CacheMessage { get; } + private IEventBus<RegisterUserProto> CacheRegisterUser { get; } + private IEventBus<CreateClientProto> CacheCreateClient { get; } + private IEventBus<DisableClientProto> CacheDisableClient { get; } private TelegramHandler TelegramHandler { get; set; } - public TelegramListener(ICacheNotify<NotifyMessage> cacheMessage, - ICacheNotify<RegisterUserProto> cacheRegisterUser, - ICacheNotify<CreateClientProto> cacheCreateClient, + public TelegramListener(IEventBus<NotifyMessage> cacheMessage, + IEventBus<RegisterUserProto> cacheRegisterUser, + IEventBus<CreateClientProto> cacheCreateClient, TelegramHandler telegramHandler, - ICacheNotify<DisableClientProto> cacheDisableClient) + IEventBus<DisableClientProto> cacheDisableClient) { CacheMessage = cacheMessage; CacheRegisterUser = cacheRegisterUser; @@ -58,19 +58,19 @@ namespace ASC.TelegramService public void Start() { - CacheMessage.Subscribe(async n => await SendMessage(n), CacheNotifyAction.Insert); - CacheRegisterUser.Subscribe(n => RegisterUser(n), CacheNotifyAction.Insert); - CacheCreateClient.Subscribe(n => CreateOrUpdateClient(n), CacheNotifyAction.Insert); - CacheDisableClient.Subscribe(n => DisableClient(n), CacheNotifyAction.Insert); + CacheMessage.Subscribe(async n => await SendMessage(n), EventType.Insert); + CacheRegisterUser.Subscribe(n => RegisterUser(n), EventType.Insert); + CacheCreateClient.Subscribe(n => CreateOrUpdateClient(n), EventType.Insert); + CacheDisableClient.Subscribe(n => DisableClient(n), EventType.Insert); } public void Stop() { - CacheMessage.Unsubscribe(CacheNotifyAction.Insert); - CacheRegisterUser.Unsubscribe(CacheNotifyAction.Insert); - CacheCreateClient.Unsubscribe(CacheNotifyAction.Insert); - CacheDisableClient.Unsubscribe(CacheNotifyAction.Insert); + CacheMessage.Unsubscribe(EventType.Insert); + CacheRegisterUser.Unsubscribe(EventType.Insert); + CacheCreateClient.Unsubscribe(EventType.Insert); + CacheDisableClient.Unsubscribe(EventType.Insert); } private void DisableClient(DisableClientProto n) diff --git a/common/services/ASC.Webhooks.Service/BuildQueueService.cs b/common/services/ASC.Webhooks.Service/BuildQueueService.cs index 9da8ba5224..84f5e0c934 100644 --- a/common/services/ASC.Webhooks.Service/BuildQueueService.cs +++ b/common/services/ASC.Webhooks.Service/BuildQueueService.cs @@ -10,9 +10,9 @@ namespace ASC.Webhooks.Service public class BuildQueueService { internal ConcurrentQueue<WebhookRequest> Queue { get; } - private ICacheNotify<WebhookRequest> WebhookNotify { get; } + private IEventBus<WebhookRequest> WebhookNotify { get; } - public BuildQueueService(ICacheNotify<WebhookRequest> webhookNotify) + public BuildQueueService(IEventBus<WebhookRequest> webhookNotify) { WebhookNotify = webhookNotify; Queue = new ConcurrentQueue<WebhookRequest>(); @@ -20,12 +20,12 @@ namespace ASC.Webhooks.Service public void Start() { - WebhookNotify.Subscribe(BuildWebhooksQueue, CacheNotifyAction.Update); + WebhookNotify.Subscribe(BuildWebhooksQueue, EventType.Update); } public void Stop() { - WebhookNotify.Unsubscribe(CacheNotifyAction.Update); + WebhookNotify.Unsubscribe(EventType.Update); } public void BuildWebhooksQueue(WebhookRequest request) diff --git a/common/services/ASC.Webhooks.Service/Program.cs b/common/services/ASC.Webhooks.Service/Program.cs index 931170ee42..d328e1f077 100644 --- a/common/services/ASC.Webhooks.Service/Program.cs +++ b/common/services/ASC.Webhooks.Service/Program.cs @@ -75,17 +75,17 @@ namespace ASC.Webhooks.Service if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); } diHelper.TryAdd<DbWorker>(); diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index d97c7b02dc..aea4e1ac3b 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -118,7 +118,7 @@ namespace ASC.Web.Files.Services.WCFService private FileOperationsManager FileOperationsManager { get; } private TenantManager TenantManager { get; } private FileTrackerHelper FileTracker { get; } - private ICacheNotify<ThumbnailRequest> ThumbnailNotify { get; } + private IEventBus<ThumbnailRequest> ThumbnailNotify { get; } private EntryStatusManager EntryStatusManager { get; } public CompressToArchive CompressToArchive { get; } private ILog Logger { get; set; } @@ -164,7 +164,7 @@ namespace ASC.Web.Files.Services.WCFService FileOperationsManager fileOperationsManager, TenantManager tenantManager, FileTrackerHelper fileTracker, - ICacheNotify<ThumbnailRequest> thumbnailNotify, + IEventBus<ThumbnailRequest> thumbnailNotify, EntryStatusManager entryStatusManager, CompressToArchive compressToArchive) { @@ -2370,7 +2370,7 @@ namespace ASC.Web.Files.Services.WCFService req.Files.Add(f); } - ThumbnailNotify.Publish(req, CacheNotifyAction.Insert); + ThumbnailNotify.Publish(req, Common.Caching.EventType.Insert); } catch (Exception e) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxProviderInfo.cs index a916b22ce7..5e3d15699d 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxProviderInfo.cs @@ -222,9 +222,9 @@ namespace ASC.Files.Thirdparty.Box private readonly ICache CacheFile; private readonly ICache CacheFolder; private readonly ICache CacheChildItems; - private readonly ICacheNotify<BoxCacheItem> CacheNotify; + private readonly IEventBus<BoxCacheItem> CacheNotify; - public BoxProviderInfoHelper(ICacheNotify<BoxCacheItem> cacheNotify, ICache cache) + public BoxProviderInfoHelper(IEventBus<BoxCacheItem> cacheNotify, ICache cache) { CacheFile = cache; CacheFolder = cache; @@ -256,7 +256,7 @@ namespace ASC.Files.Thirdparty.Box CacheFolder.Remove("boxd-" + i.Key); } } - }, CacheNotifyAction.Remove); + }, Common.Caching.EventType.Remove); } internal BoxFolder GetBoxFolder(BoxStorage storage, int id, string boxFolderId) @@ -299,7 +299,7 @@ namespace ASC.Files.Thirdparty.Box { if (boxItem != null) { - CacheNotify.Publish(new BoxCacheItem { IsFile = boxItem is BoxFile, Key = id + "-" + boxItem.Id }, CacheNotifyAction.Remove); + CacheNotify.Publish(new BoxCacheItem { IsFile = boxItem is BoxFile, Key = id + "-" + boxItem.Id }, Common.Caching.EventType.Remove); } } @@ -308,7 +308,7 @@ namespace ASC.Files.Thirdparty.Box var key = id + "-"; if (boxId == null) { - CacheNotify.Publish(new BoxCacheItem { ResetAll = true, Key = key }, CacheNotifyAction.Remove); + CacheNotify.Publish(new BoxCacheItem { ResetAll = true, Key = key }, Common.Caching.EventType.Remove); } else { @@ -318,7 +318,7 @@ namespace ASC.Files.Thirdparty.Box } key += boxId; - CacheNotify.Publish(new BoxCacheItem { IsFile = isFile ?? false, IsFileExists = isFile.HasValue, Key = key }, CacheNotifyAction.Remove); + CacheNotify.Publish(new BoxCacheItem { IsFile = isFile ?? false, IsFileExists = isFile.HasValue, Key = key }, Common.Caching.EventType.Remove); } } } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxProviderInfo.cs index 74a8148d12..e8edb422d0 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxProviderInfo.cs @@ -184,9 +184,9 @@ namespace ASC.Files.Thirdparty.Dropbox private readonly ICache CacheFile; private readonly ICache CacheFolder; private readonly ICache CacheChildItems; - private readonly ICacheNotify<DropboxCacheItem> CacheNotify; + private readonly IEventBus<DropboxCacheItem> CacheNotify; - public DropboxProviderInfoHelper(ICacheNotify<DropboxCacheItem> cacheNotify, ICache cache) + public DropboxProviderInfoHelper(IEventBus<DropboxCacheItem> cacheNotify, ICache cache) { CacheExpiration = TimeSpan.FromMinutes(1); CacheFile = cache; @@ -220,7 +220,7 @@ namespace ASC.Files.Thirdparty.Dropbox CacheFolder.Remove("dropboxd-" + i.Key); } } - }, CacheNotifyAction.Remove); + }, Common.Caching.EventType.Remove); } internal FolderMetadata GetDropboxFolder(DropboxStorage storage, int id, string dropboxFolderPath) @@ -263,7 +263,7 @@ namespace ASC.Files.Thirdparty.Dropbox { if (dropboxItem != null) { - CacheNotify.Publish(new DropboxCacheItem { IsFile = dropboxItem.AsFolder != null, Key = id + "-" + dropboxItem.PathDisplay }, CacheNotifyAction.Remove); + CacheNotify.Publish(new DropboxCacheItem { IsFile = dropboxItem.AsFolder != null, Key = id + "-" + dropboxItem.PathDisplay }, Common.Caching.EventType.Remove); } } @@ -272,13 +272,13 @@ namespace ASC.Files.Thirdparty.Dropbox var key = id + "-"; if (dropboxPath == null) { - CacheNotify.Publish(new DropboxCacheItem { ResetAll = true, Key = key }, CacheNotifyAction.Remove); + CacheNotify.Publish(new DropboxCacheItem { ResetAll = true, Key = key }, Common.Caching.EventType.Remove); } else { key += dropboxPath; - CacheNotify.Publish(new DropboxCacheItem { IsFile = isFile ?? false, IsFileExists = isFile.HasValue, Key = key }, CacheNotifyAction.Remove); + CacheNotify.Publish(new DropboxCacheItem { IsFile = isFile ?? false, IsFileExists = isFile.HasValue, Key = key }, Common.Caching.EventType.Remove); } } } diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs index fce1658a43..92037c127f 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs @@ -231,9 +231,9 @@ namespace ASC.Files.Thirdparty.GoogleDrive private readonly ICache CacheEntry; private readonly ICache CacheChildFiles; private readonly ICache CacheChildFolders; - private readonly ICacheNotify<GoogleDriveCacheItem> CacheNotify; + private readonly IEventBus<GoogleDriveCacheItem> CacheNotify; - public GoogleDriveProviderInfoHelper(ICacheNotify<GoogleDriveCacheItem> cacheNotify, ICache cache) + public GoogleDriveProviderInfoHelper(IEventBus<GoogleDriveCacheItem> cacheNotify, ICache cache) { CacheExpiration = TimeSpan.FromMinutes(1); CacheEntry = cache; @@ -264,7 +264,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive CacheChildFolders.Remove("drived-" + i.Key); } } - }, CacheNotifyAction.Remove); + }, Common.Caching.EventType.Remove); } internal DriveFile GetDriveEntry(GoogleDriveStorage storage, int id, string driveId) @@ -337,7 +337,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive { if (driveEntry != null) { - CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, Key = id + "-" + driveEntry.Id }, CacheNotifyAction.Remove); + CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, Key = id + "-" + driveEntry.Id }, Common.Caching.EventType.Remove); } } @@ -346,7 +346,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive var key = id + "-"; if (driveId == null) { - CacheNotify.Publish(new GoogleDriveCacheItem { ResetAll = true, Key = key }, CacheNotifyAction.Remove); + CacheNotify.Publish(new GoogleDriveCacheItem { ResetAll = true, Key = key }, Common.Caching.EventType.Remove); } else { @@ -356,13 +356,13 @@ namespace ASC.Files.Thirdparty.GoogleDrive } key += driveId; - CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, ResetChilds = true, Key = key, ChildFolder = childFolder ?? false, ChildFolderExist = childFolder.HasValue }, CacheNotifyAction.Remove); + CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, ResetChilds = true, Key = key, ChildFolder = childFolder ?? false, ChildFolderExist = childFolder.HasValue }, Common.Caching.EventType.Remove); } } internal void CacheResetChilds(int id, string parentDriveId, bool? childFolder = null) { - CacheNotify.Publish(new GoogleDriveCacheItem { ResetChilds = true, Key = id + "-" + parentDriveId, ChildFolder = childFolder ?? false, ChildFolderExist = childFolder.HasValue }, CacheNotifyAction.Remove); + CacheNotify.Publish(new GoogleDriveCacheItem { ResetChilds = true, Key = id + "-" + parentDriveId, ChildFolder = childFolder ?? false, ChildFolderExist = childFolder.HasValue }, Common.Caching.EventType.Remove); } } diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs index 475e472427..348e79b517 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs @@ -195,9 +195,9 @@ namespace ASC.Files.Thirdparty.OneDrive private readonly TimeSpan CacheExpiration; private readonly ICache CacheItem; private readonly ICache CacheChildItems; - private readonly ICacheNotify<OneDriveCacheItem> CacheNotify; + private readonly IEventBus<OneDriveCacheItem> CacheNotify; - public OneDriveProviderInfoHelper(ICacheNotify<OneDriveCacheItem> cacheNotify, ICache cache) + public OneDriveProviderInfoHelper(IEventBus<OneDriveCacheItem> cacheNotify, ICache cache) { CacheExpiration = TimeSpan.FromMinutes(1); CacheItem = cache; @@ -216,7 +216,7 @@ namespace ASC.Files.Thirdparty.OneDrive CacheChildItems.Remove(new Regex("onedrivei-" + i.Key)); CacheItem.Remove("onedrive-" + i.Key); } - }, CacheNotifyAction.Remove); + }, Common.Caching.EventType.Remove); } internal Item GetOneDriveItem(OneDriveStorage storage, int id, string itemId) @@ -248,13 +248,13 @@ namespace ASC.Files.Thirdparty.OneDrive var key = id + "-"; if (string.IsNullOrEmpty(onedriveId)) { - CacheNotify.Publish(new OneDriveCacheItem { ResetAll = true, Key = key }, CacheNotifyAction.Remove); + CacheNotify.Publish(new OneDriveCacheItem { ResetAll = true, Key = key }, Common.Caching.EventType.Remove); } else { key += onedriveId; - CacheNotify.Publish(new OneDriveCacheItem { Key = key }, CacheNotifyAction.Remove); + CacheNotify.Publish(new OneDriveCacheItem { Key = key }, Common.Caching.EventType.Remove); } } } diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs index 9c57234b6c..1d4c742ccc 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs @@ -592,9 +592,9 @@ namespace ASC.Files.Thirdparty.SharePoint private readonly TimeSpan CacheExpiration; private readonly ICache FileCache; private readonly ICache FolderCache; - private readonly ICacheNotify<SharePointProviderCacheItem> Notify; + private readonly IEventBus<SharePointProviderCacheItem> Notify; - public SharePointProviderInfoHelper(ICacheNotify<SharePointProviderCacheItem> notify, ICache cache) + public SharePointProviderInfoHelper(IEventBus<SharePointProviderCacheItem> notify, ICache cache) { CacheExpiration = TimeSpan.FromMinutes(1); FileCache = cache; @@ -616,16 +616,16 @@ namespace ASC.Files.Thirdparty.SharePoint FileCache.Remove(new Regex("^spointf-.*")); FolderCache.Remove(new Regex("^spointd-.*")); } - }, CacheNotifyAction.Remove); + }, Common.Caching.EventType.Remove); } public void Invalidate() { - Notify.Publish(new SharePointProviderCacheItem { }, CacheNotifyAction.Remove); + Notify.Publish(new SharePointProviderCacheItem { }, Common.Caching.EventType.Remove); } public void PublishFolder(string id) { - Notify.Publish(new SharePointProviderCacheItem { FolderKey = id }, CacheNotifyAction.Remove); + Notify.Publish(new SharePointProviderCacheItem { FolderKey = id }, Common.Caching.EventType.Remove); } public void PublishFolder(string id1, string id2) @@ -642,7 +642,7 @@ namespace ASC.Files.Thirdparty.SharePoint public void PublishFile(string fileId, string folderId) { - Notify.Publish(new SharePointProviderCacheItem { FileKey = fileId, FolderKey = folderId }, CacheNotifyAction.Remove); + Notify.Publish(new SharePointProviderCacheItem { FileKey = fileId, FolderKey = folderId }, Common.Caching.EventType.Remove); } public void CreateFolder(string id, string parentFolderId, Folder folder) diff --git a/products/ASC.Files/Core/Helpers/EasyBibHelper.cs b/products/ASC.Files/Core/Helpers/EasyBibHelper.cs index 8a2bbd69eb..762efe03d0 100644 --- a/products/ASC.Files/Core/Helpers/EasyBibHelper.cs +++ b/products/ASC.Files/Core/Helpers/EasyBibHelper.cs @@ -74,7 +74,7 @@ namespace ASC.Web.Files.Helpers CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory factory, string name, int order, diff --git a/products/ASC.Files/Core/Helpers/Global.cs b/products/ASC.Files/Core/Helpers/Global.cs index f2a0fb6577..b13ce41f0e 100644 --- a/products/ASC.Files/Core/Helpers/Global.cs +++ b/products/ASC.Files/Core/Helpers/Global.cs @@ -58,10 +58,10 @@ namespace ASC.Web.Files.Classes [Singletone] public class GlobalNotify { - private ICacheNotify<AscCacheItem> Notify { get; set; } + private IEventBus<AscCacheItem> Notify { get; set; } public ILog Logger { get; set; } - public GlobalNotify(ICacheNotify<AscCacheItem> notify, IOptionsMonitor<ILog> options, CoreBaseSettings coreBaseSettings) + public GlobalNotify(IEventBus<AscCacheItem> notify, IOptionsMonitor<ILog> options, CoreBaseSettings coreBaseSettings) { Notify = notify; Logger = options.Get("ASC.Files"); @@ -93,7 +93,7 @@ namespace ASC.Web.Files.Classes { Logger.Fatal("ClearCache action", e); } - }, CacheNotifyAction.Any); + }, Common.Caching.EventType.Any); } catch (Exception e) { diff --git a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs index 09295480fb..b1d14ff2c0 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -145,7 +145,7 @@ namespace ASC.Web.Files.ThirdPartyApp CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) diff --git a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs index fbcac00041..a25d494647 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -155,7 +155,7 @@ namespace ASC.Web.Files.ThirdPartyApp CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) diff --git a/products/ASC.Files/Service/Program.cs b/products/ASC.Files/Service/Program.cs index d0fa6bbf9d..31e65f3503 100644 --- a/products/ASC.Files/Service/Program.cs +++ b/products/ASC.Files/Service/Program.cs @@ -81,17 +81,17 @@ namespace ASC.Files.Service if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); } diff --git a/products/ASC.Files/Service/Thumbnail/Service.cs b/products/ASC.Files/Service/Thumbnail/Service.cs index 2f39310cfb..866ad0c88b 100644 --- a/products/ASC.Files/Service/Thumbnail/Service.cs +++ b/products/ASC.Files/Service/Thumbnail/Service.cs @@ -24,22 +24,22 @@ namespace ASC.Files.ThumbnailBuilder [Singletone] public class Service { - private ICacheNotify<ThumbnailRequest> CacheNotify { get; } + private IEventBus<ThumbnailRequest> CacheNotify { get; } - public Service(ICacheNotify<ThumbnailRequest> cacheNotify) + public Service(IEventBus<ThumbnailRequest> cacheNotify) { CacheNotify = cacheNotify; } public void Start() { - CacheNotify.Subscribe(BuildThumbnails, CacheNotifyAction.Insert); + CacheNotify.Subscribe(BuildThumbnails, EventType.Insert); //Cache.Subscribe } public void Stop() { - CacheNotify.Unsubscribe(CacheNotifyAction.Insert); + CacheNotify.Unsubscribe(EventType.Insert); //Cache.Subscribe } diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index cddec6aa4a..a7f888f382 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -164,7 +164,7 @@ namespace ASC.Api.Settings private EncryptionServiceClient EncryptionServiceClient { get; } private EncryptionSettingsHelper EncryptionSettingsHelper { get; } private BackupAjaxHandler BackupAjaxHandler { get; } - private ICacheNotify<DeleteSchedule> CacheDeleteSchedule { get; } + private IEventBus<DeleteSchedule> CacheDeleteSchedule { get; } private EncryptionWorker EncryptionWorker { get; } private PasswordHasher PasswordHasher { get; } private ILog Log { get; set; } @@ -231,7 +231,7 @@ namespace ASC.Api.Settings EncryptionServiceClient encryptionServiceClient, EncryptionSettingsHelper encryptionSettingsHelper, BackupAjaxHandler backupAjaxHandler, - ICacheNotify<DeleteSchedule> cacheDeleteSchedule, + IEventBus<DeleteSchedule> cacheDeleteSchedule, EncryptionWorker encryptionWorker, PasswordHasher passwordHasher, PaymentManager paymentManager, @@ -2326,7 +2326,7 @@ namespace ASC.Api.Settings foreach (var tenant in tenants) { - CacheDeleteSchedule.Publish(new DeleteSchedule() { TenantId = tenant.TenantId }, CacheNotifyAction.Insert); + CacheDeleteSchedule.Publish(new DeleteSchedule() { TenantId = tenant.TenantId }, Common.Caching.EventType.Insert); } var settings = EncryptionSettingsHelper.Load(); diff --git a/web/ASC.Web.Core/Jabber/FireBase.cs b/web/ASC.Web.Core/Jabber/FireBase.cs index 426c89e70a..e172589c0c 100644 --- a/web/ASC.Web.Core/Jabber/FireBase.cs +++ b/web/ASC.Web.Core/Jabber/FireBase.cs @@ -65,7 +65,7 @@ namespace ASC.Web.Core.Jabber CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/web/ASC.Web.Core/Mail/MailServiceHelper.cs b/web/ASC.Web.Core/Mail/MailServiceHelper.cs index 4b5c8ff026..fec7312f92 100644 --- a/web/ASC.Web.Core/Mail/MailServiceHelper.cs +++ b/web/ASC.Web.Core/Mail/MailServiceHelper.cs @@ -44,18 +44,18 @@ namespace ASC.Web.Core.Mail { public class MailServiceHelperStorage { - private ICacheNotify<MailServiceHelperCache> CacheNotify { get; } + private IEventBus<MailServiceHelperCache> CacheNotify { get; } public ICache Cache { get; } - public MailServiceHelperStorage(ICacheNotify<MailServiceHelperCache> cacheNotify, ICache cache) + public MailServiceHelperStorage(IEventBus<MailServiceHelperCache> cacheNotify, ICache cache) { Cache = cache; CacheNotify = cacheNotify; - CacheNotify.Subscribe(r => Cache.Remove(r.Key), CacheNotifyAction.Remove); + CacheNotify.Subscribe(r => Cache.Remove(r.Key), Common.Caching.EventType.Remove); } public void Remove() { - CacheNotify.Publish(new MailServiceHelperCache() { Key = MailServiceHelper.CacheKey }, CacheNotifyAction.Remove); + CacheNotify.Publish(new MailServiceHelperCache() { Key = MailServiceHelper.CacheKey }, Common.Caching.EventType.Remove); } } diff --git a/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs b/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs index 495118221e..09af57f26f 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs @@ -14,7 +14,7 @@ namespace ASC.Web.Core.Notify [Scope] public class StudioNotifyServiceHelper { - private ICacheNotify<NotifyItem> Cache { get; } + private IEventBus<NotifyItem> Cache { get; } private StudioNotifyHelper StudioNotifyHelper { get; } private AuthContext AuthContext { get; } private TenantManager TenantManager { get; } @@ -25,7 +25,7 @@ namespace ASC.Web.Core.Notify AuthContext authContext, TenantManager tenantManager, CommonLinkUtility commonLinkUtility, - ICacheNotify<NotifyItem> cache) + IEventBus<NotifyItem> cache) { StudioNotifyHelper = studioNotifyHelper; AuthContext = authContext; @@ -118,7 +118,7 @@ namespace ASC.Web.Core.Notify item.Tags.AddRange(args.Select(r => new Tag { Tag_ = r.Tag, Value = r.Value.ToString() })); } - Cache.Publish(item, CacheNotifyAction.Any); + Cache.Publish(item, EventType.Any); } } } \ No newline at end of file diff --git a/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs b/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs index 061291e4d8..abe154479f 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs @@ -52,9 +52,9 @@ namespace ASC.Web.Studio.Core.Notify private IServiceProvider ServiceProvider { get; } private IConfiguration Configuration { get; } - public StudioNotifyServiceSender(IServiceProvider serviceProvider, IConfiguration configuration, ICacheNotify<NotifyItem> cache) + public StudioNotifyServiceSender(IServiceProvider serviceProvider, IConfiguration configuration, IEventBus<NotifyItem> cache) { - cache.Subscribe(OnMessage, CacheNotifyAction.Any); + cache.Subscribe(this.OnMessage, Common.Caching.EventType.Any); ServiceProvider = serviceProvider; Configuration = configuration; } diff --git a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs index c5dc7d9cf1..414e82fbf3 100644 --- a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs +++ b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs @@ -40,21 +40,21 @@ namespace ASC.Web.Core.Sms [Singletone] public class SmsKeyStorageCache { - private ICacheNotify<SmsKeyCacheKey> KeyCacheNotify { get; } + private IEventBus<SmsKeyCacheKey> KeyCacheNotify { get; } public ICache KeyCache { get; } public ICache CheckCache { get; } - public SmsKeyStorageCache(ICacheNotify<SmsKeyCacheKey> keyCacheNotify, ICache cache) + public SmsKeyStorageCache(IEventBus<SmsKeyCacheKey> keyCacheNotify, ICache cache) { CheckCache = cache; KeyCache = cache; KeyCacheNotify = keyCacheNotify; - KeyCacheNotify.Subscribe(r => KeyCache.Remove(r.Key), CacheNotifyAction.Remove); + KeyCacheNotify.Subscribe(r => KeyCache.Remove(r.Key), Common.Caching.EventType.Remove); } public void RemoveFromCache(string cacheKey) { - KeyCacheNotify.Publish(new SmsKeyCacheKey { Key = cacheKey }, CacheNotifyAction.Remove); + KeyCacheNotify.Publish(new SmsKeyCacheKey { Key = cacheKey }, Common.Caching.EventType.Remove); } } diff --git a/web/ASC.Web.Core/Sms/SmsProvider.cs b/web/ASC.Web.Core/Sms/SmsProvider.cs index 85ab695d12..8252424321 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -137,7 +137,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, ICache memCache, @@ -204,7 +204,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, ICache memCache, @@ -345,7 +345,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, ICache memCache, @@ -366,7 +366,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, ICache memCache, @@ -448,7 +448,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, ICache memCache, @@ -499,7 +499,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - ICacheNotify<ConsumerCacheItem> cache, + IEventBus<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, ICache memCache, diff --git a/web/ASC.Web.Core/Users/UserPhotoManager.cs b/web/ASC.Web.Core/Users/UserPhotoManager.cs index be4dc9f334..077e2bc163 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -104,10 +104,10 @@ namespace ASC.Web.Core.Users public class UserPhotoManagerCache { private readonly ConcurrentDictionary<CacheSize, ConcurrentDictionary<Guid, string>> Photofiles; - private readonly ICacheNotify<UserPhotoManagerCacheItem> CacheNotify; + private readonly IEventBus<UserPhotoManagerCacheItem> CacheNotify; private readonly HashSet<int> TenantDiskCache; - public UserPhotoManagerCache(ICacheNotify<UserPhotoManagerCacheItem> notify) + public UserPhotoManagerCache(IEventBus<UserPhotoManagerCacheItem> notify) { try { @@ -119,7 +119,7 @@ namespace ASC.Web.Core.Users { var userId = new Guid(data.UserId); Photofiles.GetOrAdd(data.Size, (r) => new ConcurrentDictionary<Guid, string>())[userId] = data.FileName; - }, CacheNotifyAction.InsertOrUpdate); + }, Common.Caching.EventType.InsertOrUpdate); CacheNotify.Subscribe((data) => { @@ -135,7 +135,7 @@ namespace ASC.Web.Core.Users SetCacheLoadedForTenant(false, data.TenantId); } catch { } - }, CacheNotifyAction.Remove); + }, Common.Caching.EventType.Remove); } catch (Exception) { @@ -157,7 +157,7 @@ namespace ASC.Web.Core.Users { if (CacheNotify != null) { - CacheNotify.Publish(new UserPhotoManagerCacheItem { UserId = userID.ToString(), TenantId = tenantId }, CacheNotifyAction.Remove); + CacheNotify.Publish(new UserPhotoManagerCacheItem { UserId = userID.ToString(), TenantId = tenantId }, Common.Caching.EventType.Remove); } } @@ -165,7 +165,7 @@ namespace ASC.Web.Core.Users { if (CacheNotify != null) { - CacheNotify.Publish(new UserPhotoManagerCacheItem { UserId = userID.ToString(), Size = UserPhotoManager.ToCache(size), FileName = fileName, TenantId = tenantId }, CacheNotifyAction.InsertOrUpdate); + CacheNotify.Publish(new UserPhotoManagerCacheItem { UserId = userID.ToString(), Size = UserPhotoManager.ToCache(size), FileName = fileName, TenantId = tenantId }, Common.Caching.EventType.InsertOrUpdate); } } diff --git a/web/ASC.Web.Core/WebItemSecurity.cs b/web/ASC.Web.Core/WebItemSecurity.cs index 49c20ae116..3e15dcda52 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -46,16 +46,16 @@ namespace ASC.Web.Core public class WebItemSecurityCache { private ICache Cache { get; } - private ICacheNotify<WebItemSecurityNotifier> CacheNotify { get; } + private IEventBus<WebItemSecurityNotifier> CacheNotify { get; } - public WebItemSecurityCache(ICacheNotify<WebItemSecurityNotifier> cacheNotify, ICache cache) + public WebItemSecurityCache(IEventBus<WebItemSecurityNotifier> cacheNotify, ICache cache) { Cache = cache; CacheNotify = cacheNotify; CacheNotify.Subscribe((r) => { ClearCache(r.Tenant); - }, CacheNotifyAction.Any); + }, Common.Caching.EventType.Any); } public void ClearCache(int tenantId) @@ -70,7 +70,7 @@ namespace ASC.Web.Core public void Publish(int tenantId) { - CacheNotify.Publish(new WebItemSecurityNotifier { Tenant = tenantId }, CacheNotifyAction.Any); + CacheNotify.Publish(new WebItemSecurityNotifier { Tenant = tenantId }, Common.Caching.EventType.Any); } public Dictionary<string, bool> Get(int tenantId) diff --git a/web/ASC.Web.Core/WhiteLabel/TenantLogoManager.cs b/web/ASC.Web.Core/WhiteLabel/TenantLogoManager.cs index e885253f65..96be0b095e 100644 --- a/web/ASC.Web.Core/WhiteLabel/TenantLogoManager.cs +++ b/web/ASC.Web.Core/WhiteLabel/TenantLogoManager.cs @@ -53,7 +53,7 @@ namespace ASC.Web.Core.WhiteLabel } private ICache Cache { get; } - private ICacheNotify<TenantLogoCacheItem> CacheNotify { get; } + private IEventBus<TenantLogoCacheItem> CacheNotify { get; } public TenantLogoManager( TenantWhiteLabelSettingsHelper tenantWhiteLabelSettingsHelper, @@ -62,7 +62,7 @@ namespace ASC.Web.Core.WhiteLabel TenantManager tenantManager, AuthContext authContext, IConfiguration configuration, - ICacheNotify<TenantLogoCacheItem> cacheNotify, + IEventBus<TenantLogoCacheItem> cacheNotify, ICache cache) { TenantWhiteLabelSettingsHelper = tenantWhiteLabelSettingsHelper; @@ -216,7 +216,7 @@ namespace ASC.Web.Core.WhiteLabel public void RemoveMailLogoDataFromCache() { - CacheNotify.Publish(new TenantLogoCacheItem() { Key = CacheKey }, CacheNotifyAction.Remove); + CacheNotify.Publish(new TenantLogoCacheItem() { Key = CacheKey }, Common.Caching.EventType.Remove); } } } \ No newline at end of file From 23eaa4be39bfe491492226bcc622d8aacb4dede4 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 17:51:29 +0300 Subject: [PATCH 110/167] Common: private properties replaced with fields, used single line expressions, cosmetic --- common/ASC.Api.Core/Core/BaseStartup.cs | 6 +- common/ASC.Common/Caching/AscCache.cs | 84 ++- common/ASC.Common/Caching/EventBusKafka.cs | 200 +++++++ ...yCacheNotify.cs => EventBusMemoryCache.cs} | 21 +- .../{RedisCache.cs => EventBusRedis.cs} | 17 +- common/ASC.Common/Caching/KafkaCache.cs | 214 -------- common/ASC.Common/Caching/Protobuf.cs | 27 +- .../Collections/CachedDictionaryBase.cs | 87 +-- .../Collections/HttpRequestDictionary.cs | 64 +-- common/ASC.Common/DIHelper.cs | 176 +++--- common/ASC.Common/Data/StreamExtension.cs | 5 +- common/ASC.Common/Data/TempPath.cs | 24 +- common/ASC.Common/Data/TempStream.cs | 18 +- .../DependencyInjection/AutofacExtension.cs | 52 +- .../Geolocation/IPGeolocationInfo.cs | 6 - common/ASC.Common/Logging/EFLoggerFactory.cs | 35 +- common/ASC.Common/Logging/Log.cs | 516 +++++++----------- .../Logging/SelfCleaningAppender.cs | 48 +- .../ASC.Common/Logging/SelfCleaningTarget.cs | 74 ++- .../Logging/SpecialFolderPathConverter.cs | 32 +- common/ASC.Common/Mapping/MappingProfile.cs | 6 +- common/ASC.Common/Module/BaseWcfClient.cs | 4 +- common/ASC.Common/Security/AscRandom.cs | 79 ++- .../Security/Authentication/Account.cs | 45 +- .../Security/Authentication/IAccount.cs | 5 +- .../Security/Authentication/ISystemAccount.cs | 4 +- .../Security/Authentication/SystemAccount.cs | 4 +- .../Authorizing/AuthorizingException.cs | 43 +- .../Security/Authorizing/AzObjectIdHelper.cs | 3 +- .../AzObjectSecurityProviderHelper.cs | 52 +- .../Security/Authorizing/Domain/Ace.cs | 2 - .../Security/Authorizing/Domain/Action.cs | 23 +- .../Security/Authorizing/Domain/Role.cs | 32 +- .../Authorizing/Interfaces/IAction.cs | 3 - .../Security/Authorizing/Interfaces/IRole.cs | 4 +- .../Security/Cryptography/HashAlg.cs | 3 - .../Security/Cryptography/Hasher.cs | 90 +-- .../Security/Cryptography/InstanceCrypto.cs | 25 +- .../Cryptography/MachinePseudoKeys.cs | 21 +- .../Security/Cryptography/PasswordHasher.cs | 23 +- common/ASC.Common/Security/ISecurityObject.cs | 4 +- .../Security/ISecurityObjectProvider.cs | 3 +- .../Security/SecurityCallContext.cs | 12 +- .../ASC.Common/Security/SecurityObjectId.cs | 13 +- .../ASC.Common/Threading/DistributedTask.cs | 74 +-- .../Threading/DistributedTaskProgress.cs | 53 +- .../Threading/DistributedTaskQueue.cs | 198 +++---- .../ASC.Common/Utils/ConfigurationManager.cs | 59 +- common/ASC.Common/Utils/CrossPlatformUtils.cs | 2 + common/ASC.Common/Utils/DnsLookup.cs | 10 +- common/ASC.Common/Utils/HtmlUtil.cs | 18 +- .../ASC.Common/Utils/HttpRequestExtensions.cs | 111 ++-- common/ASC.Common/Utils/MailAddressUtils.cs | 20 +- common/ASC.Common/Utils/MimeHeaderUtils.cs | 15 +- common/ASC.Common/Utils/RandomString.cs | 2 + common/ASC.Common/Utils/Signature.cs | 33 +- .../TimeZoneConverter/TimeZoneConverter.cs | 157 +++--- common/ASC.Common/Utils/VelocityFormatter.cs | 25 +- common/ASC.Common/Utils/Wildcard.cs | 25 +- .../Web/AbstractHttpAsyncHandler.cs | 34 +- .../ASC.Common/Web/DisposableHttpContext.cs | 28 +- common/ASC.Common/Web/HttpException.cs | 43 +- .../ASC.Common/Web/ItemNotFoundException.cs | 13 +- common/ASC.Common/Web/MimeMapping.cs | 84 ++- common/ASC.Common/Web/RouteCallInfo.cs | 17 +- common/services/ASC.ClearEvents/Program.cs | 6 +- common/services/ASC.Notify/Program.cs | 6 +- common/services/ASC.Studio.Notify/Program.cs | 6 +- .../services/ASC.Webhooks.Service/Program.cs | 6 +- products/ASC.Files/Service/Program.cs | 6 +- 70 files changed, 1257 insertions(+), 2003 deletions(-) create mode 100644 common/ASC.Common/Caching/EventBusKafka.cs rename common/ASC.Common/Caching/{MemoryCacheNotify.cs => EventBusMemoryCache.cs} (57%) rename common/ASC.Common/Caching/{RedisCache.cs => EventBusRedis.cs} (83%) delete mode 100644 common/ASC.Common/Caching/KafkaCache.cs diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index ce7ed950bf..c14f326411 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -110,17 +110,17 @@ namespace ASC.Api.Core if (kafkaConfiguration != null) { - DIHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); + DIHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); } else if (redisConfiguration != null) { - DIHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); + DIHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - DIHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); + DIHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); } diff --git a/common/ASC.Common/Caching/AscCache.cs b/common/ASC.Common/Caching/AscCache.cs index 779b6d8630..e885b2333e 100644 --- a/common/ASC.Common/Caching/AscCache.cs +++ b/common/ASC.Common/Caching/AscCache.cs @@ -37,19 +37,16 @@ namespace ASC.Common.Caching [Singletone] public class AscCacheNotify { - private IEventBus<AscCacheItem> CacheNotify { get; } + private readonly IEventBus<AscCacheItem> _eventBus; - public AscCacheNotify(IEventBus<AscCacheItem> cacheNotify) + public AscCacheNotify(IEventBus<AscCacheItem> eventBus) { - CacheNotify = cacheNotify; + _eventBus = eventBus; - CacheNotify.Subscribe((item) => { OnClearCache(); }, EventType.Any); + _eventBus.Subscribe((item) => { OnClearCache(); }, EventType.Any); } - public void ClearCache() - { - CacheNotify.Publish(new AscCacheItem { Id = Guid.NewGuid().ToString() }, EventType.Any); - } + public void ClearCache() => _eventBus.Publish(new AscCacheItem { Id = Guid.NewGuid().ToString() }, EventType.Any); public static void OnClearCache() { @@ -65,19 +62,16 @@ namespace ASC.Common.Caching [Singletone] public class AscCache : ICache { - private IMemoryCache MemoryCache { get; } - private ConcurrentDictionary<string, object> MemoryCacheKeys { get; } + private readonly IMemoryCache _memoryCache; + private readonly ConcurrentDictionary<string, object> _memoryCacheKeys; public AscCache(IMemoryCache memoryCache) { - MemoryCache = memoryCache; - MemoryCacheKeys = new ConcurrentDictionary<string, object>(); + _memoryCache = memoryCache; + _memoryCacheKeys = new ConcurrentDictionary<string, object>(); } - public T Get<T>(string key) where T : class - { - return MemoryCache.Get<T>(key); - } + public T Get<T>(string key) where T : class => _memoryCache.Get<T>(key); public void Insert(string key, object value, TimeSpan sligingExpiration) { @@ -85,8 +79,8 @@ namespace ASC.Common.Caching .SetSlidingExpiration(sligingExpiration) .RegisterPostEvictionCallback(EvictionCallback); - MemoryCache.Set(key, value, options); - MemoryCacheKeys.TryAdd(key, null); + _memoryCache.Set(key, value, options); + _memoryCacheKeys.TryAdd(key, null); } public void Insert(string key, object value, DateTime absolutExpiration) @@ -95,43 +89,32 @@ namespace ASC.Common.Caching .SetAbsoluteExpiration(absolutExpiration == DateTime.MaxValue ? DateTimeOffset.MaxValue : new DateTimeOffset(absolutExpiration)) .RegisterPostEvictionCallback(EvictionCallback); - MemoryCache.Set(key, value, options); - MemoryCacheKeys.TryAdd(key, null); + _memoryCache.Set(key, value, options); + _memoryCacheKeys.TryAdd(key, null); } - private void EvictionCallback(object key, object value, EvictionReason reason, object state) - { - MemoryCacheKeys.TryRemove(key.ToString(), out _); - } - - public void Remove(string key) - { - MemoryCache.Remove(key); - } + public void Remove(string key) => _memoryCache.Remove(key); public void Remove(Regex pattern) { - var copy = MemoryCacheKeys.ToDictionary(p => p.Key, p => p.Value); + var copy = _memoryCacheKeys.ToDictionary(p => p.Key, p => p.Value); var keys = copy.Select(p => p.Key).Where(k => pattern.IsMatch(k)).ToArray(); foreach (var key in keys) { - MemoryCache.Remove(key); + _memoryCache.Remove(key); } } - - public ConcurrentDictionary<string, T> HashGetAll<T>(string key) - { - return MemoryCache.GetOrCreate(key, r => new ConcurrentDictionary<string, T>()); - } + public ConcurrentDictionary<string, T> HashGetAll<T>(string key) => + _memoryCache.GetOrCreate(key, r => new ConcurrentDictionary<string, T>()); public T HashGet<T>(string key, string field) { - if (MemoryCache.TryGetValue<ConcurrentDictionary<string, T>>(key, out var dic) && dic.TryGetValue(field, out var value)) - { - return value; - } + if (_memoryCache.TryGetValue<ConcurrentDictionary<string, T>>(key, out var dic) + && dic.TryGetValue(field, out var value)) + return value; + return default; } @@ -141,20 +124,19 @@ namespace ASC.Common.Caching if (value != null) { dic.AddOrUpdate(field, value, (k, v) => value); - MemoryCache.Set(key, dic, DateTime.MaxValue); + _memoryCache.Set(key, dic, DateTime.MaxValue); } else if (dic != null) { - dic.TryRemove(field, out _); - if (dic.Count == 0) - { - MemoryCache.Remove(key); - } - else - { - MemoryCache.Set(key, dic, DateTime.MaxValue); - } + dic.TryRemove(field, out _); + + if (dic.IsEmpty) _memoryCache.Remove(key); + + else _memoryCache.Set(key, dic, DateTime.MaxValue); } - } + } + + private void EvictionCallback(object key, object value, EvictionReason reason, object state) => + _memoryCacheKeys.TryRemove(key.ToString(), out _); } } \ No newline at end of file diff --git a/common/ASC.Common/Caching/EventBusKafka.cs b/common/ASC.Common/Caching/EventBusKafka.cs new file mode 100644 index 0000000000..56428a95ac --- /dev/null +++ b/common/ASC.Common/Caching/EventBusKafka.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Concurrent; +using System.Threading; +using System.Threading.Tasks; + +using ASC.Common.Logging; +using ASC.Common.Utils; + +using Confluent.Kafka; +using Confluent.Kafka.Admin; + +using Google.Protobuf; + +using Microsoft.Extensions.Options; + +namespace ASC.Common.Caching +{ + [Singletone] + public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, new() + { + private IProducer<AscCacheItem, T> Producer { get; set; } + + private bool _disposedValue = false; // To detect redundant calls + private readonly ClientConfig _clientConfig; + private readonly AdminClientConfig _adminClientConfig; + private readonly ILog _logger; + private readonly ConcurrentDictionary<string, CancellationTokenSource> _cancelationToken; + private readonly ConcurrentDictionary<string, Action<T>> _actions; + private readonly ProtobufSerializer<T> _valueSerializer = new ProtobufSerializer<T>(); + private readonly ProtobufDeserializer<T> _valueDeserializer = new ProtobufDeserializer<T>(); + private readonly ProtobufSerializer<AscCacheItem> _keySerializer = new ProtobufSerializer<AscCacheItem>(); + private readonly ProtobufDeserializer<AscCacheItem> _keyDeserializer = new ProtobufDeserializer<AscCacheItem>(); + private readonly Guid _key; + + public EventBusKafka(ConfigurationExtension configuration, IOptionsMonitor<ILog> options) + { + _logger = options.CurrentValue; + _cancelationToken = new ConcurrentDictionary<string, CancellationTokenSource>(); + _actions = new ConcurrentDictionary<string, Action<T>>(); + _key = Guid.NewGuid(); + + var settings = configuration.GetSetting<KafkaSettings>("kafka"); + + _clientConfig = new ClientConfig { BootstrapServers = settings.BootstrapServers }; + _adminClientConfig = new AdminClientConfig { BootstrapServers = settings.BootstrapServers }; + } + + public void Publish(T obj, EventType eventType) + { + try + { + if (Producer == null) + { + Producer = new ProducerBuilder<AscCacheItem, T>(new ProducerConfig(_clientConfig)) + .SetErrorHandler((_, e) => _logger.Error(e)) + .SetKeySerializer(_keySerializer) + .SetValueSerializer(_valueSerializer) + .Build(); + } + + var channelName = GetChannelName(eventType); + + if (_actions.TryGetValue(channelName, out var onchange)) onchange(obj); + + var message = new Message<AscCacheItem, T> + { + Value = obj, + Key = new AscCacheItem + { + Id = _key.ToString() + } + }; + + Producer.ProduceAsync(channelName, message); + } + catch (ProduceException<Null, string> e) + { + _logger.Error(e); + } + catch (Exception e) + { + _logger.Error(e); + } + } + + public void Subscribe(Action<T> onchange, EventType eventType) + { + var channelName = GetChannelName(eventType); + + _cancelationToken[channelName] = new CancellationTokenSource(); + _actions[channelName] = onchange; + + void action() + { + var conf = new ConsumerConfig(_clientConfig) + { + GroupId = Guid.NewGuid().ToString() + }; + + + using (var adminClient = new AdminClientBuilder(_adminClientConfig) + .SetErrorHandler((_, e) => _logger.Error(e)) + .Build()) + { + try + { + //TODO: must add checking exist + adminClient.CreateTopicsAsync( + new TopicSpecification[] + { + new TopicSpecification + { + Name = channelName, + NumPartitions = 1, + ReplicationFactor = 1 + } + }).Wait(); + } + catch (AggregateException) { } + } + + using var c = new ConsumerBuilder<AscCacheItem, T>(conf) + .SetErrorHandler((_, e) => _logger.Error(e)) + .SetKeyDeserializer(_keyDeserializer) + .SetValueDeserializer(_valueDeserializer) + .Build(); + + c.Assign(new TopicPartition(channelName, new Partition())); + + try + { + while (true) + { + try + { + var cr = c.Consume(_cancelationToken[channelName].Token); + if (cr != null && cr.Message != null && cr.Message.Value != null && !(new Guid(cr.Message.Key.Id)).Equals(_key) && _actions.TryGetValue(channelName, out var act)) + { + try + { + act(cr.Message.Value); + } + catch (Exception e) + { + _logger.Error("Kafka onmessage", e); + } + } + } + catch (ConsumeException e) + { + _logger.Error(e); + } + } + } + catch (OperationCanceledException) + { + c.Close(); + } + } + + var task = new Task(action, TaskCreationOptions.LongRunning); + task.Start(); + } + + public void Unsubscribe(EventType eventType) + { + _cancelationToken.TryGetValue(GetChannelName(eventType), out var source); + + if (source != null) source.Cancel(); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (!_disposedValue) + { + if (disposing && Producer != null) Producer.Dispose(); + + _disposedValue = true; + } + } + + ~EventBusKafka() + { + Dispose(false); + } + + private string GetChannelName(EventType eventType) => $"ascchannel{eventType}{typeof(T).FullName}".ToLower(); + } + + public class KafkaSettings + { + public string BootstrapServers { get; set; } + } +} \ No newline at end of file diff --git a/common/ASC.Common/Caching/MemoryCacheNotify.cs b/common/ASC.Common/Caching/EventBusMemoryCache.cs similarity index 57% rename from common/ASC.Common/Caching/MemoryCacheNotify.cs rename to common/ASC.Common/Caching/EventBusMemoryCache.cs index 88525250b2..b450fec414 100644 --- a/common/ASC.Common/Caching/MemoryCacheNotify.cs +++ b/common/ASC.Common/Caching/EventBusMemoryCache.cs @@ -8,40 +8,27 @@ using Google.Protobuf; namespace ASC.Common.Caching { [Singletone] - public class MemoryCacheNotify<T> : IEventBus<T> where T : IMessage<T>, new() + public class EventBusMemoryCache<T> : IEventBus<T> where T : IMessage<T>, new() { private readonly ConcurrentDictionary<string, List<Action<T>>> _actions; - public MemoryCacheNotify() - { - _actions = new ConcurrentDictionary<string, List<Action<T>>>(); - } + public EventBusMemoryCache() => _actions = new ConcurrentDictionary<string, List<Action<T>>>(); public void Publish(T obj, EventType action) { if (_actions.TryGetValue(GetKey(action), out var onchange) && onchange != null) - { Parallel.ForEach(onchange, a => a(obj)); - } } public void Subscribe(Action<T> onchange, EventType notifyAction) { if (onchange != null) - { _actions.GetOrAdd(GetKey(notifyAction), new List<Action<T>>()) .Add(onchange); - } } - public void Unsubscribe(EventType action) - { - _actions.TryRemove(GetKey(action), out _); - } + public void Unsubscribe(EventType action) => _actions.TryRemove(GetKey(action), out _); - private string GetKey(EventType cacheNotifyAction) - { - return $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); - } + private string GetKey(EventType cacheNotifyAction) => $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); } } \ No newline at end of file diff --git a/common/ASC.Common/Caching/RedisCache.cs b/common/ASC.Common/Caching/EventBusRedis.cs similarity index 83% rename from common/ASC.Common/Caching/RedisCache.cs rename to common/ASC.Common/Caching/EventBusRedis.cs index a11c5f4fe7..72492a2a25 100644 --- a/common/ASC.Common/Caching/RedisCache.cs +++ b/common/ASC.Common/Caching/EventBusRedis.cs @@ -25,14 +25,11 @@ using StackExchange.Redis.Extensions.Core.Abstractions; namespace ASC.Common.Caching; [Singletone] -public class RedisCache<T> : IEventBus<T> where T : IMessage<T>, new() +public class EventBusRedis<T> : IEventBus<T> where T : IMessage<T>, new() { private readonly IRedisDatabase _redis; - public RedisCache(IRedisCacheClient redisCacheClient) - { - _redis = redisCacheClient.GetDbFromConfiguration(); - } + public EventBusRedis(IRedisCacheClient redisCacheClient) => _redis = redisCacheClient.GetDbFromConfiguration(); public void Publish(T obj, EventType action) { @@ -61,10 +58,7 @@ public class RedisCache<T> : IEventBus<T> where T : IMessage<T>, new() .GetResult(); } - private string GetChannelName(EventType cacheNotifyAction) - { - return $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); - } + private string GetChannelName(EventType cacheNotifyAction) => $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); class RedisCachePubSubItem<T0> { @@ -72,7 +66,4 @@ public class RedisCache<T> : IEventBus<T> where T : IMessage<T>, new() public EventType Action { get; set; } } -} - - - +} \ No newline at end of file diff --git a/common/ASC.Common/Caching/KafkaCache.cs b/common/ASC.Common/Caching/KafkaCache.cs deleted file mode 100644 index 1ff6629d16..0000000000 --- a/common/ASC.Common/Caching/KafkaCache.cs +++ /dev/null @@ -1,214 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Threading; -using System.Threading.Tasks; - -using ASC.Common.Logging; -using ASC.Common.Utils; - -using Confluent.Kafka; -using Confluent.Kafka.Admin; - -using Google.Protobuf; - -using Microsoft.Extensions.Options; - -namespace ASC.Common.Caching -{ - [Singletone] - public class KafkaCache<T> : IDisposable, IEventBus<T> where T : IMessage<T>, new() - { - private ClientConfig ClientConfig { get; set; } - private AdminClientConfig AdminClientConfig { get; set; } - private ILog Log { get; set; } - private ConcurrentDictionary<string, CancellationTokenSource> Cts { get; set; } - private ConcurrentDictionary<string, Action<T>> Actions { get; set; } - private ProtobufSerializer<T> ValueSerializer { get; } = new ProtobufSerializer<T>(); - private ProtobufDeserializer<T> ValueDeserializer { get; } = new ProtobufDeserializer<T>(); - private ProtobufSerializer<AscCacheItem> KeySerializer { get; } = new ProtobufSerializer<AscCacheItem>(); - private ProtobufDeserializer<AscCacheItem> KeyDeserializer { get; } = new ProtobufDeserializer<AscCacheItem>(); - private IProducer<AscCacheItem, T> Producer { get; set; } - private Guid Key { get; set; } - - public KafkaCache(ConfigurationExtension configuration, IOptionsMonitor<ILog> options) - { - Log = options.CurrentValue; - Cts = new ConcurrentDictionary<string, CancellationTokenSource>(); - Actions = new ConcurrentDictionary<string, Action<T>>(); - Key = Guid.NewGuid(); - - var settings = configuration.GetSetting<KafkaSettings>("kafka"); - - ClientConfig = new ClientConfig { BootstrapServers = settings.BootstrapServers }; - AdminClientConfig = new AdminClientConfig { BootstrapServers = settings.BootstrapServers }; - } - - public void Publish(T obj, EventType cacheNotifyAction) - { - try - { - if (Producer == null) - { - Producer = new ProducerBuilder<AscCacheItem, T>(new ProducerConfig(ClientConfig)) - .SetErrorHandler((_, e) => Log.Error(e)) - .SetKeySerializer(KeySerializer) - .SetValueSerializer(ValueSerializer) - .Build(); - } - - var channelName = GetChannelName(cacheNotifyAction); - - if (Actions.TryGetValue(channelName, out var onchange)) - { - onchange(obj); - } - - var message = new Message<AscCacheItem, T> - { - Value = obj, - Key = new AscCacheItem - { - Id = Key.ToString() - } - }; - - Producer.ProduceAsync(channelName, message); - } - catch (ProduceException<Null, string> e) - { - Log.Error(e); - } - catch (Exception e) - { - Log.Error(e); - } - } - - public void Subscribe(Action<T> onchange, EventType cacheNotifyAction) - { - var channelName = GetChannelName(cacheNotifyAction); - - Cts[channelName] = new CancellationTokenSource(); - Actions[channelName] = onchange; - - void action() - { - var conf = new ConsumerConfig(ClientConfig) - { - GroupId = Guid.NewGuid().ToString() - }; - - - using (var adminClient = new AdminClientBuilder(AdminClientConfig) - .SetErrorHandler((_, e) => Log.Error(e)) - .Build()) - { - try - { - //TODO: must add checking exist - adminClient.CreateTopicsAsync( - new TopicSpecification[] - { - new TopicSpecification - { - Name = channelName, - NumPartitions = 1, - ReplicationFactor = 1 - } - }).Wait(); - } - catch (AggregateException) - { - - } - } - - - using var c = new ConsumerBuilder<AscCacheItem, T>(conf) - .SetErrorHandler((_, e) => Log.Error(e)) - .SetKeyDeserializer(KeyDeserializer) - .SetValueDeserializer(ValueDeserializer) - .Build(); - - c.Assign(new TopicPartition(channelName, new Partition())); - - try - { - while (true) - { - try - { - var cr = c.Consume(Cts[channelName].Token); - if (cr != null && cr.Message != null && cr.Message.Value != null && !(new Guid(cr.Message.Key.Id)).Equals(Key) && Actions.TryGetValue(channelName, out var act)) - { - try - { - act(cr.Message.Value); - } - catch (Exception e) - { - Log.Error("Kafka onmessage", e); - } - } - } - catch (ConsumeException e) - { - Log.Error(e); - } - } - } - catch (OperationCanceledException) - { - c.Close(); - } - } - - var task = new Task(action, TaskCreationOptions.LongRunning); - task.Start(); - } - - private string GetChannelName(EventType cacheNotifyAction) - { - return $"ascchannel{cacheNotifyAction}{typeof(T).FullName}".ToLower(); - } - - public void Unsubscribe(EventType action) - { - Cts.TryGetValue(GetChannelName(action), out var source); - if (source != null) - { - source.Cancel(); - } - } - - private bool disposedValue = false; // To detect redundant calls - - protected virtual void Dispose(bool disposing) - { - if (!disposedValue) - { - if (disposing && Producer != null) - { - Producer.Dispose(); - } - - disposedValue = true; - } - } - ~KafkaCache() - { - Dispose(false); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - } - - public class KafkaSettings - { - public string BootstrapServers { get; set; } - } -} \ No newline at end of file diff --git a/common/ASC.Common/Caching/Protobuf.cs b/common/ASC.Common/Caching/Protobuf.cs index f18f326208..4d39482d1a 100644 --- a/common/ASC.Common/Caching/Protobuf.cs +++ b/common/ASC.Common/Caching/Protobuf.cs @@ -8,36 +8,23 @@ namespace ASC.Common.Caching { public class ProtobufSerializer<T> : ISerializer<T> where T : IMessage<T>, new() { - public byte[] Serialize(T data, SerializationContext context) - { - return data.ToByteArray(); - } + public byte[] Serialize(T data, SerializationContext context) => data.ToByteArray(); } public class ProtobufDeserializer<T> : IDeserializer<T> where T : IMessage<T>, new() { - private readonly MessageParser<T> parser; + private readonly MessageParser<T> _parser; - public ProtobufDeserializer() - { - parser = new MessageParser<T>(() => new T()); - } + public ProtobufDeserializer() => _parser = new MessageParser<T>(() => new T()); public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context) - { - return parser.ParseFrom(data.ToArray()); - } + => _parser.ParseFrom(data.ToArray()); } public static class GuidExtension { - public static ByteString ToByteString(this Guid id) - { - return ByteString.CopyFrom(id.ToByteArray()); - } - public static Guid FromByteString(this ByteString id) - { - return new Guid(id.ToByteArray()); - } + public static ByteString ToByteString(this Guid id) => ByteString.CopyFrom(id.ToByteArray()); + + public static Guid FromByteString(this ByteString id) => new Guid(id.ToByteArray()); } } diff --git a/common/ASC.Common/Collections/CachedDictionaryBase.cs b/common/ASC.Common/Collections/CachedDictionaryBase.cs index 9f6b15018a..ee2e678e6c 100644 --- a/common/ASC.Common/Collections/CachedDictionaryBase.cs +++ b/common/ASC.Common/Collections/CachedDictionaryBase.cs @@ -35,64 +35,29 @@ namespace ASC.Collections protected string baseKey; protected Func<T, bool> condition; - public T this[string key] - { - get { return Get(key); } - } + public T this[string key] => Get(key); - public T this[Func<T> @default] - { - get { return Get(@default); } - } + public T this[Func<T> @default] => Get(@default); protected abstract void InsertRootKey(string rootKey); - public void Clear() - { - InsertRootKey(baseKey); - } + public void Clear() => InsertRootKey(baseKey); - public void Clear(string rootKey) - { - InsertRootKey(BuildKey(string.Empty, rootKey)); - } + public void Clear(string rootKey) => InsertRootKey(BuildKey(string.Empty, rootKey)); - public void Reset(string key) - { - Reset(string.Empty, key); - } + public void Reset(string key) => Reset(string.Empty, key); public abstract void Reset(string rootKey, string key); - public T Get(string key) - { - return Get(string.Empty, key, null); - } + public T Get(string key) => Get(string.Empty, key, null); - public T Get(string key, Func<T> defaults) - { - return Get(string.Empty, key, defaults); - } + public T Get(string key, Func<T> defaults) => Get(string.Empty, key, defaults); - - public void Add(string key, T newValue) - { - Add(string.Empty, key, newValue); - } + public void Add(string key, T newValue) => Add(string.Empty, key, newValue); public abstract void Add(string rootkey, string key, T newValue); - public bool HasItem(string key) - { - return !Equals(Get(key), default(T)); - } - - protected string BuildKey(string key, string rootkey) - { - return string.Format("{0}-{1}-{2}", baseKey, rootkey, key); - } - - protected abstract object GetObjectFromCache(string fullKey); + public bool HasItem(string key) => !Equals(Get(key), default(T)); public T Get(Func<T> @default) { @@ -104,48 +69,44 @@ namespace ASC.Collections return Get(key, @default); } - protected virtual bool FitsCondition(object cached) - { - return cached != null && cached is T; - } - public virtual T Get(string rootkey, string key, Func<T> defaults) { var fullKey = BuildKey(key, rootkey); var objectCache = GetObjectFromCache(fullKey); + if (FitsCondition(objectCache)) { OnHit(fullKey); + return ReturnCached(objectCache); } + if (defaults != null) { OnMiss(fullKey); var newValue = defaults(); + if (condition == null || condition(newValue)) - { Add(rootkey, key, newValue); - } + return newValue; } + return default; } - protected virtual T ReturnCached(object objectCache) - { - return (T)objectCache; - } + protected virtual bool FitsCondition(object cached) => cached != null && cached is T; + + protected virtual T ReturnCached(object objectCache) => (T)objectCache; + + protected string BuildKey(string key, string rootkey) => $"{baseKey}-{rootkey}-{key}"; + + protected abstract object GetObjectFromCache(string fullKey); [Conditional("DEBUG")] - protected virtual void OnHit(string fullKey) - { - Debug.Print("cache hit:{0}", fullKey); - } + protected virtual void OnHit(string fullKey) => Debug.Print("cache hit:{0}", fullKey); [Conditional("DEBUG")] - protected virtual void OnMiss(string fullKey) - { - Debug.Print("cache miss:{0}", fullKey); - } + protected virtual void OnMiss(string fullKey) => Debug.Print("cache miss:{0}", fullKey); } } \ No newline at end of file diff --git a/common/ASC.Common/Collections/HttpRequestDictionary.cs b/common/ASC.Common/Collections/HttpRequestDictionary.cs index cf8e2b0c4f..7115b4db61 100644 --- a/common/ASC.Common/Collections/HttpRequestDictionary.cs +++ b/common/ASC.Common/Collections/HttpRequestDictionary.cs @@ -29,69 +29,53 @@ namespace ASC.Collections { public sealed class HttpRequestDictionary<T> : CachedDictionaryBase<T> { - private class CachedItem - { - internal T Value { get; set; } - - internal CachedItem(T value) - { - Value = value; - } - } - - HttpContext HttpContext { get; set; } + private readonly HttpContext _httpContext; public HttpRequestDictionary(HttpContext httpContext, string baseKey) { condition = (T) => true; this.baseKey = baseKey; - HttpContext = httpContext; - } - - protected override void InsertRootKey(string rootKey) - { - //We can't expire in HtppContext in such way - } + _httpContext = httpContext; + } public override void Reset(string rootKey, string key) { - if (HttpContext != null) + if (_httpContext != null) { var builtkey = BuildKey(key, rootKey); - HttpContext.Items[builtkey] = null; + _httpContext.Items[builtkey] = null; } } public override void Add(string rootkey, string key, T newValue) { - if (HttpContext != null) + if (_httpContext != null) { var builtkey = BuildKey(key, rootkey); - HttpContext.Items[builtkey] = new CachedItem(newValue); + _httpContext.Items[builtkey] = new CachedItem(newValue); } } - protected override object GetObjectFromCache(string fullKey) - { - return HttpContext?.Items[fullKey]; - } + protected override object GetObjectFromCache(string fullKey) => _httpContext?.Items[fullKey]; - protected override bool FitsCondition(object cached) - { - return cached is CachedItem; - } - protected override T ReturnCached(object objectCache) - { - return ((CachedItem)objectCache).Value; - } + protected override bool FitsCondition(object cached) => cached is CachedItem; - protected override void OnHit(string fullKey) - { - } + protected override T ReturnCached(object objectCache) => ((CachedItem)objectCache).Value; - protected override void OnMiss(string fullKey) - { - } + protected override void OnHit(string fullKey) { } + protected override void OnMiss(string fullKey) { } + + protected override void InsertRootKey(string rootKey) + { + //We can't expire in HtppContext in such way + } + + private class CachedItem + { + internal T Value { get; set; } + + internal CachedItem(T value) => Value = value; + } } } \ No newline at end of file diff --git a/common/ASC.Common/DIHelper.cs b/common/ASC.Common/DIHelper.cs index 4af584677f..df31e65560 100644 --- a/common/ASC.Common/DIHelper.cs +++ b/common/ASC.Common/DIHelper.cs @@ -23,7 +23,7 @@ namespace ASC.Common public class TransientAttribute : DIAttribute { - public override DIAttributeEnum DIAttributeEnum { get => DIAttributeEnum.Transient; } + public override DIAttributeEnum DIAttributeEnum => DIAttributeEnum.Transient; public TransientAttribute() { } @@ -33,20 +33,15 @@ namespace ASC.Common public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) { - if (implementation != null) - { - services.AddTransient(service, implementation); - } - else - { - services.AddTransient(service); - } + if (implementation != null) services.AddTransient(service, implementation); + + else services.AddTransient(service); } } public class ScopeAttribute : DIAttribute { - public override DIAttributeEnum DIAttributeEnum { get => DIAttributeEnum.Scope; } + public override DIAttributeEnum DIAttributeEnum => DIAttributeEnum.Scope; public ScopeAttribute() { } @@ -56,20 +51,15 @@ namespace ASC.Common public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) { - if (implementation != null) - { - services.AddScoped(service, implementation); - } - else - { - services.AddScoped(service); - } + if (implementation != null) services.AddScoped(service, implementation); + + else services.AddScoped(service); } } public class SingletoneAttribute : DIAttribute { - public override DIAttributeEnum DIAttributeEnum { get => DIAttributeEnum.Singletone; } + public override DIAttributeEnum DIAttributeEnum => DIAttributeEnum.Singletone; public SingletoneAttribute() { } @@ -79,14 +69,9 @@ namespace ASC.Common public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) { - if (implementation != null) - { - services.AddSingleton(service, implementation); - } - else - { - services.AddSingleton(service); - } + if (implementation != null) services.AddSingleton(service, implementation); + + else services.AddSingleton(service); } } @@ -99,10 +84,7 @@ namespace ASC.Common public DIAttribute() { } - public DIAttribute(Type service) - { - Service = service; - } + public DIAttribute(Type service) => Service = service; public DIAttribute(Type service, Type implementation) { @@ -128,39 +110,26 @@ namespace ASC.Common { DIAttributeEnum.Scope, new List<string>() }, { DIAttributeEnum.Transient, new List<string>() } }; + Added = new List<string>(); Configured = new List<string>(); } - public DIHelper(IServiceCollection serviceCollection) : this() - { - ServiceCollection = serviceCollection; - } + public DIHelper(IServiceCollection serviceCollection) : this() => ServiceCollection = serviceCollection; - public void Configure(IServiceCollection serviceCollection) - { - ServiceCollection = serviceCollection; - } + public void Configure(IServiceCollection serviceCollection) => ServiceCollection = serviceCollection; public void RegisterProducts(IConfiguration configuration, string path) { var types = AutofacExtension.FindAndLoad(configuration, path); foreach (var t in types.Select(Type.GetType).Where(r => r != null)) - { TryAdd(t); - } } - public bool TryAdd<TService>() where TService : class - { - return TryAdd(typeof(TService)); - } + public bool TryAdd<TService>() where TService : class => TryAdd(typeof(TService)); - public bool TryAdd<TService, TImplementation>() where TService : class - { - return TryAdd(typeof(TService), typeof(TImplementation)); - } + public bool TryAdd<TService, TImplementation>() where TService : class => TryAdd(typeof(TService), typeof(TImplementation)); public bool TryAdd(Type service, Type implementation = null) { @@ -171,14 +140,14 @@ namespace ASC.Common )) { service = service.GetGenericArguments().FirstOrDefault(); - if (service == null) - { - return false; - } + + if (service == null) return false; } var serviceName = $"{service}{implementation}"; + if (Added.Contains(serviceName)) return false; + Added.Add(serviceName); var di = service.IsGenericType && ( @@ -186,6 +155,7 @@ namespace ASC.Common service.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || service.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) ) && implementation != null ? implementation.GetCustomAttribute<DIAttribute>() : service.GetCustomAttribute<DIAttribute>(); + var isnew = false; if (di != null) @@ -211,6 +181,7 @@ namespace ASC.Common x.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || x.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) )); + if (a != null) { if (!a.ContainsGenericParameters) @@ -222,10 +193,8 @@ namespace ASC.Common if (g != service) { TryAdd(g); - if (service.IsInterface && di.Implementation == null) - { - TryAdd(service, g); - } + + if (service.IsInterface && di.Implementation == null) TryAdd(service, g); } } @@ -260,11 +229,7 @@ namespace ASC.Common isnew = Register(service, di.Service); TryAdd(di.Service); } - else - { - Register(di.Service); - } - + else Register(di.Service); } } @@ -286,10 +251,7 @@ namespace ASC.Common if (g != service) { //TryAdd(g); - if (service.IsInterface && implementation == null) - { - TryAdd(service, g); - } + if (service.IsInterface && implementation == null) TryAdd(service, g); } } @@ -308,19 +270,14 @@ namespace ASC.Common TryAdd(b1); c = a1.MakeGenericType(b1); } - else - { - c = a1.MakeGenericType(service.GetGenericArguments()); - } + else c = a1.MakeGenericType(service.GetGenericArguments()); TryAdd(c, di.Implementation.MakeGenericType(service.GetGenericArguments())); //a, di.Service } } - else - { - isnew = TryAdd(service, di.Implementation); - } + + else isnew = TryAdd(service, di.Implementation); } } } @@ -329,55 +286,28 @@ namespace ASC.Common { ConstructorInfo[] props = null; - if (!service.IsInterface) - { - props = service.GetConstructors(); - } - else if (implementation != null) - { - props = implementation.GetConstructors(); - } - else if (di.Service != null) - { - props = di.Service.GetConstructors(); - } + if (!service.IsInterface) props = service.GetConstructors(); + + else if (implementation != null) props = implementation.GetConstructors(); + + else if (di.Service != null) props = di.Service.GetConstructors(); if (props != null) { var par = props.SelectMany(r => r.GetParameters()).Distinct(); + foreach (var p1 in par) - { TryAdd(p1.ParameterType); - } } } return isnew; } - private bool Register(Type service, Type implementation = null) - { - if (service.IsSubclassOf(typeof(ControllerBase)) || service.GetInterfaces().Contains(typeof(IResourceFilter)) || service.GetInterfaces().Contains(typeof(IDictionary<string, string>))) return true; - var c = service.IsGenericType && ( - service.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || - service.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || - service.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) - ) && implementation != null ? implementation.GetCustomAttribute<DIAttribute>() : service.GetCustomAttribute<DIAttribute>(); - var serviceName = $"{service}{implementation}"; - - if (!Services[c.DIAttributeEnum].Contains(serviceName)) - { - c.TryAdd(ServiceCollection, service, implementation); - Services[c.DIAttributeEnum].Add(serviceName); - return true; - } - - return false; - } - public DIHelper TryAddSingleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { var serviceName = $"{typeof(TService)}"; + if (!Services[DIAttributeEnum.Singletone].Contains(serviceName)) { Services[DIAttributeEnum.Singletone].Add(serviceName); @@ -390,6 +320,7 @@ namespace ASC.Common public DIHelper TryAddSingleton<TService, TImplementation>() where TService : class where TImplementation : class, TService { var serviceName = $"{typeof(TService)}{typeof(TImplementation)}"; + if (!Services[DIAttributeEnum.Singletone].Contains(serviceName)) { Services[DIAttributeEnum.Singletone].Add(serviceName); @@ -402,6 +333,7 @@ namespace ASC.Common public DIHelper Configure<TOptions>(Action<TOptions> configureOptions) where TOptions : class { var serviceName = $"{typeof(TOptions)}"; + if (!Configured.Contains(serviceName)) { Configured.Add(serviceName); @@ -414,6 +346,7 @@ namespace ASC.Common public DIHelper Configure<TOptions>(string name, Action<TOptions> configureOptions) where TOptions : class { var serviceName = $"{typeof(TOptions)}{name}"; + if (!Configured.Contains(serviceName)) { Configured.Add(serviceName); @@ -422,5 +355,30 @@ namespace ASC.Common return this; } + + private bool Register(Type service, Type implementation = null) + { + if (service.IsSubclassOf(typeof(ControllerBase)) || service.GetInterfaces().Contains(typeof(IResourceFilter)) + || service.GetInterfaces().Contains(typeof(IDictionary<string, string>))) + return true; + + var c = service.IsGenericType && ( + service.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || + service.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || + service.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) + ) && implementation != null ? implementation.GetCustomAttribute<DIAttribute>() : service.GetCustomAttribute<DIAttribute>(); + + var serviceName = $"{service}{implementation}"; + + if (!Services[c.DIAttributeEnum].Contains(serviceName)) + { + c.TryAdd(ServiceCollection, service, implementation); + Services[c.DIAttributeEnum].Add(serviceName); + + return true; + } + + return false; + } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Data/StreamExtension.cs b/common/ASC.Common/Data/StreamExtension.cs index c856976971..c7e0dad7d1 100644 --- a/common/ASC.Common/Data/StreamExtension.cs +++ b/common/ASC.Common/Data/StreamExtension.cs @@ -33,12 +33,13 @@ public static class StreamExtension public static void StreamCopyTo(this Stream srcStream, Stream dstStream, int length) { - if (srcStream == null) throw new ArgumentNullException("srcStream"); - if (dstStream == null) throw new ArgumentNullException("dstStream"); + if (srcStream == null) throw new ArgumentNullException(nameof(srcStream)); + if (dstStream == null) throw new ArgumentNullException(nameof(dstStream)); var buffer = new byte[BufferSize]; int totalRead = 0; int readed; + while ((readed = srcStream.Read(buffer, 0, length - totalRead > BufferSize ? BufferSize : length - totalRead)) > 0 && totalRead < length) { dstStream.Write(buffer, 0, readed); diff --git a/common/ASC.Common/Data/TempPath.cs b/common/ASC.Common/Data/TempPath.cs index 7ed8ffb87d..dd22d03d91 100644 --- a/common/ASC.Common/Data/TempPath.cs +++ b/common/ASC.Common/Data/TempPath.cs @@ -26,34 +26,24 @@ namespace System.IO [Singletone] public class TempPath { - readonly string tempFolder; + private readonly string _tempFolder; public TempPath(IConfiguration configuration) { string rootFolder = AppContext.BaseDirectory; if (string.IsNullOrEmpty(rootFolder)) - { rootFolder = Assembly.GetEntryAssembly().Location; - } - tempFolder = configuration["temp"] ?? Path.Combine("..", "Data", "temp"); + _tempFolder = configuration["temp"] ?? Path.Combine("..", "Data", "temp"); - if (!Path.IsPathRooted(tempFolder)) - { - tempFolder = Path.GetFullPath(Path.Combine(rootFolder, tempFolder)); - } + if (!Path.IsPathRooted(_tempFolder)) + _tempFolder = Path.GetFullPath(Path.Combine(rootFolder, _tempFolder)); - if (!Directory.Exists(tempFolder)) - { - Directory.CreateDirectory(tempFolder); - } + if (!Directory.Exists(_tempFolder)) Directory.CreateDirectory(_tempFolder); } - public string GetTempPath() - { - return tempFolder; - } + public string GetTempPath() => _tempFolder; public string GetTempFileName() { @@ -63,7 +53,7 @@ namespace System.IO do { - path = Path.Combine(tempFolder, Path.GetRandomFileName()); + path = Path.Combine(_tempFolder, Path.GetRandomFileName()); try { diff --git a/common/ASC.Common/Data/TempStream.cs b/common/ASC.Common/Data/TempStream.cs index 0b6ee90911..d28d54aa95 100644 --- a/common/ASC.Common/Data/TempStream.cs +++ b/common/ASC.Common/Data/TempStream.cs @@ -23,30 +23,28 @@ namespace ASC.Common [Singletone] public class TempStream { - private TempPath TempPath { get; } + private readonly TempPath _tempPath; - public TempStream(TempPath tempPath) - { - TempPath = tempPath; - } + public TempStream(TempPath tempPath) => _tempPath = tempPath; public Stream GetBuffered(Stream srcStream) { - if (srcStream == null) throw new ArgumentNullException("srcStream"); + if (srcStream == null) throw new ArgumentNullException(nameof(srcStream)); + if (!srcStream.CanSeek || srcStream.CanTimeout) { //Buffer it var memStream = Create(); srcStream.CopyTo(memStream); memStream.Position = 0; + return memStream; } + return srcStream; } - public Stream Create() - { - return new FileStream(TempPath.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose); - } + public Stream Create() => new FileStream(_tempPath.GetTempFileName(), FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose); } } \ No newline at end of file diff --git a/common/ASC.Common/DependencyInjection/AutofacExtension.cs b/common/ASC.Common/DependencyInjection/AutofacExtension.cs index 8dec7cb508..2962739483 100644 --- a/common/ASC.Common/DependencyInjection/AutofacExtension.cs +++ b/common/ASC.Common/DependencyInjection/AutofacExtension.cs @@ -25,7 +25,8 @@ namespace ASC.Common.DependencyInjection public static class AutofacExtension { - public static void Register(this ContainerBuilder builder, IConfiguration configuration, bool loadproducts = true, bool loadconsumers = true, params string[] intern) + public static void Register(this ContainerBuilder builder, IConfiguration configuration, + bool loadproducts = true, bool loadconsumers = true, params string[] intern) { var modules = new List<(bool, string)> { @@ -33,27 +34,20 @@ namespace ASC.Common.DependencyInjection }; if (loadproducts) - { modules.Add((true, "autofac.products.json")); - } if (loadconsumers) - { modules.Add((true, "autofac.consumers.json")); - } if (intern != null) - { modules.AddRange(intern.Select(r => (false, r))); - } foreach (var p in modules) { var config = new ConfigurationBuilder(); - if (p.Item1) - { - config.SetBasePath(configuration["pathToConf"]); - } + + if (p.Item1) config.SetBasePath(configuration["pathToConf"]); + config.AddJsonFile(p.Item2); var root = config.Build(); @@ -73,10 +67,7 @@ namespace ASC.Common.DependencyInjection var sectionSettings = root.GetSection("components"); - if (sectionSettings == null) - { - return new List<string>(); - } + if (sectionSettings == null) return new List<string>(); var folder = configuration["core:products:folder"]; var subfolder = configuration["core:products:subfolder"]; @@ -85,19 +76,13 @@ namespace ASC.Common.DependencyInjection if (!Path.IsPathRooted(folder)) { if (currentDir.EndsWith(CrossPlatform.PathCombine(Path.GetFileName(folder), Assembly.GetEntryAssembly().GetName().Name, subfolder))) - { productsDir = Path.GetFullPath(CrossPlatform.PathCombine("..", "..")); - } - else - { - productsDir = Path.GetFullPath(CrossPlatform.PathCombine(currentDir, folder)); - } - } - else - { - productsDir = folder; + + else productsDir = Path.GetFullPath(CrossPlatform.PathCombine(currentDir, folder)); } + else productsDir = folder; + var cs = new List<AutofacComponent>(); sectionSettings.Bind(cs); @@ -124,15 +109,15 @@ namespace ASC.Common.DependencyInjection var path = GetFullPath(dll); if (!string.IsNullOrEmpty(path)) - { AssemblyLoadContext.Default.Resolving += new Resolver(path).Resolving; - } } string GetFullPath(string n) { var productPath = CrossPlatform.PathCombine(productsDir, n, subfolder); - return GetPath(CrossPlatform.PathCombine(productPath, "bin"), n, SearchOption.AllDirectories) ?? GetPath(productPath, n, SearchOption.TopDirectoryOnly); + + return GetPath(CrossPlatform.PathCombine(productPath, "bin"), n, SearchOption.AllDirectories) + ?? GetPath(productPath, n, SearchOption.TopDirectoryOnly); } static string GetPath(string dirPath, string dll, SearchOption searchOption) @@ -142,22 +127,17 @@ namespace ASC.Common.DependencyInjection return Directory.GetFiles(dirPath, $"{dll}.dll", searchOption).FirstOrDefault(); } } - - } class Resolver { - private string ResolvePath { get; set; } + private readonly string _resolvePath; - public Resolver(string assemblyPath) - { - ResolvePath = assemblyPath; - } + public Resolver(string assemblyPath) => _resolvePath = assemblyPath; public Assembly Resolving(AssemblyLoadContext context, AssemblyName assemblyName) { - var path = CrossPlatform.PathCombine(Path.GetDirectoryName(ResolvePath), $"{assemblyName.Name}.dll"); + var path = CrossPlatform.PathCombine(Path.GetDirectoryName(_resolvePath), $"{assemblyName.Name}.dll"); if (!File.Exists(path)) return null; diff --git a/common/ASC.Common/Geolocation/IPGeolocationInfo.cs b/common/ASC.Common/Geolocation/IPGeolocationInfo.cs index 4540b1a2d3..c505926623 100644 --- a/common/ASC.Common/Geolocation/IPGeolocationInfo.cs +++ b/common/ASC.Common/Geolocation/IPGeolocationInfo.cs @@ -28,18 +28,12 @@ namespace ASC.Geolocation public class IPGeolocationInfo { public string Key { get; set; } - public string City { get; set; } - public double TimezoneOffset { get; set; } - public string TimezoneName { get; set; } - public string IPStart { get; set; } - public string IPEnd { get; set; } - public readonly static IPGeolocationInfo Default = new IPGeolocationInfo { Key = string.Empty, diff --git a/common/ASC.Common/Logging/EFLoggerFactory.cs b/common/ASC.Common/Logging/EFLoggerFactory.cs index fb79d37ff6..3db5b92bee 100644 --- a/common/ASC.Common/Logging/EFLoggerFactory.cs +++ b/common/ASC.Common/Logging/EFLoggerFactory.cs @@ -9,13 +9,13 @@ namespace ASC.Common.Logging [Singletone] public class EFLoggerFactory : ILoggerFactory { - Lazy<ILogger> Logger { get; set; } - ILoggerProvider LoggerProvider { get; set; } + private readonly Lazy<ILogger> _logger; + private readonly ILoggerProvider _loggerProvider; public EFLoggerFactory(EFLoggerProvider loggerProvider) { - LoggerProvider = loggerProvider; - Logger = new Lazy<ILogger>(() => LoggerProvider.CreateLogger("")); + _loggerProvider = loggerProvider; + _logger = new Lazy<ILogger>(() => _loggerProvider.CreateLogger("")); } public void AddProvider(ILoggerProvider provider) @@ -23,30 +23,19 @@ namespace ASC.Common.Logging //LoggerProvider = provider; } - public ILogger CreateLogger(string categoryName) - { - return Logger.Value; - } + public ILogger CreateLogger(string categoryName) => _logger.Value; - public void Dispose() - { - } + public void Dispose() { } } [Singletone] public class EFLoggerProvider : ILoggerProvider { - private IOptionsMonitor<ILog> Option { get; } + private readonly IOptionsMonitor<ILog> _option; - public EFLoggerProvider(IOptionsMonitor<ILog> option) - { - Option = option; - } + public EFLoggerProvider(IOptionsMonitor<ILog> option) => _option = option; - public ILogger CreateLogger(string categoryName) - { - return new EFLogger(Option.Get("ASC.SQL")); - } + public ILogger CreateLogger(string categoryName) => new EFLogger(_option.Get("ASC.SQL")); public void Dispose() { } } @@ -55,12 +44,10 @@ namespace ASC.Common.Logging { public ILog CustomLogger { get; } - public EFLogger(ILog customLogger) - { - CustomLogger = customLogger; - } + public EFLogger(ILog customLogger) => CustomLogger = customLogger; public IDisposable BeginScope<TState>(TState state) { return null; } + public bool IsEnabled(LogLevel logLevel) { return logLevel switch diff --git a/common/ASC.Common/Logging/Log.cs b/common/ASC.Common/Logging/Log.cs index 56f8e4eab5..3670c3276d 100644 --- a/common/ASC.Common/Logging/Log.cs +++ b/common/ASC.Common/Logging/Log.cs @@ -105,85 +105,76 @@ namespace ASC.Common.Logging public class Log : ILog { - static Log() - { - XmlConfigurator.Configure(log4net.LogManager.GetRepository(Assembly.GetCallingAssembly())); - } - - private log4net.ILog loger; - + public string Name { get; set; } public bool IsDebugEnabled { get; private set; } - public bool IsInfoEnabled { get; private set; } - public bool IsWarnEnabled { get; private set; } - public bool IsErrorEnabled { get; private set; } - public bool IsFatalEnabled { get; private set; } + public bool IsTraceEnabled { get; private set; } + public string LogDirectory => log4net.GlobalContext.Properties["LogDirectory"].ToString(); + + private log4net.ILog _logger; + + public Log(string name) => Configure(name); - public bool IsTraceEnabled { get; private set; } - - public Log(string name) - { - Configure(name); - } + static Log() => XmlConfigurator.Configure(log4net.LogManager.GetRepository(Assembly.GetCallingAssembly())); public void Configure(string name) { - loger = log4net.LogManager.GetLogger(Assembly.GetCallingAssembly(), name); + _logger = log4net.LogManager.GetLogger(Assembly.GetCallingAssembly(), name); - IsDebugEnabled = loger.IsDebugEnabled; - IsInfoEnabled = loger.IsInfoEnabled; - IsWarnEnabled = loger.IsWarnEnabled; - IsErrorEnabled = loger.IsErrorEnabled; - IsFatalEnabled = loger.IsFatalEnabled; - IsTraceEnabled = loger.Logger.IsEnabledFor(Level.Trace); + IsDebugEnabled = _logger.IsDebugEnabled; + IsInfoEnabled = _logger.IsInfoEnabled; + IsWarnEnabled = _logger.IsWarnEnabled; + IsErrorEnabled = _logger.IsErrorEnabled; + IsFatalEnabled = _logger.IsFatalEnabled; + IsTraceEnabled = _logger.Logger.IsEnabledFor(Level.Trace); } public void Trace(object message) { - if (IsTraceEnabled) loger.Logger.Log(GetType(), Level.Trace, message, null); + if (IsTraceEnabled) _logger.Logger.Log(GetType(), Level.Trace, message, null); } public void TraceFormat(string message, object arg0) { - if (IsTraceEnabled) loger.Logger.Log(GetType(), Level.Trace, string.Format(message, arg0), null); + if (IsTraceEnabled) _logger.Logger.Log(GetType(), Level.Trace, string.Format(message, arg0), null); } public void Debug(object message) { - if (IsDebugEnabled) loger.Debug(message); + if (IsDebugEnabled) _logger.Debug(message); } public void Debug(object message, Exception exception) { - if (IsDebugEnabled) loger.Debug(message, exception); + if (IsDebugEnabled) _logger.Debug(message, exception); } public void DebugFormat(string format, params object[] args) { - if (IsDebugEnabled) loger.DebugFormat(format, args); + if (IsDebugEnabled) _logger.DebugFormat(format, args); } public void DebugFormat(string format, object arg0) { - if (IsDebugEnabled) loger.DebugFormat(format, arg0); + if (IsDebugEnabled) _logger.DebugFormat(format, arg0); } public void DebugFormat(string format, object arg0, object arg1) { - if (IsDebugEnabled) loger.DebugFormat(format, arg0, arg1); + if (IsDebugEnabled) _logger.DebugFormat(format, arg0, arg1); } public void DebugFormat(string format, object arg0, object arg1, object arg2) { - if (IsDebugEnabled) loger.DebugFormat(format, arg0, arg1, arg2); + if (IsDebugEnabled) _logger.DebugFormat(format, arg0, arg1, arg2); } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { - if (IsDebugEnabled) loger.DebugFormat(provider, format, args); + if (IsDebugEnabled) _logger.DebugFormat(provider, format, args); } public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) @@ -195,151 +186,151 @@ namespace ASC.Common.Logging log4net.ThreadContext.Properties[p.Key] = p.Value; } - loger.Debug(message); + _logger.Debug(message); } public void Info(object message) { - if (IsInfoEnabled) loger.Info(message); + if (IsInfoEnabled) _logger.Info(message); } public void Info(string message, Exception exception) { - if (IsInfoEnabled) loger.Info(message, exception); + if (IsInfoEnabled) _logger.Info(message, exception); } public void InfoFormat(string format, params object[] args) { - if (IsInfoEnabled) loger.InfoFormat(format, args); + if (IsInfoEnabled) _logger.InfoFormat(format, args); } public void InfoFormat(string format, object arg0) { - if (IsInfoEnabled) loger.InfoFormat(format, arg0); + if (IsInfoEnabled) _logger.InfoFormat(format, arg0); } public void InfoFormat(string format, object arg0, object arg1) { - if (IsInfoEnabled) loger.InfoFormat(format, arg0, arg1); + if (IsInfoEnabled) _logger.InfoFormat(format, arg0, arg1); } public void InfoFormat(string format, object arg0, object arg1, object arg2) { - if (IsInfoEnabled) loger.InfoFormat(format, arg0, arg1, arg2); + if (IsInfoEnabled) _logger.InfoFormat(format, arg0, arg1, arg2); } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { - if (IsInfoEnabled) loger.InfoFormat(provider, format, args); + if (IsInfoEnabled) _logger.InfoFormat(provider, format, args); } public void Warn(object message) { - if (IsWarnEnabled) loger.Warn(message); + if (IsWarnEnabled) _logger.Warn(message); } public void Warn(object message, Exception exception) { - if (IsWarnEnabled) loger.Warn(message, exception); + if (IsWarnEnabled) _logger.Warn(message, exception); } public void WarnFormat(string format, params object[] args) { - if (IsWarnEnabled) loger.WarnFormat(format, args); + if (IsWarnEnabled) _logger.WarnFormat(format, args); } public void WarnFormat(string format, object arg0) { - if (IsWarnEnabled) loger.WarnFormat(format, arg0); + if (IsWarnEnabled) _logger.WarnFormat(format, arg0); } public void WarnFormat(string format, object arg0, object arg1) { - if (IsWarnEnabled) loger.WarnFormat(format, arg0, arg1); + if (IsWarnEnabled) _logger.WarnFormat(format, arg0, arg1); } public void WarnFormat(string format, object arg0, object arg1, object arg2) { - if (IsWarnEnabled) loger.WarnFormat(format, arg0, arg1, arg2); + if (IsWarnEnabled) _logger.WarnFormat(format, arg0, arg1, arg2); } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { - if (IsWarnEnabled) loger.WarnFormat(provider, format, args); + if (IsWarnEnabled) _logger.WarnFormat(provider, format, args); } public void Error(object message) { - if (IsErrorEnabled) loger.Error(message); + if (IsErrorEnabled) _logger.Error(message); } public void Error(object message, Exception exception) { - if (IsErrorEnabled) loger.Error(message, exception); + if (IsErrorEnabled) _logger.Error(message, exception); } public void ErrorFormat(string format, params object[] args) { - if (IsErrorEnabled) loger.ErrorFormat(format, args); + if (IsErrorEnabled) _logger.ErrorFormat(format, args); } public void ErrorFormat(string format, object arg0) { - if (IsErrorEnabled) loger.ErrorFormat(format, arg0); + if (IsErrorEnabled) _logger.ErrorFormat(format, arg0); } public void ErrorFormat(string format, object arg0, object arg1) { - if (IsErrorEnabled) loger.ErrorFormat(format, arg0, arg1); + if (IsErrorEnabled) _logger.ErrorFormat(format, arg0, arg1); } public void ErrorFormat(string format, object arg0, object arg1, object arg2) { - if (IsErrorEnabled) loger.ErrorFormat(format, arg0, arg1, arg2); + if (IsErrorEnabled) _logger.ErrorFormat(format, arg0, arg1, arg2); } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { - if (IsErrorEnabled) loger.ErrorFormat(provider, format, args); + if (IsErrorEnabled) _logger.ErrorFormat(provider, format, args); } public void Fatal(object message) { - if (IsFatalEnabled) loger.Fatal(message); + if (IsFatalEnabled) _logger.Fatal(message); } public void Fatal(string message, Exception exception) { - if (IsFatalEnabled) loger.Fatal(message, exception); + if (IsFatalEnabled) _logger.Fatal(message, exception); } public void FatalFormat(string format, params object[] args) { - if (IsFatalEnabled) loger.FatalFormat(format, args); + if (IsFatalEnabled) _logger.FatalFormat(format, args); } public void FatalFormat(string format, object arg0) { - if (IsFatalEnabled) loger.FatalFormat(format, arg0); + if (IsFatalEnabled) _logger.FatalFormat(format, arg0); } public void FatalFormat(string format, object arg0, object arg1) { - if (IsFatalEnabled) loger.FatalFormat(format, arg0, arg1); + if (IsFatalEnabled) _logger.FatalFormat(format, arg0, arg1); } public void FatalFormat(string format, object arg0, object arg1, object arg2) { - if (IsFatalEnabled) loger.FatalFormat(format, arg0, arg1, arg2); + if (IsFatalEnabled) _logger.FatalFormat(format, arg0, arg1, arg2); } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { - if (IsFatalEnabled) loger.FatalFormat(provider, format, args); + if (IsFatalEnabled) _logger.FatalFormat(provider, format, args); } public void DebugWithProps(string message, KeyValuePair<string, object> prop1, KeyValuePair<string, object> prop2, KeyValuePair<string, object> prop3) @@ -350,28 +341,13 @@ namespace ASC.Common.Logging AddProp(prop2); AddProp(prop3); - loger.Debug(message); + _logger.Debug(message); static void AddProp(KeyValuePair<string, object> p) { log4net.ThreadContext.Properties[p.Key] = p.Value; } } - - public string LogDirectory - { - get - { - return log4net.GlobalContext.Properties["LogDirectory"].ToString(); - } - } - - public string Name - { - get; - - set; - } } public class NLogSettings @@ -383,131 +359,124 @@ namespace ASC.Common.Logging [Singletone] public class ConfigureLogNLog : IConfigureNamedOptions<LogNLog> { - private IConfiguration Configuration { get; } - private ConfigurationExtension ConfigurationExtension { get; } + private readonly IConfiguration _configuration; + private readonly ConfigurationExtension _configurationExtension; public ConfigureLogNLog(IConfiguration configuration, ConfigurationExtension configurationExtension, IHostEnvironment hostingEnvironment) { - Configuration = configuration; - ConfigurationExtension = configurationExtension; + _configuration = configuration; + _configurationExtension = configurationExtension; - LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(CrossPlatform.PathCombine(Configuration["pathToConf"], "nlog.config")); + LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(CrossPlatform.PathCombine(_configuration["pathToConf"], "nlog.config")); LogManager.ThrowConfigExceptions = false; - var settings = ConfigurationExtension.GetSetting<NLogSettings>("log"); - if (!string.IsNullOrEmpty(settings.Name)) - { - LogManager.Configuration.Variables["name"] = settings.Name; - } + var settings = _configurationExtension.GetSetting<NLogSettings>("log"); - if (!string.IsNullOrEmpty(settings.Dir)) - { - LogManager.Configuration.Variables["dir"] = CrossPlatform.PathCombine(hostingEnvironment.ContentRootPath, settings.Dir).TrimEnd('/').TrimEnd('\\') + Path.DirectorySeparatorChar; - } + if (!string.IsNullOrEmpty(settings.Name)) + LogManager.Configuration.Variables["name"] = settings.Name; + + if (!string.IsNullOrEmpty(settings.Dir)) + LogManager.Configuration.Variables["dir"] = CrossPlatform.PathCombine(hostingEnvironment.ContentRootPath, settings.Dir) + .TrimEnd('/').TrimEnd('\\') + Path.DirectorySeparatorChar; NLog.Targets.Target.Register<SelfCleaningTarget>("SelfCleaning"); } - public void Configure(LogNLog options) - { - options.Configure("ASC"); - } + public void Configure(LogNLog options) => options.Configure("ASC"); public void Configure(string name, LogNLog options) { - if (string.IsNullOrEmpty(name)) - { - Configure(options); - } - else - { - options.Configure(name); - } + if (string.IsNullOrEmpty(name)) Configure(options); + + else options.Configure(name); } } public class LogNLog : ILog - { - private NLog.ILogger loger; - private NLog.ILogger Loger + { + public bool IsDebugEnabled { get; private set; } + public bool IsInfoEnabled { get; private set; } + public bool IsWarnEnabled { get; private set; } + public bool IsErrorEnabled { get; private set; } + public bool IsFatalEnabled { get; private set; } + public bool IsTraceEnabled { get; private set; } + public string LogDirectory => LogManager.Configuration.Variables["dir"].Text; + public string Name { - get - { - return loger; - } + get => _name; + set { - loger = value; - IsDebugEnabled = loger.IsDebugEnabled; - IsInfoEnabled = loger.IsInfoEnabled; - IsWarnEnabled = loger.IsWarnEnabled; - IsErrorEnabled = loger.IsErrorEnabled; - IsFatalEnabled = loger.IsFatalEnabled; - IsTraceEnabled = loger.IsEnabled(LogLevel.Trace); + _name = value; + Logger = LogManager.GetLogger(_name); } - } - - public bool IsDebugEnabled { get; private set; } - - public bool IsInfoEnabled { get; private set; } - - public bool IsWarnEnabled { get; private set; } - - public bool IsErrorEnabled { get; private set; } - - public bool IsFatalEnabled { get; private set; } - - public bool IsTraceEnabled { get; private set; } - - public void Configure(string name) - { - Name = name; } + + private NLog.ILogger Logger + { + get => _logger; + + set + { + _logger = value; + IsDebugEnabled = _logger.IsDebugEnabled; + IsInfoEnabled = _logger.IsInfoEnabled; + IsWarnEnabled = _logger.IsWarnEnabled; + IsErrorEnabled = _logger.IsErrorEnabled; + IsFatalEnabled = _logger.IsFatalEnabled; + IsTraceEnabled = _logger.IsEnabled(LogLevel.Trace); + } + } + + private NLog.ILogger _logger; + private string _name; + + public void Configure(string name) => Name = name; public void Trace(object message) { - if (IsTraceEnabled) Loger.Log(LogLevel.Trace, message); + if (IsTraceEnabled) Logger.Log(LogLevel.Trace, message); } public void TraceFormat(string message, object arg0) { - if (IsTraceEnabled) Loger.Log(LogLevel.Trace, string.Format(message, arg0)); + if (IsTraceEnabled) Logger.Log(LogLevel.Trace, string.Format(message, arg0)); } public void Debug(object message) { - if (IsDebugEnabled) Loger.Debug(message); + if (IsDebugEnabled) Logger.Debug(message); } public void Debug(object message, Exception exception) { - if (IsDebugEnabled) Loger.Debug(exception, "{0}", message); + if (IsDebugEnabled) Logger.Debug(exception, "{0}", message); } public void DebugFormat(string format, params object[] args) { - if (IsDebugEnabled) Loger.Debug(format, args); + if (IsDebugEnabled) Logger.Debug(format, args); } public void DebugFormat(string format, object arg0) { - if (IsDebugEnabled) Loger.Debug(format, arg0); + if (IsDebugEnabled) Logger.Debug(format, arg0); } public void DebugFormat(string format, object arg0, object arg1) { - if (IsDebugEnabled) Loger.Debug(format, arg0, arg1); + if (IsDebugEnabled) Logger.Debug(format, arg0, arg1); } public void DebugFormat(string format, object arg0, object arg1, object arg2) { - if (IsDebugEnabled) Loger.Debug(format, arg0, arg1, arg2); + if (IsDebugEnabled) Logger.Debug(format, arg0, arg1, arg2); } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { - if (IsDebugEnabled) Loger.Debug(provider, format, args); + if (IsDebugEnabled) Logger.Debug(provider, format, args); } public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) @@ -521,166 +490,150 @@ namespace ASC.Common.Logging theEvent.Properties[p.Key] = p.Value; } - Loger.Log(theEvent); + Logger.Log(theEvent); } public void Info(object message) { - if (IsInfoEnabled) Loger.Info(message); + if (IsInfoEnabled) Logger.Info(message); } public void Info(string message, Exception exception) { - if (IsInfoEnabled) Loger.Info(exception, message); + if (IsInfoEnabled) Logger.Info(exception, message); } public void InfoFormat(string format, params object[] args) { - if (IsInfoEnabled) Loger.Info(format, args); + if (IsInfoEnabled) Logger.Info(format, args); } public void InfoFormat(string format, object arg0) { - if (IsInfoEnabled) Loger.Info(format, arg0); + if (IsInfoEnabled) Logger.Info(format, arg0); } public void InfoFormat(string format, object arg0, object arg1) { - if (IsInfoEnabled) Loger.Info(format, arg0, arg1); + if (IsInfoEnabled) Logger.Info(format, arg0, arg1); } public void InfoFormat(string format, object arg0, object arg1, object arg2) { - if (IsInfoEnabled) Loger.Info(format, arg0, arg1, arg2); + if (IsInfoEnabled) Logger.Info(format, arg0, arg1, arg2); } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { - if (IsInfoEnabled) Loger.Info(provider, format, args); + if (IsInfoEnabled) Logger.Info(provider, format, args); } public void Warn(object message) { - if (IsWarnEnabled) Loger.Warn(message); + if (IsWarnEnabled) Logger.Warn(message); } public void Warn(object message, Exception exception) { - if (IsWarnEnabled) Loger.Warn(exception, "{0}", message); + if (IsWarnEnabled) Logger.Warn(exception, "{0}", message); } public void WarnFormat(string format, params object[] args) { - if (IsWarnEnabled) Loger.Warn(format, args); + if (IsWarnEnabled) Logger.Warn(format, args); } public void WarnFormat(string format, object arg0) { - if (IsWarnEnabled) Loger.Warn(format, arg0); + if (IsWarnEnabled) Logger.Warn(format, arg0); } public void WarnFormat(string format, object arg0, object arg1) { - if (IsWarnEnabled) Loger.Warn(format, arg0, arg1); + if (IsWarnEnabled) Logger.Warn(format, arg0, arg1); } public void WarnFormat(string format, object arg0, object arg1, object arg2) { - if (IsWarnEnabled) Loger.Warn(format, arg0, arg1, arg2); + if (IsWarnEnabled) Logger.Warn(format, arg0, arg1, arg2); } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { - if (IsWarnEnabled) Loger.Warn(provider, format, args); + if (IsWarnEnabled) Logger.Warn(provider, format, args); } public void Error(object message) { - if (IsErrorEnabled) Loger.Error(message); + if (IsErrorEnabled) Logger.Error(message); } public void Error(object message, Exception exception) { - if (IsErrorEnabled) Loger.Error(exception, "{0}", message); + if (IsErrorEnabled) Logger.Error(exception, "{0}", message); } public void ErrorFormat(string format, params object[] args) { - if (IsErrorEnabled) Loger.Error(format, args); + if (IsErrorEnabled) Logger.Error(format, args); } public void ErrorFormat(string format, object arg0) { - if (IsErrorEnabled) Loger.Error(format, arg0); + if (IsErrorEnabled) Logger.Error(format, arg0); } public void ErrorFormat(string format, object arg0, object arg1) { - if (IsErrorEnabled) Loger.Error(format, arg0, arg1); + if (IsErrorEnabled) Logger.Error(format, arg0, arg1); } public void ErrorFormat(string format, object arg0, object arg1, object arg2) { - if (IsErrorEnabled) Loger.Error(format, arg0, arg1, arg2); + if (IsErrorEnabled) Logger.Error(format, arg0, arg1, arg2); } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { - if (IsErrorEnabled) Loger.Error(provider, format, args); + if (IsErrorEnabled) Logger.Error(provider, format, args); } public void Fatal(object message) { - if (IsFatalEnabled) Loger.Fatal(message); + if (IsFatalEnabled) Logger.Fatal(message); } public void Fatal(string message, Exception exception) { - if (IsFatalEnabled) Loger.Fatal(exception, message); + if (IsFatalEnabled) Logger.Fatal(exception, message); } public void FatalFormat(string format, params object[] args) { - if (IsFatalEnabled) Loger.Fatal(format, args); + if (IsFatalEnabled) Logger.Fatal(format, args); } public void FatalFormat(string format, object arg0) { - if (IsFatalEnabled) Loger.Fatal(format, arg0); + if (IsFatalEnabled) Logger.Fatal(format, arg0); } public void FatalFormat(string format, object arg0, object arg1) { - if (IsFatalEnabled) Loger.Fatal(format, arg0, arg1); + if (IsFatalEnabled) Logger.Fatal(format, arg0, arg1); } public void FatalFormat(string format, object arg0, object arg1, object arg2) { - if (IsFatalEnabled) Loger.Fatal(format, arg0, arg1, arg2); + if (IsFatalEnabled) Logger.Fatal(format, arg0, arg1, arg2); } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { - if (IsFatalEnabled) Loger.Fatal(provider, format, args); - } - - public string LogDirectory { get { return NLog.LogManager.Configuration.Variables["dir"].Text; } } - - private string name; - public string Name - { - get - { - return name; - } - set - { - name = value; - Loger = NLog.LogManager.GetLogger(name); - } + if (IsFatalEnabled) Logger.Fatal(provider, format, args); } } @@ -691,185 +644,102 @@ namespace ASC.Common.Logging public bool IsWarnEnabled { get; set; } public bool IsErrorEnabled { get; set; } public bool IsFatalEnabled { get; set; } - public bool IsTraceEnabled { get; set; } + public bool IsTraceEnabled { get; set; } + public string Name { get; set; } + public string LogDirectory => string.Empty; - public void Trace(object message) - { - } + public void Trace(object message) { } - public void TraceFormat(string message, object arg0) - { - } + public void TraceFormat(string message, object arg0) { } - public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) - { - } + public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) { } - public void Debug(object message) - { - } + public void Debug(object message) { } - public void Debug(object message, Exception exception) - { - } + public void Debug(object message, Exception exception) { } - public void DebugFormat(string format, params object[] args) - { - } + public void DebugFormat(string format, params object[] args) { } - public void DebugFormat(string format, object arg0) - { - } + public void DebugFormat(string format, object arg0) { } - public void DebugFormat(string format, object arg0, object arg1) - { - } + public void DebugFormat(string format, object arg0, object arg1) { } - public void DebugFormat(string format, object arg0, object arg1, object arg2) - { - } + public void DebugFormat(string format, object arg0, object arg1, object arg2) { } - public void DebugFormat(IFormatProvider provider, string format, params object[] args) - { - } + public void DebugFormat(IFormatProvider provider, string format, params object[] args) { } - public void Info(object message) - { - } + public void Info(object message) { } - public void Info(string message, Exception exception) - { - } + public void Info(string message, Exception exception) { } - public void InfoFormat(string format, params object[] args) - { - } + public void InfoFormat(string format, params object[] args) { } - public void InfoFormat(string format, object arg0) - { - } + public void InfoFormat(string format, object arg0) { } - public void InfoFormat(string format, object arg0, object arg1) - { - } + public void InfoFormat(string format, object arg0, object arg1) { } - public void InfoFormat(string format, object arg0, object arg1, object arg2) - { - } + public void InfoFormat(string format, object arg0, object arg1, object arg2) { } - public void InfoFormat(IFormatProvider provider, string format, params object[] args) - { - } + public void InfoFormat(IFormatProvider provider, string format, params object[] args) { } - public void Warn(object message) - { - } + public void Warn(object message) { } - public void Warn(object message, Exception exception) - { - } + public void Warn(object message, Exception exception) { } - public void WarnFormat(string format, params object[] args) - { - } + public void WarnFormat(string format, params object[] args) { } - public void WarnFormat(string format, object arg0) - { - } + public void WarnFormat(string format, object arg0) { } - public void WarnFormat(string format, object arg0, object arg1) - { - } + public void WarnFormat(string format, object arg0, object arg1) { } - public void WarnFormat(string format, object arg0, object arg1, object arg2) - { - } + public void WarnFormat(string format, object arg0, object arg1, object arg2) { } - public void WarnFormat(IFormatProvider provider, string format, params object[] args) - { - } + public void WarnFormat(IFormatProvider provider, string format, params object[] args) { } - public void Error(object message) - { - } + public void Error(object message) { } - public void Error(object message, Exception exception) - { - } + public void Error(object message, Exception exception) { } - public void ErrorFormat(string format, params object[] args) - { - } + public void ErrorFormat(string format, params object[] args) { } - public void ErrorFormat(string format, object arg0) - { - } + public void ErrorFormat(string format, object arg0) { } - public void ErrorFormat(string format, object arg0, object arg1) - { - } + public void ErrorFormat(string format, object arg0, object arg1) { } - public void ErrorFormat(string format, object arg0, object arg1, object arg2) - { - } + public void ErrorFormat(string format, object arg0, object arg1, object arg2) { } - public void ErrorFormat(IFormatProvider provider, string format, params object[] args) - { - } + public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { } - public void Fatal(object message) - { - } + public void Fatal(object message) { } - public void Fatal(string message, Exception exception) - { - } + public void Fatal(string message, Exception exception) { } - public void FatalFormat(string format, params object[] args) - { - } + public void FatalFormat(string format, params object[] args) { } - public void FatalFormat(string format, object arg0) - { - } + public void FatalFormat(string format, object arg0) { } - public void FatalFormat(string format, object arg0, object arg1) - { - } + public void FatalFormat(string format, object arg0, object arg1) { } - public void FatalFormat(string format, object arg0, object arg1, object arg2) - { - } + public void FatalFormat(string format, object arg0, object arg1, object arg2) { } - public void FatalFormat(IFormatProvider provider, string format, params object[] args) - { - } + public void FatalFormat(IFormatProvider provider, string format, params object[] args) { } - public void Configure(string name) - { - } - - public string LogDirectory { get { return ""; } } - - public string Name { get; set; } + public void Configure(string name) { } } [Singletone] public class LogManager<T> : OptionsMonitor<T> where T : class, ILog, new() { - public LogManager(IOptionsFactory<T> factory, IEnumerable<IOptionsChangeTokenSource<T>> sources, IOptionsMonitorCache<T> cache) : base(factory, sources, cache) - { - - } + public LogManager(IOptionsFactory<T> factory, + IEnumerable<IOptionsChangeTokenSource<T>> sources, + IOptionsMonitorCache<T> cache) + : base(factory, sources, cache) { } public override T Get(string name) { var log = base.Get(name); - if (string.IsNullOrEmpty(log?.Name)) - { - log = CurrentValue; - } + if (string.IsNullOrEmpty(log?.Name)) log = CurrentValue; return log; } @@ -877,17 +747,13 @@ namespace ASC.Common.Logging public class LoggerExtension<T> where T : class, ILog, new() { - public static void RegisterLog(DIHelper services) - { + public static void RegisterLog(DIHelper services) => services.TryAdd(typeof(IOptionsMonitor<ILog>), typeof(LogManager<T>)); - } } public class LogNLogExtension : LoggerExtension<LogNLog> { - public static void Register(DIHelper services) - { + public static void Register(DIHelper services) => RegisterLog(services); - } } } diff --git a/common/ASC.Common/Logging/SelfCleaningAppender.cs b/common/ASC.Common/Logging/SelfCleaningAppender.cs index 6185efb28b..72485df77b 100644 --- a/common/ASC.Common/Logging/SelfCleaningAppender.cs +++ b/common/ASC.Common/Logging/SelfCleaningAppender.cs @@ -40,6 +40,28 @@ namespace ASC.Common.Logging private static DateTime _lastCleanDate; private static int? _cleanPeriod; + + protected override void Append(LoggingEvent loggingEvent) + { + if (DateTime.UtcNow.Date > _lastCleanDate.Date) + { + _lastCleanDate = DateTime.UtcNow.Date; + Clean(); + } + + base.Append(loggingEvent); + } + + protected override void Append(LoggingEvent[] loggingEvents) + { + if (DateTime.UtcNow.Date > _lastCleanDate.Date) + { + _lastCleanDate = DateTime.UtcNow.Date; + Clean(); + } + + base.Append(loggingEvents); + } private static int GetCleanPeriod() { @@ -52,10 +74,8 @@ namespace ASC.Common.Logging var repo = log4net.LogManager.GetRepository(Assembly.GetCallingAssembly()); - if (repo != null && repo.Properties.GetKeys().Contains(key)) - { + if (repo != null && repo.Properties.GetKeys().Contains(key)) int.TryParse(repo.Properties[key].ToString(), out value); - } _cleanPeriod = value; @@ -93,27 +113,5 @@ namespace ASC.Common.Logging LogLog.Error(GetType(), err.Message, err); } } - - protected override void Append(LoggingEvent loggingEvent) - { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) - { - _lastCleanDate = DateTime.UtcNow.Date; - Clean(); - } - - base.Append(loggingEvent); - } - - protected override void Append(LoggingEvent[] loggingEvents) - { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) - { - _lastCleanDate = DateTime.UtcNow.Date; - Clean(); - } - - base.Append(loggingEvents); - } } } diff --git a/common/ASC.Common/Logging/SelfCleaningTarget.cs b/common/ASC.Common/Logging/SelfCleaningTarget.cs index bcf43b3c17..7ec5fa3c70 100644 --- a/common/ASC.Common/Logging/SelfCleaningTarget.cs +++ b/common/ASC.Common/Logging/SelfCleaningTarget.cs @@ -42,7 +42,39 @@ namespace ASC.Common.Logging { private static DateTime _lastCleanDate; - private static int? _cleanPeriod; + private static int? _cleanPeriod; + + protected override void Write(IList<AsyncLogEventInfo> logEvents) + { + if (DateTime.UtcNow.Date > _lastCleanDate.Date) + { + _lastCleanDate = DateTime.UtcNow.Date; + Clean(); + } + + var buffer = new List<AsyncLogEventInfo>(); + + foreach (var logEvent in logEvents) + { + buffer.Add(logEvent); + if (buffer.Count < 10) continue; + base.Write(buffer); + buffer.Clear(); + } + + base.Write(buffer); + } + + protected override void Write(LogEventInfo logEvent) + { + if (DateTime.UtcNow.Date > _lastCleanDate.Date) + { + _lastCleanDate = DateTime.UtcNow.Date; + Clean(); + } + + base.Write(logEvent); + } private static int GetCleanPeriod() { @@ -53,14 +85,12 @@ namespace ASC.Common.Logging const string key = "cleanPeriod"; - if (NLog.LogManager.Configuration.Variables.Keys.Contains(key)) + if (LogManager.Configuration.Variables.Keys.Contains(key)) { - var variable = NLog.LogManager.Configuration.Variables[key]; + var variable = LogManager.Configuration.Variables[key]; - if (variable != null && !string.IsNullOrEmpty(variable.Text)) - { + if (variable != null && !string.IsNullOrEmpty(variable.Text)) int.TryParse(variable.Text, out value); - } } _cleanPeriod = value; @@ -115,38 +145,6 @@ namespace ASC.Common.Logging LoggerName = "SelfCleaningTarget" }); } - } - - protected override void Write(IList<AsyncLogEventInfo> logEvents) - { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) - { - _lastCleanDate = DateTime.UtcNow.Date; - Clean(); - } - - var buffer = new List<AsyncLogEventInfo>(); - - foreach (var logEvent in logEvents) - { - buffer.Add(logEvent); - if (buffer.Count < 10) continue; - base.Write(buffer); - buffer.Clear(); - } - - base.Write(buffer); - } - - protected override void Write(LogEventInfo logEvent) - { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) - { - _lastCleanDate = DateTime.UtcNow.Date; - Clean(); - } - - base.Write(logEvent); } } } diff --git a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs index e96bdfcd35..1b8609cef5 100644 --- a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs +++ b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs @@ -36,23 +36,20 @@ namespace ASC.Common.Logging { protected override void Convert(TextWriter writer, object state) { - if (string.IsNullOrEmpty(Option)) - { - return; - } + if (string.IsNullOrEmpty(Option)) return; + try { var result = string.Empty; - const string CMD_LINE = "CommandLine:"; + const string CMD_LINE = "CommandLine:"; + if (Option.StartsWith(CMD_LINE)) { var args = Environment.CommandLine.Split(' '); for (var i = 0; i < args.Length - 1; i++) { - if (args[i].Equals(Option.Substring(CMD_LINE.Length), StringComparison.InvariantCultureIgnoreCase)) - { + if (args[i].Equals(Option.Substring(CMD_LINE.Length), StringComparison.InvariantCultureIgnoreCase)) result = args[i + 1]; - } } } else @@ -63,14 +60,11 @@ namespace ASC.Common.Logging var realKey = Option; foreach (var key in repo.Properties.GetKeys()) { - if (Path.DirectorySeparatorChar == '/' && key == "UNIX:" + Option) - { - realKey = "UNIX:" + Option; - } - if (Path.DirectorySeparatorChar == '\\' && key == "WINDOWS:" + Option) - { + if (Path.DirectorySeparatorChar == '/' && key == "UNIX:" + Option) + realKey = "UNIX:" + Option; + + if (Path.DirectorySeparatorChar == '\\' && key == "WINDOWS:" + Option) realKey = "WINDOWS:" + Option; - } } var val = repo.Properties[realKey]; @@ -78,11 +72,9 @@ namespace ASC.Common.Logging { patternString.ActivateOptions(); patternString.Format(writer); - } - else if (val != null) - { - result = val.ToString(); - } + } + + else if (val != null) result = val.ToString(); } } diff --git a/common/ASC.Common/Mapping/MappingProfile.cs b/common/ASC.Common/Mapping/MappingProfile.cs index 3d16f3f228..943ea3ca7f 100644 --- a/common/ASC.Common/Mapping/MappingProfile.cs +++ b/common/ASC.Common/Mapping/MappingProfile.cs @@ -33,10 +33,7 @@ namespace ASC.Common.Mapping { public class MappingProfile : Profile { - public MappingProfile() - { - Array.ForEach(AppDomain.CurrentDomain.GetAssemblies(), a => ApplyMappingsFromAssembly(a)); - } + public MappingProfile() => Array.ForEach(AppDomain.CurrentDomain.GetAssemblies(), a => ApplyMappingsFromAssembly(a)); private void ApplyMappingsFromAssembly(Assembly assembly) { @@ -55,7 +52,6 @@ namespace ASC.Common.Mapping ?? type.GetInterface("IMapFrom`1").GetMethod("Mapping"); methodInfo?.Invoke(instance, new object[] { this }); - } } } diff --git a/common/ASC.Common/Module/BaseWcfClient.cs b/common/ASC.Common/Module/BaseWcfClient.cs index f512ff61d5..15035c7568 100644 --- a/common/ASC.Common/Module/BaseWcfClient.cs +++ b/common/ASC.Common/Module/BaseWcfClient.cs @@ -31,9 +31,7 @@ namespace ASC.Common.Module { public class BaseWcfClient<TService> : ClientBase<TService>, IDisposable where TService : class { - public BaseWcfClient() - { - } + public BaseWcfClient() { } void IDisposable.Dispose() { diff --git a/common/ASC.Common/Security/AscRandom.cs b/common/ASC.Common/Security/AscRandom.cs index 2e3fe2c5f2..35d42187e8 100644 --- a/common/ASC.Common/Security/AscRandom.cs +++ b/common/ASC.Common/Security/AscRandom.cs @@ -29,18 +29,16 @@ using System; namespace ASC.Common.Security { public class AscRandom : Random - { - private int inext; - private int inextp; + { private const int MBIG = int.MaxValue; private const int MSEED = 161803398; - private const int MZ = 0; + private const int MZ = 0; + + private int inext; + private int inextp; private readonly int[] seeds; - - public AscRandom() : this(Environment.TickCount) - { - } + public AscRandom() : this(Environment.TickCount) { } public AscRandom(int seed) { @@ -48,39 +46,37 @@ namespace ASC.Common.Security var num4 = (seed == int.MinValue) ? int.MaxValue : Math.Abs(seed); var num2 = 161803398 - num4; seeds[^1] = num2; - var num3 = 1; + var num3 = 1; + for (var i = 1; i < seeds.Length - 1; i++) { var index = (21 * i) % (seeds.Length - 1); seeds[index] = num3; - num3 = num2 - num3; - if (num3 < 0) - { - num3 += int.MaxValue; - } + num3 = num2 - num3; + + if (num3 < 0) num3 += int.MaxValue; + num2 = seeds[index]; - } + } + for (var j = 1; j < 5; j++) { for (var k = 1; k < seeds.Length; k++) { - seeds[k] -= seeds[1 + ((k + 30) % (seeds.Length - 1))]; - if (seeds[k] < 0) - { - seeds[k] += int.MaxValue; - } + seeds[k] -= seeds[1 + ((k + 30) % (seeds.Length - 1))]; + + if (seeds[k] < 0) seeds[k] += int.MaxValue; } - } + } + inext = 0; inextp = 21; } public override int Next(int maxValue) { - if (maxValue < 0) - { - throw new ArgumentOutOfRangeException(nameof(maxValue)); - } + if (maxValue < 0) throw new ArgumentOutOfRangeException(nameof(maxValue)); + return (int)(InternalSample() * 4.6566128752457969E-10 * maxValue); } @@ -97,27 +93,22 @@ namespace ASC.Common.Security private int InternalSample() { var inext = this.inext; - var inextp = this.inextp; - if (++inext >= seeds.Length - 1) - { - inext = 1; - } - if (++inextp >= seeds.Length - 1) - { - inextp = 1; - } - var num = seeds[inext] - seeds[inextp]; - if (num == int.MaxValue) - { - num--; - } - if (num < 0) - { - num += int.MaxValue; - } + var inextp = this.inextp; + + if (++inext >= seeds.Length - 1) inext = 1; + + if (++inextp >= seeds.Length - 1) inextp = 1; + + var num = seeds[inext] - seeds[inextp]; + + if (num == int.MaxValue) num--; + + if (num < 0) num += int.MaxValue; + seeds[inext] = num; this.inext = inext; - this.inextp = inextp; + this.inextp = inextp; + return num; } } diff --git a/common/ASC.Common/Security/Authentication/Account.cs b/common/ASC.Common/Security/Authentication/Account.cs index a81ecadba5..23cb4910be 100644 --- a/common/ASC.Common/Security/Authentication/Account.cs +++ b/common/ASC.Common/Security/Authentication/Account.cs @@ -31,6 +31,11 @@ namespace ASC.Common.Security.Authentication [Serializable] public class Account : IAccount { + public Guid ID { get; private set; } + public string Name { get; private set; } + public virtual bool IsAuthenticated { get; private set; } + public string AuthenticationType => "ASC"; + public Account(Guid id, string name, bool authenticated) { ID = id; @@ -38,44 +43,12 @@ namespace ASC.Common.Security.Authentication IsAuthenticated = authenticated; } - #region IAccount Members + public object Clone() => MemberwiseClone(); - public Guid ID { get; private set; } + public override bool Equals(object obj) => obj is IAccount a && ID.Equals(a.ID); - public string Name { get; private set; } + public override int GetHashCode() => ID.GetHashCode(); - - public object Clone() - { - return MemberwiseClone(); - } - - public string AuthenticationType - { - get { return "ASC"; } - } - - public virtual bool IsAuthenticated - { - get; - private set; - } - - #endregion - - public override bool Equals(object obj) - { - return obj is IAccount a && ID.Equals(a.ID); - } - - public override int GetHashCode() - { - return ID.GetHashCode(); - } - - public override string ToString() - { - return Name; - } + public override string ToString() => Name; } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Authentication/IAccount.cs b/common/ASC.Common/Security/Authentication/IAccount.cs index a858779c38..8671af307e 100644 --- a/common/ASC.Common/Security/Authentication/IAccount.cs +++ b/common/ASC.Common/Security/Authentication/IAccount.cs @@ -30,8 +30,5 @@ using ASC.Common.Security.Authorizing; namespace ASC.Common.Security.Authentication { - public interface IAccount : ISubject, ICloneable - { - - } + public interface IAccount : ISubject, ICloneable { } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Authentication/ISystemAccount.cs b/common/ASC.Common/Security/Authentication/ISystemAccount.cs index d3b93b89c7..f94f27b71c 100644 --- a/common/ASC.Common/Security/Authentication/ISystemAccount.cs +++ b/common/ASC.Common/Security/Authentication/ISystemAccount.cs @@ -26,7 +26,5 @@ namespace ASC.Common.Security.Authentication { - public interface ISystemAccount : IAccount - { - } + public interface ISystemAccount : IAccount { } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Authentication/SystemAccount.cs b/common/ASC.Common/Security/Authentication/SystemAccount.cs index 50639ce9a2..55d260a9d7 100644 --- a/common/ASC.Common/Security/Authentication/SystemAccount.cs +++ b/common/ASC.Common/Security/Authentication/SystemAccount.cs @@ -32,8 +32,6 @@ namespace ASC.Common.Security.Authentication public class SystemAccount : Account, ISystemAccount { public SystemAccount(Guid id, string name, bool authenticated) - : base(id, name, authenticated) - { - } + : base(id, name, authenticated) { } } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs index e1ab1be442..d5cff08688 100644 --- a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs +++ b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs @@ -36,52 +36,47 @@ namespace ASC.Common.Security.Authorizing [Serializable] public class AuthorizingException : Exception { - private readonly string _Message; + public ISubject Subject { get; internal set; } + public IAction[] Actions { get; internal set; } + public override string Message => _message; + + private readonly string _message; public AuthorizingException(string message) - : base(message) - { - } + : base(message) { } public AuthorizingException(ISubject subject, IAction[] actions) { if (actions == null || actions.Length == 0) throw new ArgumentNullException(nameof(actions)); + Subject = subject ?? throw new ArgumentNullException(nameof(subject)); Actions = actions; var sactions = ""; + Array.ForEach(actions, action => { sactions += action.ToString() + ", "; }); - _Message = string.Format( + + _message = string.Format( "\"{0}\" access denied \"{1}\"", subject, sactions ); } - public AuthorizingException(ISubject subject, IAction[] actions, ISubject[] denySubjects, IAction[] denyActions) - { - _Message = FormatErrorMessage(subject, actions, denySubjects, denyActions); - } + public AuthorizingException(ISubject subject, IAction[] actions, ISubject[] denySubjects, IAction[] denyActions) => + _message = FormatErrorMessage(subject, actions, denySubjects, denyActions); protected AuthorizingException(SerializationInfo info, StreamingContext context) : base(info, context) { - _Message = info.GetValue("_Message", typeof(string)) as string; + _message = info.GetValue("_Message", typeof(string)) as string; Subject = info.GetValue("Subject", typeof(ISubject)) as ISubject; Actions = info.GetValue("Actions", typeof(IAction[])) as IAction[]; } - public override string Message - { - get { return _Message; } - } - - public ISubject Subject { get; internal set; } - public IAction[] Actions { get; internal set; } - public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Subject", Subject, typeof(ISubject)); - info.AddValue("_Message", _Message, typeof(string)); + info.AddValue("_Message", _message, typeof(string)); info.AddValue("Actions", Actions, typeof(IAction[])); base.GetObjectData(info, context); } @@ -95,30 +90,36 @@ namespace ASC.Common.Security.Authorizing if (denyActions == null || denyActions.Length == 0) throw new ArgumentNullException(nameof(denyActions)); if (actions.Length != denySubjects.Length || actions.Length != denyActions.Length) throw new ArgumentException(); + var reasons = ""; for (var i = 0; i < actions.Length; i++) { var reason = ""; + if (denySubjects[i] != null && denyActions[i] != null) reason = string.Format("{0}:{1} access denied {2}.", actions[i].Name, (denySubjects[i] is IRole ? "role:" : "") + denySubjects[i].Name, denyActions[i].Name ); - else - reason = string.Format("{0}: access denied.", actions[i].Name); + else reason = string.Format("{0}: access denied.", actions[i].Name); + if (i != actions.Length - 1) reason += ", "; + reasons += reason; } var sactions = ""; + Array.ForEach(actions, action => { sactions += action.ToString() + ", "; }); + var message = string.Format( "\"{0}\" access denied \"{1}\". Cause: {2}.", (subject is IRole ? "role:" : "") + subject.Name, sactions, reasons ); + return message; } } diff --git a/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs b/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs index d0bbe0116a..a82b16340a 100644 --- a/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs +++ b/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs @@ -33,7 +33,8 @@ namespace ASC.Common.Security.Authorizing public static string GetFullObjectId(ISecurityObjectId objectId) { if (objectId == null) return null; - return string.Format("{0}{1}{2}", objectId.ObjectType.FullName, separator, objectId.SecurityId); + + return $"{objectId.ObjectType.FullName}{separator}{objectId.SecurityId}"; } } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs b/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs index f4b549f5d4..b9d7e0aeeb 100644 --- a/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs +++ b/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs @@ -35,51 +35,53 @@ namespace ASC.Common.Security.Authorizing { public class AzObjectSecurityProviderHelper { - private readonly SecurityCallContext callContext; - private readonly bool currObjIdAsProvider; - private ISecurityObjectProvider currSecObjProvider; + public ISecurityObjectId CurrentObjectId { get; private set; } + public bool ObjectRolesSupported => _currSecObjProvider != null && _currSecObjProvider.ObjectRolesSupported; + + private readonly SecurityCallContext _callContext; + private readonly bool _currObjIdAsProvider; + private ISecurityObjectProvider _currSecObjProvider; public AzObjectSecurityProviderHelper(ISecurityObjectId objectId, ISecurityObjectProvider secObjProvider) { - currObjIdAsProvider = false; + _currObjIdAsProvider = false; CurrentObjectId = objectId ?? throw new ArgumentNullException(nameof(objectId)); - currSecObjProvider = secObjProvider; - if (currSecObjProvider == null && CurrentObjectId is ISecurityObjectProvider securityObjectProvider) + _currSecObjProvider = secObjProvider; + + if (_currSecObjProvider == null && CurrentObjectId is ISecurityObjectProvider securityObjectProvider) { - currObjIdAsProvider = true; - currSecObjProvider = securityObjectProvider; + _currObjIdAsProvider = true; + _currSecObjProvider = securityObjectProvider; } - callContext = new SecurityCallContext(); - } - public ISecurityObjectId CurrentObjectId { get; private set; } - - public bool ObjectRolesSupported - { - get { return currSecObjProvider != null && currSecObjProvider.ObjectRolesSupported; } + _callContext = new SecurityCallContext(); } public IEnumerable<IRole> GetObjectRoles(ISubject account) { - var roles = currSecObjProvider.GetObjectRoles(account, CurrentObjectId, callContext); + var roles = _currSecObjProvider.GetObjectRoles(account, CurrentObjectId, _callContext); + foreach (var role in roles) { - if (!callContext.RolesList.Contains(role)) callContext.RolesList.Add(role); + if (!_callContext.RolesList.Contains(role)) _callContext.RolesList.Add(role); } + return roles; } public bool NextInherit() { - if (currSecObjProvider == null || !currSecObjProvider.InheritSupported) return false; - CurrentObjectId = currSecObjProvider.InheritFrom(CurrentObjectId); + if (_currSecObjProvider == null || !_currSecObjProvider.InheritSupported) return false; + + CurrentObjectId = _currSecObjProvider.InheritFrom(CurrentObjectId); + if (CurrentObjectId == null) return false; - if (currObjIdAsProvider) - { - currSecObjProvider = CurrentObjectId as ISecurityObjectProvider; - } - callContext.ObjectsStack.Insert(0, CurrentObjectId); - return currSecObjProvider != null; + + if (_currObjIdAsProvider) _currSecObjProvider = CurrentObjectId as ISecurityObjectProvider; + + _callContext.ObjectsStack.Insert(0, CurrentObjectId); + + return _currSecObjProvider != null; } } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Authorizing/Domain/Ace.cs b/common/ASC.Common/Security/Authorizing/Domain/Ace.cs index 76fe7666f3..2243b12dc9 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Ace.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Ace.cs @@ -32,10 +32,8 @@ namespace ASC.Common.Security.Authorizing public class Ace { public Guid ActionId { get; set; } - public AceType Reaction { get; set; } - public Ace(Guid actionId, AceType reaction) { ActionId = actionId; diff --git a/common/ASC.Common/Security/Authorizing/Domain/Action.cs b/common/ASC.Common/Security/Authorizing/Domain/Action.cs index 7579d27fcf..333ce6147b 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Action.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Action.cs @@ -32,18 +32,12 @@ namespace ASC.Common.Security.Authorizing public class Action : IAction { public Guid ID { get; private set; } - public string Name { get; private set; } - public bool AdministratorAlwaysAllow { get; private set; } - public bool Conjunction { get; private set; } - public Action(Guid id, string name) - : this(id, name, true, true) - { - } + : this(id, name, true, true) { } public Action(Guid id, string name, bool administratorAlwaysAllow, bool conjunction) { @@ -55,19 +49,10 @@ namespace ASC.Common.Security.Authorizing Conjunction = conjunction; } - public override int GetHashCode() - { - return ID.GetHashCode(); - } + public override int GetHashCode() => ID.GetHashCode(); - public override bool Equals(object obj) - { - return obj is Action a && a.ID == ID; - } + public override bool Equals(object obj) => obj is Action a && a.ID == ID; - public override string ToString() - { - return Name; - } + public override string ToString() => Name; } } diff --git a/common/ASC.Common/Security/Authorizing/Domain/Role.cs b/common/ASC.Common/Security/Authorizing/Domain/Role.cs index df93ff3b94..8b6e5038b5 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Role.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Role.cs @@ -37,45 +37,25 @@ namespace ASC.Common.Security.Authorizing public const string Administrators = "Administrators"; public const string System = "System"; - public Guid ID { get; internal set; } - public string Name { get; internal set; } - - public string AuthenticationType - { - get { return "ASC"; } - } - - public bool IsAuthenticated - { - get { return false; } - } + public string AuthenticationType => "ASC"; + public bool IsAuthenticated => false; public Role(Guid id, string name) { - if (id == Guid.Empty) throw new ArgumentException("id"); + if (id == Guid.Empty) throw new ArgumentException(nameof(id)); if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); ID = id; Name = name; } + public override int GetHashCode() => ID.GetHashCode(); - public override int GetHashCode() - { - return ID.GetHashCode(); - } + public override bool Equals(object obj) => obj is Role r && r.ID == ID; - public override bool Equals(object obj) - { - return obj is Role r && r.ID == ID; - } - - public override string ToString() - { - return string.Format("Role: {0}", Name); - } + public override string ToString() => $"Role: {Name}"; } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Authorizing/Interfaces/IAction.cs b/common/ASC.Common/Security/Authorizing/Interfaces/IAction.cs index 3c6e864e93..3a2b31ad02 100644 --- a/common/ASC.Common/Security/Authorizing/Interfaces/IAction.cs +++ b/common/ASC.Common/Security/Authorizing/Interfaces/IAction.cs @@ -31,11 +31,8 @@ namespace ASC.Common.Security.Authorizing public interface IAction { Guid ID { get; } - string Name { get; } - bool AdministratorAlwaysAllow { get; } - bool Conjunction { get; } } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Authorizing/Interfaces/IRole.cs b/common/ASC.Common/Security/Authorizing/Interfaces/IRole.cs index 6839748658..30c1c06042 100644 --- a/common/ASC.Common/Security/Authorizing/Interfaces/IRole.cs +++ b/common/ASC.Common/Security/Authorizing/Interfaces/IRole.cs @@ -26,7 +26,5 @@ namespace ASC.Common.Security.Authorizing { - public interface IRole : ISubject - { - } + public interface IRole : ISubject { } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Cryptography/HashAlg.cs b/common/ASC.Common/Security/Cryptography/HashAlg.cs index c89e5c4741..75105cf436 100644 --- a/common/ASC.Common/Security/Cryptography/HashAlg.cs +++ b/common/ASC.Common/Security/Cryptography/HashAlg.cs @@ -29,11 +29,8 @@ namespace ASC.Security.Cryptography public enum HashAlg { MD5, - SHA1, - SHA256, - SHA512 } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Cryptography/Hasher.cs b/common/ASC.Common/Security/Cryptography/Hasher.cs index f404b66370..6feec917c5 100644 --- a/common/ASC.Common/Security/Cryptography/Hasher.cs +++ b/common/ASC.Common/Security/Cryptography/Hasher.cs @@ -34,47 +34,27 @@ namespace ASC.Security.Cryptography { private const HashAlg DefaultAlg = HashAlg.SHA256; + public static byte[] Hash(string data, HashAlg hashAlg) => ComputeHash(data, hashAlg); - public static byte[] Hash(string data, HashAlg hashAlg) - { - return ComputeHash(data, hashAlg); - } + public static byte[] Hash(string data) => Hash(data, DefaultAlg); - public static byte[] Hash(string data) - { - return Hash(data, DefaultAlg); - } + public static byte[] Hash(byte[] data, HashAlg hashAlg) => ComputeHash(data, hashAlg); - public static byte[] Hash(byte[] data, HashAlg hashAlg) - { - return ComputeHash(data, hashAlg); - } + public static byte[] Hash(byte[] data) => Hash(data, DefaultAlg); - public static byte[] Hash(byte[] data) - { - return Hash(data, DefaultAlg); - } + public static string Base64Hash(string data, HashAlg hashAlg) => ComputeHash64(data, hashAlg); - public static string Base64Hash(string data, HashAlg hashAlg) - { - return ComputeHash64(data, hashAlg); - } + public static string Base64Hash(string data) => Base64Hash(data, DefaultAlg); - public static string Base64Hash(string data) - { - return Base64Hash(data, DefaultAlg); - } + public static string Base64Hash(byte[] data, HashAlg hashAlg) => ComputeHash64(data, hashAlg); - public static string Base64Hash(byte[] data, HashAlg hashAlg) - { - return ComputeHash64(data, hashAlg); - } + public static string Base64Hash(byte[] data) => Base64Hash(data, DefaultAlg); + public static bool EqualHash(byte[] dataToCompare, byte[] hash) => EqualHash(dataToCompare, hash, DefaultAlg); - public static string Base64Hash(byte[] data) - { - return Base64Hash(data, DefaultAlg); - } + public static bool EqualHash(string dataToCompare, string hash, HashAlg hashAlg) => EqualHash(S2B(dataToCompare), S642B(hash), hashAlg); + public static bool EqualHash(string dataToCompare, string hash) => EqualHash(dataToCompare, hash, DefaultAlg); + public static bool EqualHash(byte[] dataToCompare, byte[] hash, HashAlg hashAlg) { return string.Equals( @@ -83,22 +63,6 @@ namespace ASC.Security.Cryptography ); } - public static bool EqualHash(byte[] dataToCompare, byte[] hash) - { - return EqualHash(dataToCompare, hash, DefaultAlg); - } - - public static bool EqualHash(string dataToCompare, string hash, HashAlg hashAlg) - { - return EqualHash(S2B(dataToCompare), S642B(hash), hashAlg); - } - - public static bool EqualHash(string dataToCompare, string hash) - { - return EqualHash(dataToCompare, hash, DefaultAlg); - } - - private static HashAlgorithm GetAlg(HashAlg hashAlg) { return hashAlg switch @@ -113,47 +77,43 @@ namespace ASC.Security.Cryptography private static byte[] S2B(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if (str == null) throw new ArgumentNullException(nameof(str)); + return Encoding.UTF8.GetBytes(str); } private static string B2S(byte[] data) { - if (data == null) throw new ArgumentNullException(nameof(data)); + if (data == null) throw new ArgumentNullException(nameof(data)); + return Encoding.UTF8.GetString(data); } private static byte[] S642B(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if (str == null) throw new ArgumentNullException(nameof(str)); + return Convert.FromBase64String(str); } private static string B2S64(byte[] data) { - if (data == null) throw new ArgumentNullException(nameof(data)); + if (data == null) throw new ArgumentNullException(nameof(data)); + return Convert.ToBase64String(data); } private static byte[] ComputeHash(byte[] data, HashAlg hashAlg) { - using var alg = GetAlg(hashAlg); + using var alg = GetAlg(hashAlg); + return alg.ComputeHash(data); } - private static byte[] ComputeHash(string data, HashAlg hashAlg) - { - return ComputeHash(S2B(data), hashAlg); - } + private static byte[] ComputeHash(string data, HashAlg hashAlg) => ComputeHash(S2B(data), hashAlg); - private static string ComputeHash64(byte[] data, HashAlg hashAlg) - { - return B2S64(ComputeHash(data, hashAlg)); - } + private static string ComputeHash64(byte[] data, HashAlg hashAlg) => B2S64(ComputeHash(data, hashAlg)); - private static string ComputeHash64(string data, HashAlg hashAlg) - { - return ComputeHash64(S2B(data), hashAlg); - } + private static string ComputeHash64(string data, HashAlg hashAlg) => ComputeHash64(S2B(data), hashAlg); } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs b/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs index 81328610ba..048c57a454 100644 --- a/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs +++ b/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs @@ -36,42 +36,37 @@ namespace ASC.Security.Cryptography [Singletone] public class InstanceCrypto { - private byte[] EKey { get; } + private readonly byte[] _eKey; - public InstanceCrypto(MachinePseudoKeys machinePseudoKeys) - { - EKey = machinePseudoKeys.GetMachineConstant(32); - } + public InstanceCrypto(MachinePseudoKeys machinePseudoKeys) => + _eKey = machinePseudoKeys.GetMachineConstant(32); - public string Encrypt(string data) - { - return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(data))); - } + public string Encrypt(string data) => + Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(data))); public byte[] Encrypt(byte[] data) { using var hasher = Aes.Create(); - hasher.Key = EKey; + hasher.Key = _eKey; hasher.IV = new byte[hasher.BlockSize >> 3]; using var ms = new MemoryStream(); using var ss = new CryptoStream(ms, hasher.CreateEncryptor(), CryptoStreamMode.Write); using var plainTextStream = new MemoryStream(data); + plainTextStream.CopyTo(ss); ss.FlushFinalBlock(); hasher.Clear(); + return ms.ToArray(); } - public string Decrypt(string data) - { - return Decrypt(Convert.FromBase64String(data)); - } + public string Decrypt(string data) => Decrypt(Convert.FromBase64String(data)); public string Decrypt(byte[] data) { using var hasher = Aes.Create(); - hasher.Key = EKey; + hasher.Key = _eKey; hasher.IV = new byte[hasher.BlockSize >> 3]; using var msDecrypt = new MemoryStream(data); diff --git a/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs b/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs index faed193f6d..1befdf1b35 100644 --- a/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs +++ b/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs @@ -39,31 +39,25 @@ namespace ASC.Security.Cryptography [Singletone] public class MachinePseudoKeys { - private readonly byte[] confkey = null; + private readonly byte[] _confKey = null; public MachinePseudoKeys(IConfiguration configuration) { var key = configuration["core:machinekey"]; - if (string.IsNullOrEmpty(key)) - { - key = configuration["asc:common.machinekey"]; - } - if (!string.IsNullOrEmpty(key)) - { - confkey = Encoding.UTF8.GetBytes(key); - } + + if (string.IsNullOrEmpty(key)) key = configuration["asc:common.machinekey"]; + + if (!string.IsNullOrEmpty(key)) _confKey = Encoding.UTF8.GetBytes(key); } public byte[] GetMachineConstant() { - if (confkey != null) - { - return confkey; - } + if (_confKey != null) return _confKey; var path = typeof(MachinePseudoKeys).Assembly.Location; var fi = new FileInfo(path); + return BitConverter.GetBytes(fi.CreationTime.ToOADate()); } @@ -74,6 +68,7 @@ namespace ASC.Security.Cryptography var rnd = new AscRandom(icnst); var buff = new byte[bytesCount]; rnd.NextBytes(buff); + return buff; } } diff --git a/common/ASC.Common/Security/Cryptography/PasswordHasher.cs b/common/ASC.Common/Security/Cryptography/PasswordHasher.cs index fd4269c384..b361b24d68 100644 --- a/common/ASC.Common/Security/Cryptography/PasswordHasher.cs +++ b/common/ASC.Common/Security/Cryptography/PasswordHasher.cs @@ -37,6 +37,10 @@ namespace ASC.Security.Cryptography [Singletone] public class PasswordHasher { + public int Size { get; private set; } + public int Iterations { get; private set; } + public string Salt { get; private set; } + public PasswordHasher(IConfiguration configuration, MachinePseudoKeys machinePseudoKeys) { if (!int.TryParse(configuration["core:password:size"], out var size)) size = 256; @@ -60,24 +64,6 @@ namespace ASC.Security.Cryptography } } - public int Size - { - get; - private set; - } - - public int Iterations - { - get; - private set; - } - - public string Salt - { - get; - private set; - } - public string GetClientPassword(string password) { if (string.IsNullOrWhiteSpace(password)) password = Guid.NewGuid().ToString(); @@ -96,5 +82,4 @@ namespace ASC.Security.Cryptography return hash; } } - } \ No newline at end of file diff --git a/common/ASC.Common/Security/ISecurityObject.cs b/common/ASC.Common/Security/ISecurityObject.cs index 0007ac0c11..3f1e612d21 100644 --- a/common/ASC.Common/Security/ISecurityObject.cs +++ b/common/ASC.Common/Security/ISecurityObject.cs @@ -26,7 +26,5 @@ namespace ASC.Common.Security { - public interface ISecurityObject : ISecurityObjectId, ISecurityObjectProvider - { - } + public interface ISecurityObject : ISecurityObjectId, ISecurityObjectProvider { } } \ No newline at end of file diff --git a/common/ASC.Common/Security/ISecurityObjectProvider.cs b/common/ASC.Common/Security/ISecurityObjectProvider.cs index 2ee76e15e0..2515dcf2ac 100644 --- a/common/ASC.Common/Security/ISecurityObjectProvider.cs +++ b/common/ASC.Common/Security/ISecurityObjectProvider.cs @@ -37,10 +37,9 @@ namespace ASC.Common.Security public interface ISecurityObjectProvider { bool InheritSupported { get; } + bool ObjectRolesSupported { get; } - bool ObjectRolesSupported { get; } ISecurityObjectId InheritFrom(ISecurityObjectId objectId); - IEnumerable<IRole> GetObjectRoles(ISubject account, ISecurityObjectId objectId, SecurityCallContext callContext); } } \ No newline at end of file diff --git a/common/ASC.Common/Security/SecurityCallContext.cs b/common/ASC.Common/Security/SecurityCallContext.cs index 51e641cfe7..2785bd4ac4 100644 --- a/common/ASC.Common/Security/SecurityCallContext.cs +++ b/common/ASC.Common/Security/SecurityCallContext.cs @@ -35,17 +35,15 @@ using ASC.Common.Security.Authorizing; namespace ASC.Common.Security { public class SecurityCallContext - { + { + public object UserData { get; set; } + public List<ISecurityObjectId> ObjectsStack { get; private set; } + public List<IRole> RolesList { get; private set; } + public SecurityCallContext() { ObjectsStack = new List<ISecurityObjectId>(); RolesList = new List<IRole>(); } - - public List<ISecurityObjectId> ObjectsStack { get; private set; } - - public List<IRole> RolesList { get; private set; } - - public object UserData { get; set; } } } \ No newline at end of file diff --git a/common/ASC.Common/Security/SecurityObjectId.cs b/common/ASC.Common/Security/SecurityObjectId.cs index 3a13c162ad..8e105bf90d 100644 --- a/common/ASC.Common/Security/SecurityObjectId.cs +++ b/common/ASC.Common/Security/SecurityObjectId.cs @@ -35,25 +35,18 @@ namespace ASC.Common.Security public class SecurityObjectId : ISecurityObjectId { public object SecurityId { get; private set; } - public Type ObjectType { get; private set; } - public SecurityObjectId(object id, Type objType) { SecurityId = id; ObjectType = objType ?? throw new ArgumentNullException(nameof(objType)); } - public override int GetHashCode() - { - return AzObjectIdHelper.GetFullObjectId(this).GetHashCode(); - } + public override int GetHashCode() => AzObjectIdHelper.GetFullObjectId(this).GetHashCode(); - public override bool Equals(object obj) - { - return obj is SecurityObjectId other && + public override bool Equals(object obj) => + obj is SecurityObjectId other && Equals(AzObjectIdHelper.GetFullObjectId(other), AzObjectIdHelper.GetFullObjectId(this)); - } } } \ No newline at end of file diff --git a/common/ASC.Common/Threading/DistributedTask.cs b/common/ASC.Common/Threading/DistributedTask.cs index 2365f358c3..5c17bd180e 100644 --- a/common/ASC.Common/Threading/DistributedTask.cs +++ b/common/ASC.Common/Threading/DistributedTask.cs @@ -32,56 +32,28 @@ namespace ASC.Common.Threading { public class DistributedTask { - public Action<DistributedTask> Publication { get; set; } - - protected internal DistributedTaskCache DistributedTaskCache { get; internal set; } - + public Action<DistributedTask> Publication { get; set; } public int InstanceId { - get - { - return DistributedTaskCache.InstanceId; - } - set - { - DistributedTaskCache.InstanceId = value; - } + get => DistributedTaskCache.InstanceId; + set => DistributedTaskCache.InstanceId = value; } public string Id { - get - { - return DistributedTaskCache.Id; - } - protected set - { - DistributedTaskCache.Id = value?.ToString() ?? ""; - } + get => DistributedTaskCache.Id; + protected set => DistributedTaskCache.Id = value?.ToString() ?? ""; } - public DistributedTaskStatus Status { - get - { - return Enum.Parse<DistributedTaskStatus>(DistributedTaskCache.Status); - } - set - { - DistributedTaskCache.Status = value.ToString(); - } + get => Enum.Parse<DistributedTaskStatus>(DistributedTaskCache.Status); + set => DistributedTaskCache.Status = value.ToString(); } - public Exception Exception { - get - { - return new Exception(DistributedTaskCache.Exception); - } - set - { - DistributedTaskCache.Exception = value?.ToString() ?? ""; - } + get => new Exception(DistributedTaskCache.Exception); + set => DistributedTaskCache.Exception = value?.ToString() ?? ""; } + protected internal DistributedTaskCache DistributedTaskCache { get; internal set; } public DistributedTask() { @@ -89,11 +61,10 @@ namespace ASC.Common.Threading { Id = Guid.NewGuid().ToString() }; - } - public DistributedTask(DistributedTaskCache distributedTaskCache) - { - DistributedTaskCache = distributedTaskCache; - } + } + + public DistributedTask(DistributedTaskCache distributedTaskCache) => + DistributedTaskCache = distributedTaskCache; public T GetProperty<T>(string name) @@ -114,23 +85,16 @@ namespace ASC.Common.Threading }; var current = DistributedTaskCache.Props.SingleOrDefault(r => r.Key == name); - if (current != null) - { - DistributedTaskCache.Props.Remove(current); - } + + if (current != null) DistributedTaskCache.Props.Remove(current); - if (value != null) - { - DistributedTaskCache.Props.Add(prop); - } + if (value != null) DistributedTaskCache.Props.Add(prop); } public void PublishChanges() { - if (Publication == null) - { - throw new InvalidOperationException("Publication not found."); - } + if (Publication == null) throw new InvalidOperationException("Publication not found."); + Publication(this); } } diff --git a/common/ASC.Common/Threading/DistributedTaskProgress.cs b/common/ASC.Common/Threading/DistributedTaskProgress.cs index 22d6ae40cf..9c08e8a509 100644 --- a/common/ASC.Common/Threading/DistributedTaskProgress.cs +++ b/common/ASC.Common/Threading/DistributedTaskProgress.cs @@ -7,60 +7,35 @@ namespace ASC.Common.Threading { public double Percentage { - get - { - return Math.Min(100.0, Math.Max(0, DistributedTaskCache.Percentage)); - } - set - { - DistributedTaskCache.Percentage = value; - } + get => Math.Min(100.0, Math.Max(0, DistributedTaskCache.Percentage)); + set => DistributedTaskCache.Percentage = value; } - public bool IsCompleted { - get - { - return DistributedTaskCache.IsCompleted; - } - set - { - DistributedTaskCache.IsCompleted = value; - } + get => DistributedTaskCache.IsCompleted; + set => DistributedTaskCache.IsCompleted = value; } - protected int StepCount { - get - { - return DistributedTaskCache.StepCount; - } - set - { - DistributedTaskCache.StepCount = value; - } - } - - protected void StepDone() - { - if (StepCount > 0) - { - Percentage += 100.0 / StepCount; - } - - PublishChanges(); + get => DistributedTaskCache.StepCount; + set => DistributedTaskCache.StepCount = value; } public void RunJob() { Percentage = 0; Status = DistributedTaskStatus.Running; + DoJob(); } - protected virtual void DoJob() - { + protected virtual void DoJob() { } - } + protected void StepDone() + { + if (StepCount > 0) Percentage += 100.0 / StepCount; + + PublishChanges(); + } } } diff --git a/common/ASC.Common/Threading/DistributedTaskQueue.cs b/common/ASC.Common/Threading/DistributedTaskQueue.cs index 5627dcf827..6aa027178f 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -44,68 +44,56 @@ namespace ASC.Common.Threading { public ConcurrentDictionary<string, CancellationTokenSource> Cancelations { get; } public ICache Cache { get; } - private readonly IEventBus<DistributedTaskCancelation> notify; - private readonly IEventBus<DistributedTaskCache> notifyCache; + + private readonly IEventBus<DistributedTaskCancelation> _eventBusNotify; + private readonly IEventBus<DistributedTaskCache> _eventBusCache; public DistributedTaskCacheNotify( - IEventBus<DistributedTaskCancelation> notify, - IEventBus<DistributedTaskCache> notifyCache, + IEventBus<DistributedTaskCancelation> eventBusNotify, + IEventBus<DistributedTaskCache> eventBusCache, ICache cache) { Cancelations = new ConcurrentDictionary<string, CancellationTokenSource>(); Cache = cache; - this.notify = notify; + _eventBusNotify = eventBusNotify; - notify.Subscribe((c) => + eventBusNotify.Subscribe((c) => { - if (Cancelations.TryGetValue(c.Id, out var s)) - { - s.Cancel(); - } - }, Caching.EventType.Remove); + if (Cancelations.TryGetValue(c.Id, out var s)) s.Cancel(); + + }, EventType.Remove); - this.notifyCache = notifyCache; + _eventBusCache = eventBusCache; - notifyCache.Subscribe((c) => + eventBusCache.Subscribe((c) => { Cache.HashSet(c.Key, c.Id, (DistributedTaskCache)null); - }, Caching.EventType.Remove); + }, EventType.Remove); - notifyCache.Subscribe((c) => + eventBusCache.Subscribe((c) => { Cache.HashSet(c.Key, c.Id, c); - }, Caching.EventType.InsertOrUpdate); + }, EventType.InsertOrUpdate); } - public void CancelTask(string id) - { - notify.Publish(new DistributedTaskCancelation() { Id = id }, Caching.EventType.Remove); - } + public void CancelTask(string id) => + _eventBusNotify.Publish(new DistributedTaskCancelation() { Id = id }, EventType.Remove); - public void SetTask(DistributedTask task) - { - notifyCache.Publish(task.DistributedTaskCache, Caching.EventType.InsertOrUpdate); - } + public void SetTask(DistributedTask task) => + _eventBusCache.Publish(task.DistributedTaskCache, EventType.InsertOrUpdate); - public void RemoveTask(string id, string key) - { - notifyCache.Publish(new DistributedTaskCache() { Id = id, Key = key }, Caching.EventType.Remove); - } + public void RemoveTask(string id, string key) => + _eventBusCache.Publish(new DistributedTaskCache() { Id = id, Key = key }, EventType.Remove); } [Singletone(typeof(ConfigureDistributedTaskQueue))] public class DistributedTaskQueueOptionsManager : OptionsManager<DistributedTaskQueue> { - public DistributedTaskQueueOptionsManager(IOptionsFactory<DistributedTaskQueue> factory) : base(factory) - { - } + public DistributedTaskQueueOptionsManager(IOptionsFactory<DistributedTaskQueue> factory) : base(factory) { } - public DistributedTaskQueue Get<T>() where T : DistributedTask - { - return Get(typeof(T).FullName); - } + public DistributedTaskQueue Get<T>() where T : DistributedTask => Get(typeof(T).FullName); } [Scope] @@ -134,46 +122,39 @@ namespace ASC.Common.Threading } public class DistributedTaskQueue - { - public static readonly int InstanceId; - - private string key; - private TaskScheduler Scheduler { get; set; } = TaskScheduler.Default; - + { public IServiceProvider ServiceProvider { get; set; } - public string Name { get { return key; } set { key = value + GetType().Name; } } - private ICache Cache { get => DistributedTaskCacheNotify.Cache; } - private ConcurrentDictionary<string, CancellationTokenSource> Cancelations { get => DistributedTaskCacheNotify.Cancelations; } - + public DistributedTaskCacheNotify DistributedTaskCacheNotify { get; set; } + public string Name + { + get => _name; + set => _name = value + GetType().Name; + } public int MaxThreadsCount { - set - { - Scheduler = value <= 0 + set => Scheduler = value <= 0 ? TaskScheduler.Default - : new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, value).ConcurrentScheduler; - } + : new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, value).ConcurrentScheduler; } - public DistributedTaskCacheNotify DistributedTaskCacheNotify { get; set; } - - static DistributedTaskQueue() - { - InstanceId = Process.GetCurrentProcess().Id; - } + public static readonly int InstanceId; + + private TaskScheduler Scheduler { get; set; } = TaskScheduler.Default; + private ICache Cache => DistributedTaskCacheNotify.Cache; + private ConcurrentDictionary<string, CancellationTokenSource> Cancelations => + DistributedTaskCacheNotify.Cancelations; + + private string _name; + + static DistributedTaskQueue() => InstanceId = Process.GetCurrentProcess().Id; - public void QueueTask(DistributedTaskProgress taskProgress) - { - QueueTask((a, b) => taskProgress.RunJob(), taskProgress); - } + public void QueueTask(DistributedTaskProgress taskProgress) => + QueueTask((a, b) => taskProgress.RunJob(), taskProgress); public void QueueTask(Action<DistributedTask, CancellationToken> action, DistributedTask distributedTask = null) { - if (distributedTask == null) - { - distributedTask = new DistributedTask(); - } + if (distributedTask == null) distributedTask = new DistributedTask(); distributedTask.InstanceId = InstanceId; @@ -182,17 +163,16 @@ namespace ASC.Common.Threading Cancelations[distributedTask.Id] = cancelation; var task = new Task(() => { action(distributedTask, token); }, token, TaskCreationOptions.LongRunning); - task - .ConfigureAwait(false) + + task.ConfigureAwait(false) .GetAwaiter() .OnCompleted(() => OnCompleted(task, distributedTask.Id)); distributedTask.Status = DistributedTaskStatus.Running; - if (distributedTask.Publication == null) - { - distributedTask.Publication = GetPublication(); - } + if (distributedTask.Publication == null) + distributedTask.Publication = GetPublication(); + distributedTask.PublishChanges(); task.Start(Scheduler); @@ -200,48 +180,46 @@ namespace ASC.Common.Threading public IEnumerable<DistributedTask> GetTasks() { - var tasks = Cache.HashGetAll<DistributedTaskCache>(key).Values.Select(r => new DistributedTask(r)).ToList(); + var tasks = Cache.HashGetAll<DistributedTaskCache>(_name).Values.Select(r => new DistributedTask(r)).ToList(); + tasks.ForEach(t => { - if (t.Publication == null) - { - t.Publication = GetPublication(); - } - }); + if (t.Publication == null) t.Publication = GetPublication(); + }); + return tasks; } public IEnumerable<T> GetTasks<T>() where T : DistributedTask { - var tasks = Cache.HashGetAll<DistributedTaskCache>(key).Values.Select(r => + var tasks = Cache.HashGetAll<DistributedTaskCache>(_name).Values.Select(r => { var result = ServiceProvider.GetService<T>(); result.DistributedTaskCache = r; + return result; }).ToList(); tasks.ForEach(t => { - if (t.Publication == null) - { - t.Publication = GetPublication(); - } - }); + if (t.Publication == null) t.Publication = GetPublication(); + }); + return tasks; } public T GetTask<T>(string id) where T : DistributedTask { - var cache = Cache.HashGet<DistributedTaskCache>(key, id); + var cache = Cache.HashGet<DistributedTaskCache>(_name, id); if (cache != null) { using var scope = ServiceProvider.CreateScope(); var task = scope.ServiceProvider.GetService<T>(); task.DistributedTaskCache = cache; + if (task != null && task.Publication == null) - { task.Publication = GetPublication(); - } + return task; } @@ -250,35 +228,25 @@ namespace ASC.Common.Threading public DistributedTask GetTask(string id) { - var cache = Cache.HashGet<DistributedTaskCache>(key, id); + var cache = Cache.HashGet<DistributedTaskCache>(_name, id); if (cache != null) { var task = new DistributedTask(); task.DistributedTaskCache = cache; - if (task != null && task.Publication == null) - { - task.Publication = GetPublication(); - } + + if (task != null && task.Publication == null) task.Publication = GetPublication(); + return task; } return null; } - public void SetTask(DistributedTask task) - { - DistributedTaskCacheNotify.SetTask(task); - } + public void SetTask(DistributedTask task) => DistributedTaskCacheNotify.SetTask(task); - public void RemoveTask(string id) - { - DistributedTaskCacheNotify.RemoveTask(id, key); - } + public void RemoveTask(string id) => DistributedTaskCacheNotify.RemoveTask(id, _name); - public void CancelTask(string id) - { - DistributedTaskCacheNotify.CancelTask(id); - } + public void CancelTask(string id) => DistributedTaskCacheNotify.CancelTask(id); private void OnCompleted(Task task, string id) { @@ -286,15 +254,11 @@ namespace ASC.Common.Threading if (distributedTask != null) { distributedTask.Status = DistributedTaskStatus.Completed; - distributedTask.Exception = task.Exception; - if (task.IsFaulted) - { - distributedTask.Status = DistributedTaskStatus.Failted; - } - if (task.IsCanceled) - { - distributedTask.Status = DistributedTaskStatus.Canceled; - } + distributedTask.Exception = task.Exception; + + if (task.IsFaulted) distributedTask.Status = DistributedTaskStatus.Failted; + + if (task.IsCanceled) distributedTask.Status = DistributedTaskStatus.Canceled; Cancelations.TryRemove(id, out _); @@ -306,10 +270,8 @@ namespace ASC.Common.Threading { return (t) => { - if (t.DistributedTaskCache != null) - { - t.DistributedTaskCache.Key = key; - } + if (t.DistributedTaskCache != null) t.DistributedTaskCache.Key = _name; + DistributedTaskCacheNotify.SetTask(t); }; } @@ -324,10 +286,8 @@ namespace ASC.Common.Threading services.TryAdd<DistributedTaskQueue>(); var type = typeof(T); - if (!type.IsAbstract) - { - services.TryAdd<T>(); - } + + if (!type.IsAbstract) services.TryAdd<T>(); services.TryAddSingleton<IConfigureOptions<DistributedTaskQueue>, ConfigureDistributedTaskQueue>(); diff --git a/common/ASC.Common/Utils/ConfigurationManager.cs b/common/ASC.Common/Utils/ConfigurationManager.cs index 281821533b..888494b7f7 100644 --- a/common/ASC.Common/Utils/ConfigurationManager.cs +++ b/common/ASC.Common/Utils/ConfigurationManager.cs @@ -12,44 +12,38 @@ namespace ASC.Common.Utils { private List<ConnectionStringSettings> Data { get; set; } + public ConnectionStringSettings this[string name] => Data.FirstOrDefault(r => r.Name == name); + public ConnectionStringCollection(IEnumerable<ConnectionStringSettings> data) => Data = data.ToList(); - public IEnumerator<ConnectionStringSettings> GetEnumerator() - { - return Data.GetEnumerator(); - } + public IEnumerator<ConnectionStringSettings> GetEnumerator() => Data.GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public ConnectionStringSettings this[string name] - { - get - { - return Data.FirstOrDefault(r => r.Name == name); - } - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } [Singletone] public class ConfigurationExtension { - private IConfiguration Configuration { get; } - private Lazy<ConnectionStringCollection> ConnectionStringSettings { get; } + public string this[string key] + { + get => _configuration[key]; + set => _configuration[key] = value; + } + + private readonly IConfiguration _configuration; + private readonly Lazy<ConnectionStringCollection> _connectionStringSettings; public ConfigurationExtension(IConfiguration configuration) { - Configuration = configuration; - ConnectionStringSettings = new Lazy<ConnectionStringCollection>(new ConnectionStringCollection(GetSettings<ConnectionStringSettings>("ConnectionStrings"))); + _configuration = configuration; + _connectionStringSettings = new Lazy<ConnectionStringCollection>(new ConnectionStringCollection(GetSettings<ConnectionStringSettings>("ConnectionStrings"))); } public IEnumerable<T> GetSettings<T>(string section) where T : new() { var result = new List<T>(); - var sectionSettings = Configuration.GetSection(section); + var sectionSettings = _configuration.GetSection(section); foreach (var ch in sectionSettings.GetChildren()) { @@ -61,34 +55,19 @@ namespace ASC.Common.Utils return result; } - public T GetSetting<T>(string section) where T : new() - { - return GetSetting(section, new T()); - } + public T GetSetting<T>(string section) where T : new() => GetSetting(section, new T()); public T GetSetting<T>(string section, T instance) { - var sectionSettings = Configuration.GetSection(section); + var sectionSettings = _configuration.GetSection(section); sectionSettings.Bind(instance); return instance; } - public ConnectionStringCollection GetConnectionStrings() - { - return ConnectionStringSettings.Value; - } + public ConnectionStringCollection GetConnectionStrings() => _connectionStringSettings.Value; - public ConnectionStringSettings GetConnectionStrings(string key) - { - return GetConnectionStrings()[key]; - } - - public string this[string key] - { - get => Configuration[key]; - set => Configuration[key] = value; - } + public ConnectionStringSettings GetConnectionStrings(string key) => GetConnectionStrings()[key]; } } diff --git a/common/ASC.Common/Utils/CrossPlatformUtils.cs b/common/ASC.Common/Utils/CrossPlatformUtils.cs index 2633858cc9..1ee211890b 100644 --- a/common/ASC.Common/Utils/CrossPlatformUtils.cs +++ b/common/ASC.Common/Utils/CrossPlatformUtils.cs @@ -37,6 +37,7 @@ namespace ASC.Common.Utils var segments = new string[totalLength + 1]; segments[0] = basePath; var i = 0; + foreach (var split in splits) { foreach (var value in split) @@ -45,6 +46,7 @@ namespace ASC.Common.Utils segments[i] = value; } } + return Path.Combine(segments); } diff --git a/common/ASC.Common/Utils/DnsLookup.cs b/common/ASC.Common/Utils/DnsLookup.cs index c4f99322f4..7c2e31766d 100644 --- a/common/ASC.Common/Utils/DnsLookup.cs +++ b/common/ASC.Common/Utils/DnsLookup.cs @@ -223,10 +223,8 @@ namespace ASC.Common.Utils /// <exception cref="ArgumentException">if domainName is invalid</exception> /// <exception cref="FormatException">if ipAddress is invalid</exception> /// <returns>true if exists and vice versa</returns> - public bool IsDomainPtrRecordExists(string ipAddress, string domainName) - { - return IsDomainPtrRecordExists(IPAddress.Parse(ipAddress), domainName); - } + public bool IsDomainPtrRecordExists(string ipAddress, string domainName) => + IsDomainPtrRecordExists(IPAddress.Parse(ipAddress), domainName); private DnsMessage GetDnsMessage(string domainName, RecordType? type = null) { @@ -238,10 +236,8 @@ namespace ASC.Common.Utils var dnsMessage = type.HasValue ? _dnsClient.Resolve(domain, type.Value) : _dnsClient.Resolve(domain); if ((dnsMessage == null) || - ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain))) - { + ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain))) throw new SystemException(); // DNS request failed - } return dnsMessage; } diff --git a/common/ASC.Common/Utils/HtmlUtil.cs b/common/ASC.Common/Utils/HtmlUtil.cs index 631455bf36..36666798bf 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -42,14 +42,12 @@ namespace ASC.Common.Utils public static string GetText(string html, int maxLength = 0, string endBlockTemplate = "...") { var unformatedText = string.Empty; + if (!string.IsNullOrEmpty(html)) { html = xssReplacer.Replace(html, string.Empty); //Clean malicious tags. <script> <style> - if (string.IsNullOrEmpty(html)) - { - return html; - } + if (string.IsNullOrEmpty(html)) return html; unformatedText = tagReplacer.Replace(html, string.Empty); @@ -62,9 +60,7 @@ namespace ASC.Common.Utils if (!string.IsNullOrEmpty(unformatedText)) { if (maxLength == 0 || unformatedText.Length < maxLength) - { return HttpUtility.HtmlDecode(unformatedText); - } //Set maximum length with end block maxLength = Math.Max(0, maxLength - endBlockTemplate.Length); @@ -76,20 +72,17 @@ namespace ASC.Common.Utils unformatedText = lastSpaceIndex > 0 && lastSpaceIndex < unformatedText.Length ? unformatedText.Remove(lastSpaceIndex) : unformatedText.Substring(0, maxLength); + if (!string.IsNullOrEmpty(endBlockTemplate)) - { unformatedText += endBlockTemplate; - } } } } + return HttpUtility.HtmlDecode(unformatedText);//TODO:!!! } - public static string ToPlainText(string html) - { - return GetText(html); - } + public static string ToPlainText(string html) => GetText(html); /// <summary> /// The function highlight all words in htmlText by searchText. @@ -104,6 +97,7 @@ namespace ASC.Common.Utils var regexpstr = Worder.Matches(searchText).Cast<Match>().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); var wordsFinder = new Regex(Regex.Escape(regexpstr), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline); + return wordsFinder.Replace(htmlText, m => string.Format("<span class='searchTextHighlight{1}'>{0}</span>", m.Value, withoutLink ? " bold" : string.Empty)); } } diff --git a/common/ASC.Common/Utils/HttpRequestExtensions.cs b/common/ASC.Common/Utils/HttpRequestExtensions.cs index 5d03a133b4..d543be0ff5 100644 --- a/common/ASC.Common/Utils/HttpRequestExtensions.cs +++ b/common/ASC.Common/Utils/HttpRequestExtensions.cs @@ -41,14 +41,11 @@ namespace System.Web public static readonly string UrlRewriterHeader = "X-REWRITER-URL"; - public static Uri GetUrlRewriter(this HttpRequest request) - { - return request != null ? GetUrlRewriter(request.Headers, request) : null; - } - public static Uri Url(this HttpRequest request) - { - return request != null ? new Uri(request.GetDisplayUrl()) : null; - } + public static Uri GetUrlRewriter(this HttpRequest request) => + request != null ? GetUrlRewriter(request.Headers, request) : null; + + public static Uri Url(this HttpRequest request) => + request != null ? new Uri(request.GetDisplayUrl()) : null; /*public static Uri GetUrlRewriter(this HttpRequestBase request) { @@ -60,7 +57,8 @@ namespace System.Web if (headers != null) { var h = headers[UrlRewriterHeader]; - var rewriterUri = !string.IsNullOrEmpty(h) ? ParseRewriterUrl(h) : null; + var rewriterUri = !string.IsNullOrEmpty(h) ? ParseRewriterUrl(h) : null; + if (request != null && rewriterUri != null) { var result = new UriBuilder() @@ -69,8 +67,10 @@ namespace System.Web Host = rewriterUri.Host, Port = rewriterUri.Port }; + result.Query = request.QueryString.Value; - result.Path = request.Path.Value; + result.Path = request.Path.Value; + return result.Uri; } } @@ -97,14 +97,13 @@ namespace System.Web return request.Url(); } - public static Uri PushRewritenUri(this HttpContext context) - { - return context != null ? PushRewritenUri(context, GetUrlRewriter(context.Request)) : null; - } + public static Uri PushRewritenUri(this HttpContext context) => + context != null ? PushRewritenUri(context, GetUrlRewriter(context.Request)) : null; public static Uri PushRewritenUri(this HttpContext context, Uri rewrittenUri) { - Uri oldUri = null; + Uri oldUri = null; + if (context != null) { var request = context.Request; @@ -122,16 +121,12 @@ namespace System.Web request.Headers.SetCommaSeparatedValues("SERVER_PORT", rewrittenUri.Port.ToString(CultureInfo.InvariantCulture)); - if (rewrittenUri.IsDefaultPort) - { - request.Headers.SetCommaSeparatedValues("HTTP_HOST", - rewrittenUri.Host); - } - else - { + if (rewrittenUri.IsDefaultPort) request.Headers.SetCommaSeparatedValues("HTTP_HOST", + rewrittenUri.Host); + + else request.Headers.SetCommaSeparatedValues("HTTP_HOST", rewrittenUri.Host + ":" + requestUri.Port); - } //Hack: typeof(HttpRequest).InvokeMember("_url", BindingFlags.NonPublic | BindingFlags.SetField | @@ -142,11 +137,10 @@ namespace System.Web context.Items["oldUri"] = oldUri; } - catch (Exception) - { - } + catch (Exception) { } } - } + } + return oldUri; } @@ -154,12 +148,11 @@ namespace System.Web { if (context != null && context.Items["oldUri"] != null) { - var rewriteTo = context.Items["oldUri"] as Uri; - if (rewriteTo != null) - { - return PushRewritenUri(context, rewriteTo); - } - } + var rewriteTo = context.Items["oldUri"] as Uri; + + if (rewriteTo != null) return PushRewritenUri(context, rewriteTo); + } + return null; } @@ -176,44 +169,34 @@ namespace System.Web && (!string.IsNullOrEmpty(request.Headers["sailfish"]) || !string.IsNullOrEmpty(request.Headers[HeaderNames.UserAgent]) && request.Headers[HeaderNames.UserAgent].ToString().Contains("SailfishOS")); } - + + public static string GetUserHostAddress(this HttpRequest request) => + request.HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString(); private static Uri ParseRewriterUrl(string s) { - if (string.IsNullOrEmpty(s)) - { - return null; - } + if (string.IsNullOrEmpty(s)) return null; - const StringComparison cmp = StringComparison.OrdinalIgnoreCase; - if (0 < s.Length && (s.StartsWith("0", cmp))) - { - s = Uri.UriSchemeHttp + s.Substring(1); - } - else if (3 < s.Length && s.StartsWith("OFF", cmp)) - { - s = Uri.UriSchemeHttp + s.Substring(3); - } - else if (0 < s.Length && (s.StartsWith("1", cmp))) - { - s = Uri.UriSchemeHttps + s.Substring(1); - } - else if (2 < s.Length && s.StartsWith("ON", cmp)) - { - s = Uri.UriSchemeHttps + s.Substring(2); - } - else if (s.StartsWith(Uri.UriSchemeHttp + "%3A%2F%2F", cmp) || s.StartsWith(Uri.UriSchemeHttps + "%3A%2F%2F", cmp)) - { + const StringComparison cmp = StringComparison.OrdinalIgnoreCase; + + if (0 < s.Length && (s.StartsWith("0", cmp))) + s = Uri.UriSchemeHttp + s.Substring(1); + + else if (3 < s.Length && s.StartsWith("OFF", cmp)) + s = Uri.UriSchemeHttp + s.Substring(3); + + else if (0 < s.Length && (s.StartsWith("1", cmp))) + s = Uri.UriSchemeHttps + s.Substring(1); + + else if (2 < s.Length && s.StartsWith("ON", cmp)) + s = Uri.UriSchemeHttps + s.Substring(2); + + else if (s.StartsWith(Uri.UriSchemeHttp + "%3A%2F%2F", cmp) || s.StartsWith(Uri.UriSchemeHttps + "%3A%2F%2F", cmp)) s = HttpUtility.UrlDecode(s); - } - Uri.TryCreate(s, UriKind.Absolute, out var result); + Uri.TryCreate(s, UriKind.Absolute, out var result); + return result; } - - public static string GetUserHostAddress(this HttpRequest request) - { - return request.HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString(); - } } } \ No newline at end of file diff --git a/common/ASC.Common/Utils/MailAddressUtils.cs b/common/ASC.Common/Utils/MailAddressUtils.cs index 96ef7ea071..fe8d9b1aab 100644 --- a/common/ASC.Common/Utils/MailAddressUtils.cs +++ b/common/ASC.Common/Utils/MailAddressUtils.cs @@ -37,11 +37,11 @@ namespace ASC.Common.Utils { var firstPos = address.IndexOf('"'); var lastPos = address.LastIndexOf('"'); + if (firstPos != -1 && firstPos < lastPos && address.IndexOf('"', firstPos + 1, lastPos - firstPos - 1) != -1) - { address = new StringBuilder(address).Replace("\"", string.Empty, firstPos + 1, lastPos - firstPos - 1).ToString(); - } } + return new MailAddress(address); } @@ -50,23 +50,17 @@ namespace ASC.Common.Utils if (!string.IsNullOrEmpty(displayName)) { displayName = displayName.Replace("\"", string.Empty); + if (125 < displayName.Length) - { displayName = displayName.Substring(0, 125); - } } + return Create(ToSmtpAddress(address, displayName)); } - public static string ToEncodedString(this MailAddress m) - { - return ToSmtpAddress(m.Address, MimeHeaderUtils.EncodeMime(m.DisplayName)); - } + public static string ToEncodedString(this MailAddress m) => + ToSmtpAddress(m.Address, MimeHeaderUtils.EncodeMime(m.DisplayName)); - - private static string ToSmtpAddress(string address, string displayName) - { - return string.Format("\"{0}\" <{1}>", displayName, address); - } + private static string ToSmtpAddress(string address, string displayName) => $"\"{displayName}\" <{address}>"; } } diff --git a/common/ASC.Common/Utils/MimeHeaderUtils.cs b/common/ASC.Common/Utils/MimeHeaderUtils.cs index ee6b6952ca..15c17e734f 100644 --- a/common/ASC.Common/Utils/MimeHeaderUtils.cs +++ b/common/ASC.Common/Utils/MimeHeaderUtils.cs @@ -32,10 +32,8 @@ namespace ASC.Common.Utils { public static class MimeHeaderUtils { - public static string EncodeMime(string mimeHeaderValue) - { - return EncodeMime(mimeHeaderValue, Encoding.UTF8, false); - } + public static string EncodeMime(string mimeHeaderValue) => + EncodeMime(mimeHeaderValue, Encoding.UTF8, false); public static string EncodeMime(string mimeHeaderValue, Encoding charset, bool split) { @@ -48,6 +46,7 @@ namespace ASC.Common.Utils result.Append("=?" + charset.WebName + "?B?"); var stored = 0; var base64 = Convert.ToBase64String(data); + for (var i = 0; i < base64.Length; i += 4) { // Encoding buffer full, create new encoded-word. @@ -60,15 +59,15 @@ namespace ASC.Common.Utils result.Append(base64, i, 4); stored += 4; } + result.Append("?="); + return result.ToString(); } return mimeHeaderValue; } - public static bool MustEncode(string text) - { - return !string.IsNullOrEmpty(text) && text.Any(c => c > 127); - } + public static bool MustEncode(string text) => + !string.IsNullOrEmpty(text) && text.Any(c => c > 127); } } \ No newline at end of file diff --git a/common/ASC.Common/Utils/RandomString.cs b/common/ASC.Common/Utils/RandomString.cs index 2a8d3bd77f..445e8a74a1 100644 --- a/common/ASC.Common/Utils/RandomString.cs +++ b/common/ASC.Common/Utils/RandomString.cs @@ -36,10 +36,12 @@ namespace ASC.Common.Utils const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; var res = new StringBuilder(); var rnd = new Random(); + while (0 < length--) { res.Append(valid[rnd.Next(valid.Length)]); } + return res.ToString(); } } diff --git a/common/ASC.Common/Utils/Signature.cs b/common/ASC.Common/Utils/Signature.cs index 37a4e2f47d..b23a8c1827 100644 --- a/common/ASC.Common/Utils/Signature.cs +++ b/common/ASC.Common/Utils/Signature.cs @@ -39,29 +39,23 @@ namespace ASC.Common.Utils [Singletone] public class Signature { - public Signature(MachinePseudoKeys machinePseudoKeys) - { - MachinePseudoKeys = machinePseudoKeys; - } + private readonly MachinePseudoKeys _machinePseudoKeys; - private MachinePseudoKeys MachinePseudoKeys { get; } + public Signature(MachinePseudoKeys machinePseudoKeys) => _machinePseudoKeys = machinePseudoKeys; - public string Create<T>(T obj) - { - return Create(obj, Encoding.UTF8.GetString(MachinePseudoKeys.GetMachineConstant())); - } + public string Create<T>(T obj) => + Create(obj, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant())); public static string Create<T>(T obj, string secret) { var str = JsonConvert.SerializeObject(obj); var payload = GetHashBase64(str + secret) + "?" + str; + return WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(payload)); } - public T Read<T>(string signature) - { - return Read<T>(signature, Encoding.UTF8.GetString(MachinePseudoKeys.GetMachineConstant())); - } + public T Read<T>(string signature) => + Read<T>(signature, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant())); public static T Read<T>(string signature, string secret) { @@ -69,27 +63,26 @@ namespace ASC.Common.Utils { var rightSignature = signature.Replace("\"", ""); var payloadParts = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(rightSignature)).Split('?'); + if (GetHashBase64(payloadParts[1] + secret) == payloadParts[0]) - { - //Sig correct - return JsonConvert.DeserializeObject<T>(payloadParts[1]); - } - } - catch (Exception) - { + return JsonConvert.DeserializeObject<T>(payloadParts[1]); //Sig correct } + catch (Exception) { } + return default; } private static string GetHashBase64(string str) { using var sha256 = SHA256.Create(); + return Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))); } private static string GetHashBase64MD5(string str) { using var md5 = MD5.Create(); + return Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(str))); } } diff --git a/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs b/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs index 6a3ab2d8dd..085c73007d 100644 --- a/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs +++ b/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs @@ -44,51 +44,21 @@ namespace ASC.Common.Utils [Singletone] public class TimeZoneConverter { - private TimeZoneInfo defaultTimeZone; - + private TimeZoneInfo _defaultTimeZone; private IEnumerable<MapZone> _mapZones; - private bool _customMode; private bool _isMono; - private Dictionary<string, string> _translations; - - private IConfiguration Configuration { get; } - private ILog Log { get; } + private readonly IConfiguration _configuration; + private readonly ILog _logger; public TimeZoneConverter(IConfiguration configuration, IOptionsMonitor<ILog> option) { - Log = option.CurrentValue; - Configuration = configuration; + _logger = option.CurrentValue; + _configuration = configuration; InitMapZones(); InitTranslations(); - } - - private void InitMapZones() - { - try - { - var assembly = Assembly.GetExecutingAssembly(); - - using var stream = assembly.GetManifestResourceStream("ASC.Common.Utils.TimeZoneConverter.windowsZones.xml"); - var xml = XElement.Load(stream); - _mapZones = from row in xml.XPathSelectElements("*/mapTimezones/mapZone") - let olsonTimeZones = row.Attribute("type").Value.Split(' ') - from olsonTimeZone in olsonTimeZones - select new MapZone - { - OlsonTimeZoneId = olsonTimeZone, - WindowsTimeZoneId = row.Attribute("other").Value, - Territory = row.Attribute("territory").Value - }; - _mapZones = _mapZones.ToList(); - } - catch (Exception error) - { - _mapZones = new MapZone[0]; - Log.Error(error); - } - } + } public string GetTimeZoneDisplayName(TimeZoneInfo tz) { @@ -101,15 +71,12 @@ namespace ASC.Common.Utils var name = tz.BaseUtcOffset.ToString(@"hh\:mm"); displayName = $"(UTC{offSet}{name}) {displayName}"; } - else - { - displayName = "(UTC) " + displayName; - } + else displayName = "(UTC) " + displayName; } return displayName; } - + public string OlsonTzId2WindowsTzId(string olsonTimeZoneId, bool defaultIfNoMatch = true) { var mapZone = GetMapZoneByWindowsTzId(olsonTimeZoneId); @@ -121,12 +88,12 @@ namespace ASC.Common.Utils if (mapZone != null) return mapZone.WindowsTimeZoneId; - - Log.Error(string.Format("OlsonTimeZone {0} not found", olsonTimeZoneId)); + + _logger.Error($"OlsonTimeZone {olsonTimeZoneId} not found"); return defaultIfNoMatch ? "UTC" : null; - } - + } + public string WindowsTzId2OlsonTzId(string windowsTimeZoneId, bool defaultIfNoMatch = true) { var mapZone = GetMapZoneByOlsonTzId(windowsTimeZoneId); @@ -138,20 +105,18 @@ namespace ASC.Common.Utils if (mapZone != null) return mapZone.OlsonTimeZoneId; - - Log.Error(string.Format("WindowsTimeZone {0} not found", windowsTimeZoneId)); + + _logger.Error($"WindowsTimeZone {windowsTimeZoneId} not found"); return defaultIfNoMatch ? "Etc/GMT" : null; - } - + } + public TimeZoneInfo GetTimeZone(string timeZoneId, bool defaultIfNoMatch = true) { var defaultTimezone = GetTimeZoneDefault(); if (string.IsNullOrEmpty(timeZoneId)) - { return defaultIfNoMatch ? defaultTimezone : null; - } try { @@ -163,34 +128,34 @@ namespace ASC.Common.Utils { var mapZone = GetMapZoneByOlsonTzId(timeZoneId); - if (mapZone != null) - { + if (mapZone != null) return TimeZoneInfo.FindSystemTimeZoneById(mapZone.WindowsTimeZoneId); - } mapZone = GetMapZoneByWindowsTzId(timeZoneId); - if (mapZone != null) - { + if (mapZone != null) return TimeZoneInfo.FindSystemTimeZoneById(mapZone.OlsonTimeZoneId); - } - Log.InfoFormat("TimeZone {0} not found", timeZoneId); + _logger.InfoFormat("TimeZone {0} not found", timeZoneId); + return defaultIfNoMatch ? GetTimeZoneByOffset(timeZoneId) ?? defaultTimezone : null; } catch (Exception error) { - Log.Error(error); + _logger.Error(error); + return defaultIfNoMatch ? defaultTimezone : null; } } catch (Exception error) { - Log.Error(error); + _logger.Error(error); + return defaultIfNoMatch ? defaultTimezone : null; } - } - + } + + private MapZone GetMapZoneByOlsonTzId(string olsonTimeZoneId) { return _mapZones.FirstOrDefault(x => @@ -227,12 +192,41 @@ namespace ASC.Common.Utils return systemTimeZones.FirstOrDefault(tz => tz.BaseUtcOffset == offset); } + + private void InitMapZones() + { + try + { + var assembly = Assembly.GetExecutingAssembly(); + + using var stream = assembly.GetManifestResourceStream("ASC.Common.Utils.TimeZoneConverter.windowsZones.xml"); + + var xml = XElement.Load(stream); + + _mapZones = from row in xml.XPathSelectElements("*/mapTimezones/mapZone") + let olsonTimeZones = row.Attribute("type").Value.Split(' ') + from olsonTimeZone in olsonTimeZones + select new MapZone + { + OlsonTimeZoneId = olsonTimeZone, + WindowsTimeZoneId = row.Attribute("other").Value, + Territory = row.Attribute("territory").Value + }; + + _mapZones = _mapZones.ToList(); + } + catch (Exception error) + { + _mapZones = new MapZone[0]; + _logger.Error(error); + } + } private void InitTranslations() { try { - _customMode = Configuration["core:custom-mode"] == "true"; + _customMode = _configuration["core:custom-mode"] == "true"; if (!_customMode) { @@ -242,7 +236,8 @@ namespace ASC.Common.Utils var assembly = Assembly.GetExecutingAssembly(); - using var stream = assembly.GetManifestResourceStream("ASC.Common.Utils.TimeZoneConverter.timeZoneNames.xml"); + using var stream = assembly.GetManifestResourceStream("ASC.Common.Utils.TimeZoneConverter.timeZoneNames.xml"); + var xml = XElement.Load(stream); _translations = (from row in xml.XPathSelectElements("*/zone") select new KeyValuePair<string, string>(row.Attribute("type").Value, row.Value) @@ -251,7 +246,7 @@ namespace ASC.Common.Utils catch (Exception error) { _translations = new Dictionary<string, string>(); - Log.Error(error); + _logger.Error(error); } } @@ -265,20 +260,19 @@ namespace ASC.Common.Utils private TimeZoneInfo GetTimeZoneDefault() { - if (defaultTimeZone == null) + if (_defaultTimeZone == null) { try { var tz = TimeZoneInfo.Local; if (Path.DirectorySeparatorChar == '/') { - if (tz.StandardName == "UTC" || tz.StandardName == "UCT") - { + if (tz.StandardName == "UTC" || tz.StandardName == "UCT") tz = TimeZoneInfo.Utc; - } else { - var id = string.Empty; + var id = string.Empty; + if (File.Exists("/etc/timezone")) { _isMono = true; @@ -293,30 +287,31 @@ namespace ASC.Common.Utils Arguments = "date +%Z", RedirectStandardOutput = true, UseShellExecute = false, - }; + }; + using var p = Process.Start(psi); + if (p.WaitForExit(1000)) - { id = p.StandardOutput.ReadToEnd(); - } + p.Close(); - } - if (!string.IsNullOrEmpty(id)) - { + } + + if (!string.IsNullOrEmpty(id)) tz = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(z => z.Id == id) ?? tz; - } } - } - defaultTimeZone = tz; + } + + _defaultTimeZone = tz; } catch (Exception) { // ignore - defaultTimeZone = TimeZoneInfo.Utc; + _defaultTimeZone = TimeZoneInfo.Utc; } } - return defaultTimeZone; + return _defaultTimeZone; } private class MapZone diff --git a/common/ASC.Common/Utils/VelocityFormatter.cs b/common/ASC.Common/Utils/VelocityFormatter.cs index fecb88be69..887d9f86d4 100644 --- a/common/ASC.Common/Utils/VelocityFormatter.cs +++ b/common/ASC.Common/Utils/VelocityFormatter.cs @@ -42,20 +42,12 @@ namespace ASC.Common.Utils //nothing to configure } - public override Stream GetResourceStream(string source) - { - return new MemoryStream(Encoding.UTF8.GetBytes(source)); - } + public override Stream GetResourceStream(string source) => + new MemoryStream(Encoding.UTF8.GetBytes(source)); - public override long GetLastModified(NVelocity.Runtime.Resource.Resource resource) - { - return 1; - } + public override long GetLastModified(NVelocity.Runtime.Resource.Resource resource) => 1; - public override bool IsSourceModified(NVelocity.Runtime.Resource.Resource resource) - { - return false; - } + public override bool IsSourceModified(NVelocity.Runtime.Resource.Resource resource) => false; } public class VelocityFormatter @@ -65,9 +57,11 @@ namespace ASC.Common.Utils public static string FormatText(string templateText, IDictionary<string, object> values) { - var nvelocityContext = new VelocityContext(); + var nvelocityContext = new VelocityContext(); + foreach (var tagValue in values) - nvelocityContext.Put(tagValue.Key, tagValue.Value); + nvelocityContext.Put(tagValue.Key, tagValue.Value); + return FormatText(templateText, nvelocityContext); } @@ -86,12 +80,15 @@ namespace ASC.Common.Utils using var writer = new StringWriter(); var key = templateText.GetHashCode().ToString(); + if (!patterns.TryGetValue(key, out var template)) { template = Velocity.GetTemplate(templateText); patterns.TryAdd(key, template); } + template.Merge(context, writer); + return writer.GetStringBuilder().ToString(); } } diff --git a/common/ASC.Common/Utils/Wildcard.cs b/common/ASC.Common/Utils/Wildcard.cs index e3a36da22c..418a28f822 100644 --- a/common/ASC.Common/Utils/Wildcard.cs +++ b/common/ASC.Common/Utils/Wildcard.cs @@ -28,30 +28,25 @@ namespace ASC.Common.Utils { public static class Wildcard { - public static bool WildcardMatch(this string input, string pattern) - { - return WildcardMatch(input, pattern, true); - } + public static bool WildcardMatch(this string input, string pattern) => + WildcardMatch(input, pattern, true); public static bool WildcardMatch(this string input, string pattern, bool ignoreCase) { - if (!string.IsNullOrEmpty(input)) - { - return IsMatch(pattern, input, ignoreCase); - } + if (!string.IsNullOrEmpty(input)) return IsMatch(pattern, input, ignoreCase); + return false; } - public static bool IsMatch(string pattern, string input) - { - return IsMatch(pattern, input, true); - } + public static bool IsMatch(string pattern, string input) => + IsMatch(pattern, input, true); public static bool IsMatch(string pattern, string input, bool ignoreCase) { var offsetInput = 0; var isAsterix = false; int i; + for (i = 0; i < pattern.Length;) { switch (pattern[i]) @@ -62,17 +57,21 @@ namespace ASC.Common.Utils break; case '*': isAsterix = true; + while (i < pattern.Length && pattern[i] == '*') { i++; } + if (i >= pattern.Length) return true; + continue; default: if (offsetInput >= input.Length) return false; + if ((ignoreCase ? char.ToLower(input[offsetInput]) : input[offsetInput]) @@ -83,7 +82,9 @@ namespace ASC.Common.Utils { if (!isAsterix) return false; + offsetInput++; + continue; } offsetInput++; diff --git a/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs b/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs index 41cb24c81c..d30f2aad16 100644 --- a/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs +++ b/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs @@ -33,39 +33,31 @@ namespace ASC.Common.Web { public abstract class AbstractHttpAsyncHandler // : IHttpAsyncHandler, IReadOnlySessionState { - private Action<Microsoft.AspNetCore.Http.HttpContext> processRequest; - private IPrincipal principal; - private CultureInfo culture; - - - public bool IsReusable - { - get { return false; } - } + public bool IsReusable => false; + private Action<Microsoft.AspNetCore.Http.HttpContext> _processRequest; + private IPrincipal _principal; + private CultureInfo _culture; public void ProcessRequest(Microsoft.AspNetCore.Http.HttpContext context) { - Thread.CurrentThread.CurrentCulture = culture; - Thread.CurrentThread.CurrentUICulture = culture; - Thread.CurrentPrincipal = principal; + Thread.CurrentThread.CurrentCulture = _culture; + Thread.CurrentThread.CurrentUICulture = _culture; + Thread.CurrentPrincipal = _principal; //HttpContext.Current = context; OnProcessRequest(context); } public IAsyncResult BeginProcessRequest(Microsoft.AspNetCore.Http.HttpContext context, AsyncCallback cb, object extraData) { - culture = Thread.CurrentThread.CurrentCulture; - principal = Thread.CurrentPrincipal; - processRequest = ProcessRequest; - return processRequest.BeginInvoke(context, cb, extraData); - } - - public void EndProcessRequest(IAsyncResult result) - { - processRequest.EndInvoke(result); + _culture = Thread.CurrentThread.CurrentCulture; + _principal = Thread.CurrentPrincipal; + _processRequest = ProcessRequest; + + return _processRequest.BeginInvoke(context, cb, extraData); } + public void EndProcessRequest(IAsyncResult result) => _processRequest.EndInvoke(result); public abstract void OnProcessRequest(Microsoft.AspNetCore.Http.HttpContext context); } diff --git a/common/ASC.Common/Web/DisposableHttpContext.cs b/common/ASC.Common/Web/DisposableHttpContext.cs index 7830b08ff4..54249a17da 100644 --- a/common/ASC.Common/Web/DisposableHttpContext.cs +++ b/common/ASC.Common/Web/DisposableHttpContext.cs @@ -36,16 +36,15 @@ namespace ASC.Common.Web public class DisposableHttpContext : IDisposable { private const string key = "disposable.key"; - private readonly Microsoft.AspNetCore.Http.HttpContext ctx; + private readonly Microsoft.AspNetCore.Http.HttpContext _context; + private bool _isDisposed; - public DisposableHttpContext(Microsoft.AspNetCore.Http.HttpContext ctx) - { - this.ctx = ctx ?? throw new ArgumentNullException(); - } + public DisposableHttpContext(Microsoft.AspNetCore.Http.HttpContext ctx) => + _context = ctx ?? throw new ArgumentNullException(); public object this[string key] { - get { return Items.ContainsKey(key) ? Items[key] : null; } + get => Items.ContainsKey(key) ? Items[key] : null; set { if (value == null) throw new ArgumentNullException(); @@ -58,20 +57,18 @@ namespace ASC.Common.Web { get { - var table = (Dictionary<string, IDisposable>)ctx.Items[key]; + var table = (Dictionary<string, IDisposable>)_context.Items[key]; + if (table == null) { table = new Dictionary<string, IDisposable>(1); - ctx.Items.Add(key, table); + _context.Items.Add(key, table); } + return table; } } - #region IDisposable Members - - private bool _isDisposed; - public void Dispose() { if (!_isDisposed) @@ -82,14 +79,11 @@ namespace ASC.Common.Web { item.Dispose(); } - catch - { - } + catch { } } + _isDisposed = true; } } - - #endregion } } \ No newline at end of file diff --git a/common/ASC.Common/Web/HttpException.cs b/common/ASC.Common/Web/HttpException.cs index 840b8331a0..62b2e3f061 100644 --- a/common/ASC.Common/Web/HttpException.cs +++ b/common/ASC.Common/Web/HttpException.cs @@ -5,36 +5,19 @@ namespace ASC.Common.Web { public class HttpException : Exception { - public HttpException(int httpStatusCode) - { - StatusCode = httpStatusCode; - } - - public HttpException(HttpStatusCode httpStatusCode) - { - StatusCode = (int)httpStatusCode; - } - - public HttpException(int httpStatusCode, string message) : base(message) - { - StatusCode = httpStatusCode; - } - - public HttpException(HttpStatusCode httpStatusCode, string message) : base(message) - { - StatusCode = (int)httpStatusCode; - } - - public HttpException(int httpStatusCode, string message, Exception inner) : base(message, inner) - { - StatusCode = httpStatusCode; - } - - public HttpException(HttpStatusCode httpStatusCode, string message, Exception inner) : base(message, inner) - { - StatusCode = (int)httpStatusCode; - } - public int StatusCode { get; } + + public HttpException(int httpStatusCode) => StatusCode = httpStatusCode; + + public HttpException(HttpStatusCode httpStatusCode) => StatusCode = (int)httpStatusCode; + + public HttpException(int httpStatusCode, string message) : base(message) => StatusCode = httpStatusCode; + + public HttpException(HttpStatusCode httpStatusCode, string message) : base(message) => StatusCode = (int)httpStatusCode; + + public HttpException(int httpStatusCode, string message, Exception inner) : base(message, inner) => StatusCode = httpStatusCode; + + public HttpException(HttpStatusCode httpStatusCode, string message, Exception inner) : base(message, inner) => + StatusCode = (int)httpStatusCode; } } diff --git a/common/ASC.Common/Web/ItemNotFoundException.cs b/common/ASC.Common/Web/ItemNotFoundException.cs index 0a1985edb0..169a6d581f 100644 --- a/common/ASC.Common/Web/ItemNotFoundException.cs +++ b/common/ASC.Common/Web/ItemNotFoundException.cs @@ -5,17 +5,10 @@ namespace ASC.Common.Web [Serializable] public class ItemNotFoundException : HttpException { + public ItemNotFoundException() : base(404, "Not found") { } - public ItemNotFoundException() : base(404, "Not found") - { - } + public ItemNotFoundException(string message) : base(404, message) { } - public ItemNotFoundException(string message) : base(404, message) - { - } - - public ItemNotFoundException(string message, Exception inner) : base(404, message, inner) - { - } + public ItemNotFoundException(string message, Exception inner) : base(404, message, inner) { } } } diff --git a/common/ASC.Common/Web/MimeMapping.cs b/common/ASC.Common/Web/MimeMapping.cs index eeefcc7d18..4dc4e68218 100644 --- a/common/ASC.Common/Web/MimeMapping.cs +++ b/common/ASC.Common/Web/MimeMapping.cs @@ -32,9 +32,8 @@ namespace ASC.Common.Web { public static class MimeMapping { - private static readonly Hashtable extensionToMimeMappingTable = new Hashtable(200, StringComparer.CurrentCultureIgnoreCase); - - private static readonly IDictionary<string, IList<string>> mimeSynonyms = new Dictionary<string, IList<string>>(); + private static readonly Hashtable _extensionToMimeMappingTable = new Hashtable(200, StringComparer.CurrentCultureIgnoreCase); + private static readonly IDictionary<string, IList<string>> _mimeSynonyms = new Dictionary<string, IList<string>>(); static MimeMapping() { @@ -810,58 +809,51 @@ namespace ASC.Common.Web AddMimeMapping(".zoo", "application/octet-stream"); AddMimeMapping(".zsh", "text/x-script.zsh"); AddMimeMapping(".*", "application/octet-stream"); + } + + public static string GetExtention(string mimeMapping) + { + if (string.IsNullOrEmpty(mimeMapping)) return null; + + foreach (DictionaryEntry entry in _extensionToMimeMappingTable) + { + var mime = (string)entry.Value; + if (mime == mimeMapping.ToLowerInvariant()) return (string)entry.Key; + if (!_mimeSynonyms.ContainsKey(mime)) continue; + if (_mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; + } + + return null; + } + + public static string GetMimeMapping(string fileName) + { + string str = null; + var startIndex = fileName.LastIndexOf('.'); + + if (0 <= startIndex && fileName.LastIndexOf('\\') < startIndex) + str = (string)_extensionToMimeMappingTable[fileName.Substring(startIndex)]; + + if (str == null) str = (string)_extensionToMimeMappingTable[".*"]; + + return str; } private static void AddMimeMapping(string extension, string MimeType) { - if (extensionToMimeMappingTable.ContainsKey(extension)) - { - AddMimeSynonym((string)extensionToMimeMappingTable[extension], MimeType); - } - else - { - extensionToMimeMappingTable.Add(extension, MimeType); - } + if (_extensionToMimeMappingTable.ContainsKey(extension)) + AddMimeSynonym((string)_extensionToMimeMappingTable[extension], MimeType); + + else _extensionToMimeMappingTable.Add(extension, MimeType); } private static void AddMimeSynonym(string mime, string synonym) { - if (!mimeSynonyms.ContainsKey(mime)) - { - mimeSynonyms[mime] = new List<string>(); - } - if (!mimeSynonyms[mime].Contains(synonym)) - { - mimeSynonyms[mime].Add(synonym); - } - } + if (!_mimeSynonyms.ContainsKey(mime)) + _mimeSynonyms[mime] = new List<string>(); - public static string GetMimeMapping(string fileName) - { - string str = null; - var startIndex = fileName.LastIndexOf('.'); - if (0 <= startIndex && fileName.LastIndexOf('\\') < startIndex) - { - str = (string)extensionToMimeMappingTable[fileName.Substring(startIndex)]; - } - if (str == null) - { - str = (string)extensionToMimeMappingTable[".*"]; - } - return str; - } - - public static string GetExtention(string mimeMapping) - { - if (string.IsNullOrEmpty(mimeMapping)) return null; - foreach (DictionaryEntry entry in extensionToMimeMappingTable) - { - var mime = (string)entry.Value; - if (mime == mimeMapping.ToLowerInvariant()) return (string)entry.Key; - if (!mimeSynonyms.ContainsKey(mime)) continue; - if (mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; - } - return null; + if (!_mimeSynonyms[mime].Contains(synonym)) + _mimeSynonyms[mime].Add(synonym); } } } \ No newline at end of file diff --git a/common/ASC.Common/Web/RouteCallInfo.cs b/common/ASC.Common/Web/RouteCallInfo.cs index 5715c8484d..fec8af9555 100644 --- a/common/ASC.Common/Web/RouteCallInfo.cs +++ b/common/ASC.Common/Web/RouteCallInfo.cs @@ -35,21 +35,14 @@ namespace ASC.Common.Web public string Url { get; set; } public string AttachmentUrl { get; set; } public bool IsNewRequest { get; set; } - public string Method { get; set; } - public Dictionary<string, object> Params { get; set; } - public bool CleanupHtml { get; set; } + public RouteCallInfo() => CleanupHtml = true; //Default - public RouteCallInfo() - { - CleanupHtml = true;//Default - } - - public override string ToString() - { - return string.Format("{0} {1} T:{2},{3}", Method.ToUpper(), Url, Tid, string.Join(",", Params.Select(x => string.Format("{0}={1}", x.Key, x.Value)).ToArray())); - } + public override string ToString() => + string.Format("{0} {1} T:{2},{3}", Method.ToUpper(), Url, Tid, + string.Join(",", + Params.Select(x => string.Format("{0}={1}", x.Key, x.Value)).ToArray())); } } \ No newline at end of file diff --git a/common/services/ASC.ClearEvents/Program.cs b/common/services/ASC.ClearEvents/Program.cs index 354049b7b9..e8df38fe0d 100644 --- a/common/services/ASC.ClearEvents/Program.cs +++ b/common/services/ASC.ClearEvents/Program.cs @@ -89,15 +89,15 @@ public class Program if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); } else { - diHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); } services.AddHostedService<ClearEventsServiceLauncher>(); diff --git a/common/services/ASC.Notify/Program.cs b/common/services/ASC.Notify/Program.cs index 883c239755..b325dee7b1 100644 --- a/common/services/ASC.Notify/Program.cs +++ b/common/services/ASC.Notify/Program.cs @@ -77,17 +77,17 @@ namespace ASC.Notify if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); } diHelper.RegisterProducts(hostContext.Configuration, hostContext.HostingEnvironment.ContentRootPath); diff --git a/common/services/ASC.Studio.Notify/Program.cs b/common/services/ASC.Studio.Notify/Program.cs index 7a178cf58c..c07da548f2 100644 --- a/common/services/ASC.Studio.Notify/Program.cs +++ b/common/services/ASC.Studio.Notify/Program.cs @@ -78,17 +78,17 @@ namespace ASC.Studio.Notify if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); } diHelper.RegisterProducts(hostContext.Configuration, hostContext.HostingEnvironment.ContentRootPath); diff --git a/common/services/ASC.Webhooks.Service/Program.cs b/common/services/ASC.Webhooks.Service/Program.cs index d328e1f077..8d106cf1f8 100644 --- a/common/services/ASC.Webhooks.Service/Program.cs +++ b/common/services/ASC.Webhooks.Service/Program.cs @@ -75,17 +75,17 @@ namespace ASC.Webhooks.Service if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); } diHelper.TryAdd<DbWorker>(); diff --git a/products/ASC.Files/Service/Program.cs b/products/ASC.Files/Service/Program.cs index 31e65f3503..1f3434dbd6 100644 --- a/products/ASC.Files/Service/Program.cs +++ b/products/ASC.Files/Service/Program.cs @@ -81,17 +81,17 @@ namespace ASC.Files.Service if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(KafkaCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(RedisCache<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(IEventBus<>), typeof(MemoryCacheNotify<>)); + diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); } From e7df033899039ce13c6c1380b33d798bb93803e4 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 18:19:09 +0300 Subject: [PATCH 111/167] AuditTrail: fix --- common/services/ASC.AuditTrail/AuditReportCreator.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/common/services/ASC.AuditTrail/AuditReportCreator.cs b/common/services/ASC.AuditTrail/AuditReportCreator.cs index 94315157e1..5a1fd72140 100644 --- a/common/services/ASC.AuditTrail/AuditReportCreator.cs +++ b/common/services/ASC.AuditTrail/AuditReportCreator.cs @@ -29,8 +29,9 @@ using System; using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Text; - +using System.Text; + +using ASC.AuditTrail.Models; using ASC.Common; using ASC.Common.Logging; using ASC.Web.Core.Files; From 498045e071b5131d0b66abeb9c232d4af826d5eb Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 18:27:37 +0300 Subject: [PATCH 112/167] ClearEvents: IServiceProvider replaced by IServiceScopeFactory --- .../ASC.ClearEvents/Services/TimedClearEventsService.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs b/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs index d78715986b..e531dabf1e 100644 --- a/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs +++ b/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs @@ -49,13 +49,13 @@ namespace ASC.ClearEvents.Services public class TimedClearEventsService : IHostedService, IDisposable { private readonly ILog _logger; - private readonly IServiceProvider _serviceProvider; + private readonly IServiceScopeFactory _serviceScopeFactory; private Timer _timer = null!; - public TimedClearEventsService(IOptionsMonitor<ILog> options, IServiceProvider serviceProvider) + public TimedClearEventsService(IOptionsMonitor<ILog> options, IServiceScopeFactory serviceScopeFactory) { _logger = options.CurrentValue; - _serviceProvider = serviceProvider; + _serviceScopeFactory = serviceScopeFactory; } public Task StartAsync(CancellationToken cancellationToken) @@ -98,7 +98,7 @@ namespace ASC.ClearEvents.Services var compile = func.Compile(); do { - using var scope = _serviceProvider.CreateScope(); + using var scope = _serviceScopeFactory.CreateScope(); using var ef = scope.ServiceProvider.GetService<DbContextManager<Messages>>().Get("messages"); var table = compile.Invoke(ef); @@ -140,5 +140,4 @@ namespace ASC.ClearEvents.Services { public static void Register(DIHelper services) => services.TryAdd<DbContextManager<Messages>>(); } - } \ No newline at end of file From 084e3a8d30bd6ab2d86c809a4292e71b132d03d1 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 1 Feb 2022 20:07:26 +0300 Subject: [PATCH 113/167] ApiCore: IServiceProvider replaced by IServiceScopeFactory --- common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs index 0401004f15..b3502d80e6 100644 --- a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs @@ -22,7 +22,7 @@ namespace ASC.Api.Core.Auth { private readonly SecurityContext _securityContext; private readonly UserManager _userManager; - private readonly IServiceProvider _serviceProvider; + private readonly IServiceScopeFactory _serviceScopeFactory; public ConfirmAuthHandler( IOptionsMonitor<AuthenticationSchemeOptions> options, @@ -39,17 +39,17 @@ namespace ASC.Api.Core.Auth ISystemClock clock, SecurityContext securityContext, UserManager userManager, - IServiceProvider serviceProvider) : + IServiceScopeFactory serviceScopeFactory) : base(options, logger, encoder, clock) { _securityContext = securityContext; _userManager = userManager; - _serviceProvider = serviceProvider; + _serviceScopeFactory = serviceScopeFactory; } protected override Task<AuthenticateResult> HandleAuthenticateAsync() { - using var scope = _serviceProvider.CreateScope(); + using var scope = _serviceScopeFactory.CreateScope(); var emailValidationKeyHelper = scope.ServiceProvider.GetService<EmailValidationKeyModelHelper>(); var emailValidationKeyModel = emailValidationKeyHelper.GetModel(); From bb28679fdf05ddaa845c0c822cac435d280fd280 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 2 Feb 2022 14:05:06 +0300 Subject: [PATCH 114/167] analizators: bugfix --- products/ASC.Files/Core/Core/FileStorageService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index bd2fb5c234..be3045ec18 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -436,7 +436,7 @@ namespace ASC.Web.Files.Services.WCFService var folderAccess = folder.Access; - if (string.Equals(folder.Title, title, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(folder.Title, title, StringComparison.OrdinalIgnoreCase)) { var newFolderID = folderDao.RenameFolder(folder, title); folder = folderDao.GetFolder(newFolderID); From 81e50c856e9bfc02c4d9bf1199a3a6f5c7357c98 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 14:01:34 +0300 Subject: [PATCH 115/167] AuditTrail: remove unnecessary --- .../Mapping/Profiles/AuditEventProfile.cs | 29 --------------- .../Mapping/Profiles/LoginEventProfile.cs | 26 -------------- .../Resolvers/ActionTextValueResolver.cs | 30 ---------------- .../Resolvers/ActionTypeTextValueResolver.cs | 27 -------------- .../Resolvers/DescriptionValueResolver.cs | 30 ---------------- .../Mapping/Resolvers/ModuleValueResolver.cs | 16 --------- .../Mapping/Resolvers/ProductValueResolver.cs | 17 --------- .../Mapping/Resolvers/TargetValueResolver.cs | 16 --------- .../Resolvers/UserNameValueResolver.cs | 35 ------------------- 9 files changed, 226 deletions(-) delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Profiles/AuditEventProfile.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Profiles/LoginEventProfile.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTextValueResolver.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTypeTextValueResolver.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/DescriptionValueResolver.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ModuleValueResolver.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ProductValueResolver.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/TargetValueResolver.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/Resolvers/UserNameValueResolver.cs diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Profiles/AuditEventProfile.cs b/common/services/ASC.AuditTrail/Models/Mapping/Profiles/AuditEventProfile.cs deleted file mode 100644 index ec83f3fc29..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/Profiles/AuditEventProfile.cs +++ /dev/null @@ -1,29 +0,0 @@ -using ASC.AuditTrail.Models.Mapping.Resolvers; -using ASC.Common.Mapping; - -namespace ASC.AuditTrail.Models.Profiles -{ - public class AuditEventProfile : MappingProfile - { - public AuditEventProfile() - { - CreateMap<AuditEventQuery, AuditEvent>() - .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.AuditEvent.Id)) - .ForMember(dest => dest.Ip, opt => opt.MapFrom(src => src.AuditEvent.Ip)) - .ForMember(dest => dest.Initiator, opt => opt.MapFrom(src => src.AuditEvent.Initiator)) - .ForMember(dest => dest.Browser, opt => opt.MapFrom(src => src.AuditEvent.Browser)) - .ForMember(dest => dest.Platform, opt => opt.MapFrom(src => src.AuditEvent.Platform)) - .ForMember(dest => dest.Date, opt => opt.MapFrom(src => src.AuditEvent.Date)) - .ForMember(dest => dest.TenantId, opt => opt.MapFrom(src => src.AuditEvent.TenantId)) - .ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.AuditEvent.UserId)) - .ForMember(dest => dest.Page, opt => opt.MapFrom(src => src.AuditEvent.Page)) - .ForMember(dest => dest.Action, opt => opt.MapFrom(src => src.AuditEvent.Action)) - .ForMember(dest => dest.Description, opt => opt.MapFrom<AuditEventDescriptionValueResolver>()) - .ForMember(dest => dest.UserName, opt => opt.MapFrom<AuditEventUserNameValueResolver>()) - .ForMember(dest => dest.ActionText, opt => opt.MapFrom<AuditEventActionTextValueResolver>()) - .ForMember(dest => dest.ActionTypeText, opt => opt.MapFrom<AuditEventActionTypeValueResolver>()) - .ForMember(dest => dest.Product, opt => opt.MapFrom<ProductValueResolver>()) - .ForMember(dest => dest.Module, opt => opt.MapFrom<ModuleValueResolver>()); - } - } -} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Profiles/LoginEventProfile.cs b/common/services/ASC.AuditTrail/Models/Mapping/Profiles/LoginEventProfile.cs deleted file mode 100644 index 3940aa3982..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/Profiles/LoginEventProfile.cs +++ /dev/null @@ -1,26 +0,0 @@ -using ASC.AuditTrail.Models.Mapping.Resolvers; -using ASC.Common.Mapping; - -namespace ASC.AuditTrail.Models.Mapping.Profiles -{ - public class LoginEventProfile : MappingProfile - { - public LoginEventProfile() - { - CreateMap<LoginEventQuery, LoginEvent>() - .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.LoginEvents.Id)) - .ForMember(dest => dest.Ip, opt => opt.MapFrom(src => src.LoginEvents.Ip)) - .ForMember(dest => dest.Login, opt => opt.MapFrom(src => src.LoginEvents.Login)) - .ForMember(dest => dest.Browser, opt => opt.MapFrom(src => src.LoginEvents.Browser)) - .ForMember(dest => dest.Platform, opt => opt.MapFrom(src => src.LoginEvents.Platform)) - .ForMember(dest => dest.Date, opt => opt.MapFrom(src => src.LoginEvents.Date)) - .ForMember(dest => dest.TenantId, opt => opt.MapFrom(src => src.LoginEvents.TenantId)) - .ForMember(dest => dest.Page, opt => opt.MapFrom(src => src.LoginEvents.Page)) - .ForMember(dest => dest.Action, opt => opt.MapFrom(src => src.LoginEvents.Action)) - .ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.LoginEvents.UserId)) - .ForMember(dest => dest.Description, opt => opt.MapFrom<LoginEventDescriptionValueResolver>()) - .ForMember(dest => dest.UserName, opt => opt.MapFrom<LoginEventUserNameValueResolver>()) - .ForMember(dest => dest.ActionText, opt => opt.MapFrom<ActionTextValueResolver>()); - } - } -} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTextValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTextValueResolver.cs deleted file mode 100644 index 63772a83d9..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTextValueResolver.cs +++ /dev/null @@ -1,30 +0,0 @@ -using ASC.AuditTrail.Mappers; - -using AutoMapper; - -namespace ASC.AuditTrail.Models.Mapping.Resolvers -{ - public class ActionTextValueResolver : IValueResolver<LoginEventQuery, LoginEvent, string> - { - private readonly AuditActionMapper _actionMapper; - - public ActionTextValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; - - public string Resolve(LoginEventQuery source, LoginEvent destination, string destMember, ResolutionContext context) - { - return _actionMapper.GetActionText(destination); - } - } - - public class AuditEventActionTextValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> - { - private readonly AuditActionMapper _actionMapper; - - public AuditEventActionTextValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; - - public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) - { - return _actionMapper.GetActionText(destination); - } - } -} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTypeTextValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTypeTextValueResolver.cs deleted file mode 100644 index 95e6f3c1e9..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ActionTypeTextValueResolver.cs +++ /dev/null @@ -1,27 +0,0 @@ - -using ASC.AuditTrail.Mappers; - -using AutoMapper; - -namespace ASC.AuditTrail.Models.Mapping.Resolvers -{ - public class LoginEventActionTypeTextValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> - { - private readonly AuditActionMapper _actionMapper; - - public LoginEventActionTypeTextValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; - - public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) => - _actionMapper.GetActionTypeText(destination); - } - - public class AuditEventActionTypeValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> - { - private readonly AuditActionMapper _actionMapper; - - public AuditEventActionTypeValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; - - public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) => - _actionMapper.GetActionTypeText(destination); - } -} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/DescriptionValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/DescriptionValueResolver.cs deleted file mode 100644 index f3d446e5a2..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/DescriptionValueResolver.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; - -using AutoMapper; - -using Newtonsoft.Json; - -namespace ASC.AuditTrail.Models.Mapping.Resolvers -{ - public class LoginEventDescriptionValueResolver : IValueResolver<LoginEventQuery, LoginEvent, IList<string>> - { - public IList<string> Resolve(LoginEventQuery source, LoginEvent destination, IList<string> destMember, ResolutionContext context) - { - if (source.LoginEvents.Description == null) return null; - - return JsonConvert.DeserializeObject<IList<string>>(source.LoginEvents.Description, - new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); - } - } - - public class AuditEventDescriptionValueResolver : IValueResolver<AuditEventQuery, AuditEvent, IList<string>> - { - public IList<string> Resolve(AuditEventQuery source, AuditEvent destination, IList<string> destMember, ResolutionContext context) - { - if (source.AuditEvent.Description == null) return null; - - return JsonConvert.DeserializeObject<IList<string>>(source.AuditEvent.Description, - new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); - } - } -} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ModuleValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ModuleValueResolver.cs deleted file mode 100644 index 290ec1721c..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ModuleValueResolver.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ASC.AuditTrail.Mappers; - -using AutoMapper; - -namespace ASC.AuditTrail.Models.Mapping.Resolvers -{ - public class ModuleValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> - { - private readonly AuditActionMapper _actionMapper; - - public ModuleValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; - - public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) => - _actionMapper.GetModuleText(destination); - } -} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ProductValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ProductValueResolver.cs deleted file mode 100644 index d6afe4ed24..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/ProductValueResolver.cs +++ /dev/null @@ -1,17 +0,0 @@ - -using ASC.AuditTrail.Mappers; - -using AutoMapper; - -namespace ASC.AuditTrail.Models.Mapping.Resolvers -{ - public class ProductValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> - { - private readonly AuditActionMapper _actionMapper; - - public ProductValueResolver(AuditActionMapper actionMapper) => _actionMapper = actionMapper; - - public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) => - _actionMapper.GetProductText(destination); - } -} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/TargetValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/TargetValueResolver.cs deleted file mode 100644 index 65153b6b16..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/TargetValueResolver.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ASC.MessagingSystem; - -using AutoMapper; - -namespace ASC.AuditTrail.Models.Mapping.Resolvers -{ - public class TargetValueResolver : IValueResolver<AuditEventQuery, AuditEvent, MessageTarget> - { - private readonly MessageTarget _target; - - public TargetValueResolver(MessageTarget messageTarget) => _target = messageTarget; - - public MessageTarget Resolve(AuditEventQuery source, AuditEvent destination, MessageTarget destMember, ResolutionContext context) => - _target.Parse(source.AuditEvent.Target); - } -} diff --git a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/UserNameValueResolver.cs b/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/UserNameValueResolver.cs deleted file mode 100644 index 17341ec4f1..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/Resolvers/UserNameValueResolver.cs +++ /dev/null @@ -1,35 +0,0 @@ -using ASC.Core.Users; - -using AutoMapper; - -namespace ASC.AuditTrail.Models.Mapping.Resolvers -{ - public class LoginEventUserNameValueResolver : IValueResolver<LoginEventQuery, LoginEvent, string> - { - private readonly UserFormatter _formatter; - - public LoginEventUserNameValueResolver(UserFormatter userFormatter) => _formatter = userFormatter; - - public string Resolve(LoginEventQuery source, LoginEvent destination, string destMember, ResolutionContext context) => - (!string.IsNullOrEmpty(source.User?.FirstName) && !string.IsNullOrEmpty(source.User?.LastName)) - ? _formatter.GetUserName(source.User.FirstName, source.User.LastName) - : !string.IsNullOrWhiteSpace(source.LoginEvents.Login) - ? source.LoginEvents.Login - : source.LoginEvents.UserId == Core.Configuration.Constants.Guest.ID - ? AuditReportResource.GuestAccount - : AuditReportResource.UnknownAccount; - } - - public class AuditEventUserNameValueResolver : IValueResolver<AuditEventQuery, AuditEvent, string> - { - private readonly UserFormatter _formatter; - - public AuditEventUserNameValueResolver(UserFormatter userFormatter) => _formatter = userFormatter; - - public string Resolve(AuditEventQuery source, AuditEvent destination, string destMember, ResolutionContext context) => - (source.User.FirstName != null && source.User.LastName != null) ? _formatter.GetUserName(source.User.FirstName, source.User.LastName) : - source.AuditEvent.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : - source.AuditEvent.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : - source.AuditEvent.Initiator ?? AuditReportResource.UnknownAccount; - } -} From 342daa3d183cd7d988b1dffab156e09720e93f86 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 14:02:27 +0300 Subject: [PATCH 116/167] AuditTrail: rename to Dto, change mapping --- .../{AuditEvent.cs => AuditEventDto.cs} | 20 ++++++++++++++++- .../{LoginEvent.cs => LoginEventDto.cs} | 22 ++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) rename common/services/ASC.AuditTrail/Models/{AuditEvent.cs => AuditEventDto.cs} (73%) rename common/services/ASC.AuditTrail/Models/{LoginEvent.cs => LoginEventDto.cs} (68%) diff --git a/common/services/ASC.AuditTrail/Models/AuditEvent.cs b/common/services/ASC.AuditTrail/Models/AuditEventDto.cs similarity index 73% rename from common/services/ASC.AuditTrail/Models/AuditEvent.cs rename to common/services/ASC.AuditTrail/Models/AuditEventDto.cs index f0bf43361f..d7392eeda6 100644 --- a/common/services/ASC.AuditTrail/Models/AuditEvent.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEventDto.cs @@ -26,10 +26,15 @@ using ASC.MessagingSystem; using ASC.AuditTrail.Attributes; +using ASC.Common.Mapping; +using AutoMapper; +using ASC.Core.Common.EF; +using ASC.AuditTrail.Models.Mapping.Actions; +using ASC.Core.Common.EF.Model; namespace ASC.AuditTrail.Models { - public class AuditEvent : BaseEvent + public class AuditEventDto : BaseEvent, IMapFrom<AuditEventQuery> { public string Initiator { get; set; } @@ -47,5 +52,18 @@ namespace ASC.AuditTrail.Models [Event("TargetIdCol", 34)] public MessageTarget Target { get; set; } + + public void Mapping(Profile profile) + { + profile.CreateMap<AuditEvent, AuditEventDto>() + .ForMember(src => src.Description, opt => opt.Ignore()); + + profile.CreateMap<User, AuditEventDto>() + .ForMember(src => src.Id, opt => opt.Ignore()); + + profile.CreateMap<AuditEventQuery, AuditEventDto>() + .IncludeMembers(src => src.AuditEvent, src => src.User) + .AfterMap<AuditEventMappingAction>(); + } } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/LoginEvent.cs b/common/services/ASC.AuditTrail/Models/LoginEventDto.cs similarity index 68% rename from common/services/ASC.AuditTrail/Models/LoginEvent.cs rename to common/services/ASC.AuditTrail/Models/LoginEventDto.cs index 0529014c02..10b2111b4c 100644 --- a/common/services/ASC.AuditTrail/Models/LoginEvent.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEventDto.cs @@ -26,11 +26,31 @@ +using ASC.AuditTrail.Models.Mapping.Actions; +using ASC.Common.Mapping; +using ASC.Core.Common.EF; +using ASC.Core.Common.EF.Model; + +using AutoMapper; + namespace ASC.AuditTrail.Models { - public class LoginEvent : BaseEvent + public class LoginEventDTO : BaseEvent, IMapFrom<LoginEventQuery> { public string Login { get; set; } public int Action { get; set; } + + public void Mapping(Profile profile) + { + profile.CreateMap<LoginEvents, LoginEventDTO>() + .ForMember(src => src.Description, opt => opt.Ignore()); + + profile.CreateMap<User, LoginEventDTO>() + .ForMember(src => src.Id, opt => opt.Ignore()); + + profile.CreateMap<LoginEventQuery, LoginEventDTO>() + .IncludeMembers(src => src.LoginEvents, src => src.User) + .AfterMap<LoginEventMappingAction>(); + } } } \ No newline at end of file From 0a17af12ebbf8b1921f371c28c2ddc94ccec0915 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 14:02:49 +0300 Subject: [PATCH 117/167] AuditTrail: add mapping actions --- .../Models/Mapping/AuditEventMappingAction.cs | 49 +++++++++++++++++++ .../Models/Mapping/LoginEventMappingAction.cs | 44 +++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs diff --git a/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs b/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs new file mode 100644 index 0000000000..0ae6d098b9 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using System; + +using AutoMapper; + +using Newtonsoft.Json; +using ASC.MessagingSystem; +using ASC.Core.Users; +using ASC.AuditTrail.Mappers; + +namespace ASC.AuditTrail.Models.Mapping.Actions +{ + public class AuditEventMappingAction : IMappingAction<AuditEventQuery, AuditEventDto> + { + private MessageTarget _messageTarget; + private UserFormatter _userFormatter; + private AuditActionMapper _auditActionMapper; + + public AuditEventMappingAction( + MessageTarget messageTarget, + UserFormatter userFormatter, + AuditActionMapper auditActionMapper) + { + _messageTarget = messageTarget; + _userFormatter = userFormatter; + _auditActionMapper = auditActionMapper; + } + + public void Process(AuditEventQuery source, AuditEventDto destination, ResolutionContext context) + { + if (source.AuditEvent.Description != null) + destination.Description = JsonConvert.DeserializeObject<IList<string>>( + Convert.ToString(source.AuditEvent.Description), + new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); + + destination.Target = _messageTarget.Parse(source.AuditEvent.Target); + + destination.UserName = (source.User.FirstName != null && source.User.LastName != null) ? _userFormatter.GetUserName(source.User.FirstName, source.User.LastName) : + source.AuditEvent.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : + source.AuditEvent.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : + source.AuditEvent.Initiator ?? AuditReportResource.UnknownAccount; + + destination.ActionText = _auditActionMapper.GetActionText(destination); + destination.ActionTypeText = _auditActionMapper.GetActionTypeText(destination); + destination.Product = _auditActionMapper.GetProductText(destination); + destination.Module = _auditActionMapper.GetModuleText(destination); + } + } +} \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs b/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs new file mode 100644 index 0000000000..3c61ee6e60 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; + +using ASC.AuditTrail.Mappers; +using ASC.Core.Users; + +using AutoMapper; + +using Newtonsoft.Json; + +namespace ASC.AuditTrail.Models.Mapping.Actions +{ + public class LoginEventMappingAction : IMappingAction<LoginEventQuery, LoginEventDTO> + { + private readonly UserFormatter _userFormatter; + private readonly AuditActionMapper _auditActionMapper; + + public LoginEventMappingAction(UserFormatter userFormatter, AuditActionMapper auditActionMapper) + { + _userFormatter = userFormatter; + _auditActionMapper = auditActionMapper; + } + + public void Process(LoginEventQuery source, LoginEventDTO destination, ResolutionContext context) + { + if (source.LoginEvents.Description != null) + destination.Description = JsonConvert.DeserializeObject<IList<string>>( + source.LoginEvents.Description, + new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.Utc + }); + + destination.UserName = (!string.IsNullOrEmpty(source.User?.FirstName) && !string.IsNullOrEmpty(source.User?.LastName)) + ? _userFormatter.GetUserName(source.User.FirstName, source.User.LastName) + : !string.IsNullOrWhiteSpace(source.LoginEvents.Login) + ? source.LoginEvents.Login + : source.LoginEvents.UserId == Core.Configuration.Constants.Guest.ID + ? AuditReportResource.GuestAccount + : AuditReportResource.UnknownAccount; + + destination.ActionText = _auditActionMapper.GetActionText(destination); + } + } +} \ No newline at end of file From 0cc387a4b8db580715a9a91399730418134b4195 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 14:15:42 +0300 Subject: [PATCH 118/167] rename LoginEvents to LoginEvent --- .../EF/Context/MessagesContext.cs | 2 +- .../Audit/{LoginEvents.cs => LoginEvent.cs} | 286 +++++++++--------- .../DbSender/MessagesRepository.cs | 2 +- 3 files changed, 145 insertions(+), 145 deletions(-) rename common/ASC.Core.Common/EF/Model/Audit/{LoginEvents.cs => LoginEvent.cs} (94%) diff --git a/common/ASC.Core.Common/EF/Context/MessagesContext.cs b/common/ASC.Core.Common/EF/Context/MessagesContext.cs index 47ccadd4d4..7fafbeffdd 100644 --- a/common/ASC.Core.Common/EF/Context/MessagesContext.cs +++ b/common/ASC.Core.Common/EF/Context/MessagesContext.cs @@ -12,7 +12,7 @@ namespace ASC.Core.Common.EF.Context public class PostgreSqlMessagesContext : MessagesContext { } public class MessagesContext : BaseDbContext { - public DbSet<LoginEvents> LoginEvents { get; set; } + public DbSet<LoginEvent> LoginEvents { get; set; } public DbSet<User> Users { get; set; } protected override Dictionary<Provider, Func<BaseDbContext>> ProviderContext diff --git a/common/ASC.Core.Common/EF/Model/Audit/LoginEvents.cs b/common/ASC.Core.Common/EF/Model/Audit/LoginEvent.cs similarity index 94% rename from common/ASC.Core.Common/EF/Model/Audit/LoginEvents.cs rename to common/ASC.Core.Common/EF/Model/Audit/LoginEvent.cs index 780087c8a1..13f6be06fd 100644 --- a/common/ASC.Core.Common/EF/Model/Audit/LoginEvents.cs +++ b/common/ASC.Core.Common/EF/Model/Audit/LoginEvent.cs @@ -1,143 +1,143 @@ - -using Microsoft.EntityFrameworkCore; - -namespace ASC.Core.Common.EF.Model -{ - public class LoginEvents : MessageEvent - { - public string Login { get; set; } - } - public static class LoginEventsExtension - { - public static ModelBuilderWrapper AddLoginEvents(this ModelBuilderWrapper modelBuilder) - { - modelBuilder - .Add(MySqlAddLoginEvents, Provider.MySql) - .Add(PgSqlAddLoginEvents, Provider.PostgreSql); - return modelBuilder; - } - public static void MySqlAddLoginEvents(this ModelBuilder modelBuilder) - { - modelBuilder.Entity<LoginEvents>(entity => - { - entity.ToTable("login_events"); - - entity.HasIndex(e => e.Date) - .HasDatabaseName("date"); - - entity.HasIndex(e => new { e.TenantId, e.UserId }) - .HasDatabaseName("tenant_id"); - - entity.Property(e => e.Id).HasColumnName("id"); - - entity.Property(e => e.Action).HasColumnName("action"); - - entity.Property(e => e.Browser) - .HasColumnName("browser") - .HasColumnType("varchar(200)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Date) - .HasColumnName("date") - .HasColumnType("datetime"); - - entity.Property(e => e.Description) - .HasColumnName("description") - .HasColumnType("varchar(500)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Ip) - .HasColumnName("ip") - .HasColumnType("varchar(50)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Login) - .HasColumnName("login") - .HasColumnType("varchar(200)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Page) - .HasColumnName("page") - .HasColumnType("varchar(300)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Platform) - .HasColumnName("platform") - .HasColumnType("varchar(200)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.TenantId).HasColumnName("tenant_id"); - - entity.Property(e => e.UserId) - .IsRequired() - .HasColumnName("user_id") - .HasColumnType("char(38)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - }); - } - public static void PgSqlAddLoginEvents(this ModelBuilder modelBuilder) - { - modelBuilder.Entity<LoginEvents>(entity => - { - entity.ToTable("login_events", "onlyoffice"); - - entity.HasIndex(e => e.Date) - .HasDatabaseName("date_login_events"); - - entity.HasIndex(e => new { e.UserId, e.TenantId }) - .HasDatabaseName("tenant_id_login_events"); - - entity.Property(e => e.Id).HasColumnName("id"); - - entity.Property(e => e.Action).HasColumnName("action"); - - entity.Property(e => e.Browser) - .HasColumnName("browser") - .HasMaxLength(200) - .HasDefaultValueSql("NULL::character varying"); - - entity.Property(e => e.Date).HasColumnName("date"); - - entity.Property(e => e.Description) - .HasColumnName("description") - .HasMaxLength(500) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.Ip) - .HasColumnName("ip") - .HasMaxLength(50) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.Login) - .HasColumnName("login") - .HasMaxLength(200) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.Page) - .HasColumnName("page") - .HasMaxLength(300) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.Platform) - .HasColumnName("platform") - .HasMaxLength(200) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.TenantId).HasColumnName("tenant_id"); - - entity.Property(e => e.UserId) - .IsRequired() - .HasColumnName("user_id") - .HasMaxLength(38) - .IsFixedLength(); - }); - } - } -} + +using Microsoft.EntityFrameworkCore; + +namespace ASC.Core.Common.EF.Model +{ + public class LoginEvent : MessageEvent + { + public string Login { get; set; } + } + public static class LoginEventsExtension + { + public static ModelBuilderWrapper AddLoginEvents(this ModelBuilderWrapper modelBuilder) + { + modelBuilder + .Add(MySqlAddLoginEvents, Provider.MySql) + .Add(PgSqlAddLoginEvents, Provider.PostgreSql); + return modelBuilder; + } + public static void MySqlAddLoginEvents(this ModelBuilder modelBuilder) + { + modelBuilder.Entity<LoginEvent>(entity => + { + entity.ToTable("login_events"); + + entity.HasIndex(e => e.Date) + .HasDatabaseName("date"); + + entity.HasIndex(e => new { e.TenantId, e.UserId }) + .HasDatabaseName("tenant_id"); + + entity.Property(e => e.Id).HasColumnName("id"); + + entity.Property(e => e.Action).HasColumnName("action"); + + entity.Property(e => e.Browser) + .HasColumnName("browser") + .HasColumnType("varchar(200)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Date) + .HasColumnName("date") + .HasColumnType("datetime"); + + entity.Property(e => e.Description) + .HasColumnName("description") + .HasColumnType("varchar(500)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Ip) + .HasColumnName("ip") + .HasColumnType("varchar(50)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Login) + .HasColumnName("login") + .HasColumnType("varchar(200)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Page) + .HasColumnName("page") + .HasColumnType("varchar(300)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Platform) + .HasColumnName("platform") + .HasColumnType("varchar(200)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.TenantId).HasColumnName("tenant_id"); + + entity.Property(e => e.UserId) + .IsRequired() + .HasColumnName("user_id") + .HasColumnType("char(38)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + }); + } + public static void PgSqlAddLoginEvents(this ModelBuilder modelBuilder) + { + modelBuilder.Entity<LoginEvent>(entity => + { + entity.ToTable("login_events", "onlyoffice"); + + entity.HasIndex(e => e.Date) + .HasDatabaseName("date_login_events"); + + entity.HasIndex(e => new { e.UserId, e.TenantId }) + .HasDatabaseName("tenant_id_login_events"); + + entity.Property(e => e.Id).HasColumnName("id"); + + entity.Property(e => e.Action).HasColumnName("action"); + + entity.Property(e => e.Browser) + .HasColumnName("browser") + .HasMaxLength(200) + .HasDefaultValueSql("NULL::character varying"); + + entity.Property(e => e.Date).HasColumnName("date"); + + entity.Property(e => e.Description) + .HasColumnName("description") + .HasMaxLength(500) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.Ip) + .HasColumnName("ip") + .HasMaxLength(50) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.Login) + .HasColumnName("login") + .HasMaxLength(200) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.Page) + .HasColumnName("page") + .HasMaxLength(300) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.Platform) + .HasColumnName("platform") + .HasMaxLength(200) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.TenantId).HasColumnName("tenant_id"); + + entity.Property(e => e.UserId) + .IsRequired() + .HasColumnName("user_id") + .HasMaxLength(38) + .IsFixedLength(); + }); + } + } +} diff --git a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs index 32bf2ca09b..746e3327c8 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -168,7 +168,7 @@ namespace ASC.MessagingSystem.DbSender private static void AddLoginEvent(EventMessage message, MessagesContext dbContext) { - var le = new LoginEvents + var le = new LoginEvent { Ip = message.IP, Login = message.Initiator, From fdc4652edb0e7a44d1b2a09cdc71ecbf556a9c5e Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 14:16:34 +0300 Subject: [PATCH 119/167] AuditTrail: used file-scope namespaces --- .../Attributes/EventAttribute.cs | 25 +- .../ASC.AuditTrail/AuditReportCreator.cs | 95 ++++---- .../Mappers/AuditActionMapper.cs | 229 +++++++++--------- .../ASC.AuditTrail/Mappers/CrmActionMapper.cs | 23 +- .../Mappers/DocumentsActionMapper.cs | 19 +- .../Mappers/LoginActionMapper.cs | 19 +- .../ASC.AuditTrail/Mappers/MessageMaps.cs | 89 ++++--- .../Mappers/OthersActionMapper.cs | 19 +- .../Mappers/PeopleActionMapper.cs | 19 +- .../Mappers/ProjectsActionMapper.cs | 23 +- .../Mappers/SettingsActionMapper.cs | 19 +- .../ASC.AuditTrail/Models/AuditEventDto.cs | 57 +++-- .../ASC.AuditTrail/Models/AuditEventQuery.cs | 12 +- .../ASC.AuditTrail/Models/BaseEvent.cs | 87 ++++--- .../ASC.AuditTrail/Models/LoginEventDto.cs | 29 ++- .../ASC.AuditTrail/Models/LoginEventQuery.cs | 13 +- .../Models/Mapping/AuditEventMappingAction.cs | 61 +++-- .../Models/Mapping/LoginEventMappingAction.cs | 55 +++-- .../Repositories/AuditEventsRepository.cs | 77 +++--- .../Repositories/LoginEventsRepository.cs | 89 ++++--- 20 files changed, 520 insertions(+), 539 deletions(-) diff --git a/common/services/ASC.AuditTrail/Attributes/EventAttribute.cs b/common/services/ASC.AuditTrail/Attributes/EventAttribute.cs index a805f832fd..a1c11e4714 100644 --- a/common/services/ASC.AuditTrail/Attributes/EventAttribute.cs +++ b/common/services/ASC.AuditTrail/Attributes/EventAttribute.cs @@ -1,17 +1,16 @@ using System; -namespace ASC.AuditTrail.Attributes -{ - [AttributeUsage(AttributeTargets.Property)] - public class EventAttribute : Attribute - { - public string Resource { get; private set; } - public int Order { get; private set; } +namespace ASC.AuditTrail.Attributes; - public EventAttribute(string resource, int order = 0) - { - Resource = resource; - Order = order; - } +[AttributeUsage(AttributeTargets.Property)] +public class EventAttribute : Attribute +{ + public string Resource { get; private set; } + public int Order { get; private set; } + + public EventAttribute(string resource, int order = 0) + { + Resource = resource; + Order = order; } -} +} \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/AuditReportCreator.cs b/common/services/ASC.AuditTrail/AuditReportCreator.cs index 5a1fd72140..d85ee1ac5c 100644 --- a/common/services/ASC.AuditTrail/AuditReportCreator.cs +++ b/common/services/ASC.AuditTrail/AuditReportCreator.cs @@ -43,58 +43,57 @@ using CsvHelper; using Microsoft.Extensions.Options; -namespace ASC.AuditTrail +namespace ASC.AuditTrail; + +[Scope] +public class AuditReportCreator { - [Scope] - public class AuditReportCreator - { - private readonly GlobalFolderHelper _globalFolderHelper; - private readonly FileUploader _fileUploader; - private readonly FilesLinkUtility _filesLinkUtility; - private readonly CommonLinkUtility _commonLinkUtility; - private readonly ILog _logger; - - public AuditReportCreator( - GlobalFolderHelper globalFolderHelper, - IOptionsMonitor<ILog> options, - FileUploader fileUploader, - FilesLinkUtility filesLinkUtility, - CommonLinkUtility commonLinkUtility) - { - _globalFolderHelper = globalFolderHelper; - _logger = options.CurrentValue; - _fileUploader = fileUploader; - _filesLinkUtility = filesLinkUtility; - _commonLinkUtility = commonLinkUtility; - } - - public string CreateCsvReport<TEvent>(IEnumerable<TEvent> events, string reportName) where TEvent : BaseEvent - { - try - { - using var stream = new MemoryStream(); - using var writer = new StreamWriter(stream, Encoding.UTF8); - using var csv = new CsvWriter(writer, CultureInfo.CurrentCulture); + private readonly GlobalFolderHelper _globalFolderHelper; + private readonly FileUploader _fileUploader; + private readonly FilesLinkUtility _filesLinkUtility; + private readonly CommonLinkUtility _commonLinkUtility; + private readonly ILog _logger; - csv.Configuration.RegisterClassMap(new BaseEventMap<TEvent>()); + public AuditReportCreator( + GlobalFolderHelper globalFolderHelper, + IOptionsMonitor<ILog> options, + FileUploader fileUploader, + FilesLinkUtility filesLinkUtility, + CommonLinkUtility commonLinkUtility) + { + _globalFolderHelper = globalFolderHelper; + _logger = options.CurrentValue; + _fileUploader = fileUploader; + _filesLinkUtility = filesLinkUtility; + _commonLinkUtility = commonLinkUtility; + } - csv.WriteHeader<TEvent>(); - csv.NextRecord(); - csv.WriteRecords(events); - writer.Flush(); + public string CreateCsvReport<TEvent>(IEnumerable<TEvent> events, string reportName) where TEvent : BaseEvent + { + try + { + using var stream = new MemoryStream(); + using var writer = new StreamWriter(stream, Encoding.UTF8); + using var csv = new CsvWriter(writer, CultureInfo.CurrentCulture); - var file = _fileUploader.Exec(_globalFolderHelper.FolderMy, reportName, stream.Length, stream, true); - var fileUrl = _commonLinkUtility.GetFullAbsolutePath(_filesLinkUtility.GetFileWebEditorUrl(file.ID)); + csv.Configuration.RegisterClassMap(new BaseEventMap<TEvent>()); - fileUrl += string.Format("&options={{\"codePage\":{0}}}", Encoding.UTF8.CodePage); + csv.WriteHeader<TEvent>(); + csv.NextRecord(); + csv.WriteRecords(events); + writer.Flush(); - return fileUrl; - } - catch (Exception ex) - { - _logger.Error("Error while generating login report: " + ex); - throw; - } - } - } + var file = _fileUploader.Exec(_globalFolderHelper.FolderMy, reportName, stream.Length, stream, true); + var fileUrl = _commonLinkUtility.GetFullAbsolutePath(_filesLinkUtility.GetFileWebEditorUrl(file.ID)); + + fileUrl += string.Format("&options={{\"codePage\":{0}}}", Encoding.UTF8.CodePage); + + return fileUrl; + } + catch (Exception ex) + { + _logger.Error("Error while generating login report: " + ex); + throw; + } + } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs index bd76781d76..87ec97ed4c 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -35,120 +35,119 @@ using ASC.MessagingSystem; using Microsoft.Extensions.Options; -namespace ASC.AuditTrail.Mappers +namespace ASC.AuditTrail.Mappers; + +[Singletone] +public class AuditActionMapper { - [Singletone] - public class AuditActionMapper - { - private readonly Dictionary<MessageAction, MessageMaps> _actions; - private readonly ILog _logger; - - public AuditActionMapper(IOptionsMonitor<ILog> options) - { - _actions = new Dictionary<MessageAction, MessageMaps>(); - _logger = options.CurrentValue; - - _actions = _actions - .Union(LoginActionsMapper.GetMaps()) - .Union(ProjectsActionsMapper.GetMaps()) - .Union(CrmActionMapper.GetMaps()) - .Union(PeopleActionMapper.GetMaps()) - .Union(DocumentsActionMapper.GetMaps()) - .Union(SettingsActionsMapper.GetMaps()) - .Union(OthersActionsMapper.GetMaps()) - .ToDictionary(x => x.Key, x => x.Value); - } - - public string GetActionText(AuditEvent evt) - { - var action = (MessageAction)evt.Action; - if (!_actions.ContainsKey(action)) - { - _logger.Error(string.Format("There is no action text for \"{0}\" type of event", action)); - - return string.Empty; - } - - try - { - var actionText = _actions[(MessageAction)evt.Action].GetActionText(); - - if (evt.Description == null || !evt.Description.Any()) return actionText; - - var description = evt.Description - .Select(t => t.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) - .Select(split => string.Join(", ", split.Select(ToLimitedText))).ToArray(); - - - return string.Format(actionText, description); - } - catch - { - //log.Error(string.Format("Error while building action text for \"{0}\" type of event", action)); - return string.Empty; - } - } - - public string GetActionText(LoginEvent evt) - { - var action = (MessageAction)evt.Action; - if (!_actions.ContainsKey(action)) - { - //log.Error(string.Format("There is no action text for \"{0}\" type of event", action)); - return string.Empty; - } - - try - { - var actionText = _actions[(MessageAction)evt.Action].GetActionText(); - - if (evt.Description == null || !evt.Description.Any()) return actionText; - - var description = evt.Description - .Select(t => t.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) - .Select(split => string.Join(", ", split.Select(ToLimitedText))).ToArray(); - - return string.Format(actionText, description); - } - catch - { - //log.Error(string.Format("Error while building action text for \"{0}\" type of event", action)); - return string.Empty; - } - } - - public string GetActionTypeText(AuditEvent evt) - { - var action = (MessageAction)evt.Action; - - return !_actions.ContainsKey(action) - ? string.Empty - : _actions[(MessageAction)evt.Action].GetActionTypeText(); - } - - public string GetProductText(AuditEvent evt) - { - var action = (MessageAction)evt.Action; - - return !_actions.ContainsKey(action) - ? string.Empty - : _actions[(MessageAction)evt.Action].GetProduct(); - } - - public string GetModuleText(AuditEvent evt) - { - var action = (MessageAction)evt.Action; - - return !_actions.ContainsKey(action) - ? string.Empty - : _actions[(MessageAction)evt.Action].GetModule(); - } - - private string ToLimitedText(string text) - { - if (text == null) return null; - - return text.Length < 50 ? text : string.Format("{0}...", text.Substring(0, 47)); - } - } + private readonly Dictionary<MessageAction, MessageMaps> _actions; + private readonly ILog _logger; + + public AuditActionMapper(IOptionsMonitor<ILog> options) + { + _actions = new Dictionary<MessageAction, MessageMaps>(); + _logger = options.CurrentValue; + + _actions = _actions + .Union(LoginActionsMapper.GetMaps()) + .Union(ProjectsActionsMapper.GetMaps()) + .Union(CrmActionMapper.GetMaps()) + .Union(PeopleActionMapper.GetMaps()) + .Union(DocumentsActionMapper.GetMaps()) + .Union(SettingsActionsMapper.GetMaps()) + .Union(OthersActionsMapper.GetMaps()) + .ToDictionary(x => x.Key, x => x.Value); + } + + public string GetActionText(AuditEventDto evt) + { + var action = (MessageAction)evt.Action; + if (!_actions.ContainsKey(action)) + { + _logger.Error(string.Format("There is no action text for \"{0}\" type of event", action)); + + return string.Empty; + } + + try + { + var actionText = _actions[(MessageAction)evt.Action].GetActionText(); + + if (evt.Description == null || !evt.Description.Any()) return actionText; + + var description = evt.Description + .Select(t => t.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + .Select(split => string.Join(", ", split.Select(ToLimitedText))).ToArray(); + + + return string.Format(actionText, description); + } + catch + { + //log.Error(string.Format("Error while building action text for \"{0}\" type of event", action)); + return string.Empty; + } + } + + public string GetActionText(LoginEventDTO evt) + { + var action = (MessageAction)evt.Action; + if (!_actions.ContainsKey(action)) + { + //log.Error(string.Format("There is no action text for \"{0}\" type of event", action)); + return string.Empty; + } + + try + { + var actionText = _actions[(MessageAction)evt.Action].GetActionText(); + + if (evt.Description == null || !evt.Description.Any()) return actionText; + + var description = evt.Description + .Select(t => t.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + .Select(split => string.Join(", ", split.Select(ToLimitedText))).ToArray(); + + return string.Format(actionText, description); + } + catch + { + //log.Error(string.Format("Error while building action text for \"{0}\" type of event", action)); + return string.Empty; + } + } + + public string GetActionTypeText(AuditEventDto evt) + { + var action = (MessageAction)evt.Action; + + return !_actions.ContainsKey(action) + ? string.Empty + : _actions[(MessageAction)evt.Action].GetActionTypeText(); + } + + public string GetProductText(AuditEventDto evt) + { + var action = (MessageAction)evt.Action; + + return !_actions.ContainsKey(action) + ? string.Empty + : _actions[(MessageAction)evt.Action].GetProduct(); + } + + public string GetModuleText(AuditEventDto evt) + { + var action = (MessageAction)evt.Action; + + return !_actions.ContainsKey(action) + ? string.Empty + : _actions[(MessageAction)evt.Action].GetModule(); + } + + private string ToLimitedText(string text) + { + if (text == null) return null; + + return text.Length < 50 ? text : string.Format("{0}...", text.Substring(0, 47)); + } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs index 27401f3b2b..0d896fe156 100644 --- a/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs @@ -30,13 +30,13 @@ using System.Collections.Generic; using ASC.MessagingSystem; -namespace ASC.AuditTrail.Mappers -{ - internal class CrmActionMapper - { - public static Dictionary<MessageAction, MessageMaps> GetMaps() => - new Dictionary<MessageAction, MessageMaps> - { +namespace ASC.AuditTrail.Mappers; + +internal class CrmActionMapper +{ + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { #region companies { @@ -1618,9 +1618,8 @@ namespace ASC.AuditTrail.Mappers ProductResourceName = "CrmProduct", ModuleResourceName = "CasesModule" } - }, - - #endregion - }; - } + }, + + #endregion + }; } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs index 05c3cd6dd0..ebc6ee2a38 100644 --- a/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs @@ -29,13 +29,13 @@ using System.Collections.Generic; using ASC.MessagingSystem; -namespace ASC.AuditTrail.Mappers -{ - internal class DocumentsActionMapper - { - public static Dictionary<MessageAction, MessageMaps> GetMaps() => - new Dictionary<MessageAction, MessageMaps> - { +namespace ASC.AuditTrail.Mappers; + +internal class DocumentsActionMapper +{ + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { { MessageAction.FileRenamed, new MessageMaps { @@ -413,7 +413,6 @@ namespace ASC.AuditTrail.Mappers ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } - }, - }; - } + }, + }; } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs index 877faf6fa1..b1b4a3d6e5 100644 --- a/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs @@ -30,13 +30,13 @@ using System.Collections.Generic; using ASC.MessagingSystem; -namespace ASC.AuditTrail.Mappers -{ - internal class LoginActionsMapper - { - public static Dictionary<MessageAction, MessageMaps> GetMaps() => - new Dictionary<MessageAction, MessageMaps> - { +namespace ASC.AuditTrail.Mappers; + +internal class LoginActionsMapper +{ + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { { MessageAction.LoginSuccess, new MessageMaps { ActionTextResourceName = "LoginSuccess"} }, { MessageAction.LoginSuccessViaSocialAccount, new MessageMaps { ActionTextResourceName = "LoginSuccessSocialAccount"} }, { MessageAction.LoginSuccessViaSocialApp, new MessageMaps { ActionTextResourceName = "LoginSuccessSocialApp"} }, @@ -63,7 +63,6 @@ namespace ASC.AuditTrail.Mappers { MessageAction.LoginFailRecaptcha, new MessageMaps { ActionTextResourceName = "LoginFailRecaptcha" } }, { MessageAction.Logout, new MessageMaps { ActionTextResourceName = "Logout" } }, { MessageAction.SessionStarted, new MessageMaps { ActionTextResourceName = "SessionStarted" } }, - { MessageAction.SessionCompleted, new MessageMaps { ActionTextResourceName = "SessionCompleted" } } - }; - } + { MessageAction.SessionCompleted, new MessageMaps { ActionTextResourceName = "SessionCompleted" } } + }; } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/MessageMaps.cs b/common/services/ASC.AuditTrail/Mappers/MessageMaps.cs index dd157c8824..d909aa19da 100644 --- a/common/services/ASC.AuditTrail/Mappers/MessageMaps.cs +++ b/common/services/ASC.AuditTrail/Mappers/MessageMaps.cs @@ -28,61 +28,60 @@ -namespace ASC.AuditTrail.Mappers +namespace ASC.AuditTrail.Mappers; + +internal class MessageMaps { - internal class MessageMaps + public string ActionTypeTextResourceName { get; set; } + public string ActionTextResourceName { get; set; } + public string ProductResourceName { get; set; } + public string ModuleResourceName { get; set; } + + public string GetActionTypeText() { - public string ActionTypeTextResourceName { get; set; } - public string ActionTextResourceName { get; set; } - public string ProductResourceName { get; set; } - public string ModuleResourceName { get; set; } - - public string GetActionTypeText() + try { - try - { - return AuditReportResource.ResourceManager.GetString(ActionTypeTextResourceName); - } - catch - { - return null; - } + return AuditReportResource.ResourceManager.GetString(ActionTypeTextResourceName); } - - public string GetActionText() + catch { - try - { - return AuditReportResource.ResourceManager.GetString(ActionTextResourceName); - } - catch - { - return null; - } + return null; } + } - public string GetProduct() + public string GetActionText() + { + try { - try - { - return AuditReportResource.ResourceManager.GetString(ProductResourceName); - } - catch - { - return null; - } + return AuditReportResource.ResourceManager.GetString(ActionTextResourceName); } - - public string GetModule() + catch { - try - { - return AuditReportResource.ResourceManager.GetString(ModuleResourceName); - } - catch - { - return null; - } + return null; + } + } + + public string GetProduct() + { + try + { + return AuditReportResource.ResourceManager.GetString(ProductResourceName); + } + catch + { + return null; + } + } + + public string GetModule() + { + try + { + return AuditReportResource.ResourceManager.GetString(ModuleResourceName); + } + catch + { + return null; } } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs index 6e4524f42d..45ff346220 100644 --- a/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs @@ -30,13 +30,13 @@ using System.Collections.Generic; using ASC.MessagingSystem; -namespace ASC.AuditTrail.Mappers -{ - internal class OthersActionsMapper - { - public static Dictionary<MessageAction, MessageMaps> GetMaps() => - new Dictionary<MessageAction, MessageMaps> - { +namespace ASC.AuditTrail.Mappers; + +internal class OthersActionsMapper +{ + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { { MessageAction.ContactAdminMailSent, new MessageMaps { @@ -44,7 +44,6 @@ namespace ASC.AuditTrail.Mappers ActionTextResourceName = "ContactAdminMailSent", ProductResourceName = "OthersProduct" } - } - }; - } + } + }; } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs index 286b6367e3..b7c561121d 100644 --- a/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs @@ -30,13 +30,13 @@ using System.Collections.Generic; using ASC.MessagingSystem; -namespace ASC.AuditTrail.Mappers -{ - internal class PeopleActionMapper - { - public static Dictionary<MessageAction, MessageMaps> GetMaps() => - new Dictionary<MessageAction, MessageMaps> - { +namespace ASC.AuditTrail.Mappers; + +internal class PeopleActionMapper +{ + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { { MessageAction.UserCreated, new MessageMaps { @@ -351,7 +351,6 @@ namespace ASC.AuditTrail.Mappers ProductResourceName = "PeopleProduct", ModuleResourceName = "UsersModule" } - } - }; - } + } + }; } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs index 97ba08b181..9f0ce87461 100644 --- a/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs @@ -29,13 +29,13 @@ using System.Collections.Generic; using ASC.MessagingSystem; -namespace ASC.AuditTrail.Mappers -{ - internal class ProjectsActionsMapper - { - public static Dictionary<MessageAction, MessageMaps> GetMaps() => - new Dictionary<MessageAction, MessageMaps> - { +namespace ASC.AuditTrail.Mappers; + +internal class ProjectsActionsMapper +{ + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { #region projects { @@ -604,9 +604,8 @@ namespace ASC.AuditTrail.Mappers ProductResourceName = "ProjectsProduct", ModuleResourceName = "ProjectsModule" } - }, - - #endregion - }; - } + }, + + #endregion + }; } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs index e347d8ba7f..a363a73190 100644 --- a/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs @@ -29,13 +29,13 @@ using System.Collections.Generic; using ASC.MessagingSystem; -namespace ASC.AuditTrail.Mappers -{ - internal class SettingsActionsMapper - { - public static Dictionary<MessageAction, MessageMaps> GetMaps() => - new Dictionary<MessageAction, MessageMaps> - { +namespace ASC.AuditTrail.Mappers; + +internal class SettingsActionsMapper +{ + public static Dictionary<MessageAction, MessageMaps> GetMaps() => + new Dictionary<MessageAction, MessageMaps> + { { MessageAction.LanguageSettingsUpdated, new MessageMaps { @@ -476,7 +476,6 @@ namespace ASC.AuditTrail.Mappers ProductResourceName = "SettingsProduct", ModuleResourceName = "ProductsModule" } - } - }; - } + } + }; } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/AuditEventDto.cs b/common/services/ASC.AuditTrail/Models/AuditEventDto.cs index d7392eeda6..22cb1de1c0 100644 --- a/common/services/ASC.AuditTrail/Models/AuditEventDto.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEventDto.cs @@ -32,38 +32,37 @@ using ASC.Core.Common.EF; using ASC.AuditTrail.Models.Mapping.Actions; using ASC.Core.Common.EF.Model; -namespace ASC.AuditTrail.Models +namespace ASC.AuditTrail.Models; + +public class AuditEventDto : BaseEvent, IMapFrom<AuditEventQuery> { - public class AuditEventDto : BaseEvent, IMapFrom<AuditEventQuery> + public string Initiator { get; set; } + + [Event("ActionIdCol", 33)] + public int Action { get; set; } + + [Event("ActionTypeCol", 30)] + public string ActionTypeText { get; set; } + + [Event("ProductCol", 31)] + public string Product { get; set; } + + [Event("ModuleCol", 32)] + public string Module { get; set; } + + [Event("TargetIdCol", 34)] + public MessageTarget Target { get; set; } + + public void Mapping(Profile profile) { - public string Initiator { get; set; } + profile.CreateMap<AuditEvent, AuditEventDto>() + .ForMember(src => src.Description, opt => opt.Ignore()); - [Event("ActionIdCol", 33)] - public int Action { get; set; } + profile.CreateMap<User, AuditEventDto>() + .ForMember(src => src.Id, opt => opt.Ignore()); - [Event("ActionTypeCol", 30)] - public string ActionTypeText { get; set; } - - [Event("ProductCol", 31)] - public string Product { get; set; } - - [Event("ModuleCol", 32)] - public string Module { get; set; } - - [Event("TargetIdCol", 34)] - public MessageTarget Target { get; set; } - - public void Mapping(Profile profile) - { - profile.CreateMap<AuditEvent, AuditEventDto>() - .ForMember(src => src.Description, opt => opt.Ignore()); - - profile.CreateMap<User, AuditEventDto>() - .ForMember(src => src.Id, opt => opt.Ignore()); - - profile.CreateMap<AuditEventQuery, AuditEventDto>() - .IncludeMembers(src => src.AuditEvent, src => src.User) - .AfterMap<AuditEventMappingAction>(); - } + profile.CreateMap<AuditEventQuery, AuditEventDto>() + .IncludeMembers(src => src.AuditEvent, src => src.User) + .AfterMap<AuditEventMappingAction>(); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs b/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs index 766d771bed..126ade721d 100644 --- a/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs @@ -1,10 +1,10 @@ using ASC.Core.Common.EF; +using ASC.Core.Common.EF.Model; -namespace ASC.AuditTrail.Models +namespace ASC.AuditTrail.Models; + +public class AuditEventQuery { - public class AuditEventQuery - { - public Core.Common.EF.Model.AuditEvent AuditEvent { get; set; } - public User User { get; set; } - } + public AuditEvent AuditEvent { get; set; } + public User User { get; set; } } diff --git a/common/services/ASC.AuditTrail/Models/BaseEvent.cs b/common/services/ASC.AuditTrail/Models/BaseEvent.cs index 98f8e441ba..a061f048f0 100644 --- a/common/services/ASC.AuditTrail/Models/BaseEvent.cs +++ b/common/services/ASC.AuditTrail/Models/BaseEvent.cs @@ -35,53 +35,52 @@ using ASC.AuditTrail.Attributes; using CsvHelper.Configuration; -namespace ASC.AuditTrail.Models +namespace ASC.AuditTrail.Models; + +public class BaseEvent { - public class BaseEvent + public int Id { get; set; } + public int TenantId { get; set; } + public Guid UserId { get; set; } + public bool Mobile { get; set; } + public IList<string> Description { get; set; } + + [Event("IpCol")] + public string Ip { get; set; } + + [Event("BrowserCol")] + public string Browser { get; set; } + + [Event("PlatformCol")] + public string Platform { get; set; } + + [Event("DateCol")] + public DateTime Date { get; set; } + + [Event("UserCol")] + public string UserName { get; set; } + + [Event("PageCol")] + public string Page { get; set; } + + [Event("ActionCol")] + public string ActionText { get; set; } +} + +internal class BaseEventMap<T> : ClassMap<T> where T : BaseEvent +{ + public BaseEventMap() { - public int Id { get; set; } - public int TenantId { get; set; } - public Guid UserId { get; set; } - public bool Mobile { get; set; } - public IList<string> Description { get; set; } + var eventType = typeof(T); + var eventProps = eventType + .GetProperties() + .Where(r => r.GetCustomAttribute<EventAttribute>() != null) + .OrderBy(r => r.GetCustomAttribute<EventAttribute>().Order); - [Event("IpCol")] - public string Ip { get; set; } - - [Event("BrowserCol")] - public string Browser { get; set; } - - [Event("PlatformCol")] - public string Platform { get; set; } - - [Event("DateCol")] - public DateTime Date { get; set; } - - [Event("UserCol")] - public string UserName { get; set; } - - [Event("PageCol")] - public string Page { get; set; } - - [Event("ActionCol")] - public string ActionText { get; set; } - } - - internal class BaseEventMap<T> : ClassMap<T> where T : BaseEvent - { - public BaseEventMap() + foreach (var prop in eventProps) { - var eventType = typeof(T); - var eventProps = eventType - .GetProperties() - .Where(r => r.GetCustomAttribute<EventAttribute>() != null) - .OrderBy(r=> r.GetCustomAttribute<EventAttribute>().Order); - - foreach (var prop in eventProps) - { - var attr = prop.GetCustomAttribute<EventAttribute>().Resource; - Map(eventType, prop).Name(AuditReportResource.ResourceManager.GetString(attr)); - } + var attr = prop.GetCustomAttribute<EventAttribute>().Resource; + Map(eventType, prop).Name(AuditReportResource.ResourceManager.GetString(attr)); } } -} +} \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/LoginEventDto.cs b/common/services/ASC.AuditTrail/Models/LoginEventDto.cs index 10b2111b4c..2f87ee377e 100644 --- a/common/services/ASC.AuditTrail/Models/LoginEventDto.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEventDto.cs @@ -33,24 +33,23 @@ using ASC.Core.Common.EF.Model; using AutoMapper; -namespace ASC.AuditTrail.Models +namespace ASC.AuditTrail.Models; + +public class LoginEventDTO : BaseEvent, IMapFrom<LoginEventQuery> { - public class LoginEventDTO : BaseEvent, IMapFrom<LoginEventQuery> + public string Login { get; set; } + public int Action { get; set; } + + public void Mapping(Profile profile) { - public string Login { get; set; } - public int Action { get; set; } + profile.CreateMap<LoginEvent, LoginEventDTO>() + .ForMember(src => src.Description, opt => opt.Ignore()); - public void Mapping(Profile profile) - { - profile.CreateMap<LoginEvents, LoginEventDTO>() - .ForMember(src => src.Description, opt => opt.Ignore()); + profile.CreateMap<User, LoginEventDTO>() + .ForMember(src => src.Id, opt => opt.Ignore()); - profile.CreateMap<User, LoginEventDTO>() - .ForMember(src => src.Id, opt => opt.Ignore()); - - profile.CreateMap<LoginEventQuery, LoginEventDTO>() - .IncludeMembers(src => src.LoginEvents, src => src.User) - .AfterMap<LoginEventMappingAction>(); - } + profile.CreateMap<LoginEventQuery, LoginEventDTO>() + .IncludeMembers(src => src.LoginEvents, src => src.User) + .AfterMap<LoginEventMappingAction>(); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs b/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs index 778d35e93b..44a73114b3 100644 --- a/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs @@ -1,11 +1,10 @@ using ASC.Core.Common.EF; using ASC.Core.Common.EF.Model; -namespace ASC.AuditTrail.Models +namespace ASC.AuditTrail.Models; + +public class LoginEventQuery { - public class LoginEventQuery - { - public LoginEvents LoginEvents { get; set; } - public User User { get; set; } - } -} + public LoginEvent LoginEvents { get; set; } + public User User { get; set; } +} \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs b/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs index 0ae6d098b9..7a7caf6eb8 100644 --- a/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs +++ b/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs @@ -8,42 +8,41 @@ using ASC.MessagingSystem; using ASC.Core.Users; using ASC.AuditTrail.Mappers; -namespace ASC.AuditTrail.Models.Mapping.Actions +namespace ASC.AuditTrail.Models.Mapping.Actions; + +public class AuditEventMappingAction : IMappingAction<AuditEventQuery, AuditEventDto> { - public class AuditEventMappingAction : IMappingAction<AuditEventQuery, AuditEventDto> + private MessageTarget _messageTarget; + private UserFormatter _userFormatter; + private AuditActionMapper _auditActionMapper; + + public AuditEventMappingAction( + MessageTarget messageTarget, + UserFormatter userFormatter, + AuditActionMapper auditActionMapper) { - private MessageTarget _messageTarget; - private UserFormatter _userFormatter; - private AuditActionMapper _auditActionMapper; + _messageTarget = messageTarget; + _userFormatter = userFormatter; + _auditActionMapper = auditActionMapper; + } - public AuditEventMappingAction( - MessageTarget messageTarget, - UserFormatter userFormatter, - AuditActionMapper auditActionMapper) - { - _messageTarget = messageTarget; - _userFormatter = userFormatter; - _auditActionMapper = auditActionMapper; - } + public void Process(AuditEventQuery source, AuditEventDto destination, ResolutionContext context) + { + if (source.AuditEvent.Description != null) + destination.Description = JsonConvert.DeserializeObject<IList<string>>( + Convert.ToString(source.AuditEvent.Description), + new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); - public void Process(AuditEventQuery source, AuditEventDto destination, ResolutionContext context) - { - if (source.AuditEvent.Description != null) - destination.Description = JsonConvert.DeserializeObject<IList<string>>( - Convert.ToString(source.AuditEvent.Description), - new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); + destination.Target = _messageTarget.Parse(source.AuditEvent.Target); - destination.Target = _messageTarget.Parse(source.AuditEvent.Target); + destination.UserName = (source.User.FirstName != null && source.User.LastName != null) ? _userFormatter.GetUserName(source.User.FirstName, source.User.LastName) : + source.AuditEvent.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : + source.AuditEvent.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : + source.AuditEvent.Initiator ?? AuditReportResource.UnknownAccount; - destination.UserName = (source.User.FirstName != null && source.User.LastName != null) ? _userFormatter.GetUserName(source.User.FirstName, source.User.LastName) : - source.AuditEvent.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : - source.AuditEvent.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : - source.AuditEvent.Initiator ?? AuditReportResource.UnknownAccount; - - destination.ActionText = _auditActionMapper.GetActionText(destination); - destination.ActionTypeText = _auditActionMapper.GetActionTypeText(destination); - destination.Product = _auditActionMapper.GetProductText(destination); - destination.Module = _auditActionMapper.GetModuleText(destination); - } + destination.ActionText = _auditActionMapper.GetActionText(destination); + destination.ActionTypeText = _auditActionMapper.GetActionTypeText(destination); + destination.Product = _auditActionMapper.GetProductText(destination); + destination.Module = _auditActionMapper.GetModuleText(destination); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs b/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs index 3c61ee6e60..d08ee4634b 100644 --- a/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs +++ b/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs @@ -7,38 +7,37 @@ using AutoMapper; using Newtonsoft.Json; -namespace ASC.AuditTrail.Models.Mapping.Actions +namespace ASC.AuditTrail.Models.Mapping.Actions; + +public class LoginEventMappingAction : IMappingAction<LoginEventQuery, LoginEventDTO> { - public class LoginEventMappingAction : IMappingAction<LoginEventQuery, LoginEventDTO> + private readonly UserFormatter _userFormatter; + private readonly AuditActionMapper _auditActionMapper; + + public LoginEventMappingAction(UserFormatter userFormatter, AuditActionMapper auditActionMapper) { - private readonly UserFormatter _userFormatter; - private readonly AuditActionMapper _auditActionMapper; + _userFormatter = userFormatter; + _auditActionMapper = auditActionMapper; + } - public LoginEventMappingAction(UserFormatter userFormatter, AuditActionMapper auditActionMapper) - { - _userFormatter = userFormatter; - _auditActionMapper = auditActionMapper; - } + public void Process(LoginEventQuery source, LoginEventDTO destination, ResolutionContext context) + { + if (source.LoginEvents.Description != null) + destination.Description = JsonConvert.DeserializeObject<IList<string>>( + source.LoginEvents.Description, + new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.Utc + }); - public void Process(LoginEventQuery source, LoginEventDTO destination, ResolutionContext context) - { - if (source.LoginEvents.Description != null) - destination.Description = JsonConvert.DeserializeObject<IList<string>>( - source.LoginEvents.Description, - new JsonSerializerSettings - { - DateTimeZoneHandling = DateTimeZoneHandling.Utc - }); + destination.UserName = (!string.IsNullOrEmpty(source.User?.FirstName) && !string.IsNullOrEmpty(source.User?.LastName)) + ? _userFormatter.GetUserName(source.User.FirstName, source.User.LastName) + : !string.IsNullOrWhiteSpace(source.LoginEvents.Login) + ? source.LoginEvents.Login + : source.LoginEvents.UserId == Core.Configuration.Constants.Guest.ID + ? AuditReportResource.GuestAccount + : AuditReportResource.UnknownAccount; - destination.UserName = (!string.IsNullOrEmpty(source.User?.FirstName) && !string.IsNullOrEmpty(source.User?.LastName)) - ? _userFormatter.GetUserName(source.User.FirstName, source.User.LastName) - : !string.IsNullOrWhiteSpace(source.LoginEvents.Login) - ? source.LoginEvents.Login - : source.LoginEvents.UserId == Core.Configuration.Constants.Guest.ID - ? AuditReportResource.GuestAccount - : AuditReportResource.UnknownAccount; - - destination.ActionText = _auditActionMapper.GetActionText(destination); - } + destination.ActionText = _auditActionMapper.GetActionText(destination); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs index 7924193de8..6f1fd555e5 100644 --- a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs @@ -35,55 +35,54 @@ using ASC.Core.Common.EF.Context; using AutoMapper; -namespace ASC.AuditTrail.Repositories +namespace ASC.AuditTrail.Repositories; + +[Scope] +public class AuditEventsRepository { - [Scope] - public class AuditEventsRepository + private AuditTrailContext AuditTrailContext => _lazyAuditTrailContext.Value; + + private readonly Lazy<AuditTrailContext> _lazyAuditTrailContext; + private readonly IMapper _mapper; + + public AuditEventsRepository( + DbContextManager<AuditTrailContext> dbContextManager, + IMapper mapper) { - private AuditTrailContext AuditTrailContext => _lazyAuditTrailContext.Value; + _lazyAuditTrailContext = new Lazy<AuditTrailContext>(() => dbContextManager.Value); + _mapper = mapper; + } - private readonly Lazy<AuditTrailContext> _lazyAuditTrailContext; - private readonly IMapper _mapper; + public IEnumerable<AuditEventDto> GetLast(int tenant, int chunk) => Get(tenant, null, null, chunk); - public AuditEventsRepository( - DbContextManager<AuditTrailContext> dbContextManager, - IMapper mapper) - { - _lazyAuditTrailContext = new Lazy<AuditTrailContext>(() => dbContextManager.Value); - _mapper = mapper; - } + public IEnumerable<AuditEventDto> Get(int tenant, DateTime from, DateTime to) => Get(tenant, from, to, null); - public IEnumerable<AuditEvent> GetLast(int tenant, int chunk) => Get(tenant, null, null, chunk); + public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) + { + IQueryable<Core.Common.EF.Model.AuditEvent> query = AuditTrailContext.AuditEvents + .Where(a => a.TenantId == tenant) + .OrderByDescending(a => a.Date); - public IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) => Get(tenant, from, to, null); + if (from.HasValue && to.HasValue) + query = query.Where(a => a.Date >= from & a.Date <= to); - private IEnumerable<AuditEvent> Get(int tenant, DateTime? fromDate, DateTime? to, int? limit) - { - var query = - from q in AuditTrailContext.AuditEvents - from p in AuditTrailContext.Users.Where(p => q.UserId == p.Id).DefaultIfEmpty() - where q.TenantId == tenant - orderby q.Date descending - select new AuditEventQuery { AuditEvent = q, User = p }; + return query.Count(); + } - if (fromDate.HasValue && to.HasValue) - query = query.Where(q => q.AuditEvent.Date >= fromDate & q.AuditEvent.Date <= to); + private IEnumerable<AuditEventDto> Get(int tenant, DateTime? fromDate, DateTime? to, int? limit) + { + var query = + from q in AuditTrailContext.AuditEvents + from p in AuditTrailContext.Users.Where(p => q.UserId == p.Id).DefaultIfEmpty() + where q.TenantId == tenant + orderby q.Date descending + select new AuditEventQuery { AuditEvent = q, User = p }; - if (limit.HasValue) query = query.Take((int)limit); + if (fromDate.HasValue && to.HasValue) + query = query.Where(q => q.AuditEvent.Date >= fromDate & q.AuditEvent.Date <= to); - return query.AsEnumerable().Select(_mapper.Map<AuditEvent>).ToList(); - } + if (limit.HasValue) query = query.Take((int)limit); - public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) - { - IQueryable<Core.Common.EF.Model.AuditEvent> query = AuditTrailContext.AuditEvents - .Where(a => a.TenantId == tenant) - .OrderByDescending(a => a.Date); - - if (from.HasValue && to.HasValue) - query = query.Where(a => a.Date >= from & a.Date <= to); - - return query.Count(); - } + return query.AsEnumerable().Select(_mapper.Map<AuditEventDto>).ToList(); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs index c276542802..46e0dda9ff 100644 --- a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs @@ -36,59 +36,58 @@ using ASC.Core.Common.EF.Context; using AutoMapper; -namespace ASC.AuditTrail.Data.Repositories +namespace ASC.AuditTrail.Data.Repositories; + +[Scope] +public class LoginEventsRepository { - [Scope] - public class LoginEventsRepository + private MessagesContext MessagesContext => _lazyMessagesContext.Value; + + private readonly Lazy<MessagesContext> _lazyMessagesContext; + private readonly IMapper _mapper; + + public LoginEventsRepository( + DbContextManager<MessagesContext> dbMessagesContext, + IMapper mapper) { - private MessagesContext MessagesContext => _lazyMessagesContext.Value; + _lazyMessagesContext = new Lazy<MessagesContext>(() => dbMessagesContext.Value); + _mapper = mapper; + } - private readonly Lazy<MessagesContext> _lazyMessagesContext; - private readonly IMapper _mapper; + public IEnumerable<LoginEventDTO> GetLast(int tenant, int chunk) + { + var query = + (from b in MessagesContext.LoginEvents + from p in MessagesContext.Users.Where(p => b.UserId == p.Id).DefaultIfEmpty() + where b.TenantId == tenant + orderby b.Date descending + select new LoginEventQuery { LoginEvents = b, User = p }) + .Take(chunk); - public LoginEventsRepository( - DbContextManager<MessagesContext> dbMessagesContext, - IMapper mapper) - { - _lazyMessagesContext = new Lazy<MessagesContext>(() => dbMessagesContext.Value); - _mapper = mapper; - } + return query.AsEnumerable().Select(_mapper.Map<LoginEventDTO>).ToList(); + } - public IEnumerable<LoginEvent> GetLast(int tenant, int chunk) - { - var query = - (from b in MessagesContext.LoginEvents - from p in MessagesContext.Users.Where(p => b.UserId == p.Id).DefaultIfEmpty() - where b.TenantId == tenant - orderby b.Date descending - select new LoginEventQuery { LoginEvents = b, User = p }) - .Take(chunk); + public IEnumerable<LoginEventDTO> Get(int tenant, DateTime fromDate, DateTime to) + { + var query = + from q in MessagesContext.LoginEvents + from p in MessagesContext.Users.Where(p => q.UserId == p.Id).DefaultIfEmpty() + where q.TenantId == tenant + where q.Date >= fromDate + where q.Date <= to + orderby q.Date descending + select new LoginEventQuery { LoginEvents = q, User = p }; - return query.AsEnumerable().Select(_mapper.Map<LoginEvent>).ToList(); - } + return query.AsEnumerable().Select(_mapper.Map<LoginEventDTO>).ToList(); + } - public IEnumerable<LoginEvent> Get(int tenant, DateTime fromDate, DateTime to) - { - var query = - from q in MessagesContext.LoginEvents - from p in MessagesContext.Users.Where(p => q.UserId == p.Id).DefaultIfEmpty() - where q.TenantId == tenant - where q.Date >= fromDate - where q.Date <= to - orderby q.Date descending - select new LoginEventQuery { LoginEvents = q, User = p }; + public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) + { + var query = MessagesContext.LoginEvents + .Where(l => l.TenantId == tenant); - return query.AsEnumerable().Select(_mapper.Map<LoginEvent>).ToList(); - } + if (from.HasValue && to.HasValue) query = query.Where(l => l.Date >= from & l.Date <= to); - public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) - { - var query = MessagesContext.LoginEvents - .Where(l => l.TenantId == tenant); - - if (from.HasValue && to.HasValue) query = query.Where(l => l.Date >= from & l.Date <= to); - - return query.Count(); - } + return query.Count(); } } \ No newline at end of file From 9f670d2b2527f18d5af35638b6f92f5ba84b8e58 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 14:53:23 +0300 Subject: [PATCH 120/167] ClearEvents: add waiting for the end of the timer --- .../Services/TimedClearEventsService.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs b/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs index e531dabf1e..f67e567760 100644 --- a/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs +++ b/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs @@ -77,7 +77,15 @@ namespace ASC.ClearEvents.Services return Task.CompletedTask; } - public void Dispose() => _timer?.Dispose(); + public void Dispose() + { + var handle = new AutoResetEvent(false); + + if ((bool)!(_timer?.Dispose(handle))) + throw new Exception("Timer already disposed"); + + handle.WaitOne(); + } private void DeleteOldEvents(object state) { From b5e4d68550928ac5f7e9c25ffc4a6f1dd0cfba28 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 14:54:31 +0300 Subject: [PATCH 121/167] ClearEvents: used file-scope namespaces --- .../Services/TimedClearEventsService.cs | 187 +++++++++--------- 1 file changed, 93 insertions(+), 94 deletions(-) diff --git a/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs b/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs index f67e567760..9ee0ddc659 100644 --- a/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs +++ b/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs @@ -43,109 +43,108 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; -namespace ASC.ClearEvents.Services +namespace ASC.ClearEvents.Services; + +[Scope(Additional = typeof(MessagesRepositoryExtension))] +public class TimedClearEventsService : IHostedService, IDisposable { - [Scope(Additional = typeof(MessagesRepositoryExtension))] - public class TimedClearEventsService : IHostedService, IDisposable + private readonly ILog _logger; + private readonly IServiceScopeFactory _serviceScopeFactory; + private Timer _timer = null!; + + public TimedClearEventsService(IOptionsMonitor<ILog> options, IServiceScopeFactory serviceScopeFactory) { - private readonly ILog _logger; - private readonly IServiceScopeFactory _serviceScopeFactory; - private Timer _timer = null!; + _logger = options.CurrentValue; + _serviceScopeFactory = serviceScopeFactory; + } - public TimedClearEventsService(IOptionsMonitor<ILog> options, IServiceScopeFactory serviceScopeFactory) + public Task StartAsync(CancellationToken cancellationToken) + { + _logger.Info("Timer Clear Events Service running."); + + _timer = new Timer(DeleteOldEvents, null, TimeSpan.Zero, + TimeSpan.FromDays(1)); + + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + _logger.Info("Timed Clear Events Service is stopping."); + + _timer?.Change(Timeout.Infinite, 0); + + return Task.CompletedTask; + } + + public void Dispose() + { + var handle = new AutoResetEvent(false); + + if ((bool)!(_timer?.Dispose(handle))) + throw new Exception("Timer already disposed"); + + handle.WaitOne(); + } + + private void DeleteOldEvents(object state) + { + try { - _logger = options.CurrentValue; - _serviceScopeFactory = serviceScopeFactory; + GetOldEvents(r => r.LoginEvents, "LoginHistoryLifeTime"); + GetOldEvents(r => r.AuditEvents, "AuditTrailLifeTime"); } - - public Task StartAsync(CancellationToken cancellationToken) + catch (Exception ex) { - _logger.Info("Timer Clear Events Service running."); - - _timer = new Timer(DeleteOldEvents, null, TimeSpan.Zero, - TimeSpan.FromDays(1)); - - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - _logger.Info("Timed Clear Events Service is stopping."); - - _timer?.Change(Timeout.Infinite, 0); - - return Task.CompletedTask; - } - - public void Dispose() - { - var handle = new AutoResetEvent(false); - - if ((bool)!(_timer?.Dispose(handle))) - throw new Exception("Timer already disposed"); - - handle.WaitOne(); - } - - private void DeleteOldEvents(object state) - { - try - { - GetOldEvents(r => r.LoginEvents, "LoginHistoryLifeTime"); - GetOldEvents(r => r.AuditEvents, "AuditTrailLifeTime"); - } - catch (Exception ex) - { - _logger.Error(ex.Message, ex); - } - } - - private void GetOldEvents<T>(Expression<Func<Messages, DbSet<T>>> func, string settings) where T : MessageEvent - { - List<T> ids; - var compile = func.Compile(); - do - { - using var scope = _serviceScopeFactory.CreateScope(); - using var ef = scope.ServiceProvider.GetService<DbContextManager<Messages>>().Get("messages"); - var table = compile.Invoke(ef); - - var ae = table - .Join(ef.Tenants, r => r.TenantId, r => r.Id, (audit, tenant) => audit) - .Select(r => new - { - r.Id, - r.Date, - r.TenantId, - ef = r - }) - .Where(r => r.Date < DateTime.UtcNow.AddDays(-Convert.ToDouble( - ef.WebstudioSettings - .Where(a => a.TenantId == r.TenantId && a.Id == TenantAuditSettings.Guid) - .Select(r => JsonExtensions.JsonValue(nameof(r.Data).ToLower(), settings)) - .FirstOrDefault() ?? TenantAuditSettings.MaxLifeTime.ToString()))) - .Take(1000); - - ids = ae.Select(r => r.ef).ToList(); - - if (!ids.Any()) return; - - table.RemoveRange(ids); - ef.SaveChanges(); - - } while (ids.Any()); + _logger.Error(ex.Message, ex); } } - public class Messages : MessagesContext + private void GetOldEvents<T>(Expression<Func<Messages, DbSet<T>>> func, string settings) where T : MessageEvent { - public DbSet<AuditEvent> AuditEvents { get; } - public DbSet<DbTenant> Tenants { get; } - public DbSet<DbWebstudioSettings> WebstudioSettings { get; } - } - - public class MessagesRepositoryExtension - { - public static void Register(DIHelper services) => services.TryAdd<DbContextManager<Messages>>(); + List<T> ids; + var compile = func.Compile(); + do + { + using var scope = _serviceScopeFactory.CreateScope(); + using var ef = scope.ServiceProvider.GetService<DbContextManager<Messages>>().Get("messages"); + var table = compile.Invoke(ef); + + var ae = table + .Join(ef.Tenants, r => r.TenantId, r => r.Id, (audit, tenant) => audit) + .Select(r => new + { + r.Id, + r.Date, + r.TenantId, + ef = r + }) + .Where(r => r.Date < DateTime.UtcNow.AddDays(-Convert.ToDouble( + ef.WebstudioSettings + .Where(a => a.TenantId == r.TenantId && a.Id == TenantAuditSettings.Guid) + .Select(r => JsonExtensions.JsonValue(nameof(r.Data).ToLower(), settings)) + .FirstOrDefault() ?? TenantAuditSettings.MaxLifeTime.ToString()))) + .Take(1000); + + ids = ae.Select(r => r.ef).ToList(); + + if (!ids.Any()) return; + + table.RemoveRange(ids); + ef.SaveChanges(); + + } while (ids.Any()); } +} + +public class Messages : MessagesContext +{ + public DbSet<AuditEvent> AuditEvents { get; } + public DbSet<DbTenant> Tenants { get; } + public DbSet<DbWebstudioSettings> WebstudioSettings { get; } +} + +public class MessagesRepositoryExtension +{ + public static void Register(DIHelper services) => services.TryAdd<DbContextManager<Messages>>(); } \ No newline at end of file From 487a55a99e49ad63de678d84d321acb4ef2757bf Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 16:19:48 +0300 Subject: [PATCH 122/167] ApiCore: used file-scope namespaces, fix conflicts --- .../ASC.Api.Core/Auth/ConfirmAuthHandler.cs | 157 +++--- common/ASC.Api.Core/Auth/CookieAuthHandler.cs | 87 ++- .../ControllerNameAttributeConvention.cs | 27 +- common/ASC.Api.Core/Core/ApiContext.cs | 393 +++++++------- common/ASC.Api.Core/Core/ApiDateTime.cs | 499 +++++++++--------- common/ASC.Api.Core/Core/BaseStartup.cs | 323 ++++++------ common/ASC.Api.Core/Core/BaseWorkerStartup.cs | 65 ++- .../Core/CustomEndpointDataSource.cs | 67 ++- common/ASC.Api.Core/Core/CustomHealthCheck.cs | 95 ++-- common/ASC.Api.Core/Core/ItemDictionary.cs | 17 +- common/ASC.Api.Core/Core/ItemKeyValuePair.cs | 13 +- common/ASC.Api.Core/Core/Module.cs | 51 +- common/ASC.Api.Core/Core/Update.cs | 25 +- common/ASC.Api.Core/Core/Validate.cs | 31 +- .../ASC.Api.Core/Core/XmlOutputFormatter.cs | 29 +- common/ASC.Api.Core/GlobalUsings.cs | 2 +- .../Middleware/CommonApiResponse.cs | 107 ++-- .../Middleware/CultureMiddleware.cs | 49 +- .../Middleware/DisposeMiddleware.cs | 31 +- .../Middleware/IpSecurityFilter.cs | 49 +- .../ASC.Api.Core/Middleware/PaymentFilter.cs | 55 +- .../Middleware/ProductSecurityFilter.cs | 127 +++-- .../Middleware/ResponseWrapper.cs | 85 ++- .../Middleware/TenantStatusFilter.cs | 55 +- .../WebhooksGlobalFilterAttribute.cs | 93 ++-- common/ASC.Api.Core/Model/Contact.cs | 29 +- common/ASC.Api.Core/Model/EmployeeWraper.cs | 143 +++-- .../ASC.Api.Core/Model/EmployeeWraperFull.cs | 357 +++++++------ .../ASC.Api.Core/Model/GroupWrapperSummary.cs | 33 +- common/ASC.Api.Core/Routing/DefaultRoute.cs | 13 +- common/ASC.Api.Core/Routing/FormatRoute.cs | 93 ++-- .../Controllers/AuthenticationController.cs | 5 +- .../Controllers/ModulesController.cs | 4 +- .../Controllers/SettingsController.cs | 2 + web/ASC.Web.Api/Models/QuotaWrapper.cs | 2 + web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs | 1 + 36 files changed, 1596 insertions(+), 1618 deletions(-) diff --git a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs index 152e557676..945aadfbd2 100644 --- a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs @@ -1,102 +1,101 @@ using SecurityContext = ASC.Core.SecurityContext; -namespace ASC.Api.Core.Auth +namespace ASC.Api.Core.Auth; + +[Scope(Additional = typeof(ConfirmAuthHandlerExtension))] +public class ConfirmAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions> { - [Scope(Additional = typeof(ConfirmAuthHandlerExtension))] - public class ConfirmAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions> + private readonly SecurityContext _securityContext; + private readonly UserManager _userManager; + private readonly IServiceScopeFactory _serviceScopeFactory; + + public ConfirmAuthHandler( + IOptionsMonitor<AuthenticationSchemeOptions> options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock) : + base(options, logger, encoder, clock) + { } + + public ConfirmAuthHandler( + IOptionsMonitor<AuthenticationSchemeOptions> options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock, + SecurityContext securityContext, + UserManager userManager, + IServiceScopeFactory serviceScopeFactory) : + base(options, logger, encoder, clock) { - private readonly SecurityContext _securityContext; - private readonly UserManager _userManager; - private readonly IServiceScopeFactory _serviceScopeFactory; + _securityContext = securityContext; + _userManager = userManager; + _serviceScopeFactory = serviceScopeFactory; + } - public ConfirmAuthHandler( - IOptionsMonitor<AuthenticationSchemeOptions> options, - ILoggerFactory logger, - UrlEncoder encoder, - ISystemClock clock) : - base(options, logger, encoder, clock) - { } + protected override Task<AuthenticateResult> HandleAuthenticateAsync() + { + using var scope = _serviceScopeFactory.CreateScope(); - public ConfirmAuthHandler( - IOptionsMonitor<AuthenticationSchemeOptions> options, - ILoggerFactory logger, - UrlEncoder encoder, - ISystemClock clock, - SecurityContext securityContext, - UserManager userManager, - IServiceScopeFactory serviceScopeFactory) : - base(options, logger, encoder, clock) + var emailValidationKeyHelper = scope.ServiceProvider.GetService<EmailValidationKeyModelHelper>(); + var emailValidationKeyModel = emailValidationKeyHelper.GetModel(); + + if (!emailValidationKeyModel.Type.HasValue) { - _securityContext = securityContext; - _userManager = userManager; - _serviceScopeFactory = serviceScopeFactory; + return _securityContext.IsAuthenticated + ? Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name))) + : Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString()))); } - protected override Task<AuthenticateResult> HandleAuthenticateAsync() + EmailValidationKeyProvider.ValidationResult checkKeyResult; + try { - using var scope = _serviceScopeFactory.CreateScope(); + checkKeyResult = emailValidationKeyHelper.Validate(emailValidationKeyModel); + } + catch (ArgumentNullException) + { + checkKeyResult = EmailValidationKeyProvider.ValidationResult.Invalid; + } - var emailValidationKeyHelper = scope.ServiceProvider.GetService<EmailValidationKeyModelHelper>(); - var emailValidationKeyModel = emailValidationKeyHelper.GetModel(); - - if (!emailValidationKeyModel.Type.HasValue) - { - return _securityContext.IsAuthenticated - ? Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name))) - : Task.FromResult(AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString()))); - } - - EmailValidationKeyProvider.ValidationResult checkKeyResult; - try - { - checkKeyResult = emailValidationKeyHelper.Validate(emailValidationKeyModel); - } - catch (ArgumentNullException) - { - checkKeyResult = EmailValidationKeyProvider.ValidationResult.Invalid; - } - - var claims = new List<Claim>() + var claims = new List<Claim>() { new Claim(ClaimTypes.Role, emailValidationKeyModel.Type.ToString()) }; - if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Ok) + if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Ok) + { + Guid userId; + if (!_securityContext.IsAuthenticated) { - Guid userId; - if (!_securityContext.IsAuthenticated) - { - if (emailValidationKeyModel.UiD.HasValue && !emailValidationKeyModel.UiD.Equals(Guid.Empty)) - userId = emailValidationKeyModel.UiD.Value; - else - { - if(emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmailActivation - || emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmpInvite - || emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.LinkInvite) - userId = ASC.Core.Configuration.Constants.CoreSystem.ID; - else - userId = _userManager.GetUserByEmail(emailValidationKeyModel.Email).ID; - } - } + if (emailValidationKeyModel.UiD.HasValue && !emailValidationKeyModel.UiD.Equals(Guid.Empty)) + userId = emailValidationKeyModel.UiD.Value; else - userId = _securityContext.CurrentAccount.ID; - - _securityContext.AuthenticateMeWithoutCookie(userId, claims); + { + if (emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmailActivation + || emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmpInvite + || emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.LinkInvite) + userId = ASC.Core.Configuration.Constants.CoreSystem.ID; + else + userId = _userManager.GetUserByEmail(emailValidationKeyModel.Email).ID; + } } + else + userId = _securityContext.CurrentAccount.ID; - var result = checkKeyResult switch - { - EmailValidationKeyProvider.ValidationResult.Ok => AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)), - _ => AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString())) - }; - - return Task.FromResult(result); + _securityContext.AuthenticateMeWithoutCookie(userId, claims); } - } - public class ConfirmAuthHandlerExtension - { - public static void Register(DIHelper services) => - services.TryAdd<EmailValidationKeyModelHelper>(); + var result = checkKeyResult switch + { + EmailValidationKeyProvider.ValidationResult.Ok => AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)), + _ => AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString())) + }; + + return Task.FromResult(result); } +} + +public class ConfirmAuthHandlerExtension +{ + public static void Register(DIHelper services) => + services.TryAdd<EmailValidationKeyModelHelper>(); } \ No newline at end of file diff --git a/common/ASC.Api.Core/Auth/CookieAuthHandler.cs b/common/ASC.Api.Core/Auth/CookieAuthHandler.cs index 929a1d23c9..19c1b45ed2 100644 --- a/common/ASC.Api.Core/Auth/CookieAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/CookieAuthHandler.cs @@ -1,49 +1,48 @@ using SecurityContext = ASC.Core.SecurityContext; -namespace ASC.Api.Core.Auth +namespace ASC.Api.Core.Auth; + +[Scope] +public class CookieAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions> { - [Scope] - public class CookieAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions> + private readonly AuthorizationHelper _authorizationHelper; + private readonly SecurityContext _securityContext; + private readonly CookiesManager _cookiesManager; + + public CookieAuthHandler( + IOptionsMonitor<AuthenticationSchemeOptions> options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock) + : base(options, logger, encoder, clock) { } + + public CookieAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, + ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, + AuthorizationHelper authorizationHelper, + SecurityContext securityContext, + CookiesManager cookiesManager) + : this(options, logger, encoder, clock) { - private readonly AuthorizationHelper _authorizationHelper; - private readonly SecurityContext _securityContext; - private readonly CookiesManager _cookiesManager; - - public CookieAuthHandler( - IOptionsMonitor<AuthenticationSchemeOptions> options, - ILoggerFactory logger, - UrlEncoder encoder, - ISystemClock clock) - : base(options, logger, encoder, clock) { } - - public CookieAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, - ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, - AuthorizationHelper authorizationHelper, - SecurityContext securityContext, - CookiesManager cookiesManager) - : this(options, logger, encoder, clock) - { - _authorizationHelper = authorizationHelper; - _securityContext = securityContext; - _cookiesManager = cookiesManager; - } - - protected override Task<AuthenticateResult> HandleAuthenticateAsync() - { - var result = _authorizationHelper.ProcessBasicAuthorization(out _); - - if (!result) - { - _securityContext.Logout(); - _cookiesManager.ClearCookies(CookiesType.AuthKey); - _cookiesManager.ClearCookies(CookiesType.SocketIO); - } - - return Task.FromResult( - result ? - AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)) : - AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString())) - ); - } + _authorizationHelper = authorizationHelper; + _securityContext = securityContext; + _cookiesManager = cookiesManager; } -} + + protected override Task<AuthenticateResult> HandleAuthenticateAsync() + { + var result = _authorizationHelper.ProcessBasicAuthorization(out _); + + if (!result) + { + _securityContext.Logout(); + _cookiesManager.ClearCookies(CookiesType.AuthKey); + _cookiesManager.ClearCookies(CookiesType.SocketIO); + } + + return Task.FromResult( + result ? + AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)) : + AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString())) + ); + } +} \ No newline at end of file diff --git a/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs b/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs index e1cb0cd078..24028c2ff3 100644 --- a/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs +++ b/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs @@ -1,20 +1,19 @@ -namespace ASC.Api.Core.Convention +namespace ASC.Api.Core.Convention; + +[AttributeUsage(AttributeTargets.Class)] +public class ControllerNameAttribute : Attribute { - [AttributeUsage(AttributeTargets.Class)] - public class ControllerNameAttribute : Attribute - { - public string Name { get; } + public string Name { get; } - public ControllerNameAttribute(string name) => Name = name; - } + public ControllerNameAttribute(string name) => Name = name; +} - public class ControllerNameAttributeConvention : IControllerModelConvention +public class ControllerNameAttributeConvention : IControllerModelConvention +{ + public void Apply(ControllerModel controller) { - public void Apply(ControllerModel controller) - { - var controllerNameAttribute = controller.Attributes.OfType<ControllerNameAttribute>().SingleOrDefault(); - if (controllerNameAttribute != null) - controller.ControllerName = controllerNameAttribute.Name; - } + var controllerNameAttribute = controller.Attributes.OfType<ControllerNameAttribute>().SingleOrDefault(); + if (controllerNameAttribute != null) + controller.ControllerName = controllerNameAttribute.Name; } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/ApiContext.cs b/common/ASC.Api.Core/Core/ApiContext.cs index e1ef9484fc..6e043854fa 100644 --- a/common/ASC.Api.Core/Core/ApiContext.cs +++ b/common/ASC.Api.Core/Core/ApiContext.cs @@ -25,217 +25,216 @@ using SecurityContext = ASC.Core.SecurityContext; -namespace ASC.Api.Core +namespace ASC.Api.Core; + +[Scope] +public class ApiContext : ICloneable { - [Scope] - public class ApiContext : ICloneable + public IHttpContextAccessor HttpContextAccessor { get; set; } + public string[] Fields { get; set; } + public string[] FilterValues { get; set; } + public bool FromCache { get; set; } + public Tenant Tenant => _tenant ??= _tenantManager.GetCurrentTenant(HttpContextAccessor?.HttpContext); + public long? TotalCount { - public IHttpContextAccessor HttpContextAccessor { get; set; } - public string[] Fields { get; set; } - public string[] FilterValues { get; set; } - public bool FromCache { get; set; } - public Tenant Tenant => _tenant ??= _tenantManager.GetCurrentTenant(HttpContextAccessor?.HttpContext); - public long? TotalCount + set { - set - { - if (HttpContextAccessor.HttpContext.Items.ContainsKey(nameof(TotalCount))) - HttpContextAccessor.HttpContext.Items[nameof(TotalCount)] = value; - else - HttpContextAccessor.HttpContext.Items.Add(nameof(TotalCount), value); - } - } - - /// <summary> - /// Filters responce to specific type from request parameter "type" - /// </summary> - /// <remarks> - /// The type name is retrieved from [DataContractAttribute] name - /// </remarks> - public string FilterToType { get; set; } - - /// <summary> - /// Gets count to get item from collection. Request parameter "count" - /// </summary> - /// <remarks> - /// Don't forget to call _context.SetDataPaginated() to prevent SmartList from filtering response if you fetch data from DB with TOP & COUNT - /// </remarks> - public long Count { get; set; } - - /// <summary> - /// Gets start index to get item from collection. Request parameter "startIndex" - /// </summary> - /// <remarks> - /// Don't forget to call _context.SetDataPaginated() to prevent SmartList from filtering response if you fetch data from DB with TOP & COUNT - /// </remarks> - public long StartIndex { get; set; } - - /// <summary> - /// Gets field to sort by from request parameter "sortBy" - /// </summary> - public string SortBy { get; set; } - - /// <summary> - /// Gets field to filter from request parameter "filterBy" - /// </summary> - public string FilterBy { get; set; } - - /// <summary> - /// Gets filter operation from request parameter "filterOp" - /// can be one of the following:"contains","equals","startsWith","present" - /// </summary> - public string FilterOp { get; set; } - - /// <summary> - /// Gets value to filter from request parameter "filterValue" - /// </summary> - public string FilterValue { get; set; } - - /// <summary> - /// Sort direction. From request parameter "sortOrder" can be "descending" or "ascending" - /// Like ...&sortOrder=descending&... - /// </summary> - public bool SortDescending { get; set; } - - /// <summary> - /// Gets value to filter from request parameter "updatedSince" - /// </summary> - public DateTime UpdatedSince { get; set; } - - internal long SpecifiedCount { get; private set; } - internal long SpecifiedStartIndex { get; set; } - - private Tenant _tenant; - private static int s_maxCount = 1000; - private readonly SecurityContext _securityContext; - private readonly TenantManager _tenantManager; - - public ApiContext(IHttpContextAccessor httpContextAccessor, SecurityContext securityContext, TenantManager tenantManager) - { - _securityContext = securityContext; - _tenantManager = tenantManager; - HttpContextAccessor = httpContextAccessor; - if (httpContextAccessor.HttpContext == null) return; - - Count = s_maxCount; - var query = HttpContextAccessor.HttpContext.Request.Query; - //Try parse values - var count = query.GetRequestValue("count"); - if (!string.IsNullOrEmpty(count) && ulong.TryParse(count, out var countParsed)) - Count = Math.Min((long)countParsed, s_maxCount); //Count specified and valid - - var startIndex = query.GetRequestValue("startIndex"); - if (startIndex != null && long.TryParse(startIndex, out var startIndexParsed)) - { - StartIndex = Math.Max(0, startIndexParsed); - SpecifiedStartIndex = StartIndex; - } - - var sortOrder = query.GetRequestValue("sortOrder"); - if ("descending".Equals(sortOrder)) SortDescending = true; - - FilterToType = query.GetRequestValue("type"); - SortBy = query.GetRequestValue("sortBy"); - FilterBy = query.GetRequestValue("filterBy"); - FilterOp = query.GetRequestValue("filterOp"); - FilterValue = query.GetRequestValue("filterValue"); - FilterValues = query.GetRequestArray("filterValue"); - Fields = query.GetRequestArray("fields"); - - var updatedSince = query.GetRequestValue("updatedSince"); - if (updatedSince != null) UpdatedSince = Convert.ToDateTime(updatedSince); - } - - /// <summary> - /// Set mark that data is already paginated and additional filtering is not needed - /// </summary> - public ApiContext SetDataPaginated() - { - //Count = 0;//We always ask for +1 count so smart list should cut it - StartIndex = 0; - - return this; - } - - public ApiContext SetDataSorted() - { - SortBy = string.Empty; - - return this; - } - - public ApiContext SetDataFiltered() - { - FilterBy = string.Empty; - FilterOp = string.Empty; - FilterValue = string.Empty; - - return this; - } - - public ApiContext SetTotalCount(long totalCollectionCount) - { - TotalCount = totalCollectionCount; - - return this; - } - - public ApiContext SetCount(int count) - { - HttpContextAccessor.HttpContext.Items[nameof(Count)] = count; - - return this; - } - - public object Clone() => MemberwiseClone(); - - public override string ToString() => string.Format("C:{0},S:{1},So:{2},Sd:{3},Fb;{4},Fo:{5},Fv:{6},Us:{7},Ftt:{8}", Count, StartIndex, - SortBy, SortDescending, FilterBy, FilterOp, FilterValue, UpdatedSince.Ticks, FilterToType); - - public void AuthByClaim() - { - var id = HttpContextAccessor.HttpContext.User.Claims.FirstOrDefault(r => r.Type == ClaimTypes.Sid); - if (Guid.TryParse(id?.Value, out var userId)) _securityContext.AuthenticateMeWithoutCookie(userId); + if (HttpContextAccessor.HttpContext.Items.ContainsKey(nameof(TotalCount))) + HttpContextAccessor.HttpContext.Items[nameof(TotalCount)] = value; + else + HttpContextAccessor.HttpContext.Items.Add(nameof(TotalCount), value); } } - public static class QueryExtension - { - internal static string[] GetRequestArray(this IQueryCollection query, string key) - { - if (query != null) - { - var values = query[key + "[]"]; - if (values.Count > 0) return values; + /// <summary> + /// Filters responce to specific type from request parameter "type" + /// </summary> + /// <remarks> + /// The type name is retrieved from [DataContractAttribute] name + /// </remarks> + public string FilterToType { get; set; } - values = query[key]; - if (values.Count > 0) + /// <summary> + /// Gets count to get item from collection. Request parameter "count" + /// </summary> + /// <remarks> + /// Don't forget to call _context.SetDataPaginated() to prevent SmartList from filtering response if you fetch data from DB with TOP & COUNT + /// </remarks> + public long Count { get; set; } + + /// <summary> + /// Gets start index to get item from collection. Request parameter "startIndex" + /// </summary> + /// <remarks> + /// Don't forget to call _context.SetDataPaginated() to prevent SmartList from filtering response if you fetch data from DB with TOP & COUNT + /// </remarks> + public long StartIndex { get; set; } + + /// <summary> + /// Gets field to sort by from request parameter "sortBy" + /// </summary> + public string SortBy { get; set; } + + /// <summary> + /// Gets field to filter from request parameter "filterBy" + /// </summary> + public string FilterBy { get; set; } + + /// <summary> + /// Gets filter operation from request parameter "filterOp" + /// can be one of the following:"contains","equals","startsWith","present" + /// </summary> + public string FilterOp { get; set; } + + /// <summary> + /// Gets value to filter from request parameter "filterValue" + /// </summary> + public string FilterValue { get; set; } + + /// <summary> + /// Sort direction. From request parameter "sortOrder" can be "descending" or "ascending" + /// Like ...&sortOrder=descending&... + /// </summary> + public bool SortDescending { get; set; } + + /// <summary> + /// Gets value to filter from request parameter "updatedSince" + /// </summary> + public DateTime UpdatedSince { get; set; } + + internal long SpecifiedCount { get; private set; } + internal long SpecifiedStartIndex { get; set; } + + private Tenant _tenant; + private static int s_maxCount = 1000; + private readonly SecurityContext _securityContext; + private readonly TenantManager _tenantManager; + + public ApiContext(IHttpContextAccessor httpContextAccessor, SecurityContext securityContext, TenantManager tenantManager) + { + _securityContext = securityContext; + _tenantManager = tenantManager; + HttpContextAccessor = httpContextAccessor; + if (httpContextAccessor.HttpContext == null) return; + + Count = s_maxCount; + var query = HttpContextAccessor.HttpContext.Request.Query; + //Try parse values + var count = query.GetRequestValue("count"); + if (!string.IsNullOrEmpty(count) && ulong.TryParse(count, out var countParsed)) + Count = Math.Min((long)countParsed, s_maxCount); //Count specified and valid + + var startIndex = query.GetRequestValue("startIndex"); + if (startIndex != null && long.TryParse(startIndex, out var startIndexParsed)) + { + StartIndex = Math.Max(0, startIndexParsed); + SpecifiedStartIndex = StartIndex; + } + + var sortOrder = query.GetRequestValue("sortOrder"); + if ("descending".Equals(sortOrder)) SortDescending = true; + + FilterToType = query.GetRequestValue("type"); + SortBy = query.GetRequestValue("sortBy"); + FilterBy = query.GetRequestValue("filterBy"); + FilterOp = query.GetRequestValue("filterOp"); + FilterValue = query.GetRequestValue("filterValue"); + FilterValues = query.GetRequestArray("filterValue"); + Fields = query.GetRequestArray("fields"); + + var updatedSince = query.GetRequestValue("updatedSince"); + if (updatedSince != null) UpdatedSince = Convert.ToDateTime(updatedSince); + } + + /// <summary> + /// Set mark that data is already paginated and additional filtering is not needed + /// </summary> + public ApiContext SetDataPaginated() + { + //Count = 0;//We always ask for +1 count so smart list should cut it + StartIndex = 0; + + return this; + } + + public ApiContext SetDataSorted() + { + SortBy = string.Empty; + + return this; + } + + public ApiContext SetDataFiltered() + { + FilterBy = string.Empty; + FilterOp = string.Empty; + FilterValue = string.Empty; + + return this; + } + + public ApiContext SetTotalCount(long totalCollectionCount) + { + TotalCount = totalCollectionCount; + + return this; + } + + public ApiContext SetCount(int count) + { + HttpContextAccessor.HttpContext.Items[nameof(Count)] = count; + + return this; + } + + public object Clone() => MemberwiseClone(); + + public override string ToString() => string.Format("C:{0},S:{1},So:{2},Sd:{3},Fb;{4},Fo:{5},Fv:{6},Us:{7},Ftt:{8}", Count, StartIndex, + SortBy, SortDescending, FilterBy, FilterOp, FilterValue, UpdatedSince.Ticks, FilterToType); + + public void AuthByClaim() + { + var id = HttpContextAccessor.HttpContext.User.Claims.FirstOrDefault(r => r.Type == ClaimTypes.Sid); + if (Guid.TryParse(id?.Value, out var userId)) _securityContext.AuthenticateMeWithoutCookie(userId); + } +} + +public static class QueryExtension +{ + internal static string[] GetRequestArray(this IQueryCollection query, string key) + { + if (query != null) + { + var values = query[key + "[]"]; + if (values.Count > 0) return values; + + values = query[key]; + if (values.Count > 0) + { + if (values.Count == 1) //If it's only one element { - if (values.Count == 1) //If it's only one element - { - //Try split - if (!string.IsNullOrEmpty(values[0])) - return values[0].Split(','); - } - - return values; + //Try split + if (!string.IsNullOrEmpty(values[0])) + return values[0].Split(','); } + + return values; } - - return null; } - public static string GetRequestValue(this IQueryCollection query, string key) - { - var reqArray = query.GetRequestArray(key); - - return reqArray?.FirstOrDefault(); - } + return null; } - public static class ApiContextExtension + public static string GetRequestValue(this IQueryCollection query, string key) { - public static bool Check(this ApiContext context, string field) => - context?.Fields == null || (context.Fields != null && context.Fields.Contains(field, StringComparer.InvariantCultureIgnoreCase)); + var reqArray = query.GetRequestArray(key); + + return reqArray?.FirstOrDefault(); } +} + +public static class ApiContextExtension +{ + public static bool Check(this ApiContext context, string field) => + context?.Fields == null || (context.Fields != null && context.Fields.Contains(field, StringComparer.InvariantCultureIgnoreCase)); } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/ApiDateTime.cs b/common/ASC.Api.Core/Core/ApiDateTime.cs index 07e57784c1..b890d695fa 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -23,16 +23,16 @@ * */ -namespace ASC.Api.Core -{ - [TypeConverter(typeof(ApiDateTimeTypeConverter))] - public class ApiDateTime : IComparable<ApiDateTime>, IComparable - { - public DateTime UtcTime { get; private set; } - public TimeSpan TimeZoneOffset { get; private set; } +namespace ASC.Api.Core; - internal static readonly string[] Formats = new[] - { +[TypeConverter(typeof(ApiDateTimeTypeConverter))] +public class ApiDateTime : IComparable<ApiDateTime>, IComparable +{ + public DateTime UtcTime { get; private set; } + public TimeSpan TimeZoneOffset { get; private set; } + + internal static readonly string[] Formats = new[] + { "o", "yyyy'-'MM'-'dd'T'HH'-'mm'-'ss'.'fffffffK", "yyyy'-'MM'-'dd'T'HH'-'mm'-'ss'.'fffK", @@ -42,288 +42,287 @@ namespace ASC.Api.Core "yyyy'-'MM'-'dd" }; - private readonly TenantManager _tenantManager; - private readonly TimeZoneConverter _timeZoneConverter; + private readonly TenantManager _tenantManager; + private readonly TimeZoneConverter _timeZoneConverter; - public ApiDateTime() : this(null, null, null) { } + public ApiDateTime() : this(null, null, null) { } - public ApiDateTime( - TenantManager tenantManager, - TimeZoneConverter timeZoneConverter, - DateTime? dateTime) - : this(tenantManager, dateTime, null, timeZoneConverter) { } + public ApiDateTime( + TenantManager tenantManager, + TimeZoneConverter timeZoneConverter, + DateTime? dateTime) + : this(tenantManager, dateTime, null, timeZoneConverter) { } - public ApiDateTime( - TenantManager tenantManager, - DateTime? dateTime, - TimeZoneInfo timeZone, - TimeZoneConverter timeZoneConverter) + public ApiDateTime( + TenantManager tenantManager, + DateTime? dateTime, + TimeZoneInfo timeZone, + TimeZoneConverter timeZoneConverter) + { + if (dateTime.HasValue && dateTime.Value > DateTime.MinValue && dateTime.Value < DateTime.MaxValue) { - if (dateTime.HasValue && dateTime.Value > DateTime.MinValue && dateTime.Value < DateTime.MaxValue) - { - _tenantManager = tenantManager; - _timeZoneConverter = timeZoneConverter; - SetDate(dateTime.Value, timeZone); - } - else - { - UtcTime = DateTime.MinValue; - TimeZoneOffset = TimeSpan.Zero; - } + _tenantManager = tenantManager; + _timeZoneConverter = timeZoneConverter; + SetDate(dateTime.Value, timeZone); } - - public ApiDateTime(DateTime utcTime, TimeSpan offset) + else { - UtcTime = new DateTime(utcTime.Ticks, DateTimeKind.Utc); - TimeZoneOffset = offset; + UtcTime = DateTime.MinValue; + TimeZoneOffset = TimeSpan.Zero; } + } - public static ApiDateTime Parse(string data, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) => - Parse(data, null, tenantManager, timeZoneConverter); + public ApiDateTime(DateTime utcTime, TimeSpan offset) + { + UtcTime = new DateTime(utcTime.Ticks, DateTimeKind.Utc); + TimeZoneOffset = offset; + } - public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) + public static ApiDateTime Parse(string data, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) => + Parse(data, null, tenantManager, timeZoneConverter); + + public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) + { + if (string.IsNullOrEmpty(data)) throw new ArgumentNullException(nameof(data)); + + if (data.Length < 7) throw new ArgumentException("invalid date time format"); + + var offsetPart = data.Substring(data.Length - 6, 6); + if (DateTime.TryParseExact(data, Formats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var dateTime)) { - if (string.IsNullOrEmpty(data)) throw new ArgumentNullException(nameof(data)); - - if (data.Length < 7) throw new ArgumentException("invalid date time format"); - - var offsetPart = data.Substring(data.Length - 6, 6); - if (DateTime.TryParseExact(data, Formats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var dateTime)) - { - //Parse time - var tzOffset = TimeSpan.Zero; - if (offsetPart.Contains(':') && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset)) - return new ApiDateTime(dateTime, tzOffset); - - if (!data.EndsWith("Z", true, CultureInfo.InvariantCulture)) - { - if (tz == null) tz = GetTimeZoneInfo(tenantManager, timeZoneConverter); - - tzOffset = tz.GetUtcOffset(dateTime); - dateTime = dateTime.Subtract(tzOffset); - } - + //Parse time + var tzOffset = TimeSpan.Zero; + if (offsetPart.Contains(':') && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset)) return new ApiDateTime(dateTime, tzOffset); - } - - throw new ArgumentException("invalid date time format: " + data); - } - - - private void SetDate(DateTime value, TimeZoneInfo timeZone) - { - TimeZoneOffset = TimeSpan.Zero; - UtcTime = DateTime.MinValue; - - if (timeZone == null) - timeZone = GetTimeZoneInfo(_tenantManager, _timeZoneConverter); - - //Hack - if (timeZone.IsInvalidTime(new DateTime(value.Ticks, DateTimeKind.Unspecified))) - value = value.AddHours(1); - - if (value.Kind == DateTimeKind.Local) - value = TimeZoneInfo.ConvertTimeToUtc(new DateTime(value.Ticks, DateTimeKind.Unspecified), timeZone); - - if (value.Kind == DateTimeKind.Unspecified) - value = new DateTime(value.Ticks, DateTimeKind.Utc); //Assume it's utc - - if (value.Kind == DateTimeKind.Utc) + if (!data.EndsWith("Z", true, CultureInfo.InvariantCulture)) { - UtcTime = value; //Set UTC time - TimeZoneOffset = timeZone.GetUtcOffset(value); + if (tz == null) tz = GetTimeZoneInfo(tenantManager, timeZoneConverter); + + tzOffset = tz.GetUtcOffset(dateTime); + dateTime = dateTime.Subtract(tzOffset); } + + return new ApiDateTime(dateTime, tzOffset); + } - private static TimeZoneInfo GetTimeZoneInfo(TenantManager tenantManager, TimeZoneConverter timeZoneConverter) + throw new ArgumentException("invalid date time format: " + data); + } + + + private void SetDate(DateTime value, TimeZoneInfo timeZone) + { + TimeZoneOffset = TimeSpan.Zero; + UtcTime = DateTime.MinValue; + + if (timeZone == null) + timeZone = GetTimeZoneInfo(_tenantManager, _timeZoneConverter); + + //Hack + if (timeZone.IsInvalidTime(new DateTime(value.Ticks, DateTimeKind.Unspecified))) + value = value.AddHours(1); + + if (value.Kind == DateTimeKind.Local) + value = TimeZoneInfo.ConvertTimeToUtc(new DateTime(value.Ticks, DateTimeKind.Unspecified), timeZone); + + if (value.Kind == DateTimeKind.Unspecified) + value = new DateTime(value.Ticks, DateTimeKind.Utc); //Assume it's utc + + if (value.Kind == DateTimeKind.Utc) { - var timeZone = TimeZoneInfo.Local; - try - { - timeZone = timeZoneConverter.GetTimeZone(tenantManager.GetCurrentTenant().TimeZone); - } - catch (Exception) - { - //Tenant failed - } - - return timeZone; + UtcTime = value; //Set UTC time + TimeZoneOffset = timeZone.GetUtcOffset(value); } + } - private string ToRoundTripString(DateTime date, TimeSpan offset) + private static TimeZoneInfo GetTimeZoneInfo(TenantManager tenantManager, TimeZoneConverter timeZoneConverter) + { + var timeZone = TimeZoneInfo.Local; + try { - var dateString = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff", CultureInfo.InvariantCulture); - var offsetString = offset.Ticks == 0 ? "Z" : ((offset < TimeSpan.Zero) ? "-" : "+") + offset.ToString("hh\\:mm", CultureInfo.InvariantCulture); - - return dateString + offsetString; + timeZone = timeZoneConverter.GetTimeZone(tenantManager.GetCurrentTenant().TimeZone); + } + catch (Exception) + { + //Tenant failed } - public static ApiDateTime FromDate(TenantManager tenantManager, TimeZoneConverter timeZoneConverter, DateTime d) + return timeZone; + } + + private string ToRoundTripString(DateTime date, TimeSpan offset) + { + var dateString = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff", CultureInfo.InvariantCulture); + var offsetString = offset.Ticks == 0 ? "Z" : ((offset < TimeSpan.Zero) ? "-" : "+") + offset.ToString("hh\\:mm", CultureInfo.InvariantCulture); + + return dateString + offsetString; + } + + public static ApiDateTime FromDate(TenantManager tenantManager, TimeZoneConverter timeZoneConverter, DateTime d) + { + var date = new ApiDateTime(tenantManager, timeZoneConverter, d); + + return date; + } + + public static ApiDateTime FromDate(TenantManager tenantManager, TimeZoneConverter timeZoneConverter, DateTime? d) + { + if (d.HasValue) { var date = new ApiDateTime(tenantManager, timeZoneConverter, d); return date; } - public static ApiDateTime FromDate(TenantManager tenantManager, TimeZoneConverter timeZoneConverter, DateTime? d) - { - if (d.HasValue) - { - var date = new ApiDateTime(tenantManager, timeZoneConverter, d); - - return date; - } - - return null; - } - - public static bool operator >(ApiDateTime left, ApiDateTime right) - { - if (ReferenceEquals(left, right)) return false; - if (left == null) return false; - - return left.CompareTo(right) > 0; - } - - public static bool operator >=(ApiDateTime left, ApiDateTime right) - { - if (ReferenceEquals(left, right)) return false; - if (left == null) return false; - - return left.CompareTo(right) >= 0; - } - - public static bool operator <=(ApiDateTime left, ApiDateTime right) => !(left >= right); - - public static bool operator <(ApiDateTime left, ApiDateTime right) => !(left > right); - - public static bool operator ==(ApiDateTime left, ApiDateTime right) => Equals(left, right); - - public static bool operator !=(ApiDateTime left, ApiDateTime right) => !(left == right); - - public static implicit operator DateTime(ApiDateTime d) - { - if (d == null) return DateTime.MinValue; - - return d.UtcTime; - } - - public static implicit operator DateTime?(ApiDateTime d) - { - if (d == null) return null; - - return d.UtcTime; - } - - public int CompareTo(DateTime other) => CompareTo(new ApiDateTime(_tenantManager, _timeZoneConverter, other)); - - public int CompareTo(ApiDateTime other) - { - if (other == null) return 1; - - return UtcTime.CompareTo(other.UtcTime); - } - - public override bool Equals(object obj) - { - if (obj is null) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != typeof(ApiDateTime)) return false; - - return Equals((ApiDateTime)obj); - } - - public bool Equals(ApiDateTime other) - { - if (other is null) return false; - if (ReferenceEquals(this, other)) return true; - - return UtcTime.Equals(other.UtcTime) && TimeZoneOffset.Equals(other.TimeZoneOffset); - } - - public override int GetHashCode() - { - unchecked - { - return UtcTime.GetHashCode() * 397 + TimeZoneOffset.GetHashCode(); - } - } - - public int CompareTo(object obj) - { - if (obj is DateTime dateTime) - return CompareTo(dateTime); - - return obj is ApiDateTime apiDateTime ? CompareTo(apiDateTime) : 0; - } - - public override string ToString() - { - var localUtcTime = UtcTime; - - if (!UtcTime.Equals(DateTime.MinValue)) - localUtcTime = UtcTime.Add(TimeZoneOffset); - - return ToRoundTripString(localUtcTime, TimeZoneOffset); - } - - public static ApiDateTime GetSample() => new ApiDateTime(DateTime.UtcNow, TimeSpan.Zero); + return null; } - public class ApiDateTimeTypeConverter : DateTimeConverter + public static bool operator >(ApiDateTime left, ApiDateTime right) { - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + if (ReferenceEquals(left, right)) return false; + if (left == null) return false; + + return left.CompareTo(right) > 0; + } + + public static bool operator >=(ApiDateTime left, ApiDateTime right) + { + if (ReferenceEquals(left, right)) return false; + if (left == null) return false; + + return left.CompareTo(right) >= 0; + } + + public static bool operator <=(ApiDateTime left, ApiDateTime right) => !(left >= right); + + public static bool operator <(ApiDateTime left, ApiDateTime right) => !(left > right); + + public static bool operator ==(ApiDateTime left, ApiDateTime right) => Equals(left, right); + + public static bool operator !=(ApiDateTime left, ApiDateTime right) => !(left == right); + + public static implicit operator DateTime(ApiDateTime d) + { + if (d == null) return DateTime.MinValue; + + return d.UtcTime; + } + + public static implicit operator DateTime?(ApiDateTime d) + { + if (d == null) return null; + + return d.UtcTime; + } + + public int CompareTo(DateTime other) => CompareTo(new ApiDateTime(_tenantManager, _timeZoneConverter, other)); + + public int CompareTo(ApiDateTime other) + { + if (other == null) return 1; + + return UtcTime.CompareTo(other.UtcTime); + } + + public override bool Equals(object obj) + { + if (obj is null) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != typeof(ApiDateTime)) return false; + + return Equals((ApiDateTime)obj); + } + + public bool Equals(ApiDateTime other) + { + if (other is null) return false; + if (ReferenceEquals(this, other)) return true; + + return UtcTime.Equals(other.UtcTime) && TimeZoneOffset.Equals(other.TimeZoneOffset); + } + + public override int GetHashCode() + { + unchecked { - if (destinationType == typeof(string)) - return value.ToString(); - - return base.ConvertTo(context, culture, value, destinationType); - } - - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - if (value is string @string) - return ApiDateTime.Parse(@string, null, null); - - if (value is DateTime time) - return new ApiDateTime(null, null, time); - - return base.ConvertFrom(context, culture, value); + return UtcTime.GetHashCode() * 397 + TimeZoneOffset.GetHashCode(); } } - public class ApiDateTimeConverter : System.Text.Json.Serialization.JsonConverter<ApiDateTime> + public int CompareTo(object obj) { - public override ApiDateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + if (obj is DateTime dateTime) + return CompareTo(dateTime); + + return obj is ApiDateTime apiDateTime ? CompareTo(apiDateTime) : 0; + } + + public override string ToString() + { + var localUtcTime = UtcTime; + + if (!UtcTime.Equals(DateTime.MinValue)) + localUtcTime = UtcTime.Add(TimeZoneOffset); + + return ToRoundTripString(localUtcTime, TimeZoneOffset); + } + + public static ApiDateTime GetSample() => new ApiDateTime(DateTime.UtcNow, TimeSpan.Zero); +} + +public class ApiDateTimeTypeConverter : DateTimeConverter +{ + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (destinationType == typeof(string)) + return value.ToString(); + + return base.ConvertTo(context, culture, value, destinationType); + } + + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + if (value is string @string) + return ApiDateTime.Parse(@string, null, null); + + if (value is DateTime time) + return new ApiDateTime(null, null, time); + + return base.ConvertFrom(context, culture, value); + } +} + +public class ApiDateTimeConverter : System.Text.Json.Serialization.JsonConverter<ApiDateTime> +{ + public override ApiDateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TryGetDateTime(out var result)) + return new ApiDateTime(result, TimeSpan.Zero); + else { - if (reader.TryGetDateTime(out var result)) - return new ApiDateTime(result, TimeSpan.Zero); + if (DateTime.TryParseExact(reader.GetString(), ApiDateTime.Formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var dateTime)) + return new ApiDateTime(dateTime, TimeSpan.Zero); else - { - if (DateTime.TryParseExact(reader.GetString(), ApiDateTime.Formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var dateTime)) - return new ApiDateTime(dateTime, TimeSpan.Zero); - else - return new ApiDateTime(); - } + return new ApiDateTime(); } - - public override void Write(Utf8JsonWriter writer, ApiDateTime value, JsonSerializerOptions options) => - writer.WriteStringValue(value.ToString()); } - [Scope] - public class ApiDateTimeHelper + public override void Write(Utf8JsonWriter writer, ApiDateTime value, JsonSerializerOptions options) => + writer.WriteStringValue(value.ToString()); +} + +[Scope] +public class ApiDateTimeHelper +{ + private readonly TenantManager _tenantManager; + private readonly TimeZoneConverter _timeZoneConverter; + + public ApiDateTimeHelper(TenantManager tenantManager, TimeZoneConverter timeZoneConverter) { - private readonly TenantManager _tenantManager; - private readonly TimeZoneConverter _timeZoneConverter; - - public ApiDateTimeHelper(TenantManager tenantManager, TimeZoneConverter timeZoneConverter) - { - _tenantManager = tenantManager; - _timeZoneConverter = timeZoneConverter; - } - - public ApiDateTime Get(DateTime? from) => ApiDateTime.FromDate(_tenantManager, _timeZoneConverter, from); + _tenantManager = tenantManager; + _timeZoneConverter = timeZoneConverter; } + + public ApiDateTime Get(DateTime? from) => ApiDateTime.FromDate(_tenantManager, _timeZoneConverter, from); } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index 50fe9f6c51..35aef132cb 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -1,175 +1,172 @@ -using StackExchange.Redis.Extensions.Newtonsoft; +using JsonConverter = System.Text.Json.Serialization.JsonConverter; -using JsonConverter = System.Text.Json.Serialization.JsonConverter; +namespace ASC.Api.Core; -namespace ASC.Api.Core +public abstract class BaseStartup { - public abstract class BaseStartup - { - public IConfiguration Configuration { get; } - public IHostEnvironment HostEnvironment { get; } - public virtual JsonConverter[] Converters { get; } - public virtual bool AddControllersAsServices { get; } = false; - public virtual bool ConfirmAddScheme { get; } = false; - public virtual bool AddAndUseSession { get; } = false; - protected DIHelper DIHelper { get; } - protected bool LoadProducts { get; set; } = true; - protected bool LoadConsumers { get; } = true; - - public BaseStartup(IConfiguration configuration, IHostEnvironment hostEnvironment) - { - Configuration = configuration; - HostEnvironment = hostEnvironment; - DIHelper = new DIHelper(); - - if (bool.TryParse(Configuration["core:products"], out var loadProducts)) - LoadProducts = loadProducts; - } + public IConfiguration Configuration { get; } + public IHostEnvironment HostEnvironment { get; } + public virtual JsonConverter[] Converters { get; } + public virtual bool AddControllersAsServices { get; } = false; + public virtual bool ConfirmAddScheme { get; } = false; + public virtual bool AddAndUseSession { get; } = false; + protected DIHelper DIHelper { get; } + protected bool LoadProducts { get; set; } = true; + protected bool LoadConsumers { get; } = true; - public virtual void ConfigureServices(IServiceCollection services) - { - services.AddCustomHealthCheck(Configuration); - services.AddHttpContextAccessor(); - services.AddMemoryCache(); + public BaseStartup(IConfiguration configuration, IHostEnvironment hostEnvironment) + { + Configuration = configuration; + HostEnvironment = hostEnvironment; + DIHelper = new DIHelper(); - if (AddAndUseSession) - services.AddSession(); - - DIHelper.Configure(services); - - Action<JsonOptions> jsonOptions = options => - { - options.JsonSerializerOptions.WriteIndented = false; - options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; - options.JsonSerializerOptions.Converters.Add(new ApiDateTimeConverter()); - - if (Converters != null) - { - foreach (var c in Converters) - { - options.JsonSerializerOptions.Converters.Add(c); - } - } - }; - - services.AddControllers() - .AddXmlSerializerFormatters() - .AddJsonOptions(jsonOptions); - - services.AddSingleton(jsonOptions); - - DIHelper.TryAdd<DisposeMiddleware>(); - DIHelper.TryAdd<CultureMiddleware>(); - DIHelper.TryAdd<IpSecurityFilter>(); - DIHelper.TryAdd<PaymentFilter>(); - DIHelper.TryAdd<ProductSecurityFilter>(); - DIHelper.TryAdd<TenantStatusFilter>(); - DIHelper.TryAdd<ConfirmAuthHandler>(); - DIHelper.TryAdd<CookieAuthHandler>(); - DIHelper.TryAdd<WebhooksGlobalFilterAttribute>(); - - var redisConfiguration = Configuration.GetSection("Redis").Get<RedisConfiguration>(); - var kafkaConfiguration = Configuration.GetSection("kafka").Get<KafkaSettings>(); - - if (kafkaConfiguration != null) - DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); - - else if (redisConfiguration != null) - { - DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); - - services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); - } - else - DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); - - DIHelper.TryAdd(typeof(IWebhookPublisher), typeof(WebhookPublisher)); - - if (LoadProducts) - DIHelper.RegisterProducts(Configuration, HostEnvironment.ContentRootPath); - - var builder = services.AddMvcCore(config => - { - config.Conventions.Add(new ControllerNameAttributeConvention()); - - var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); - - config.Filters.Add(new AuthorizeFilter(policy)); - config.Filters.Add(new TypeFilterAttribute(typeof(TenantStatusFilter))); - config.Filters.Add(new TypeFilterAttribute(typeof(PaymentFilter))); - config.Filters.Add(new TypeFilterAttribute(typeof(IpSecurityFilter))); - config.Filters.Add(new TypeFilterAttribute(typeof(ProductSecurityFilter))); - config.Filters.Add(new CustomResponseFilterAttribute()); - config.Filters.Add(new CustomExceptionFilterAttribute()); - config.Filters.Add(new TypeFilterAttribute(typeof(FormatFilter))); - config.Filters.Add(new TypeFilterAttribute(typeof(WebhooksGlobalFilterAttribute))); - - config.OutputFormatters.RemoveType<XmlSerializerOutputFormatter>(); - config.OutputFormatters.Add(new XmlOutputFormatter()); - }); - - - var authBuilder = services.AddAuthentication("cookie") - .AddScheme<AuthenticationSchemeOptions, CookieAuthHandler>("cookie", a => { }); - - if (ConfirmAddScheme) - authBuilder.AddScheme<AuthenticationSchemeOptions, ConfirmAuthHandler>("confirm", a => { }); - - services.AddAutoMapper(Assembly.GetAssembly(typeof(MappingProfile))); - } - - public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.UseForwardedHeaders(new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto - }); - - app.UseRouting(); - - if (AddAndUseSession) - app.UseSession(); - - app.UseAuthentication(); - - app.UseAuthorization(); - - app.UseCultureMiddleware(); - - app.UseDisposeMiddleware(); - - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - endpoints.MapCustom(); - - endpoints.MapHealthChecks("/health", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - endpoints.MapHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - }); - } - - public void ConfigureContainer(ContainerBuilder builder) - { - builder.Register(Configuration, LoadProducts, LoadConsumers); - } + if (bool.TryParse(Configuration["core:products"], out var loadProducts)) + LoadProducts = loadProducts; } - public static class LogNLogConfigureExtenstion + public virtual void ConfigureServices(IServiceCollection services) { - public static IHostBuilder ConfigureNLogLogging(this IHostBuilder hostBuilder) + services.AddCustomHealthCheck(Configuration); + services.AddHttpContextAccessor(); + services.AddMemoryCache(); + + if (AddAndUseSession) + services.AddSession(); + + DIHelper.Configure(services); + + Action<JsonOptions> jsonOptions = options => { - return hostBuilder.ConfigureLogging((hostBuildexContext, r) => + options.JsonSerializerOptions.WriteIndented = false; + options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; + options.JsonSerializerOptions.Converters.Add(new ApiDateTimeConverter()); + + if (Converters != null) { - _ = new ConfigureLogNLog(hostBuildexContext.Configuration, new ConfigurationExtension(hostBuildexContext.Configuration), hostBuildexContext.HostingEnvironment); - r.AddNLog(LogManager.Configuration); - }); + foreach (var c in Converters) + { + options.JsonSerializerOptions.Converters.Add(c); + } + } + }; + + services.AddControllers() + .AddXmlSerializerFormatters() + .AddJsonOptions(jsonOptions); + + services.AddSingleton(jsonOptions); + + DIHelper.TryAdd<DisposeMiddleware>(); + DIHelper.TryAdd<CultureMiddleware>(); + DIHelper.TryAdd<IpSecurityFilter>(); + DIHelper.TryAdd<PaymentFilter>(); + DIHelper.TryAdd<ProductSecurityFilter>(); + DIHelper.TryAdd<TenantStatusFilter>(); + DIHelper.TryAdd<ConfirmAuthHandler>(); + DIHelper.TryAdd<CookieAuthHandler>(); + DIHelper.TryAdd<WebhooksGlobalFilterAttribute>(); + + var redisConfiguration = Configuration.GetSection("Redis").Get<RedisConfiguration>(); + var kafkaConfiguration = Configuration.GetSection("kafka").Get<KafkaSettings>(); + + if (kafkaConfiguration != null) + DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); + + else if (redisConfiguration != null) + { + DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); + + services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } - } + else + DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + + DIHelper.TryAdd(typeof(IWebhookPublisher), typeof(WebhookPublisher)); + + if (LoadProducts) + DIHelper.RegisterProducts(Configuration, HostEnvironment.ContentRootPath); + + var builder = services.AddMvcCore(config => + { + config.Conventions.Add(new ControllerNameAttributeConvention()); + + var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); + + config.Filters.Add(new AuthorizeFilter(policy)); + config.Filters.Add(new TypeFilterAttribute(typeof(TenantStatusFilter))); + config.Filters.Add(new TypeFilterAttribute(typeof(PaymentFilter))); + config.Filters.Add(new TypeFilterAttribute(typeof(IpSecurityFilter))); + config.Filters.Add(new TypeFilterAttribute(typeof(ProductSecurityFilter))); + config.Filters.Add(new CustomResponseFilterAttribute()); + config.Filters.Add(new CustomExceptionFilterAttribute()); + config.Filters.Add(new TypeFilterAttribute(typeof(FormatFilter))); + config.Filters.Add(new TypeFilterAttribute(typeof(WebhooksGlobalFilterAttribute))); + + config.OutputFormatters.RemoveType<XmlSerializerOutputFormatter>(); + config.OutputFormatters.Add(new XmlOutputFormatter()); + }); + + + var authBuilder = services.AddAuthentication("cookie") + .AddScheme<AuthenticationSchemeOptions, CookieAuthHandler>("cookie", a => { }); + + if (ConfirmAddScheme) + authBuilder.AddScheme<AuthenticationSchemeOptions, ConfirmAuthHandler>("confirm", a => { }); + + services.AddAutoMapper(Assembly.GetAssembly(typeof(MappingProfile))); + } + + public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto + }); + + app.UseRouting(); + + if (AddAndUseSession) + app.UseSession(); + + app.UseAuthentication(); + + app.UseAuthorization(); + + app.UseCultureMiddleware(); + + app.UseDisposeMiddleware(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + endpoints.MapCustom(); + + endpoints.MapHealthChecks("/health", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + }); + } + + public void ConfigureContainer(ContainerBuilder builder) + { + builder.Register(Configuration, LoadProducts, LoadConsumers); + } +} + +public static class LogNLogConfigureExtenstion +{ + public static IHostBuilder ConfigureNLogLogging(this IHostBuilder hostBuilder) + { + return hostBuilder.ConfigureLogging((hostBuildexContext, r) => + { + _ = new ConfigureLogNLog(hostBuildexContext.Configuration, new ConfigurationExtension(hostBuildexContext.Configuration), hostBuildexContext.HostingEnvironment); + r.AddNLog(LogManager.Configuration); + }); + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/BaseWorkerStartup.cs b/common/ASC.Api.Core/Core/BaseWorkerStartup.cs index aa91a034db..39028d118d 100644 --- a/common/ASC.Api.Core/Core/BaseWorkerStartup.cs +++ b/common/ASC.Api.Core/Core/BaseWorkerStartup.cs @@ -1,36 +1,35 @@ -namespace ASC.Api.Core -{ - public class BaseWorkerStartup - { - public IConfiguration Configuration { get; } +namespace ASC.Api.Core; - public BaseWorkerStartup(IConfiguration configuration) - { - Configuration = configuration; - } - - public virtual void ConfigureServices(IServiceCollection services) +public class BaseWorkerStartup +{ + public IConfiguration Configuration { get; } + + public BaseWorkerStartup(IConfiguration configuration) + { + Configuration = configuration; + } + + public virtual void ConfigureServices(IServiceCollection services) + { + services.AddHttpContextAccessor(); + services.AddCustomHealthCheck(Configuration); + } + + public virtual void Configure(IApplicationBuilder app) + { + app.UseRouting(); + + app.UseEndpoints(endpoints => { - services.AddHttpContextAccessor(); - services.AddCustomHealthCheck(Configuration); - } - - public virtual void Configure(IApplicationBuilder app) - { - app.UseRouting(); - - app.UseEndpoints(endpoints => - { - endpoints.MapHealthChecks("/health", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - endpoints.MapHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - }); - } - } + endpoints.MapHealthChecks("/health", new HealthCheckOptions() + { + Predicate = _ => true, + ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse + }); + endpoints.MapHealthChecks("/liveness", new HealthCheckOptions + { + Predicate = r => r.Name.Contains("self") + }); + }); + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs b/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs index 3559617688..0d1d4f6155 100644 --- a/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs +++ b/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs @@ -1,44 +1,43 @@ -namespace ASC.Api.Core.Core +namespace ASC.Api.Core.Core; + +public class CustomEndpointDataSource : EndpointDataSource { - public class CustomEndpointDataSource : EndpointDataSource + public EndpointDataSource Source { get; } + public override IReadOnlyList<Endpoint> Endpoints { get; } + + public CustomEndpointDataSource(EndpointDataSource source) { - public EndpointDataSource Source { get; } - public override IReadOnlyList<Endpoint> Endpoints { get; } + Source = source; + var endpoints = Source.Endpoints.Cast<RouteEndpoint>(); + Endpoints = endpoints + .SelectMany(r => + { + var endpoints = new List<RouteEndpoint>(); - public CustomEndpointDataSource(EndpointDataSource source) - { - Source = source; - var endpoints = Source.Endpoints.Cast<RouteEndpoint>(); - Endpoints = endpoints - .SelectMany(r => + var attr = r.Metadata.OfType<CustomHttpMethodAttribute>().FirstOrDefault(); + var enableFormat = attr == null || !attr.DisableFormat; + + if (enableFormat) + endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".{format}"), r.Order, r.Metadata, r.DisplayName)); + else { - var endpoints = new List<RouteEndpoint>(); + endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".json"), r.Order - 1, r.Metadata, r.DisplayName)); + endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".xml"), r.Order - 1, r.Metadata, r.DisplayName)); + } - var attr = r.Metadata.OfType<CustomHttpMethodAttribute>().FirstOrDefault(); - var enableFormat = attr == null || !attr.DisableFormat; - - if (enableFormat) - endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".{format}"), r.Order, r.Metadata, r.DisplayName)); - else - { - endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".json"), r.Order - 1, r.Metadata, r.DisplayName)); - endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".xml"), r.Order - 1, r.Metadata, r.DisplayName)); - } - - return endpoints; - }).ToList(); - } - - public override IChangeToken GetChangeToken() => Source.GetChangeToken(); + return endpoints; + }).ToList(); } - public static class EndpointExtension - { - public static IEndpointRouteBuilder MapCustom(this IEndpointRouteBuilder endpoints) - { - endpoints.DataSources.Add(new CustomEndpointDataSource(endpoints.DataSources.First())); + public override IChangeToken GetChangeToken() => Source.GetChangeToken(); +} - return endpoints; - } +public static class EndpointExtension +{ + public static IEndpointRouteBuilder MapCustom(this IEndpointRouteBuilder endpoints) + { + endpoints.DataSources.Add(new CustomEndpointDataSource(endpoints.DataSources.First())); + + return endpoints; } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/CustomHealthCheck.cs b/common/ASC.Api.Core/Core/CustomHealthCheck.cs index a0e40319c5..9a3a152051 100644 --- a/common/ASC.Api.Core/Core/CustomHealthCheck.cs +++ b/common/ASC.Api.Core/Core/CustomHealthCheck.cs @@ -1,56 +1,55 @@ -namespace ASC.Api.Core.Core +namespace ASC.Api.Core.Core; + +public static class CustomHealthCheck { - public static class CustomHealthCheck + public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration) { - public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration) + var hcBuilder = services.AddHealthChecks(); + + hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy()); + + var configurationExtension = new ConfigurationExtension(configuration); + + var connectionString = configurationExtension.GetConnectionStrings("default"); + + if (string.Compare(connectionString.ProviderName, "MySql.Data.MySqlClient") == 0) + hcBuilder.AddMySql(connectionString.ConnectionString, + name: "mysqldb", + tags: new string[] { "mysqldb" }); + + if (string.Compare(connectionString.ProviderName, "Npgsql") == 0) + hcBuilder.AddNpgSql(connectionString.ConnectionString, + name: "postgredb", + tags: new string[] { "postgredb" }); + + var kafkaSettings = configurationExtension.GetSetting<KafkaSettings>("kafka"); + + if (kafkaSettings != null && !string.IsNullOrEmpty(kafkaSettings.BootstrapServers)) { - var hcBuilder = services.AddHealthChecks(); + var clientConfig = new ClientConfig { BootstrapServers = kafkaSettings.BootstrapServers }; - hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy()); + hcBuilder.AddKafka(new ProducerConfig(clientConfig), + name: "kafka", + tags: new string[] { "kafka" }); - var configurationExtension = new ConfigurationExtension(configuration); - - var connectionString = configurationExtension.GetConnectionStrings("default"); - - if (string.Compare(connectionString.ProviderName, "MySql.Data.MySqlClient") == 0) - hcBuilder.AddMySql(connectionString.ConnectionString, - name: "mysqldb", - tags: new string[] { "mysqldb" }); - - if (string.Compare(connectionString.ProviderName, "Npgsql") == 0) - hcBuilder.AddNpgSql(connectionString.ConnectionString, - name: "postgredb", - tags: new string[] { "postgredb" }); - - var kafkaSettings = configurationExtension.GetSetting<KafkaSettings>("kafka"); - - if (kafkaSettings != null && !string.IsNullOrEmpty(kafkaSettings.BootstrapServers)) - { - var clientConfig = new ClientConfig { BootstrapServers = kafkaSettings.BootstrapServers }; - - hcBuilder.AddKafka(new ProducerConfig(clientConfig), - name: "kafka", - tags: new string[] { "kafka" }); - - } - - - var elasticSettings = configuration.GetSection("elastic"); - - if (elasticSettings != null && elasticSettings.GetChildren().Any()) - { - var host = elasticSettings.GetSection("Host").Value ?? "localhost"; - var scheme = elasticSettings.GetSection("Scheme").Value ?? "http"; - var port = elasticSettings.GetSection("Port").Value ?? "9200"; - var elasticSearchUri = $"{scheme}://{host}:{port}"; - - if (Uri.IsWellFormedUriString(elasticSearchUri, UriKind.Absolute)) - hcBuilder.AddElasticsearch(elasticSearchUri, - name: "elasticsearch", - tags: new string[] { "elasticsearch" }); - } - - return services; } + + + var elasticSettings = configuration.GetSection("elastic"); + + if (elasticSettings != null && elasticSettings.GetChildren().Any()) + { + var host = elasticSettings.GetSection("Host").Value ?? "localhost"; + var scheme = elasticSettings.GetSection("Scheme").Value ?? "http"; + var port = elasticSettings.GetSection("Port").Value ?? "9200"; + var elasticSearchUri = $"{scheme}://{host}:{port}"; + + if (Uri.IsWellFormedUriString(elasticSearchUri, UriKind.Absolute)) + hcBuilder.AddElasticsearch(elasticSearchUri, + name: "elasticsearch", + tags: new string[] { "elasticsearch" }); + } + + return services; } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/ItemDictionary.cs b/common/ASC.Api.Core/Core/ItemDictionary.cs index 9be2778dc0..6862003e74 100644 --- a/common/ASC.Api.Core/Core/ItemDictionary.cs +++ b/common/ASC.Api.Core/Core/ItemDictionary.cs @@ -23,14 +23,13 @@ * */ -namespace ASC.Api.Collections -{ - [CollectionDataContract(Name = "hash", Namespace = "", ItemName = "entry", KeyName = "key", ValueName = "value")] - public class ItemDictionary<TKey, TValue> : Dictionary<TKey, TValue> - { - public ItemDictionary() { } +namespace ASC.Api.Collections; - public ItemDictionary(IDictionary<TKey, TValue> items) - : base(items) { } - } +[CollectionDataContract(Name = "hash", Namespace = "", ItemName = "entry", KeyName = "key", ValueName = "value")] +public class ItemDictionary<TKey, TValue> : Dictionary<TKey, TValue> +{ + public ItemDictionary() { } + + public ItemDictionary(IDictionary<TKey, TValue> items) + : base(items) { } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/ItemKeyValuePair.cs b/common/ASC.Api.Core/Core/ItemKeyValuePair.cs index 0d0c698668..f9d5e562c4 100644 --- a/common/ASC.Api.Core/Core/ItemKeyValuePair.cs +++ b/common/ASC.Api.Core/Core/ItemKeyValuePair.cs @@ -23,12 +23,11 @@ * */ -namespace ASC.Api.Collections -{ - public class ItemKeyValuePair<TKey, TValue> - { - public TKey Key { get; set; } - public TValue Value { get; set; } +namespace ASC.Api.Collections; + +public class ItemKeyValuePair<TKey, TValue> +{ + public TKey Key { get; set; } + public TValue Value { get; set; } - } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/Module.cs b/common/ASC.Api.Core/Core/Module.cs index fa076dbb6b..5930694f55 100644 --- a/common/ASC.Api.Core/Core/Module.cs +++ b/common/ASC.Api.Core/Core/Module.cs @@ -1,28 +1,27 @@ -namespace ASC.Api.Core -{ - public class Module - { - public Guid Id { get; set; } - public string AppName { get; set; } - public string Title { get; set; } - public string Link { get; set; } - public string IconUrl { get; set; } - public string ImageUrl { get; set; } - public string HelpUrl { get; set; } - public string Description { get; set; } - public bool IsPrimary { get; set; } +namespace ASC.Api.Core; - public Module(Product product) - { - Id = product.ProductID; - AppName = product.ProductClassName; - Title = product.Name; - Description = product.Description; - IconUrl = product.Context.IconFileName; - ImageUrl = product.Context.LargeIconFileName; - Link = product.StartURL; - IsPrimary = product.IsPrimary; - HelpUrl = product.HelpURL; - } - } +public class Module +{ + public Guid Id { get; set; } + public string AppName { get; set; } + public string Title { get; set; } + public string Link { get; set; } + public string IconUrl { get; set; } + public string ImageUrl { get; set; } + public string HelpUrl { get; set; } + public string Description { get; set; } + public bool IsPrimary { get; set; } + + public Module(Product product) + { + Id = product.ProductID; + AppName = product.ProductClassName; + Title = product.Name; + Description = product.Description; + IconUrl = product.Context.IconFileName; + ImageUrl = product.Context.LargeIconFileName; + Link = product.StartURL; + IsPrimary = product.IsPrimary; + HelpUrl = product.HelpURL; + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/Update.cs b/common/ASC.Api.Core/Core/Update.cs index 88799b1012..72b02367ba 100644 --- a/common/ASC.Api.Core/Core/Update.cs +++ b/common/ASC.Api.Core/Core/Update.cs @@ -24,24 +24,23 @@ */ -namespace ASC.Api.Utils +namespace ASC.Api.Utils; + +public static class Update { - public static class Update + public static T IfNotEquals<T>(T current, T @new) { - public static T IfNotEquals<T>(T current, T @new) - { - if (!Equals(current, @new)) return @new; + if (!Equals(current, @new)) return @new; - return current; - } + return current; + } - public static T IfNotEmptyAndNotEquals<T>(T current, T @new) - { - if (Equals(@new, default(T))) return current; + public static T IfNotEmptyAndNotEquals<T>(T current, T @new) + { + if (Equals(@new, default(T))) return current; - if (!Equals(current, @new)) return @new; + if (!Equals(current, @new)) return @new; - return current; - } + return current; } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/Validate.cs b/common/ASC.Api.Core/Core/Validate.cs index 9fffa125c0..a63d949ff3 100644 --- a/common/ASC.Api.Core/Core/Validate.cs +++ b/common/ASC.Api.Core/Core/Validate.cs @@ -23,26 +23,25 @@ * */ -namespace ASC.Api.Utils +namespace ASC.Api.Utils; + +public static class Validate { - public static class Validate - { - public static T If<T>(this T item, Func<T, bool> @if, Func<T> then) where T : class => - @if(item) ? then() : item; + public static T If<T>(this T item, Func<T, bool> @if, Func<T> then) where T : class => + @if(item) ? then() : item; - public static T IfNull<T>(this T item, Func<T> func) where T : class => item.If((x) => - x == default(T), func); + public static T IfNull<T>(this T item, Func<T> func) where T : class => item.If((x) => + x == default(T), func); - public static T ThrowIfNull<T>(this T item, Exception e) where T : class => - item.IfNull(() => { throw e; }); + public static T ThrowIfNull<T>(this T item, Exception e) where T : class => + item.IfNull(() => { throw e; }); - public static T NotFoundIfNull<T>(this T item) where T : class => - NotFoundIfNull(item, "Item not found"); + public static T NotFoundIfNull<T>(this T item) where T : class => + NotFoundIfNull(item, "Item not found"); - public static T NotFoundIfNull<T>(this T item, string message) where T : class => - item.IfNull(() => { throw new ItemNotFoundException(message); }); + public static T NotFoundIfNull<T>(this T item, string message) where T : class => + item.IfNull(() => { throw new ItemNotFoundException(message); }); - public static T? NullIfDefault<T>(this T item) where T : struct => - EqualityComparer<T>.Default.Equals(item, default(T)) ? default(T?) : item; - } + public static T? NullIfDefault<T>(this T item) where T : struct => + EqualityComparer<T>.Default.Equals(item, default(T)) ? default(T?) : item; } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/XmlOutputFormatter.cs b/common/ASC.Api.Core/Core/XmlOutputFormatter.cs index 44ac9bf7e3..8fb1039788 100644 --- a/common/ASC.Api.Core/Core/XmlOutputFormatter.cs +++ b/common/ASC.Api.Core/Core/XmlOutputFormatter.cs @@ -1,22 +1,21 @@ -namespace ASC.Api.Core.Core +namespace ASC.Api.Core.Core; + +public class XmlOutputFormatter : IOutputFormatter { - public class XmlOutputFormatter : IOutputFormatter + public bool CanWriteResult(OutputFormatterCanWriteContext context) => + context.ContentType == MimeMapping.GetMimeMapping(".xml"); + + public Task WriteAsync(OutputFormatterWriteContext context) { - public bool CanWriteResult(OutputFormatterCanWriteContext context) => - context.ContentType == MimeMapping.GetMimeMapping(".xml"); - - public Task WriteAsync(OutputFormatterWriteContext context) + var settings = new JsonSerializerSettings { - var settings = new JsonSerializerSettings - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - DateParseHandling = DateParseHandling.None - }; + ContractResolver = new CamelCasePropertyNamesContractResolver(), + DateParseHandling = DateParseHandling.None + }; - var responseJson = JsonConvert.SerializeObject(context.Object, Formatting.Indented, settings); - responseJson = JsonConvert.DeserializeObject<XDocument>("{\"result\":" + responseJson + "}", settings).ToString(SaveOptions.None); + var responseJson = JsonConvert.SerializeObject(context.Object, Formatting.Indented, settings); + responseJson = JsonConvert.DeserializeObject<XDocument>("{\"result\":" + responseJson + "}", settings).ToString(SaveOptions.None); - return context.HttpContext.Response.WriteAsync(responseJson); - } + return context.HttpContext.Response.WriteAsync(responseJson); } } \ No newline at end of file diff --git a/common/ASC.Api.Core/GlobalUsings.cs b/common/ASC.Api.Core/GlobalUsings.cs index b326879afa..632da821ba 100644 --- a/common/ASC.Api.Core/GlobalUsings.cs +++ b/common/ASC.Api.Core/GlobalUsings.cs @@ -36,7 +36,6 @@ global using ASC.Core; global using ASC.Core.Common.EF; global using ASC.Core.Tenants; global using ASC.Core.Users; -global using ASC.IPSecurity; global using ASC.Security.Cryptography; global using ASC.Web.Api.Routing; global using ASC.Web.Core; @@ -82,3 +81,4 @@ global using NLog; global using NLog.Extensions.Logging; global using StackExchange.Redis.Extensions.Core.Configuration; +global using StackExchange.Redis.Extensions.Newtonsoft; \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/CommonApiResponse.cs b/common/ASC.Api.Core/Middleware/CommonApiResponse.cs index 53e6124ec0..2d21843487 100644 --- a/common/ASC.Api.Core/Middleware/CommonApiResponse.cs +++ b/common/ASC.Api.Core/Middleware/CommonApiResponse.cs @@ -1,67 +1,66 @@ -namespace ASC.Api.Core.Middleware +namespace ASC.Api.Core.Middleware; + +public abstract class CommonApiResponse { - public abstract class CommonApiResponse + public int Status { get; set; } + public HttpStatusCode StatusCode { get; set; } + + protected CommonApiResponse(HttpStatusCode statusCode) => StatusCode = statusCode; + + public static SuccessApiResponse Create(HttpStatusCode statusCode, object response) => + new SuccessApiResponse(statusCode, response); + + public static ErrorApiResponse CreateError(HttpStatusCode statusCode, Exception error) => + new ErrorApiResponse(statusCode, error); +} + +public class ErrorApiResponse : CommonApiResponse +{ + public CommonApiError Error { get; set; } + + protected internal ErrorApiResponse(HttpStatusCode statusCode, Exception error, string message = null) : base(statusCode) { - public int Status { get; set; } - public HttpStatusCode StatusCode { get; set; } - - protected CommonApiResponse(HttpStatusCode statusCode) => StatusCode = statusCode; - - public static SuccessApiResponse Create(HttpStatusCode statusCode, object response) => - new SuccessApiResponse(statusCode, response); - - public static ErrorApiResponse CreateError(HttpStatusCode statusCode, Exception error) => - new ErrorApiResponse(statusCode, error); + Status = 1; + Error = CommonApiError.FromException(error, message); } +} - public class ErrorApiResponse : CommonApiResponse +public class SuccessApiResponse : CommonApiResponse +{ + public int? Count { get; set; } + public long? Total { get; set; } + public object Response { get; set; } + + protected internal SuccessApiResponse(HttpStatusCode statusCode, object response, long? total = null, int? count = null) : base(statusCode) { - public CommonApiError Error { get; set; } + Status = 0; + Response = response; + Total = total; - protected internal ErrorApiResponse(HttpStatusCode statusCode, Exception error, string message = null) : base(statusCode) + if (count.HasValue) Count = count; + else { - Status = 1; - Error = CommonApiError.FromException(error, message); + if (response is List<object> list) Count = list.Count; + else if (response is IEnumerable<object> collection) Count = collection.Count(); + else if (response == null) Count = 0; + else Count = 1; } } +} - public class SuccessApiResponse : CommonApiResponse - { - public int? Count { get; set; } - public long? Total { get; set; } - public object Response { get; set; } +public class CommonApiError +{ + public string Message { get; set; } + public string Type { get; set; } + public string Stack { get; set; } + public int Hresult { get; set; } - protected internal SuccessApiResponse(HttpStatusCode statusCode, object response, long? total = null, int? count = null) : base(statusCode) + public static CommonApiError FromException(Exception exception, string message = null) => + new CommonApiError() { - Status = 0; - Response = response; - Total = total; - - if (count.HasValue) Count = count; - else - { - if (response is List<object> list) Count = list.Count; - else if (response is IEnumerable<object> collection) Count = collection.Count(); - else if (response == null) Count = 0; - else Count = 1; - } - } - } - - public class CommonApiError - { - public string Message { get; set; } - public string Type { get; set; } - public string Stack { get; set; } - public int Hresult { get; set; } - - public static CommonApiError FromException(Exception exception, string message = null) => - new CommonApiError() - { - Message = message ?? exception.Message, - Type = exception.GetType().ToString(), - Stack = exception.StackTrace, - Hresult = exception.HResult - }; - } + Message = message ?? exception.Message, + Type = exception.GetType().ToString(), + Stack = exception.StackTrace, + Hresult = exception.HResult + }; } \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/CultureMiddleware.cs b/common/ASC.Api.Core/Middleware/CultureMiddleware.cs index a72c1eed78..b5f1397099 100644 --- a/common/ASC.Api.Core/Middleware/CultureMiddleware.cs +++ b/common/ASC.Api.Core/Middleware/CultureMiddleware.cs @@ -1,34 +1,33 @@ -namespace ASC.Api.Core.Middleware +namespace ASC.Api.Core.Middleware; + +public class CultureMiddleware { - public class CultureMiddleware + private readonly RequestDelegate _next; + + public CultureMiddleware(RequestDelegate next) => _next = next; + + public async Task Invoke(HttpContext context, UserManager userManager, TenantManager tenantManager, AuthContext authContext) { - private readonly RequestDelegate _next; + CultureInfo culture = null; - public CultureMiddleware(RequestDelegate next) => _next = next; - - public async Task Invoke(HttpContext context, UserManager userManager, TenantManager tenantManager, AuthContext authContext) + if (authContext.IsAuthenticated) { - CultureInfo culture = null; + var user = userManager.GetUsers(authContext.CurrentAccount.ID); - if (authContext.IsAuthenticated) - { - var user = userManager.GetUsers(authContext.CurrentAccount.ID); - - if (!string.IsNullOrEmpty(user.CultureName)) culture = user.GetCulture(); - } - - if (culture == null) culture = tenantManager.GetCurrentTenant().GetCulture(); - - Thread.CurrentThread.CurrentCulture = culture; - Thread.CurrentThread.CurrentUICulture = culture; - - await _next.Invoke(context); + if (!string.IsNullOrEmpty(user.CultureName)) culture = user.GetCulture(); } - } - public static class CultureMiddlewareExtensions - { - public static IApplicationBuilder UseCultureMiddleware(this IApplicationBuilder builder) => - builder.UseMiddleware<CultureMiddleware>(); + if (culture == null) culture = tenantManager.GetCurrentTenant().GetCulture(); + + Thread.CurrentThread.CurrentCulture = culture; + Thread.CurrentThread.CurrentUICulture = culture; + + await _next.Invoke(context); } +} + +public static class CultureMiddlewareExtensions +{ + public static IApplicationBuilder UseCultureMiddleware(this IApplicationBuilder builder) => + builder.UseMiddleware<CultureMiddleware>(); } \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs b/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs index 49642da691..9f38589fa0 100644 --- a/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs +++ b/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs @@ -1,22 +1,21 @@ -namespace ASC.Api.Core.Middleware +namespace ASC.Api.Core.Middleware; + +public class DisposeMiddleware { - public class DisposeMiddleware + private readonly RequestDelegate _next; + + public DisposeMiddleware(RequestDelegate next) => _next = next; + + public async Task Invoke(HttpContext context) { - private readonly RequestDelegate _next; + context.Response.RegisterForDispose(new DisposableHttpContext(context)); - public DisposeMiddleware(RequestDelegate next) => _next = next; - - public async Task Invoke(HttpContext context) - { - context.Response.RegisterForDispose(new DisposableHttpContext(context)); - - await _next.Invoke(context); - } + await _next.Invoke(context); } +} - public static class DisposeMiddlewareExtensions - { - public static IApplicationBuilder UseDisposeMiddleware(this IApplicationBuilder builder) => - builder.UseMiddleware<DisposeMiddleware>(); - } +public static class DisposeMiddlewareExtensions +{ + public static IApplicationBuilder UseDisposeMiddleware(this IApplicationBuilder builder) => + builder.UseMiddleware<DisposeMiddleware>(); } \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/IpSecurityFilter.cs b/common/ASC.Api.Core/Middleware/IpSecurityFilter.cs index e0000d5152..d2898693ee 100644 --- a/common/ASC.Api.Core/Middleware/IpSecurityFilter.cs +++ b/common/ASC.Api.Core/Middleware/IpSecurityFilter.cs @@ -1,33 +1,32 @@ -namespace ASC.Api.Core.Middleware +namespace ASC.Api.Core.Middleware; + +[Scope] +public class IpSecurityFilter : IResourceFilter { - [Scope] - public class IpSecurityFilter : IResourceFilter + private readonly AuthContext _authContext; + private readonly IPSecurity.IPSecurity _iPSecurity; + private readonly ILog _logger; + + public IpSecurityFilter( + IOptionsMonitor<ILog> options, + AuthContext authContext, + IPSecurity.IPSecurity IPSecurity) { - private readonly AuthContext _authContext; - private readonly IPSecurity.IPSecurity _iPSecurity; - private readonly ILog _logger; + _logger = options.CurrentValue; + _authContext = authContext; + _iPSecurity = IPSecurity; + } - public IpSecurityFilter( - IOptionsMonitor<ILog> options, - AuthContext authContext, - IPSecurity.IPSecurity IPSecurity) + public void OnResourceExecuted(ResourceExecutedContext context) { } + + public void OnResourceExecuting(ResourceExecutingContext context) + { + if (_authContext.IsAuthenticated && !_iPSecurity.Verify()) { - _logger = options.CurrentValue; - _authContext = authContext; - _iPSecurity = IPSecurity; - } + context.Result = new StatusCodeResult((int)HttpStatusCode.Forbidden); + _logger.WarnFormat("IPSecurity: user {0}", _authContext.CurrentAccount.ID); - public void OnResourceExecuted(ResourceExecutedContext context) { } - - public void OnResourceExecuting(ResourceExecutingContext context) - { - if (_authContext.IsAuthenticated && !_iPSecurity.Verify()) - { - context.Result = new StatusCodeResult((int)HttpStatusCode.Forbidden); - _logger.WarnFormat("IPSecurity: user {0}", _authContext.CurrentAccount.ID); - - return; - } + return; } } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/PaymentFilter.cs b/common/ASC.Api.Core/Middleware/PaymentFilter.cs index 608cbeed62..598b731ea3 100644 --- a/common/ASC.Api.Core/Middleware/PaymentFilter.cs +++ b/common/ASC.Api.Core/Middleware/PaymentFilter.cs @@ -1,37 +1,36 @@ -namespace ASC.Api.Core.Middleware -{ - [Scope] - public class PaymentFilter : IResourceFilter - { - private readonly TenantExtra _tenantExtra; - private readonly ILog _logger; +namespace ASC.Api.Core.Middleware; - public PaymentFilter(IOptionsMonitor<ILog> options, TenantExtra tenantExtra) +[Scope] +public class PaymentFilter : IResourceFilter +{ + private readonly TenantExtra _tenantExtra; + private readonly ILog _logger; + + public PaymentFilter(IOptionsMonitor<ILog> options, TenantExtra tenantExtra) + { + _logger = options.CurrentValue; + _tenantExtra = tenantExtra; + } + + public void OnResourceExecuted(ResourceExecutedContext context) { } + + public void OnResourceExecuting(ResourceExecutingContext context) + { + if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor + && !controllerActionDescriptor.EndpointMetadata.OfType<CustomHttpMethodAttribute>().FirstOrDefault().Check) { - _logger = options.CurrentValue; - _tenantExtra = tenantExtra; + _logger.Debug("Payment is not required"); + + return; } - public void OnResourceExecuted(ResourceExecutedContext context) { } - - public void OnResourceExecuting(ResourceExecutingContext context) + var header = context.HttpContext.Request.Headers["Payment-Info"]; + if (string.IsNullOrEmpty(header) || (bool.TryParse(header, out var flag) && flag)) { - if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor - && !controllerActionDescriptor.EndpointMetadata.OfType<CustomHttpMethodAttribute>().FirstOrDefault().Check) + if (_tenantExtra.IsNotPaid()) { - _logger.Debug("Payment is not required"); - - return; - } - - var header = context.HttpContext.Request.Headers["Payment-Info"]; - if (string.IsNullOrEmpty(header) || (bool.TryParse(header, out var flag) && flag)) - { - if (_tenantExtra.IsNotPaid()) - { - context.Result = new StatusCodeResult((int)HttpStatusCode.PaymentRequired); - _logger.WarnFormat("Payment Required {0}.", context.HttpContext.Request.Url()); - } + context.Result = new StatusCodeResult((int)HttpStatusCode.PaymentRequired); + _logger.WarnFormat("Payment Required {0}.", context.HttpContext.Request.Url()); } } } diff --git a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs index eaa62bad0d..0636af7bfd 100644 --- a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs +++ b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs @@ -1,23 +1,23 @@ -namespace ASC.Api.Core.Middleware +namespace ASC.Api.Core.Middleware; + +[Scope] +public class ProductSecurityFilter : IResourceFilter { - [Scope] - public class ProductSecurityFilter : IResourceFilter + private static readonly IDictionary<string, Guid> _products; + private readonly ILog _logger; + private readonly WebItemSecurity _webItemSecurity; + private readonly AuthContext _authContext; + + static ProductSecurityFilter() { - private static readonly IDictionary<string, Guid> _products; - private readonly ILog _logger; - private readonly WebItemSecurity _webItemSecurity; - private readonly AuthContext _authContext; + var blog = new Guid("6a598c74-91ae-437d-a5f4-ad339bd11bb2"); + var bookmark = new Guid("28b10049-dd20-4f54-b986-873bc14ccfc7"); + var forum = new Guid("853b6eb9-73ee-438d-9b09-8ffeedf36234"); + var news = new Guid("3cfd481b-46f2-4a4a-b55c-b8c0c9def02c"); + var wiki = new Guid("742cf945-cbbc-4a57-82d6-1600a12cf8ca"); + var photo = new Guid("9d51954f-db9b-4aed-94e3-ed70b914e101"); - static ProductSecurityFilter() - { - var blog = new Guid("6a598c74-91ae-437d-a5f4-ad339bd11bb2"); - var bookmark = new Guid("28b10049-dd20-4f54-b986-873bc14ccfc7"); - var forum = new Guid("853b6eb9-73ee-438d-9b09-8ffeedf36234"); - var news = new Guid("3cfd481b-46f2-4a4a-b55c-b8c0c9def02c"); - var wiki = new Guid("742cf945-cbbc-4a57-82d6-1600a12cf8ca"); - var photo = new Guid("9d51954f-db9b-4aed-94e3-ed70b914e101"); - - _products = new Dictionary<string, Guid> + _products = new Dictionary<string, Guid> { { "blog", blog }, { "bookmark", bookmark }, @@ -33,60 +33,59 @@ { "calendar", WebItemManager.CalendarProductID }, { "mail", WebItemManager.MailProductID }, }; - } + } - public ProductSecurityFilter( - IOptionsMonitor<ILog> options, - WebItemSecurity webItemSecurity, - AuthContext authContext) + public ProductSecurityFilter( + IOptionsMonitor<ILog> options, + WebItemSecurity webItemSecurity, + AuthContext authContext) + { + _logger = options.CurrentValue; + _webItemSecurity = webItemSecurity; + _authContext = authContext; + } + + public void OnResourceExecuted(ResourceExecutedContext context) { } + + public void OnResourceExecuting(ResourceExecutingContext context) + { + if (!_authContext.IsAuthenticated) return; + + if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor) { - _logger = options.CurrentValue; - _webItemSecurity = webItemSecurity; - _authContext = authContext; - } - - public void OnResourceExecuted(ResourceExecutedContext context) { } - - public void OnResourceExecuting(ResourceExecutingContext context) - { - if (!_authContext.IsAuthenticated) return; - - if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor) + var pid = FindProduct(controllerActionDescriptor); + if (pid != Guid.Empty) { - var pid = FindProduct(controllerActionDescriptor); - if (pid != Guid.Empty) - { - if (CallContext.GetData("asc.web.product_id") == null) - CallContext.SetData("asc.web.product_id", pid); + if (CallContext.GetData("asc.web.product_id") == null) + CallContext.SetData("asc.web.product_id", pid); - if (!_webItemSecurity.IsAvailableForMe(pid)) - { - context.Result = new StatusCodeResult((int)HttpStatusCode.Forbidden); - _logger.WarnFormat("Product {0} denied for user {1}", controllerActionDescriptor.ControllerName, _authContext.CurrentAccount); - } + if (!_webItemSecurity.IsAvailableForMe(pid)) + { + context.Result = new StatusCodeResult((int)HttpStatusCode.Forbidden); + _logger.WarnFormat("Product {0} denied for user {1}", controllerActionDescriptor.ControllerName, _authContext.CurrentAccount); } } } - - private static Guid FindProduct(ControllerActionDescriptor method) - { - if (method == null || string.IsNullOrEmpty(method.ControllerName)) return default; - - var name = method.ControllerName.ToLower(); - if (name == "community") - { - var url = method.MethodInfo.GetCustomAttribute<HttpMethodAttribute>().Template; - if (!string.IsNullOrEmpty(url)) - { - var module = url.Split('/')[0]; - if (_products.ContainsKey(module)) return _products[module]; - } - } - - if (_products.ContainsKey(name)) return _products[name]; - - return default; - } + } + + private static Guid FindProduct(ControllerActionDescriptor method) + { + if (method == null || string.IsNullOrEmpty(method.ControllerName)) return default; + + var name = method.ControllerName.ToLower(); + if (name == "community") + { + var url = method.MethodInfo.GetCustomAttribute<HttpMethodAttribute>().Template; + if (!string.IsNullOrEmpty(url)) + { + var module = url.Split('/')[0]; + if (_products.ContainsKey(module)) return _products[module]; + } + } + + if (_products.ContainsKey(name)) return _products[name]; + + return default; } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/ResponseWrapper.cs b/common/ASC.Api.Core/Middleware/ResponseWrapper.cs index a9dbc476c5..454f7cef50 100644 --- a/common/ASC.Api.Core/Middleware/ResponseWrapper.cs +++ b/common/ASC.Api.Core/Middleware/ResponseWrapper.cs @@ -1,54 +1,53 @@ -namespace ASC.Api.Core.Middleware +namespace ASC.Api.Core.Middleware; + +public class CustomExceptionFilterAttribute : ExceptionFilterAttribute { - public class CustomExceptionFilterAttribute : ExceptionFilterAttribute + public override void OnException(ExceptionContext context) { - public override void OnException(ExceptionContext context) + var status = (HttpStatusCode)context.HttpContext.Response.StatusCode; + string message = null; + + if (status == HttpStatusCode.OK) status = HttpStatusCode.InternalServerError; + + switch (context.Exception) { - var status = (HttpStatusCode)context.HttpContext.Response.StatusCode; - string message = null; - - if (status == HttpStatusCode.OK) status = HttpStatusCode.InternalServerError; - - switch (context.Exception) - { - case ItemNotFoundException: - status = HttpStatusCode.NotFound; - message = "The record could not be found"; - break; - case ArgumentException: - status = HttpStatusCode.BadRequest; - message = "Invalid arguments"; - break; - case SecurityException: - status = HttpStatusCode.Forbidden; - message = "Access denied"; - break; - case InvalidOperationException: - status = HttpStatusCode.Forbidden; - break; - } - - var result = new ObjectResult(new ErrorApiResponse(status, context.Exception, message)) - { - StatusCode = (int)status - }; - - context.Result = result; + case ItemNotFoundException: + status = HttpStatusCode.NotFound; + message = "The record could not be found"; + break; + case ArgumentException: + status = HttpStatusCode.BadRequest; + message = "Invalid arguments"; + break; + case SecurityException: + status = HttpStatusCode.Forbidden; + message = "Access denied"; + break; + case InvalidOperationException: + status = HttpStatusCode.Forbidden; + break; } + + var result = new ObjectResult(new ErrorApiResponse(status, context.Exception, message)) + { + StatusCode = (int)status + }; + + context.Result = result; } +} - public class CustomResponseFilterAttribute : ResultFilterAttribute +public class CustomResponseFilterAttribute : ResultFilterAttribute +{ + public override void OnResultExecuting(ResultExecutingContext context) { - public override void OnResultExecuting(ResultExecutingContext context) + if (context.Result is ObjectResult result) { - if (context.Result is ObjectResult result) - { - context.HttpContext.Items.TryGetValue("TotalCount", out var total); - context.HttpContext.Items.TryGetValue("Count", out var count); - result.Value = new SuccessApiResponse((HttpStatusCode)context.HttpContext.Response.StatusCode, result.Value, (long?)total, (int?)count); - } - - base.OnResultExecuting(context); + context.HttpContext.Items.TryGetValue("TotalCount", out var total); + context.HttpContext.Items.TryGetValue("Count", out var count); + result.Value = new SuccessApiResponse((HttpStatusCode)context.HttpContext.Response.StatusCode, result.Value, (long?)total, (int?)count); } + + base.OnResultExecuting(context); } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs b/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs index a02857176d..bad1d104e1 100644 --- a/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs +++ b/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs @@ -1,37 +1,36 @@ -namespace ASC.Api.Core.Middleware -{ - [Scope] - public class TenantStatusFilter : IResourceFilter - { - private readonly TenantManager _tenantManager; - private readonly ILog _logger; +namespace ASC.Api.Core.Middleware; - public TenantStatusFilter(IOptionsMonitor<ILog> options, TenantManager tenantManager) +[Scope] +public class TenantStatusFilter : IResourceFilter +{ + private readonly TenantManager _tenantManager; + private readonly ILog _logger; + + public TenantStatusFilter(IOptionsMonitor<ILog> options, TenantManager tenantManager) + { + _logger = options.CurrentValue; + _tenantManager = tenantManager; + } + + public void OnResourceExecuted(ResourceExecutedContext context) { } + + public void OnResourceExecuting(ResourceExecutingContext context) + { + var tenant = _tenantManager.GetCurrentTenant(false); + if (tenant == null) { - _logger = options.CurrentValue; - _tenantManager = tenantManager; + context.Result = new StatusCodeResult((int)HttpStatusCode.NotFound); + _logger.WarnFormat("Tenant {0} not found", tenant.TenantId); + + return; } - public void OnResourceExecuted(ResourceExecutedContext context) { } - - public void OnResourceExecuting(ResourceExecutingContext context) + if (tenant.Status == TenantStatus.RemovePending || tenant.Status == TenantStatus.Suspended) { - var tenant = _tenantManager.GetCurrentTenant(false); - if (tenant == null) - { - context.Result = new StatusCodeResult((int)HttpStatusCode.NotFound); - _logger.WarnFormat("Tenant {0} not found", tenant.TenantId); + context.Result = new StatusCodeResult((int)HttpStatusCode.NotFound); + _logger.WarnFormat("Tenant {0} is not removed or suspended", tenant.TenantId); - return; - } - - if (tenant.Status == TenantStatus.RemovePending || tenant.Status == TenantStatus.Suspended) - { - context.Result = new StatusCodeResult((int)HttpStatusCode.NotFound); - _logger.WarnFormat("Tenant {0} is not removed or suspended", tenant.TenantId); - - return; - } + return; } } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs b/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs index b7ca9e6de2..1252a1c864 100644 --- a/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs +++ b/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs @@ -1,54 +1,53 @@ using JsonSerializer = System.Text.Json.JsonSerializer; -namespace ASC.Api.Core.Middleware -{ - [Scope] - public class WebhooksGlobalFilterAttribute : ResultFilterAttribute - { - private readonly IWebhookPublisher _webhookPublisher; - private readonly JsonSerializerOptions _jsonSerializerOptions; - private static List<string> _methodList = new List<string> { "POST", "UPDATE", "DELETE" }; - - public WebhooksGlobalFilterAttribute(IWebhookPublisher webhookPublisher, Action<JsonOptions> projectJsonOptions) - { - _webhookPublisher = webhookPublisher; - - var jsonOptions = new JsonOptions(); - projectJsonOptions.Invoke(jsonOptions); - _jsonSerializerOptions = jsonOptions.JsonSerializerOptions; +namespace ASC.Api.Core.Middleware; + +[Scope] +public class WebhooksGlobalFilterAttribute : ResultFilterAttribute +{ + private readonly IWebhookPublisher _webhookPublisher; + private readonly JsonSerializerOptions _jsonSerializerOptions; + private static List<string> _methodList = new List<string> { "POST", "UPDATE", "DELETE" }; + + public WebhooksGlobalFilterAttribute(IWebhookPublisher webhookPublisher, Action<JsonOptions> projectJsonOptions) + { + _webhookPublisher = webhookPublisher; + + var jsonOptions = new JsonOptions(); + projectJsonOptions.Invoke(jsonOptions); + _jsonSerializerOptions = jsonOptions.JsonSerializerOptions; + } + + public override void OnResultExecuted(ResultExecutedContext context) + { + var method = context.HttpContext.Request.Method; + + if (!_methodList.Contains(method) || context.Canceled) + { + base.OnResultExecuted(context); + + return; } - - public override void OnResultExecuted(ResultExecutedContext context) - { - var method = context.HttpContext.Request.Method; - - if (!_methodList.Contains(method) || context.Canceled) - { - base.OnResultExecuted(context); - - return; - } - - var endpoint = (RouteEndpoint)context.HttpContext.GetEndpoint(); - var routePattern = endpoint?.RoutePattern.RawText; - - if (routePattern == null) - { - base.OnResultExecuted(context); - - return; - } - if (context.Result is ObjectResult objectResult) - { - var resultContent = JsonSerializer.Serialize(objectResult.Value, _jsonSerializerOptions); + var endpoint = (RouteEndpoint)context.HttpContext.GetEndpoint(); + var routePattern = endpoint?.RoutePattern.RawText; - var eventName = $"method: {method}, route: {routePattern}"; + if (routePattern == null) + { + base.OnResultExecuted(context); - _webhookPublisher.Publish(eventName, resultContent); - } - - base.OnResultExecuted(context); - } - } + return; + } + + if (context.Result is ObjectResult objectResult) + { + var resultContent = JsonSerializer.Serialize(objectResult.Value, _jsonSerializerOptions); + + var eventName = $"method: {method}, route: {routePattern}"; + + _webhookPublisher.Publish(eventName, resultContent); + } + + base.OnResultExecuted(context); + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Model/Contact.cs b/common/ASC.Api.Core/Model/Contact.cs index e82c789edb..959a41b534 100644 --- a/common/ASC.Api.Core/Model/Contact.cs +++ b/common/ASC.Api.Core/Model/Contact.cs @@ -23,22 +23,21 @@ * */ -namespace ASC.Web.Api.Models +namespace ASC.Web.Api.Models; + +public class Contact { - public class Contact + public string Type { get; set; } + public string Value { get; set; } + + //For binder + public Contact() { } + + public Contact(string type, string value) { - public string Type { get; set; } - public string Value { get; set; } - - //For binder - public Contact() { } - - public Contact(string type, string value) - { - Type = type; - Value = value; - } - - public static Contact GetSample() => new Contact("GTalk", "my@gmail.com"); + Type = type; + Value = value; } + + public static Contact GetSample() => new Contact("GTalk", "my@gmail.com"); } \ No newline at end of file diff --git a/common/ASC.Api.Core/Model/EmployeeWraper.cs b/common/ASC.Api.Core/Model/EmployeeWraper.cs index 4a07f34760..f3d095e45f 100644 --- a/common/ASC.Api.Core/Model/EmployeeWraper.cs +++ b/common/ASC.Api.Core/Model/EmployeeWraper.cs @@ -23,84 +23,83 @@ * */ -namespace ASC.Web.Api.Models -{ - public class EmployeeWraper - { - public Guid Id { get; set; } - public string DisplayName { get; set; } - public string Title { get; set; } - public string AvatarSmall { get; set; } - public string ProfileUrl { get; set; } +namespace ASC.Web.Api.Models; + +public class EmployeeWraper +{ + public Guid Id { get; set; } + public string DisplayName { get; set; } + public string Title { get; set; } + public string AvatarSmall { get; set; } + public string ProfileUrl { get; set; } + + public static EmployeeWraper GetSample() => + new EmployeeWraper + { + Id = Guid.Empty, + DisplayName = "Mike Zanyatski", + Title = "Manager", + AvatarSmall = "url to small avatar", + }; +} + +[Scope] +public class EmployeeWraperHelper +{ + protected UserPhotoManager UserPhotoManager { get; } + protected UserManager UserManager { get; } + + private readonly ApiContext _httpContext; + private readonly DisplayUserSettingsHelper _displayUserSettingsHelper; + private readonly CommonLinkUtility _commonLinkUtility; + + public EmployeeWraperHelper( + ApiContext httpContext, + DisplayUserSettingsHelper displayUserSettingsHelper, + UserPhotoManager userPhotoManager, + CommonLinkUtility commonLinkUtility, + UserManager userManager) + { + UserPhotoManager = userPhotoManager; + UserManager = userManager; + _httpContext = httpContext; + _displayUserSettingsHelper = displayUserSettingsHelper; + _commonLinkUtility = commonLinkUtility; - public static EmployeeWraper GetSample() => - new EmployeeWraper - { - Id = Guid.Empty, - DisplayName = "Mike Zanyatski", - Title = "Manager", - AvatarSmall = "url to small avatar", - }; } - [Scope] - public class EmployeeWraperHelper + public EmployeeWraper Get(UserInfo userInfo) => Init(new EmployeeWraper(), userInfo); + + public EmployeeWraper Get(Guid userId) { - protected UserPhotoManager UserPhotoManager { get; } - protected UserManager UserManager { get; } - - private readonly ApiContext _httpContext; - private readonly DisplayUserSettingsHelper _displayUserSettingsHelper; - private readonly CommonLinkUtility _commonLinkUtility; - - public EmployeeWraperHelper( - ApiContext httpContext, - DisplayUserSettingsHelper displayUserSettingsHelper, - UserPhotoManager userPhotoManager, - CommonLinkUtility commonLinkUtility, - UserManager userManager) + try { - UserPhotoManager = userPhotoManager; - UserManager = userManager; - _httpContext = httpContext; - _displayUserSettingsHelper = displayUserSettingsHelper; - _commonLinkUtility = commonLinkUtility; - + return Get(UserManager.GetUsers(userId)); + } + catch (Exception) + { + return Get(Constants.LostUser); + } + } + + protected EmployeeWraper Init(EmployeeWraper result, UserInfo userInfo) + { + result.Id = userInfo.ID; + result.DisplayName = _displayUserSettingsHelper.GetFullUserName(userInfo); + + if (!string.IsNullOrEmpty(userInfo.Title)) result.Title = userInfo.Title; + + var userInfoLM = userInfo.LastModified.GetHashCode(); + + if (_httpContext.Check("avatarSmall")) + result.AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + + if (result.Id != Guid.Empty) + { + var profileUrl = _commonLinkUtility.GetUserProfile(userInfo, false); + result.ProfileUrl = _commonLinkUtility.GetFullAbsolutePath(profileUrl); } - public EmployeeWraper Get(UserInfo userInfo) => Init(new EmployeeWraper(), userInfo); - - public EmployeeWraper Get(Guid userId) - { - try - { - return Get(UserManager.GetUsers(userId)); - } - catch (Exception) - { - return Get(Constants.LostUser); - } - } - - protected EmployeeWraper Init(EmployeeWraper result, UserInfo userInfo) - { - result.Id = userInfo.ID; - result.DisplayName = _displayUserSettingsHelper.GetFullUserName(userInfo); - - if (!string.IsNullOrEmpty(userInfo.Title)) result.Title = userInfo.Title; - - var userInfoLM = userInfo.LastModified.GetHashCode(); - - if (_httpContext.Check("avatarSmall")) - result.AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); - - if (result.Id != Guid.Empty) - { - var profileUrl = _commonLinkUtility.GetUserProfile(userInfo, false); - result.ProfileUrl = _commonLinkUtility.GetFullAbsolutePath(profileUrl); - } - - return result; - } + return result; } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Model/EmployeeWraperFull.cs b/common/ASC.Api.Core/Model/EmployeeWraperFull.cs index 4459cbb562..0054a6be17 100644 --- a/common/ASC.Api.Core/Model/EmployeeWraperFull.cs +++ b/common/ASC.Api.Core/Model/EmployeeWraperFull.cs @@ -23,201 +23,200 @@ * */ -namespace ASC.Web.Api.Models -{ - public class EmployeeWraperFull : EmployeeWraper - { - public string FirstName { get; set; } - public string LastName { get; set; } - public string UserName { get; set; } - public string Email { get; set; } - public List<Contact> Contacts { get; set; } - public ApiDateTime Birthday { get; set; } - public string Sex { get; set; } - public EmployeeStatus Status { get; set; } - public EmployeeActivationStatus ActivationStatus { get; set; } - public ApiDateTime Terminated { get; set; } - public string Department { get; set; } - public ApiDateTime WorkFrom { get; set; } - public List<GroupWrapperSummary> Groups { get; set; } - public string Location { get; set; } - public string Notes { get; set; } - public string AvatarMax { get; set; } - public string AvatarMedium { get; set; } - public string Avatar { get; set; } - public bool IsAdmin { get; set; } - public bool IsLDAP { get; set; } - public List<string> ListAdminModules { get; set; } - public bool IsOwner { get; set; } - public bool IsVisitor { get; set; } - public string CultureName { get; set; } - public string MobilePhone { get; set; } - public MobilePhoneActivationStatus MobilePhoneActivationStatus { get; set; } - public bool IsSSO { get; set; } +namespace ASC.Web.Api.Models; - public new static EmployeeWraperFull GetSample() +public class EmployeeWraperFull : EmployeeWraper +{ + public string FirstName { get; set; } + public string LastName { get; set; } + public string UserName { get; set; } + public string Email { get; set; } + public List<Contact> Contacts { get; set; } + public ApiDateTime Birthday { get; set; } + public string Sex { get; set; } + public EmployeeStatus Status { get; set; } + public EmployeeActivationStatus ActivationStatus { get; set; } + public ApiDateTime Terminated { get; set; } + public string Department { get; set; } + public ApiDateTime WorkFrom { get; set; } + public List<GroupWrapperSummary> Groups { get; set; } + public string Location { get; set; } + public string Notes { get; set; } + public string AvatarMax { get; set; } + public string AvatarMedium { get; set; } + public string Avatar { get; set; } + public bool IsAdmin { get; set; } + public bool IsLDAP { get; set; } + public List<string> ListAdminModules { get; set; } + public bool IsOwner { get; set; } + public bool IsVisitor { get; set; } + public string CultureName { get; set; } + public string MobilePhone { get; set; } + public MobilePhoneActivationStatus MobilePhoneActivationStatus { get; set; } + public bool IsSSO { get; set; } + + public new static EmployeeWraperFull GetSample() + { + return new EmployeeWraperFull { - return new EmployeeWraperFull - { - Avatar = "url to big avatar", - AvatarSmall = "url to small avatar", - AvatarMax = "url to max avatar", - Contacts = new List<Contact> { Contact.GetSample() }, - Email = "my@gmail.com", - FirstName = "Mike", - Id = Guid.Empty, - IsAdmin = false, - ListAdminModules = new List<string> { "projects", "crm" }, - UserName = "Mike.Zanyatski", - LastName = "Zanyatski", - Title = "Manager", - Groups = new List<GroupWrapperSummary> { GroupWrapperSummary.GetSample() }, - AvatarMedium = "url to medium avatar", - Birthday = ApiDateTime.GetSample(), - Department = "Marketing", - Location = "Palo Alto", - Notes = "Notes to worker", - Sex = "male", - Status = EmployeeStatus.Active, - WorkFrom = ApiDateTime.GetSample(), - Terminated = ApiDateTime.GetSample(), - CultureName = "en-EN", - IsLDAP = false, - IsSSO = false - }; - } + Avatar = "url to big avatar", + AvatarSmall = "url to small avatar", + AvatarMax = "url to max avatar", + Contacts = new List<Contact> { Contact.GetSample() }, + Email = "my@gmail.com", + FirstName = "Mike", + Id = Guid.Empty, + IsAdmin = false, + ListAdminModules = new List<string> { "projects", "crm" }, + UserName = "Mike.Zanyatski", + LastName = "Zanyatski", + Title = "Manager", + Groups = new List<GroupWrapperSummary> { GroupWrapperSummary.GetSample() }, + AvatarMedium = "url to medium avatar", + Birthday = ApiDateTime.GetSample(), + Department = "Marketing", + Location = "Palo Alto", + Notes = "Notes to worker", + Sex = "male", + Status = EmployeeStatus.Active, + WorkFrom = ApiDateTime.GetSample(), + Terminated = ApiDateTime.GetSample(), + CultureName = "en-EN", + IsLDAP = false, + IsSSO = false + }; + } +} + +[Scope] +public class EmployeeWraperFullHelper : EmployeeWraperHelper +{ + private readonly ApiContext _context; + private readonly WebItemSecurity _webItemSecurity; + private readonly ApiDateTimeHelper _apiDateTimeHelper; + + public EmployeeWraperFullHelper( + ApiContext context, + UserManager userManager, + UserPhotoManager userPhotoManager, + WebItemSecurity webItemSecurity, + CommonLinkUtility commonLinkUtility, + DisplayUserSettingsHelper displayUserSettingsHelper, + ApiDateTimeHelper apiDateTimeHelper) + : base(context, displayUserSettingsHelper, userPhotoManager, commonLinkUtility, userManager) + { + _context = context; + _webItemSecurity = webItemSecurity; + _apiDateTimeHelper = apiDateTimeHelper; } - [Scope] - public class EmployeeWraperFullHelper : EmployeeWraperHelper + public static Expression<Func<User, UserInfo>> GetExpression(ApiContext apiContext) { - private readonly ApiContext _context; - private readonly WebItemSecurity _webItemSecurity; - private readonly ApiDateTimeHelper _apiDateTimeHelper; + if (apiContext?.Fields == null) return null; + var newExpr = Expression.New(typeof(UserInfo)); - public EmployeeWraperFullHelper( - ApiContext context, - UserManager userManager, - UserPhotoManager userPhotoManager, - WebItemSecurity webItemSecurity, - CommonLinkUtility commonLinkUtility, - DisplayUserSettingsHelper displayUserSettingsHelper, - ApiDateTimeHelper apiDateTimeHelper) - : base(context, displayUserSettingsHelper, userPhotoManager, commonLinkUtility, userManager) + //i => new UserInfo { ID = i.id } + var parameter = Expression.Parameter(typeof(User), "i"); + var bindExprs = new List<MemberAssignment>(); + + if (apiContext.Check("Id")) + bindExprs.Add(Expression.Bind(typeof(UserInfo).GetProperty("ID"), Expression.Property(parameter, typeof(User).GetProperty("Id")))); + + var body = Expression.MemberInit(newExpr, bindExprs); + var lambda = Expression.Lambda<Func<User, UserInfo>>(body, parameter); + + return lambda; + } + + public EmployeeWraperFull GetFull(UserInfo userInfo) + { + var result = new EmployeeWraperFull { - _context = context; - _webItemSecurity = webItemSecurity; - _apiDateTimeHelper = apiDateTimeHelper; - } + UserName = userInfo.UserName, + FirstName = userInfo.FirstName, + LastName = userInfo.LastName, + Birthday = _apiDateTimeHelper.Get(userInfo.BirthDate), + Status = userInfo.Status, + ActivationStatus = userInfo.ActivationStatus & ~EmployeeActivationStatus.AutoGenerated, + Terminated = _apiDateTimeHelper.Get(userInfo.TerminatedDate), + WorkFrom = _apiDateTimeHelper.Get(userInfo.WorkFromDate), + Email = userInfo.Email, + IsVisitor = userInfo.IsVisitor(UserManager), + IsAdmin = userInfo.IsAdmin(UserManager), + IsOwner = userInfo.IsOwner(_context.Tenant), + IsLDAP = userInfo.IsLDAP(), + IsSSO = userInfo.IsSSO() + }; - public static Expression<Func<User, UserInfo>> GetExpression(ApiContext apiContext) + Init(result, userInfo); + + if (userInfo.Sex.HasValue) + result.Sex = userInfo.Sex.Value ? "male" : "female"; + + if (!string.IsNullOrEmpty(userInfo.Location)) + result.Location = userInfo.Location; + + if (!string.IsNullOrEmpty(userInfo.Notes)) + result.Notes = userInfo.Notes; + + if (!string.IsNullOrEmpty(userInfo.MobilePhone)) + result.MobilePhone = userInfo.MobilePhone; + + result.MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus; + + if (!string.IsNullOrEmpty(userInfo.CultureName)) + result.CultureName = userInfo.CultureName; + + FillConacts(result, userInfo); + + if (_context.Check("groups") || _context.Check("department")) { - if (apiContext?.Fields == null) return null; - var newExpr = Expression.New(typeof(UserInfo)); + var groups = UserManager.GetUserGroups(userInfo.ID) + .Select(x => new GroupWrapperSummary(x, UserManager)) + .ToList(); - //i => new UserInfo { ID = i.id } - var parameter = Expression.Parameter(typeof(User), "i"); - var bindExprs = new List<MemberAssignment>(); - - if (apiContext.Check("Id")) - bindExprs.Add(Expression.Bind(typeof(UserInfo).GetProperty("ID"), Expression.Property(parameter, typeof(User).GetProperty("Id")))); - - var body = Expression.MemberInit(newExpr, bindExprs); - var lambda = Expression.Lambda<Func<User, UserInfo>>(body, parameter); - - return lambda; - } - - public EmployeeWraperFull GetFull(UserInfo userInfo) - { - var result = new EmployeeWraperFull + if (groups.Count > 0) { - UserName = userInfo.UserName, - FirstName = userInfo.FirstName, - LastName = userInfo.LastName, - Birthday = _apiDateTimeHelper.Get(userInfo.BirthDate), - Status = userInfo.Status, - ActivationStatus = userInfo.ActivationStatus & ~EmployeeActivationStatus.AutoGenerated, - Terminated = _apiDateTimeHelper.Get(userInfo.TerminatedDate), - WorkFrom = _apiDateTimeHelper.Get(userInfo.WorkFromDate), - Email = userInfo.Email, - IsVisitor = userInfo.IsVisitor(UserManager), - IsAdmin = userInfo.IsAdmin(UserManager), - IsOwner = userInfo.IsOwner(_context.Tenant), - IsLDAP = userInfo.IsLDAP(), - IsSSO = userInfo.IsSSO() - }; - - Init(result, userInfo); - - if (userInfo.Sex.HasValue) - result.Sex = userInfo.Sex.Value ? "male" : "female"; - - if (!string.IsNullOrEmpty(userInfo.Location)) - result.Location = userInfo.Location; - - if (!string.IsNullOrEmpty(userInfo.Notes)) - result.Notes = userInfo.Notes; - - if (!string.IsNullOrEmpty(userInfo.MobilePhone)) - result.MobilePhone = userInfo.MobilePhone; - - result.MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus; - - if (!string.IsNullOrEmpty(userInfo.CultureName)) - result.CultureName = userInfo.CultureName; - - FillConacts(result, userInfo); - - if (_context.Check("groups") || _context.Check("department")) - { - var groups = UserManager.GetUserGroups(userInfo.ID) - .Select(x => new GroupWrapperSummary(x, UserManager)) - .ToList(); - - if (groups.Count > 0) - { - result.Groups = groups; - result.Department = string.Join(", ", result.Groups.Select(d => d.Name.HtmlEncode())); - } - else result.Department = ""; + result.Groups = groups; + result.Department = string.Join(", ", result.Groups.Select(d => d.Name.HtmlEncode())); } - - var userInfoLM = userInfo.LastModified.GetHashCode(); - - if (_context.Check("avatarMax")) - result.AvatarMax = UserPhotoManager.GetMaxPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); - - if (_context.Check("avatarMedium")) - result.AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); - - if (_context.Check("avatar")) - result.Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); - - if (_context.Check("listAdminModules")) - { - var listAdminModules = userInfo.GetListAdminModules(_webItemSecurity); - - if (listAdminModules.Any()) result.ListAdminModules = listAdminModules; - } - - return result; + else result.Department = ""; } - private void FillConacts(EmployeeWraperFull employeeWraperFull, UserInfo userInfo) + var userInfoLM = userInfo.LastModified.GetHashCode(); + + if (_context.Check("avatarMax")) + result.AvatarMax = UserPhotoManager.GetMaxPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + + if (_context.Check("avatarMedium")) + result.AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + + if (_context.Check("avatar")) + result.Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + + if (_context.Check("listAdminModules")) { - if (userInfo.ContactsList == null) return; + var listAdminModules = userInfo.GetListAdminModules(_webItemSecurity); - var contacts = new List<Contact>(); - - for (var i = 0; i < userInfo.ContactsList.Count; i += 2) - { - if (i + 1 < userInfo.ContactsList.Count) - contacts.Add(new Contact(userInfo.ContactsList[i], userInfo.ContactsList[i + 1])); - } - - if (contacts.Any()) - employeeWraperFull.Contacts = contacts; + if (listAdminModules.Any()) result.ListAdminModules = listAdminModules; } + + return result; + } + + private void FillConacts(EmployeeWraperFull employeeWraperFull, UserInfo userInfo) + { + if (userInfo.ContactsList == null) return; + + var contacts = new List<Contact>(); + + for (var i = 0; i < userInfo.ContactsList.Count; i += 2) + { + if (i + 1 < userInfo.ContactsList.Count) + contacts.Add(new Contact(userInfo.ContactsList[i], userInfo.ContactsList[i + 1])); + } + + if (contacts.Any()) + employeeWraperFull.Contacts = contacts; } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Model/GroupWrapperSummary.cs b/common/ASC.Api.Core/Model/GroupWrapperSummary.cs index 015a3d3298..0730231a5d 100644 --- a/common/ASC.Api.Core/Model/GroupWrapperSummary.cs +++ b/common/ASC.Api.Core/Model/GroupWrapperSummary.cs @@ -25,24 +25,23 @@ using GroupInfo = ASC.Core.Users.GroupInfo; -namespace ASC.Web.Api.Models +namespace ASC.Web.Api.Models; + +public class GroupWrapperSummary { - public class GroupWrapperSummary + public Guid Id { get; set; } + public string Name { get; set; } + public string Manager { get; set; } + + protected GroupWrapperSummary() { } + + public GroupWrapperSummary(GroupInfo group, UserManager userManager) { - public Guid Id { get; set; } - public string Name { get; set; } - public string Manager { get; set; } - - protected GroupWrapperSummary() { } - - public GroupWrapperSummary(GroupInfo group, UserManager userManager) - { - Id = group.ID; - Name = group.Name; - Manager = userManager.GetUsers(userManager.GetDepartmentManager(group.ID)).UserName; - } - - public static GroupWrapperSummary GetSample() => - new GroupWrapperSummary { Id = Guid.Empty, Manager = "Jake.Zazhitski", Name = "Group Name" }; + Id = group.ID; + Name = group.Name; + Manager = userManager.GetUsers(userManager.GetDepartmentManager(group.ID)).UserName; } + + public static GroupWrapperSummary GetSample() => + new GroupWrapperSummary { Id = Guid.Empty, Manager = "Jake.Zazhitski", Name = "Group Name" }; } \ No newline at end of file diff --git a/common/ASC.Api.Core/Routing/DefaultRoute.cs b/common/ASC.Api.Core/Routing/DefaultRoute.cs index 1ed47a993f..578a7da0f9 100644 --- a/common/ASC.Api.Core/Routing/DefaultRoute.cs +++ b/common/ASC.Api.Core/Routing/DefaultRoute.cs @@ -1,11 +1,10 @@ -namespace ASC.Web.Api.Routing +namespace ASC.Web.Api.Routing; + +public class DefaultRouteAttribute : RouteAttribute { - public class DefaultRouteAttribute : RouteAttribute - { - public static string BaseUrl { get; set; } + public static string BaseUrl { get; set; } - static DefaultRouteAttribute() => BaseUrl = "api/2.0"; + static DefaultRouteAttribute() => BaseUrl = "api/2.0"; - public DefaultRouteAttribute() : base(BaseUrl) { } - } + public DefaultRouteAttribute() : base(BaseUrl) { } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Routing/FormatRoute.cs b/common/ASC.Api.Core/Routing/FormatRoute.cs index 570ac592dd..0efa28983d 100644 --- a/common/ASC.Api.Core/Routing/FormatRoute.cs +++ b/common/ASC.Api.Core/Routing/FormatRoute.cs @@ -1,56 +1,55 @@ -namespace ASC.Web.Api.Routing +namespace ASC.Web.Api.Routing; + +public abstract class CustomHttpMethodAttribute : HttpMethodAttribute { - public abstract class CustomHttpMethodAttribute : HttpMethodAttribute + public bool Check { get; set; } + public bool DisableFormat { get; set; } + + public CustomHttpMethodAttribute(string method, string template = null, bool check = true, int order = 1) + : base(new List<string>() { method }, $"[controller]{(template != null ? $"/{template}" : "")}") { - public bool Check { get; set; } - public bool DisableFormat { get; set; } - - public CustomHttpMethodAttribute(string method, string template = null, bool check = true, int order = 1) - : base(new List<string>() { method }, $"[controller]{(template != null ? $"/{template}" : "")}") - { - Check = check; - Order = order; - } + Check = check; + Order = order; } +} - public class ReadAttribute : CustomHttpMethodAttribute - { - public ReadAttribute(bool check = true, int order = 1) : - this(null, check, order) - { } +public class ReadAttribute : CustomHttpMethodAttribute +{ + public ReadAttribute(bool check = true, int order = 1) : + this(null, check, order) + { } - public ReadAttribute(string template, bool check = true, int order = 1) : - base(HttpMethod.Get.Method, template, check, order) - { } - } - public class CreateAttribute : CustomHttpMethodAttribute - { - public CreateAttribute(bool check = true, int order = 1) : - this(null, check, order) - { } + public ReadAttribute(string template, bool check = true, int order = 1) : + base(HttpMethod.Get.Method, template, check, order) + { } +} +public class CreateAttribute : CustomHttpMethodAttribute +{ + public CreateAttribute(bool check = true, int order = 1) : + this(null, check, order) + { } - public CreateAttribute(string template, bool check = true, int order = 1) : - base(HttpMethod.Post.Method, template, check, order) - { } - } - public class UpdateAttribute : CustomHttpMethodAttribute - { - public UpdateAttribute(bool check = true, int order = 1) : - this(null, check, order) - { } + public CreateAttribute(string template, bool check = true, int order = 1) : + base(HttpMethod.Post.Method, template, check, order) + { } +} +public class UpdateAttribute : CustomHttpMethodAttribute +{ + public UpdateAttribute(bool check = true, int order = 1) : + this(null, check, order) + { } - public UpdateAttribute(string template, bool check = true, int order = 1) : - base(HttpMethod.Put.Method, template, check, order) - { } - } - public class DeleteAttribute : CustomHttpMethodAttribute - { - public DeleteAttribute(bool check = true, int order = 1) : - this(null, check, order) - { } + public UpdateAttribute(string template, bool check = true, int order = 1) : + base(HttpMethod.Put.Method, template, check, order) + { } +} +public class DeleteAttribute : CustomHttpMethodAttribute +{ + public DeleteAttribute(bool check = true, int order = 1) : + this(null, check, order) + { } - public DeleteAttribute(string template, bool check = true, int order = 1) : - base(HttpMethod.Delete.Method, template, check, order) - { } - } + public DeleteAttribute(string template, bool check = true, int order = 1) : + base(HttpMethod.Delete.Method, template, check, order) + { } } \ No newline at end of file diff --git a/web/ASC.Web.Api/Controllers/AuthenticationController.cs b/web/ASC.Web.Api/Controllers/AuthenticationController.cs index 8118a22140..91b76e6b9f 100644 --- a/web/ASC.Web.Api/Controllers/AuthenticationController.cs +++ b/web/ASC.Web.Api/Controllers/AuthenticationController.cs @@ -1,4 +1,7 @@ -namespace ASC.Web.Api.Controllers +using Constants = ASC.Core.Users.Constants; +using SecurityContext = ASC.Core.SecurityContext; + +namespace ASC.Web.Api.Controllers { [Scope] [DefaultRoute] diff --git a/web/ASC.Web.Api/Controllers/ModulesController.cs b/web/ASC.Web.Api/Controllers/ModulesController.cs index ef930b6893..b08470f5f5 100644 --- a/web/ASC.Web.Api/Controllers/ModulesController.cs +++ b/web/ASC.Web.Api/Controllers/ModulesController.cs @@ -1,4 +1,6 @@ -namespace ASC.Web.Api.Controllers +using Module = ASC.Api.Core.Module; + +namespace ASC.Web.Api.Controllers { [Scope] [DefaultRoute] diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index 9abb983c9b..cd305f819f 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -23,6 +23,8 @@ * */ +using Constants = ASC.Core.Users.Constants; + namespace ASC.Api.Settings { [Scope] diff --git a/web/ASC.Web.Api/Models/QuotaWrapper.cs b/web/ASC.Web.Api/Models/QuotaWrapper.cs index 9f64332d32..512ded5901 100644 --- a/web/ASC.Web.Api/Models/QuotaWrapper.cs +++ b/web/ASC.Web.Api/Models/QuotaWrapper.cs @@ -26,6 +26,8 @@ using System.Text.Json.Serialization; +using Constants = ASC.Core.Users.Constants; + namespace ASC.Web.Studio.Core.Quota { public class QuotaWrapper diff --git a/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs b/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs index 26cb70a566..1932902922 100644 --- a/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs +++ b/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs @@ -36,6 +36,7 @@ using MimeKit; using AuthenticationException = System.Security.Authentication.AuthenticationException; using SecurityContext = ASC.Core.SecurityContext; +using SmtpClient = MailKit.Net.Smtp.SmtpClient; namespace ASC.Api.Settings.Smtp { From 3ad4ba6c0855bb4c74073257be54de27937f170c Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 16:53:34 +0300 Subject: [PATCH 123/167] fix after merge --- common/ASC.Api.Core/GlobalUsings.cs | 1 + .../ASC.AuditTrail/Repositories/LoginEventsRepository.cs | 2 +- web/ASC.Web.Api/Controllers/AuthenticationController.cs | 5 ++++- web/ASC.Web.Api/Controllers/ModulesController.cs | 4 +++- web/ASC.Web.Api/Controllers/SettingsController.cs | 2 ++ web/ASC.Web.Api/GlobalUsings.cs | 4 +++- web/ASC.Web.Api/Models/QuotaWrapper.cs | 4 +++- web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs | 1 + 8 files changed, 18 insertions(+), 5 deletions(-) diff --git a/common/ASC.Api.Core/GlobalUsings.cs b/common/ASC.Api.Core/GlobalUsings.cs index b326879afa..7d18c68999 100644 --- a/common/ASC.Api.Core/GlobalUsings.cs +++ b/common/ASC.Api.Core/GlobalUsings.cs @@ -82,3 +82,4 @@ global using NLog; global using NLog.Extensions.Logging; global using StackExchange.Redis.Extensions.Core.Configuration; +global using StackExchange.Redis.Extensions.Newtonsoft; \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs index 99294b2454..f62fcf86be 100644 --- a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs @@ -23,7 +23,7 @@ * */ -namespace ASC.AuditTrail.Data.Repositories; +namespace ASC.AuditTrail.Repositories; [Scope] public class LoginEventsRepository diff --git a/web/ASC.Web.Api/Controllers/AuthenticationController.cs b/web/ASC.Web.Api/Controllers/AuthenticationController.cs index 8118a22140..91b76e6b9f 100644 --- a/web/ASC.Web.Api/Controllers/AuthenticationController.cs +++ b/web/ASC.Web.Api/Controllers/AuthenticationController.cs @@ -1,4 +1,7 @@ -namespace ASC.Web.Api.Controllers +using Constants = ASC.Core.Users.Constants; +using SecurityContext = ASC.Core.SecurityContext; + +namespace ASC.Web.Api.Controllers { [Scope] [DefaultRoute] diff --git a/web/ASC.Web.Api/Controllers/ModulesController.cs b/web/ASC.Web.Api/Controllers/ModulesController.cs index ef930b6893..b08470f5f5 100644 --- a/web/ASC.Web.Api/Controllers/ModulesController.cs +++ b/web/ASC.Web.Api/Controllers/ModulesController.cs @@ -1,4 +1,6 @@ -namespace ASC.Web.Api.Controllers +using Module = ASC.Api.Core.Module; + +namespace ASC.Web.Api.Controllers { [Scope] [DefaultRoute] diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index 9abb983c9b..cd305f819f 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -23,6 +23,8 @@ * */ +using Constants = ASC.Core.Users.Constants; + namespace ASC.Api.Settings { [Scope] diff --git a/web/ASC.Web.Api/GlobalUsings.cs b/web/ASC.Web.Api/GlobalUsings.cs index a9b939a994..d3cc638d09 100644 --- a/web/ASC.Web.Api/GlobalUsings.cs +++ b/web/ASC.Web.Api/GlobalUsings.cs @@ -8,12 +8,13 @@ global using System.Security; global using System.Security.Authentication; global using System.Threading; global using System.Web; +global using System.Text.Json.Serialization; global using ASC.Api.Core; global using ASC.Api.Security; global using ASC.Api.Utils; global using ASC.AuditTrail; -global using ASC.AuditTrail.Data; +global using ASC.AuditTrail.Models; global using ASC.Common; global using ASC.Common.Caching; global using ASC.Common.Logging; @@ -47,6 +48,7 @@ global using ASC.Web.Studio.Core.SMS; global using ASC.Web.Studio.Core.TFA; global using ASC.Web.Studio.UserControls.Management; global using ASC.Web.Studio.Utility; +global using ASC.AuditTrail.Repositories; global using Microsoft.AspNetCore.Authorization; global using Microsoft.AspNetCore.Http; diff --git a/web/ASC.Web.Api/Models/QuotaWrapper.cs b/web/ASC.Web.Api/Models/QuotaWrapper.cs index 9f64332d32..09c823d638 100644 --- a/web/ASC.Web.Api/Models/QuotaWrapper.cs +++ b/web/ASC.Web.Api/Models/QuotaWrapper.cs @@ -24,7 +24,9 @@ */ -using System.Text.Json.Serialization; + + +using Constants = ASC.Core.Users.Constants; namespace ASC.Web.Studio.Core.Quota { diff --git a/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs b/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs index 26cb70a566..1932902922 100644 --- a/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs +++ b/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs @@ -36,6 +36,7 @@ using MimeKit; using AuthenticationException = System.Security.Authentication.AuthenticationException; using SecurityContext = ASC.Core.SecurityContext; +using SmtpClient = MailKit.Net.Smtp.SmtpClient; namespace ASC.Api.Settings.Smtp { From 2f0fce66de33a1d50250429b9bd6cc14a4e978c4 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 17:18:58 +0300 Subject: [PATCH 124/167] cosmetic --- common/ASC.Common/Caching/EventBusKafka.cs | 10 ++-- .../Collections/CachedDictionaryBase.cs | 10 ++-- .../Collections/HttpRequestDictionary.cs | 4 +- common/ASC.Common/Data/StreamExtension.cs | 2 +- common/ASC.Common/Data/TempPath.cs | 2 +- .../DependencyInjection/AutofacExtension.cs | 3 +- .../Geolocation/IPGeolocationInfo.cs | 2 +- common/ASC.Common/Logging/EFLoggerFactory.cs | 2 +- .../Logging/SelfCleaningAppender.cs | 2 +- .../ASC.Common/Logging/SelfCleaningTarget.cs | 2 +- .../Logging/SpecialFolderPathConverter.cs | 2 +- common/ASC.Common/Mapping/IMapFrom.cs | 2 +- common/ASC.Common/Module/BaseWcfClient.cs | 2 +- .../ASC.Common/Module/IServiceController.cs | 2 +- common/ASC.Common/Security/AscRandom.cs | 50 +++++++++---------- .../Security/Authentication/IUserAccount.cs | 2 - .../Security/Authorizing/Domain/Action.cs | 2 +- .../ASC.Common/Threading/DistributedTask.cs | 3 +- .../Threading/DistributedTaskProgress.cs | 2 +- .../Threading/DistributedTaskStatus.cs | 2 +- .../ASC.Common/Utils/ConfigurationManager.cs | 10 ++-- common/ASC.Common/Utils/CrossPlatformUtils.cs | 10 ++-- common/ASC.Common/Utils/DnsLookup.cs | 2 +- common/ASC.Common/Utils/HtmlUtil.cs | 24 ++++++--- .../ASC.Common/Utils/HttpRequestExtensions.cs | 1 - common/ASC.Common/Utils/JsonWebToken.cs | 2 +- common/ASC.Common/Utils/MailAddressUtils.cs | 2 +- common/ASC.Common/Utils/RandomString.cs | 2 +- common/ASC.Common/Utils/VelocityFormatter.cs | 2 +- .../Web/AbstractHttpAsyncHandler.cs | 2 +- .../ASC.Common/Web/DisposableHttpContext.cs | 17 ++++--- common/ASC.Common/Web/HttpException.cs | 2 +- .../ASC.Common/Web/ItemNotFoundException.cs | 2 +- common/ASC.Common/Web/VirtualPathUtility.cs | 2 +- 34 files changed, 97 insertions(+), 91 deletions(-) diff --git a/common/ASC.Common/Caching/EventBusKafka.cs b/common/ASC.Common/Caching/EventBusKafka.cs index 56428a95ac..08e2ea9b1e 100644 --- a/common/ASC.Common/Caching/EventBusKafka.cs +++ b/common/ASC.Common/Caching/EventBusKafka.cs @@ -18,7 +18,7 @@ namespace ASC.Common.Caching [Singletone] public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, new() { - private IProducer<AscCacheItem, T> Producer { get; set; } + private IProducer<AscCacheItem, T> _producer; private bool _disposedValue = false; // To detect redundant calls private readonly ClientConfig _clientConfig; @@ -49,9 +49,9 @@ namespace ASC.Common.Caching { try { - if (Producer == null) + if (_producer == null) { - Producer = new ProducerBuilder<AscCacheItem, T>(new ProducerConfig(_clientConfig)) + _producer = new ProducerBuilder<AscCacheItem, T>(new ProducerConfig(_clientConfig)) .SetErrorHandler((_, e) => _logger.Error(e)) .SetKeySerializer(_keySerializer) .SetValueSerializer(_valueSerializer) @@ -71,7 +71,7 @@ namespace ASC.Common.Caching } }; - Producer.ProduceAsync(channelName, message); + _producer.ProduceAsync(channelName, message); } catch (ProduceException<Null, string> e) { @@ -179,7 +179,7 @@ namespace ASC.Common.Caching { if (!_disposedValue) { - if (disposing && Producer != null) Producer.Dispose(); + if (disposing && _producer != null) _producer.Dispose(); _disposedValue = true; } diff --git a/common/ASC.Common/Collections/CachedDictionaryBase.cs b/common/ASC.Common/Collections/CachedDictionaryBase.cs index ee2e678e6c..87965acd66 100644 --- a/common/ASC.Common/Collections/CachedDictionaryBase.cs +++ b/common/ASC.Common/Collections/CachedDictionaryBase.cs @@ -32,8 +32,8 @@ namespace ASC.Collections { public abstract class CachedDictionaryBase<T> { - protected string baseKey; - protected Func<T, bool> condition; + protected string BaseKey; + protected Func<T, bool> Condition; public T this[string key] => Get(key); @@ -41,7 +41,7 @@ namespace ASC.Collections protected abstract void InsertRootKey(string rootKey); - public void Clear() => InsertRootKey(baseKey); + public void Clear() => InsertRootKey(BaseKey); public void Clear(string rootKey) => InsertRootKey(BuildKey(string.Empty, rootKey)); @@ -86,7 +86,7 @@ namespace ASC.Collections OnMiss(fullKey); var newValue = defaults(); - if (condition == null || condition(newValue)) + if (Condition == null || Condition(newValue)) Add(rootkey, key, newValue); return newValue; @@ -99,7 +99,7 @@ namespace ASC.Collections protected virtual T ReturnCached(object objectCache) => (T)objectCache; - protected string BuildKey(string key, string rootkey) => $"{baseKey}-{rootkey}-{key}"; + protected string BuildKey(string key, string rootkey) => $"{BaseKey}-{rootkey}-{key}"; protected abstract object GetObjectFromCache(string fullKey); diff --git a/common/ASC.Common/Collections/HttpRequestDictionary.cs b/common/ASC.Common/Collections/HttpRequestDictionary.cs index 7115b4db61..d6af39461e 100644 --- a/common/ASC.Common/Collections/HttpRequestDictionary.cs +++ b/common/ASC.Common/Collections/HttpRequestDictionary.cs @@ -33,8 +33,8 @@ namespace ASC.Collections public HttpRequestDictionary(HttpContext httpContext, string baseKey) { - condition = (T) => true; - this.baseKey = baseKey; + Condition = (T) => true; + BaseKey = baseKey; _httpContext = httpContext; } diff --git a/common/ASC.Common/Data/StreamExtension.cs b/common/ASC.Common/Data/StreamExtension.cs index c7e0dad7d1..f8ca664cd9 100644 --- a/common/ASC.Common/Data/StreamExtension.cs +++ b/common/ASC.Common/Data/StreamExtension.cs @@ -46,4 +46,4 @@ public static class StreamExtension totalRead += readed; } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Data/TempPath.cs b/common/ASC.Common/Data/TempPath.cs index dd22d03d91..33194d7d00 100644 --- a/common/ASC.Common/Data/TempPath.cs +++ b/common/ASC.Common/Data/TempPath.cs @@ -77,4 +77,4 @@ namespace System.IO return path; } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/DependencyInjection/AutofacExtension.cs b/common/ASC.Common/DependencyInjection/AutofacExtension.cs index 2962739483..da8790e387 100644 --- a/common/ASC.Common/DependencyInjection/AutofacExtension.cs +++ b/common/ASC.Common/DependencyInjection/AutofacExtension.cs @@ -18,6 +18,7 @@ namespace ASC.Common.DependencyInjection public string Type { get; set; } public IEnumerable<AutofacService> Services { get; set; } } + internal class AutofacService { public string Type { get; set; } @@ -144,4 +145,4 @@ namespace ASC.Common.DependencyInjection return context.LoadFromAssemblyPath(path); } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Geolocation/IPGeolocationInfo.cs b/common/ASC.Common/Geolocation/IPGeolocationInfo.cs index c505926623..7ec1a796d3 100644 --- a/common/ASC.Common/Geolocation/IPGeolocationInfo.cs +++ b/common/ASC.Common/Geolocation/IPGeolocationInfo.cs @@ -43,4 +43,4 @@ namespace ASC.Geolocation TimezoneName = string.Empty, }; } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Logging/EFLoggerFactory.cs b/common/ASC.Common/Logging/EFLoggerFactory.cs index 3db5b92bee..98ad6ded37 100644 --- a/common/ASC.Common/Logging/EFLoggerFactory.cs +++ b/common/ASC.Common/Logging/EFLoggerFactory.cs @@ -79,4 +79,4 @@ namespace ASC.Common.Logging } } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Logging/SelfCleaningAppender.cs b/common/ASC.Common/Logging/SelfCleaningAppender.cs index 72485df77b..25d41706d3 100644 --- a/common/ASC.Common/Logging/SelfCleaningAppender.cs +++ b/common/ASC.Common/Logging/SelfCleaningAppender.cs @@ -114,4 +114,4 @@ namespace ASC.Common.Logging } } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Logging/SelfCleaningTarget.cs b/common/ASC.Common/Logging/SelfCleaningTarget.cs index 7ec5fa3c70..18c27207da 100644 --- a/common/ASC.Common/Logging/SelfCleaningTarget.cs +++ b/common/ASC.Common/Logging/SelfCleaningTarget.cs @@ -147,4 +147,4 @@ namespace ASC.Common.Logging } } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs index 1b8609cef5..8fbb458da9 100644 --- a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs +++ b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs @@ -90,4 +90,4 @@ namespace ASC.Common.Logging } } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Mapping/IMapFrom.cs b/common/ASC.Common/Mapping/IMapFrom.cs index 3be8426f16..9f59cc0d55 100644 --- a/common/ASC.Common/Mapping/IMapFrom.cs +++ b/common/ASC.Common/Mapping/IMapFrom.cs @@ -31,4 +31,4 @@ namespace ASC.Common.Mapping { void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType()); } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Module/BaseWcfClient.cs b/common/ASC.Common/Module/BaseWcfClient.cs index 15035c7568..b6e567864b 100644 --- a/common/ASC.Common/Module/BaseWcfClient.cs +++ b/common/ASC.Common/Module/BaseWcfClient.cs @@ -55,4 +55,4 @@ namespace ASC.Common.Module } } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Module/IServiceController.cs b/common/ASC.Common/Module/IServiceController.cs index a43870ff1b..90f40098cd 100644 --- a/common/ASC.Common/Module/IServiceController.cs +++ b/common/ASC.Common/Module/IServiceController.cs @@ -32,4 +32,4 @@ namespace ASC.Common.Module void Stop(); } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Security/AscRandom.cs b/common/ASC.Common/Security/AscRandom.cs index 35d42187e8..9ac74898e8 100644 --- a/common/ASC.Common/Security/AscRandom.cs +++ b/common/ASC.Common/Security/AscRandom.cs @@ -30,47 +30,47 @@ namespace ASC.Common.Security { public class AscRandom : Random { - private const int MBIG = int.MaxValue; - private const int MSEED = 161803398; - private const int MZ = 0; + private const int Mbig = int.MaxValue; + private const int Mseed = 161803398; + private const int Mz = 0; - private int inext; - private int inextp; - private readonly int[] seeds; + private int _inext; + private int _inextp; + private readonly int[] _seeds; public AscRandom() : this(Environment.TickCount) { } public AscRandom(int seed) { - seeds = new int[56]; + _seeds = new int[56]; var num4 = (seed == int.MinValue) ? int.MaxValue : Math.Abs(seed); var num2 = 161803398 - num4; - seeds[^1] = num2; + _seeds[^1] = num2; var num3 = 1; - for (var i = 1; i < seeds.Length - 1; i++) + for (var i = 1; i < _seeds.Length - 1; i++) { - var index = (21 * i) % (seeds.Length - 1); - seeds[index] = num3; + var index = (21 * i) % (_seeds.Length - 1); + _seeds[index] = num3; num3 = num2 - num3; if (num3 < 0) num3 += int.MaxValue; - num2 = seeds[index]; + num2 = _seeds[index]; } for (var j = 1; j < 5; j++) { - for (var k = 1; k < seeds.Length; k++) + for (var k = 1; k < _seeds.Length; k++) { - seeds[k] -= seeds[1 + ((k + 30) % (seeds.Length - 1))]; + _seeds[k] -= _seeds[1 + ((k + 30) % (_seeds.Length - 1))]; - if (seeds[k] < 0) seeds[k] += int.MaxValue; + if (_seeds[k] < 0) _seeds[k] += int.MaxValue; } } - inext = 0; - inextp = 21; + _inext = 0; + _inextp = 21; } public override int Next(int maxValue) @@ -92,22 +92,22 @@ namespace ASC.Common.Security private int InternalSample() { - var inext = this.inext; - var inextp = this.inextp; + var inext = this._inext; + var inextp = this._inextp; - if (++inext >= seeds.Length - 1) inext = 1; + if (++inext >= _seeds.Length - 1) inext = 1; - if (++inextp >= seeds.Length - 1) inextp = 1; + if (++inextp >= _seeds.Length - 1) inextp = 1; - var num = seeds[inext] - seeds[inextp]; + var num = _seeds[inext] - _seeds[inextp]; if (num == int.MaxValue) num--; if (num < 0) num += int.MaxValue; - seeds[inext] = num; - this.inext = inext; - this.inextp = inextp; + _seeds[inext] = num; + this._inext = inext; + this._inextp = inextp; return num; } diff --git a/common/ASC.Common/Security/Authentication/IUserAccount.cs b/common/ASC.Common/Security/Authentication/IUserAccount.cs index 2636054f42..a3a211dd3e 100644 --- a/common/ASC.Common/Security/Authentication/IUserAccount.cs +++ b/common/ASC.Common/Security/Authentication/IUserAccount.cs @@ -30,9 +30,7 @@ namespace ASC.Common.Security.Authentication { string Email { get; } string FirstName { get; } - string LastName { get; } - string Title { get; } int Tenant { get; } } diff --git a/common/ASC.Common/Security/Authorizing/Domain/Action.cs b/common/ASC.Common/Security/Authorizing/Domain/Action.cs index 333ce6147b..3412d26d1a 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Action.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Action.cs @@ -55,4 +55,4 @@ namespace ASC.Common.Security.Authorizing public override string ToString() => Name; } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Threading/DistributedTask.cs b/common/ASC.Common/Threading/DistributedTask.cs index 5c17bd180e..b973d4d66d 100644 --- a/common/ASC.Common/Threading/DistributedTask.cs +++ b/common/ASC.Common/Threading/DistributedTask.cs @@ -66,7 +66,6 @@ namespace ASC.Common.Threading public DistributedTask(DistributedTaskCache distributedTaskCache) => DistributedTaskCache = distributedTaskCache; - public T GetProperty<T>(string name) { var prop = DistributedTaskCache.Props.FirstOrDefault(r => r.Key == name); @@ -98,4 +97,4 @@ namespace ASC.Common.Threading Publication(this); } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Threading/DistributedTaskProgress.cs b/common/ASC.Common/Threading/DistributedTaskProgress.cs index 9c08e8a509..471cbf5e25 100644 --- a/common/ASC.Common/Threading/DistributedTaskProgress.cs +++ b/common/ASC.Common/Threading/DistributedTaskProgress.cs @@ -38,4 +38,4 @@ namespace ASC.Common.Threading PublishChanges(); } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Threading/DistributedTaskStatus.cs b/common/ASC.Common/Threading/DistributedTaskStatus.cs index 740897c45f..34e5d626e7 100644 --- a/common/ASC.Common/Threading/DistributedTaskStatus.cs +++ b/common/ASC.Common/Threading/DistributedTaskStatus.cs @@ -34,4 +34,4 @@ namespace ASC.Common.Threading Canceled, Failted } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/ConfigurationManager.cs b/common/ASC.Common/Utils/ConfigurationManager.cs index 888494b7f7..a2ac1c667b 100644 --- a/common/ASC.Common/Utils/ConfigurationManager.cs +++ b/common/ASC.Common/Utils/ConfigurationManager.cs @@ -10,13 +10,13 @@ namespace ASC.Common.Utils { public class ConnectionStringCollection : IEnumerable<ConnectionStringSettings> { - private List<ConnectionStringSettings> Data { get; set; } + private List<ConnectionStringSettings> _data; - public ConnectionStringSettings this[string name] => Data.FirstOrDefault(r => r.Name == name); + public ConnectionStringSettings this[string name] => _data.FirstOrDefault(r => r.Name == name); - public ConnectionStringCollection(IEnumerable<ConnectionStringSettings> data) => Data = data.ToList(); + public ConnectionStringCollection(IEnumerable<ConnectionStringSettings> data) => _data = data.ToList(); - public IEnumerator<ConnectionStringSettings> GetEnumerator() => Data.GetEnumerator(); + public IEnumerator<ConnectionStringSettings> GetEnumerator() => _data.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } @@ -70,4 +70,4 @@ namespace ASC.Common.Utils public ConnectionStringSettings GetConnectionStrings(string key) => GetConnectionStrings()[key]; } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/CrossPlatformUtils.cs b/common/ASC.Common/Utils/CrossPlatformUtils.cs index 1ee211890b..ab9b111a60 100644 --- a/common/ASC.Common/Utils/CrossPlatformUtils.cs +++ b/common/ASC.Common/Utils/CrossPlatformUtils.cs @@ -30,9 +30,11 @@ namespace ASC.Common.Utils { public static class CrossPlatform { + private static char[] _pathSplitCharacters = new char[] { '/', '\\' }; + public static string PathCombine(string basePath, params string[] additional) { - var splits = additional.Select(s => s.Split(pathSplitCharacters)).ToArray(); + var splits = additional.Select(s => s.Split(_pathSplitCharacters)).ToArray(); var totalLength = splits.Sum(arr => arr.Length); var segments = new string[totalLength + 1]; segments[0] = basePath; @@ -48,8 +50,6 @@ namespace ASC.Common.Utils } return Path.Combine(segments); - } - - static char[] pathSplitCharacters = new char[] { '/', '\\' }; + } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/DnsLookup.cs b/common/ASC.Common/Utils/DnsLookup.cs index 7c2e31766d..72ebf33163 100644 --- a/common/ASC.Common/Utils/DnsLookup.cs +++ b/common/ASC.Common/Utils/DnsLookup.cs @@ -252,4 +252,4 @@ namespace ASC.Common.Utils return dnsMessage.AnswerRecords.Where(r => r.RecordType == type).Cast<T>().ToList(); } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/HtmlUtil.cs b/common/ASC.Common/Utils/HtmlUtil.cs index 36666798bf..84a3ebd2bb 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -33,10 +33,18 @@ namespace ASC.Common.Utils { public static class HtmlUtil { - private static readonly Regex tagReplacer = new Regex("<[^>]*>", RegexOptions.Multiline | RegexOptions.Compiled); - private static readonly Regex commentsReplacer = new Regex("<!--(?s).*?-->", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex xssReplacer = new Regex(@"<\s*(style|script)[^>]*>(.*?)<\s*/\s*(style|script)>", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Singleline); - private static readonly Regex Worder = new Regex(@"\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + private static readonly Regex _tagReplacer + = new Regex("<[^>]*>", RegexOptions.Multiline | RegexOptions.Compiled); + + private static readonly Regex _commentsReplacer + = new Regex("<!--(?s).*?-->", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + private static readonly Regex _xssReplacer + = new Regex(@"<\s*(style|script)[^>]*>(.*?)<\s*/\s*(style|script)>", RegexOptions.IgnoreCase + | RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Singleline); + + private static readonly Regex _worder = + new Regex(@"\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); public static string GetText(string html, int maxLength = 0, string endBlockTemplate = "...") @@ -45,16 +53,16 @@ namespace ASC.Common.Utils if (!string.IsNullOrEmpty(html)) { - html = xssReplacer.Replace(html, string.Empty); //Clean malicious tags. <script> <style> + html = _xssReplacer.Replace(html, string.Empty); //Clean malicious tags. <script> <style> if (string.IsNullOrEmpty(html)) return html; - unformatedText = tagReplacer.Replace(html, string.Empty); + unformatedText = _tagReplacer.Replace(html, string.Empty); if (!string.IsNullOrEmpty(unformatedText)) { // kill comments - unformatedText = commentsReplacer.Replace(unformatedText, string.Empty); + unformatedText = _commentsReplacer.Replace(unformatedText, string.Empty); unformatedText = unformatedText.Trim(); if (!string.IsNullOrEmpty(unformatedText)) @@ -95,7 +103,7 @@ namespace ASC.Common.Utils { if (string.IsNullOrEmpty(searchText) || string.IsNullOrEmpty(htmlText)) return htmlText; - var regexpstr = Worder.Matches(searchText).Cast<Match>().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); + var regexpstr = _worder.Matches(searchText).Cast<Match>().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); var wordsFinder = new Regex(Regex.Escape(regexpstr), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline); return wordsFinder.Replace(htmlText, m => string.Format("<span class='searchTextHighlight{1}'>{0}</span>", m.Value, withoutLink ? " bold" : string.Empty)); diff --git a/common/ASC.Common/Utils/HttpRequestExtensions.cs b/common/ASC.Common/Utils/HttpRequestExtensions.cs index d543be0ff5..6f5f4ec4b0 100644 --- a/common/ASC.Common/Utils/HttpRequestExtensions.cs +++ b/common/ASC.Common/Utils/HttpRequestExtensions.cs @@ -40,7 +40,6 @@ namespace System.Web { public static readonly string UrlRewriterHeader = "X-REWRITER-URL"; - public static Uri GetUrlRewriter(this HttpRequest request) => request != null ? GetUrlRewriter(request.Headers, request) : null; diff --git a/common/ASC.Common/Utils/JsonWebToken.cs b/common/ASC.Common/Utils/JsonWebToken.cs index 25481d3cb8..718afa6b9c 100644 --- a/common/ASC.Common/Utils/JsonWebToken.cs +++ b/common/ASC.Common/Utils/JsonWebToken.cs @@ -101,4 +101,4 @@ namespace ASC.Web.Core.Files return JsonConvert.DeserializeObject<T>(json, settings); } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/MailAddressUtils.cs b/common/ASC.Common/Utils/MailAddressUtils.cs index fe8d9b1aab..19baf4e96b 100644 --- a/common/ASC.Common/Utils/MailAddressUtils.cs +++ b/common/ASC.Common/Utils/MailAddressUtils.cs @@ -63,4 +63,4 @@ namespace ASC.Common.Utils private static string ToSmtpAddress(string address, string displayName) => $"\"{displayName}\" <{address}>"; } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/RandomString.cs b/common/ASC.Common/Utils/RandomString.cs index 445e8a74a1..0f2dbdaa1b 100644 --- a/common/ASC.Common/Utils/RandomString.cs +++ b/common/ASC.Common/Utils/RandomString.cs @@ -45,4 +45,4 @@ namespace ASC.Common.Utils return res.ToString(); } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/VelocityFormatter.cs b/common/ASC.Common/Utils/VelocityFormatter.cs index 887d9f86d4..e4d20fae8a 100644 --- a/common/ASC.Common/Utils/VelocityFormatter.cs +++ b/common/ASC.Common/Utils/VelocityFormatter.cs @@ -92,4 +92,4 @@ namespace ASC.Common.Utils return writer.GetStringBuilder().ToString(); } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs b/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs index d30f2aad16..bde89d4b9e 100644 --- a/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs +++ b/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs @@ -61,4 +61,4 @@ namespace ASC.Common.Web public abstract void OnProcessRequest(Microsoft.AspNetCore.Http.HttpContext context); } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Web/DisposableHttpContext.cs b/common/ASC.Common/Web/DisposableHttpContext.cs index 54249a17da..c51dd232dc 100644 --- a/common/ASC.Common/Web/DisposableHttpContext.cs +++ b/common/ASC.Common/Web/DisposableHttpContext.cs @@ -35,12 +35,7 @@ namespace ASC.Common.Web { public class DisposableHttpContext : IDisposable { - private const string key = "disposable.key"; - private readonly Microsoft.AspNetCore.Http.HttpContext _context; - private bool _isDisposed; - - public DisposableHttpContext(Microsoft.AspNetCore.Http.HttpContext ctx) => - _context = ctx ?? throw new ArgumentNullException(); + private const string Key = "disposable.key"; public object this[string key] { @@ -53,16 +48,22 @@ namespace ASC.Common.Web } } + private readonly Microsoft.AspNetCore.Http.HttpContext _context; + private bool _isDisposed; + + public DisposableHttpContext(Microsoft.AspNetCore.Http.HttpContext ctx) => + _context = ctx ?? throw new ArgumentNullException(nameof(ctx)); + private Dictionary<string, IDisposable> Items { get { - var table = (Dictionary<string, IDisposable>)_context.Items[key]; + var table = (Dictionary<string, IDisposable>)_context.Items[Key]; if (table == null) { table = new Dictionary<string, IDisposable>(1); - _context.Items.Add(key, table); + _context.Items.Add(Key, table); } return table; diff --git a/common/ASC.Common/Web/HttpException.cs b/common/ASC.Common/Web/HttpException.cs index 62b2e3f061..6ac6d93e7c 100644 --- a/common/ASC.Common/Web/HttpException.cs +++ b/common/ASC.Common/Web/HttpException.cs @@ -20,4 +20,4 @@ namespace ASC.Common.Web public HttpException(HttpStatusCode httpStatusCode, string message, Exception inner) : base(message, inner) => StatusCode = (int)httpStatusCode; } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Web/ItemNotFoundException.cs b/common/ASC.Common/Web/ItemNotFoundException.cs index 169a6d581f..5d66665d22 100644 --- a/common/ASC.Common/Web/ItemNotFoundException.cs +++ b/common/ASC.Common/Web/ItemNotFoundException.cs @@ -11,4 +11,4 @@ namespace ASC.Common.Web public ItemNotFoundException(string message, Exception inner) : base(404, message, inner) { } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Web/VirtualPathUtility.cs b/common/ASC.Common/Web/VirtualPathUtility.cs index dc08c41c32..506b1408ba 100644 --- a/common/ASC.Common/Web/VirtualPathUtility.cs +++ b/common/ASC.Common/Web/VirtualPathUtility.cs @@ -15,4 +15,4 @@ namespace ASC.Common.Web return "/" + virtualPath.TrimStart('~', '/'); } } -} +} \ No newline at end of file From 4097f72e9407a41a5e837c6c12cf45ecd01270e6 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 3 Feb 2022 18:26:44 +0300 Subject: [PATCH 125/167] Common: used file-scope namespaces, remove unnecessary --- common/ASC.Common/ASC.Common.csproj | 6 - common/ASC.Common/Caching/AscCache.cs | 183 +- common/ASC.Common/Caching/EventBusKafka.cs | 294 ++- .../ASC.Common/Caching/EventBusMemoryCache.cs | 50 +- common/ASC.Common/Caching/EventType.cs | 21 +- common/ASC.Common/Caching/ICache.cs | 43 +- common/ASC.Common/Caching/IEventBus.cs | 17 +- common/ASC.Common/Caching/Protobuf.cs | 43 +- .../Collections/CachedDictionaryBase.cs | 155 +- .../Collections/HttpRequestDictionary.cs | 101 +- common/ASC.Common/DIHelper.cs | 625 ++++--- common/ASC.Common/Data/StreamExtension.cs | 2 + common/ASC.Common/Data/TempPath.cs | 95 +- common/ASC.Common/Data/TempStream.cs | 41 +- .../DependencyInjection/AutofacExtension.cs | 219 ++- .../Geolocation/IPGeolocationInfo.cs | 41 +- common/ASC.Common/GlobalUsings.cs | 2 + common/ASC.Common/Logging/EFLoggerFactory.cs | 121 +- common/ASC.Common/Logging/Log.cs | 1409 +++++++------- .../Logging/SelfCleaningAppender.cs | 149 +- .../ASC.Common/Logging/SelfCleaningTarget.cs | 211 ++- .../Logging/SpecialFolderPathConverter.cs | 121 +- common/ASC.Common/Mapping/IMapFrom.cs | 11 +- common/ASC.Common/Mapping/MappingProfile.cs | 37 +- common/ASC.Common/Module/BaseWcfClient.cs | 46 +- .../ASC.Common/Module/IServiceController.cs | 15 +- common/ASC.Common/Notify/AWSEmail.cs | 192 -- common/ASC.Common/Security/AscRandom.cs | 169 +- .../Security/Authentication/Account.cs | 45 +- .../Security/Authentication/IAccount.cs | 7 +- .../Security/Authentication/ISystemAccount.cs | 7 +- .../Security/Authentication/IUserAccount.cs | 19 +- .../Security/Authentication/SystemAccount.cs | 15 +- .../Authorizing/AuthorizingException.cs | 177 +- .../Security/Authorizing/AzObjectIdHelper.cs | 19 +- .../AzObjectSecurityProviderHelper.cs | 79 +- .../Security/Authorizing/Constants.cs | 23 +- .../Security/Authorizing/Domain/Ace.cs | 27 +- .../Security/Authorizing/Domain/AceType.cs | 13 +- .../Security/Authorizing/Domain/Action.cs | 51 +- .../Security/Authorizing/Domain/Role.cs | 57 +- .../Authorizing/Interfaces/IAction.cs | 17 +- .../Security/Authorizing/Interfaces/IRole.cs | 7 +- .../Authorizing/Interfaces/ISubject.cs | 11 +- .../Security/Cryptography/HashAlg.cs | 17 +- .../Security/Cryptography/Hasher.cs | 173 +- .../Security/Cryptography/InstanceCrypto.cs | 83 +- .../Cryptography/MachinePseudoKeys.cs | 67 +- .../Security/Cryptography/PasswordHasher.cs | 87 +- common/ASC.Common/Security/ISecurityObject.cs | 7 +- .../ASC.Common/Security/ISecurityObjectId.cs | 13 +- .../Security/ISecurityObjectProvider.cs | 21 +- .../Security/SecurityCallContext.cs | 27 +- .../ASC.Common/Security/SecurityObjectId.cs | 41 +- .../ASC.Common/Threading/DistributedTask.cs | 131 +- .../Threading/DistributedTaskProgress.cs | 71 +- .../Threading/DistributedTaskQueue.cs | 477 +++-- .../Threading/DistributedTaskStatus.cs | 19 +- .../Threading/Progress/IProgressItem.cs | 23 +- .../ASC.Common/Utils/ConfigurationManager.cs | 117 +- common/ASC.Common/Utils/CrossPlatformUtils.cs | 37 +- common/ASC.Common/Utils/DnsLookup.cs | 441 +++-- common/ASC.Common/Utils/HtmlUtil.cs | 125 +- .../ASC.Common/Utils/HttpRequestExtensions.cs | 321 ++-- common/ASC.Common/Utils/JsonWebToken.cs | 109 +- common/ASC.Common/Utils/MailAddressUtils.cs | 59 +- common/ASC.Common/Utils/MimeHeaderUtils.cs | 65 +- common/ASC.Common/Utils/RandomString.cs | 27 +- common/ASC.Common/Utils/Signature.cs | 97 +- .../TimeZoneConverter/TimeZoneConverter.cs | 525 +++--- common/ASC.Common/Utils/VelocityFormatter.cs | 113 +- common/ASC.Common/Utils/Wildcard.cs | 129 +- .../Web/AbstractHttpAsyncHandler.cs | 59 +- .../ASC.Common/Web/DisposableHttpContext.cs | 81 +- common/ASC.Common/Web/HttpException.cs | 25 +- .../ASC.Common/Web/ItemNotFoundException.cs | 17 +- common/ASC.Common/Web/MimeMapping.cs | 1651 ++++++++--------- common/ASC.Common/Web/RouteCallInfo.cs | 36 +- common/ASC.Common/Web/VirtualPathUtility.cs | 21 +- 79 files changed, 4997 insertions(+), 5308 deletions(-) delete mode 100644 common/ASC.Common/Notify/AWSEmail.cs diff --git a/common/ASC.Common/ASC.Common.csproj b/common/ASC.Common/ASC.Common.csproj index 6038ef792c..c5e0cd08fe 100644 --- a/common/ASC.Common/ASC.Common.csproj +++ b/common/ASC.Common/ASC.Common.csproj @@ -24,9 +24,6 @@ <EmbeddedResource Include="Utils\TimeZoneConverter\windowsZones.xml" /> <EmbeddedResource Include="Utils\TimeZoneConverter\timeZoneNames.xml" /> </ItemGroup> - <ItemGroup> - <Compile Remove="Notify\AWSEmail.cs" /> - </ItemGroup> <ItemGroup> <PackageReference Include="ARSoft.Tools.NetStandard.DXSdata" Version="1.0.0" /> <PackageReference Include="Autofac.Configuration" Version="6.0.0" /> @@ -64,7 +61,4 @@ <Protobuf Include="protos\distributed_task_cache.proto" /> <Protobuf Include="protos\distributed_task_cancelation.proto" /> </ItemGroup> - <ItemGroup> - <Folder Include="Notify\" /> - </ItemGroup> </Project> \ No newline at end of file diff --git a/common/ASC.Common/Caching/AscCache.cs b/common/ASC.Common/Caching/AscCache.cs index 162d3e0da9..87ada38b7e 100644 --- a/common/ASC.Common/Caching/AscCache.cs +++ b/common/ASC.Common/Caching/AscCache.cs @@ -23,111 +23,110 @@ * */ -namespace ASC.Common.Caching +namespace ASC.Common.Caching; + +[Singletone] +public class AscCacheNotify { - [Singletone] - public class AscCacheNotify + private readonly IEventBus<AscCacheItem> _eventBus; + + public AscCacheNotify(IEventBus<AscCacheItem> eventBus) { - private readonly IEventBus<AscCacheItem> _eventBus; + _eventBus = eventBus; - public AscCacheNotify(IEventBus<AscCacheItem> eventBus) + _eventBus.Subscribe((item) => { OnClearCache(); }, EventType.Any); + } + + public void ClearCache() => _eventBus.Publish(new AscCacheItem { Id = Guid.NewGuid().ToString() }, EventType.Any); + + public static void OnClearCache() + { + var keys = MemoryCache.Default.Select(r => r.Key).ToList(); + + foreach (var k in keys) { - _eventBus = eventBus; - - _eventBus.Subscribe((item) => { OnClearCache(); }, EventType.Any); + MemoryCache.Default.Remove(k); } + } +} - public void ClearCache() => _eventBus.Publish(new AscCacheItem { Id = Guid.NewGuid().ToString() }, EventType.Any); +[Singletone] +public class AscCache : ICache +{ + private readonly IMemoryCache _memoryCache; + private readonly ConcurrentDictionary<string, object> _memoryCacheKeys; - public static void OnClearCache() - { - var keys = MemoryCache.Default.Select(r => r.Key).ToList(); - - foreach (var k in keys) - { - MemoryCache.Default.Remove(k); - } + public AscCache(IMemoryCache memoryCache) + { + _memoryCache = memoryCache; + _memoryCacheKeys = new ConcurrentDictionary<string, object>(); + } + + public T Get<T>(string key) where T : class => _memoryCache.Get<T>(key); + + public void Insert(string key, object value, TimeSpan sligingExpiration) + { + var options = new MemoryCacheEntryOptions() + .SetSlidingExpiration(sligingExpiration) + .RegisterPostEvictionCallback(EvictionCallback); + + _memoryCache.Set(key, value, options); + _memoryCacheKeys.TryAdd(key, null); + } + + public void Insert(string key, object value, DateTime absolutExpiration) + { + var options = new MemoryCacheEntryOptions() + .SetAbsoluteExpiration(absolutExpiration == DateTime.MaxValue ? DateTimeOffset.MaxValue : new DateTimeOffset(absolutExpiration)) + .RegisterPostEvictionCallback(EvictionCallback); + + _memoryCache.Set(key, value, options); + _memoryCacheKeys.TryAdd(key, null); + } + + public void Remove(string key) => _memoryCache.Remove(key); + + public void Remove(Regex pattern) + { + var copy = _memoryCacheKeys.ToDictionary(p => p.Key, p => p.Value); + var keys = copy.Select(p => p.Key).Where(k => pattern.IsMatch(k)).ToArray(); + + foreach (var key in keys) + { + _memoryCache.Remove(key); } } - [Singletone] - public class AscCache : ICache + public ConcurrentDictionary<string, T> HashGetAll<T>(string key) => + _memoryCache.GetOrCreate(key, r => new ConcurrentDictionary<string, T>()); + + public T HashGet<T>(string key, string field) { - private readonly IMemoryCache _memoryCache; - private readonly ConcurrentDictionary<string, object> _memoryCacheKeys; + if (_memoryCache.TryGetValue<ConcurrentDictionary<string, T>>(key, out var dic) + && dic.TryGetValue(field, out var value)) + return value; - public AscCache(IMemoryCache memoryCache) + return default; + } + + public void HashSet<T>(string key, string field, T value) + { + var dic = HashGetAll<T>(key); + if (value != null) { - _memoryCache = memoryCache; - _memoryCacheKeys = new ConcurrentDictionary<string, object>(); - } - - public T Get<T>(string key) where T : class => _memoryCache.Get<T>(key); - - public void Insert(string key, object value, TimeSpan sligingExpiration) - { - var options = new MemoryCacheEntryOptions() - .SetSlidingExpiration(sligingExpiration) - .RegisterPostEvictionCallback(EvictionCallback); - - _memoryCache.Set(key, value, options); - _memoryCacheKeys.TryAdd(key, null); - } - - public void Insert(string key, object value, DateTime absolutExpiration) - { - var options = new MemoryCacheEntryOptions() - .SetAbsoluteExpiration(absolutExpiration == DateTime.MaxValue ? DateTimeOffset.MaxValue : new DateTimeOffset(absolutExpiration)) - .RegisterPostEvictionCallback(EvictionCallback); - - _memoryCache.Set(key, value, options); - _memoryCacheKeys.TryAdd(key, null); + dic.AddOrUpdate(field, value, (k, v) => value); + _memoryCache.Set(key, dic, DateTime.MaxValue); } - - public void Remove(string key) => _memoryCache.Remove(key); - - public void Remove(Regex pattern) - { - var copy = _memoryCacheKeys.ToDictionary(p => p.Key, p => p.Value); - var keys = copy.Select(p => p.Key).Where(k => pattern.IsMatch(k)).ToArray(); - - foreach (var key in keys) - { - _memoryCache.Remove(key); - } - } - - public ConcurrentDictionary<string, T> HashGetAll<T>(string key) => - _memoryCache.GetOrCreate(key, r => new ConcurrentDictionary<string, T>()); - - public T HashGet<T>(string key, string field) - { - if (_memoryCache.TryGetValue<ConcurrentDictionary<string, T>>(key, out var dic) - && dic.TryGetValue(field, out var value)) - return value; - - return default; - } - - public void HashSet<T>(string key, string field, T value) - { - var dic = HashGetAll<T>(key); - if (value != null) - { - dic.AddOrUpdate(field, value, (k, v) => value); - _memoryCache.Set(key, dic, DateTime.MaxValue); - } - else if (dic != null) - { - dic.TryRemove(field, out _); - - if (dic.IsEmpty) _memoryCache.Remove(key); - - else _memoryCache.Set(key, dic, DateTime.MaxValue); - } - } + else if (dic != null) + { + dic.TryRemove(field, out _); - private void EvictionCallback(object key, object value, EvictionReason reason, object state) => - _memoryCacheKeys.TryRemove(key.ToString(), out _); - } + if (dic.IsEmpty) _memoryCache.Remove(key); + + else _memoryCache.Set(key, dic, DateTime.MaxValue); + } + } + + private void EvictionCallback(object key, object value, EvictionReason reason, object state) => + _memoryCacheKeys.TryRemove(key.ToString(), out _); } \ No newline at end of file diff --git a/common/ASC.Common/Caching/EventBusKafka.cs b/common/ASC.Common/Caching/EventBusKafka.cs index 08e2ea9b1e..9d83fc4102 100644 --- a/common/ASC.Common/Caching/EventBusKafka.cs +++ b/common/ASC.Common/Caching/EventBusKafka.cs @@ -1,200 +1,184 @@ -using System; -using System.Collections.Concurrent; -using System.Threading; -using System.Threading.Tasks; +namespace ASC.Common.Caching; -using ASC.Common.Logging; -using ASC.Common.Utils; - -using Confluent.Kafka; -using Confluent.Kafka.Admin; - -using Google.Protobuf; - -using Microsoft.Extensions.Options; - -namespace ASC.Common.Caching +[Singletone] +public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, new() { - [Singletone] - public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, new() + private IProducer<AscCacheItem, T> _producer; + + private bool _disposedValue = false; // To detect redundant calls + private readonly ClientConfig _clientConfig; + private readonly AdminClientConfig _adminClientConfig; + private readonly ILog _logger; + private readonly ConcurrentDictionary<string, CancellationTokenSource> _cancelationToken; + private readonly ConcurrentDictionary<string, Action<T>> _actions; + private readonly ProtobufSerializer<T> _valueSerializer = new ProtobufSerializer<T>(); + private readonly ProtobufDeserializer<T> _valueDeserializer = new ProtobufDeserializer<T>(); + private readonly ProtobufSerializer<AscCacheItem> _keySerializer = new ProtobufSerializer<AscCacheItem>(); + private readonly ProtobufDeserializer<AscCacheItem> _keyDeserializer = new ProtobufDeserializer<AscCacheItem>(); + private readonly Guid _key; + + public EventBusKafka(ConfigurationExtension configuration, IOptionsMonitor<ILog> options) { - private IProducer<AscCacheItem, T> _producer; + _logger = options.CurrentValue; + _cancelationToken = new ConcurrentDictionary<string, CancellationTokenSource>(); + _actions = new ConcurrentDictionary<string, Action<T>>(); + _key = Guid.NewGuid(); - private bool _disposedValue = false; // To detect redundant calls - private readonly ClientConfig _clientConfig; - private readonly AdminClientConfig _adminClientConfig; - private readonly ILog _logger; - private readonly ConcurrentDictionary<string, CancellationTokenSource> _cancelationToken; - private readonly ConcurrentDictionary<string, Action<T>> _actions; - private readonly ProtobufSerializer<T> _valueSerializer = new ProtobufSerializer<T>(); - private readonly ProtobufDeserializer<T> _valueDeserializer = new ProtobufDeserializer<T>(); - private readonly ProtobufSerializer<AscCacheItem> _keySerializer = new ProtobufSerializer<AscCacheItem>(); - private readonly ProtobufDeserializer<AscCacheItem> _keyDeserializer = new ProtobufDeserializer<AscCacheItem>(); - private readonly Guid _key; + var settings = configuration.GetSetting<KafkaSettings>("kafka"); - public EventBusKafka(ConfigurationExtension configuration, IOptionsMonitor<ILog> options) + _clientConfig = new ClientConfig { BootstrapServers = settings.BootstrapServers }; + _adminClientConfig = new AdminClientConfig { BootstrapServers = settings.BootstrapServers }; + } + + public void Publish(T obj, EventType eventType) + { + try { - _logger = options.CurrentValue; - _cancelationToken = new ConcurrentDictionary<string, CancellationTokenSource>(); - _actions = new ConcurrentDictionary<string, Action<T>>(); - _key = Guid.NewGuid(); - - var settings = configuration.GetSetting<KafkaSettings>("kafka"); - - _clientConfig = new ClientConfig { BootstrapServers = settings.BootstrapServers }; - _adminClientConfig = new AdminClientConfig { BootstrapServers = settings.BootstrapServers }; - } - - public void Publish(T obj, EventType eventType) - { - try + if (_producer == null) { - if (_producer == null) - { - _producer = new ProducerBuilder<AscCacheItem, T>(new ProducerConfig(_clientConfig)) - .SetErrorHandler((_, e) => _logger.Error(e)) - .SetKeySerializer(_keySerializer) - .SetValueSerializer(_valueSerializer) - .Build(); - } - - var channelName = GetChannelName(eventType); - - if (_actions.TryGetValue(channelName, out var onchange)) onchange(obj); - - var message = new Message<AscCacheItem, T> - { - Value = obj, - Key = new AscCacheItem - { - Id = _key.ToString() - } - }; - - _producer.ProduceAsync(channelName, message); + _producer = new ProducerBuilder<AscCacheItem, T>(new ProducerConfig(_clientConfig)) + .SetErrorHandler((_, e) => _logger.Error(e)) + .SetKeySerializer(_keySerializer) + .SetValueSerializer(_valueSerializer) + .Build(); } - catch (ProduceException<Null, string> e) - { - _logger.Error(e); - } - catch (Exception e) - { - _logger.Error(e); - } - } - public void Subscribe(Action<T> onchange, EventType eventType) - { var channelName = GetChannelName(eventType); - _cancelationToken[channelName] = new CancellationTokenSource(); - _actions[channelName] = onchange; + if (_actions.TryGetValue(channelName, out var onchange)) onchange(obj); - void action() + var message = new Message<AscCacheItem, T> { - var conf = new ConsumerConfig(_clientConfig) + Value = obj, + Key = new AscCacheItem { - GroupId = Guid.NewGuid().ToString() - }; + Id = _key.ToString() + } + }; + + _producer.ProduceAsync(channelName, message); + } + catch (ProduceException<Null, string> e) + { + _logger.Error(e); + } + catch (Exception e) + { + _logger.Error(e); + } + } + + public void Subscribe(Action<T> onchange, EventType eventType) + { + var channelName = GetChannelName(eventType); + + _cancelationToken[channelName] = new CancellationTokenSource(); + _actions[channelName] = onchange; + + void action() + { + var conf = new ConsumerConfig(_clientConfig) + { + GroupId = Guid.NewGuid().ToString() + }; - using (var adminClient = new AdminClientBuilder(_adminClientConfig) - .SetErrorHandler((_, e) => _logger.Error(e)) - .Build()) + using (var adminClient = new AdminClientBuilder(_adminClientConfig) + .SetErrorHandler((_, e) => _logger.Error(e)) + .Build()) + { + try { - try - { - //TODO: must add checking exist - adminClient.CreateTopicsAsync( - new TopicSpecification[] - { + //TODO: must add checking exist + adminClient.CreateTopicsAsync( + new TopicSpecification[] + { new TopicSpecification { Name = channelName, NumPartitions = 1, ReplicationFactor = 1 } - }).Wait(); - } - catch (AggregateException) { } + }).Wait(); } + catch (AggregateException) { } + } - using var c = new ConsumerBuilder<AscCacheItem, T>(conf) - .SetErrorHandler((_, e) => _logger.Error(e)) - .SetKeyDeserializer(_keyDeserializer) - .SetValueDeserializer(_valueDeserializer) - .Build(); + using var c = new ConsumerBuilder<AscCacheItem, T>(conf) + .SetErrorHandler((_, e) => _logger.Error(e)) + .SetKeyDeserializer(_keyDeserializer) + .SetValueDeserializer(_valueDeserializer) + .Build(); - c.Assign(new TopicPartition(channelName, new Partition())); + c.Assign(new TopicPartition(channelName, new Partition())); - try + try + { + while (true) { - while (true) + try { - try + var cr = c.Consume(_cancelationToken[channelName].Token); + if (cr != null && cr.Message != null && cr.Message.Value != null && !(new Guid(cr.Message.Key.Id)).Equals(_key) && _actions.TryGetValue(channelName, out var act)) { - var cr = c.Consume(_cancelationToken[channelName].Token); - if (cr != null && cr.Message != null && cr.Message.Value != null && !(new Guid(cr.Message.Key.Id)).Equals(_key) && _actions.TryGetValue(channelName, out var act)) + try { - try - { - act(cr.Message.Value); - } - catch (Exception e) - { - _logger.Error("Kafka onmessage", e); - } + act(cr.Message.Value); + } + catch (Exception e) + { + _logger.Error("Kafka onmessage", e); } } - catch (ConsumeException e) - { - _logger.Error(e); - } + } + catch (ConsumeException e) + { + _logger.Error(e); } } - catch (OperationCanceledException) - { - c.Close(); - } } - - var task = new Task(action, TaskCreationOptions.LongRunning); - task.Start(); - } - - public void Unsubscribe(EventType eventType) - { - _cancelationToken.TryGetValue(GetChannelName(eventType), out var source); - - if (source != null) source.Cancel(); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (!_disposedValue) + catch (OperationCanceledException) { - if (disposing && _producer != null) _producer.Dispose(); - - _disposedValue = true; + c.Close(); } } - ~EventBusKafka() - { - Dispose(false); - } - - private string GetChannelName(EventType eventType) => $"ascchannel{eventType}{typeof(T).FullName}".ToLower(); + var task = new Task(action, TaskCreationOptions.LongRunning); + task.Start(); } - public class KafkaSettings + public void Unsubscribe(EventType eventType) { - public string BootstrapServers { get; set; } + _cancelationToken.TryGetValue(GetChannelName(eventType), out var source); + + if (source != null) source.Cancel(); } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (!_disposedValue) + { + if (disposing && _producer != null) _producer.Dispose(); + + _disposedValue = true; + } + } + + ~EventBusKafka() + { + Dispose(false); + } + + private string GetChannelName(EventType eventType) => $"ascchannel{eventType}{typeof(T).FullName}".ToLower(); +} + +public class KafkaSettings +{ + public string BootstrapServers { get; set; } } \ No newline at end of file diff --git a/common/ASC.Common/Caching/EventBusMemoryCache.cs b/common/ASC.Common/Caching/EventBusMemoryCache.cs index b450fec414..c777f0c2a2 100644 --- a/common/ASC.Common/Caching/EventBusMemoryCache.cs +++ b/common/ASC.Common/Caching/EventBusMemoryCache.cs @@ -1,34 +1,26 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading.Tasks; +namespace ASC.Common.Caching; -using Google.Protobuf; - -namespace ASC.Common.Caching +[Singletone] +public class EventBusMemoryCache<T> : IEventBus<T> where T : IMessage<T>, new() { - [Singletone] - public class EventBusMemoryCache<T> : IEventBus<T> where T : IMessage<T>, new() + private readonly ConcurrentDictionary<string, List<Action<T>>> _actions; + + public EventBusMemoryCache() => _actions = new ConcurrentDictionary<string, List<Action<T>>>(); + + public void Publish(T obj, EventType action) { - private readonly ConcurrentDictionary<string, List<Action<T>>> _actions; - - public EventBusMemoryCache() => _actions = new ConcurrentDictionary<string, List<Action<T>>>(); - - public void Publish(T obj, EventType action) - { - if (_actions.TryGetValue(GetKey(action), out var onchange) && onchange != null) - Parallel.ForEach(onchange, a => a(obj)); - } - - public void Subscribe(Action<T> onchange, EventType notifyAction) - { - if (onchange != null) - _actions.GetOrAdd(GetKey(notifyAction), new List<Action<T>>()) - .Add(onchange); - } - - public void Unsubscribe(EventType action) => _actions.TryRemove(GetKey(action), out _); - - private string GetKey(EventType cacheNotifyAction) => $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); + if (_actions.TryGetValue(GetKey(action), out var onchange) && onchange != null) + Parallel.ForEach(onchange, a => a(obj)); } + + public void Subscribe(Action<T> onchange, EventType notifyAction) + { + if (onchange != null) + _actions.GetOrAdd(GetKey(notifyAction), new List<Action<T>>()) + .Add(onchange); + } + + public void Unsubscribe(EventType action) => _actions.TryRemove(GetKey(action), out _); + + private string GetKey(EventType cacheNotifyAction) => $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); } \ No newline at end of file diff --git a/common/ASC.Common/Caching/EventType.cs b/common/ASC.Common/Caching/EventType.cs index 767af8f106..1c0134f723 100644 --- a/common/ASC.Common/Caching/EventType.cs +++ b/common/ASC.Common/Caching/EventType.cs @@ -23,15 +23,14 @@ * */ -namespace ASC.Common.Caching +namespace ASC.Common.Caching; + +[Flags] +public enum EventType { - [Flags] - public enum EventType - { - Insert = 1, - Update = 2, - Remove = 4, - InsertOrUpdate = Insert | Update, - Any = InsertOrUpdate | Remove, - } -} + Insert = 1, + Update = 2, + Remove = 4, + InsertOrUpdate = Insert | Update, + Any = InsertOrUpdate | Remove, +} \ No newline at end of file diff --git a/common/ASC.Common/Caching/ICache.cs b/common/ASC.Common/Caching/ICache.cs index db28129777..80d1b6c869 100644 --- a/common/ASC.Common/Caching/ICache.cs +++ b/common/ASC.Common/Caching/ICache.cs @@ -23,26 +23,25 @@ * */ -namespace ASC.Common.Caching +namespace ASC.Common.Caching; + +[Singletone(typeof(AscCache))] +public interface ICache { - [Singletone(typeof(AscCache))] - public interface ICache - { - T Get<T>(string key) where T : class; - - void Insert(string key, object value, TimeSpan sligingExpiration); - - void Insert(string key, object value, DateTime absolutExpiration); - - void Remove(string key); - - void Remove(Regex pattern); - - - ConcurrentDictionary<string, T> HashGetAll<T>(string key); - - T HashGet<T>(string key, string field); - - void HashSet<T>(string key, string field, T value); - } -} + T Get<T>(string key) where T : class; + + void Insert(string key, object value, TimeSpan sligingExpiration); + + void Insert(string key, object value, DateTime absolutExpiration); + + void Remove(string key); + + void Remove(Regex pattern); + + + ConcurrentDictionary<string, T> HashGetAll<T>(string key); + + T HashGet<T>(string key, string field); + + void HashSet<T>(string key, string field, T value); +} \ No newline at end of file diff --git a/common/ASC.Common/Caching/IEventBus.cs b/common/ASC.Common/Caching/IEventBus.cs index 1f093a4e2e..25e61b703d 100644 --- a/common/ASC.Common/Caching/IEventBus.cs +++ b/common/ASC.Common/Caching/IEventBus.cs @@ -23,15 +23,14 @@ * */ -namespace ASC.Common.Caching +namespace ASC.Common.Caching; + +[Singletone] +public interface IEventBus<T> where T : IMessage<T>, new() { - [Singletone] - public interface IEventBus<T> where T : IMessage<T>, new() - { - void Publish(T obj, EventType action); + void Publish(T obj, EventType action); - void Subscribe(Action<T> onchange, EventType action); + void Subscribe(Action<T> onchange, EventType action); - void Unsubscribe(EventType action); - } -} + void Unsubscribe(EventType action); +} \ No newline at end of file diff --git a/common/ASC.Common/Caching/Protobuf.cs b/common/ASC.Common/Caching/Protobuf.cs index d0bc3de348..69c1cf7398 100644 --- a/common/ASC.Common/Caching/Protobuf.cs +++ b/common/ASC.Common/Caching/Protobuf.cs @@ -1,24 +1,23 @@ -namespace ASC.Common.Caching +namespace ASC.Common.Caching; + +public class ProtobufSerializer<T> : ISerializer<T> where T : IMessage<T>, new() { - public class ProtobufSerializer<T> : ISerializer<T> where T : IMessage<T>, new() - { - public byte[] Serialize(T data, SerializationContext context) => data.ToByteArray(); - } - - public class ProtobufDeserializer<T> : IDeserializer<T> where T : IMessage<T>, new() - { - private readonly MessageParser<T> _parser; - - public ProtobufDeserializer() => _parser = new MessageParser<T>(() => new T()); - - public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context) - => _parser.ParseFrom(data.ToArray()); - } - - public static class GuidExtension - { - public static ByteString ToByteString(this Guid id) => ByteString.CopyFrom(id.ToByteArray()); - - public static Guid FromByteString(this ByteString id) => new Guid(id.ToByteArray()); - } + public byte[] Serialize(T data, SerializationContext context) => data.ToByteArray(); } + +public class ProtobufDeserializer<T> : IDeserializer<T> where T : IMessage<T>, new() +{ + private readonly MessageParser<T> _parser; + + public ProtobufDeserializer() => _parser = new MessageParser<T>(() => new T()); + + public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context) + => _parser.ParseFrom(data.ToArray()); +} + +public static class GuidExtension +{ + public static ByteString ToByteString(this Guid id) => ByteString.CopyFrom(id.ToByteArray()); + + public static Guid FromByteString(this ByteString id) => new Guid(id.ToByteArray()); +} \ No newline at end of file diff --git a/common/ASC.Common/Collections/CachedDictionaryBase.cs b/common/ASC.Common/Collections/CachedDictionaryBase.cs index aa3f0864f4..3c265b4294 100644 --- a/common/ASC.Common/Collections/CachedDictionaryBase.cs +++ b/common/ASC.Common/Collections/CachedDictionaryBase.cs @@ -23,85 +23,84 @@ * */ -namespace ASC.Collections +namespace ASC.Collections; + +public abstract class CachedDictionaryBase<T> { - public abstract class CachedDictionaryBase<T> + protected string BaseKey { get; set; } + protected Func<T, bool> Condition { get; set; } + + public T this[string key] => Get(key); + + public T this[Func<T> @default] => Get(@default); + + protected abstract void InsertRootKey(string rootKey); + + public void Clear() => InsertRootKey(BaseKey); + + public void Clear(string rootKey) => InsertRootKey(BuildKey(string.Empty, rootKey)); + + public void Reset(string key) => Reset(string.Empty, key); + + public abstract void Reset(string rootKey, string key); + + public T Get(string key) => Get(string.Empty, key, null); + + public T Get(string key, Func<T> defaults) => Get(string.Empty, key, defaults); + + public void Add(string key, T newValue) => Add(string.Empty, key, newValue); + + public abstract void Add(string rootkey, string key, T newValue); + + public bool HasItem(string key) => !Equals(Get(key), default(T)); + + public T Get(Func<T> @default) { - protected string BaseKey; - protected Func<T, bool> Condition; - - public T this[string key] => Get(key); - - public T this[Func<T> @default] => Get(@default); - - protected abstract void InsertRootKey(string rootKey); - - public void Clear() => InsertRootKey(BaseKey); - - public void Clear(string rootKey) => InsertRootKey(BuildKey(string.Empty, rootKey)); - - public void Reset(string key) => Reset(string.Empty, key); - - public abstract void Reset(string rootKey, string key); - - public T Get(string key) => Get(string.Empty, key, null); - - public T Get(string key, Func<T> defaults) => Get(string.Empty, key, defaults); - - public void Add(string key, T newValue) => Add(string.Empty, key, newValue); - - public abstract void Add(string rootkey, string key, T newValue); - - public bool HasItem(string key) => !Equals(Get(key), default(T)); - - public T Get(Func<T> @default) - { - var key = string.Format("func {0} {2}.{1}({3})", @default.Method.ReturnType, @default.Method.Name, - @default.Method.DeclaringType.FullName, - string.Join(",", - @default.Method.GetGenericArguments().Select(x => x.FullName).ToArray - ())); - return Get(key, @default); - } - - public virtual T Get(string rootkey, string key, Func<T> defaults) - { - var fullKey = BuildKey(key, rootkey); - var objectCache = GetObjectFromCache(fullKey); - - if (FitsCondition(objectCache)) - { - OnHit(fullKey); - - return ReturnCached(objectCache); - } - - if (defaults != null) - { - OnMiss(fullKey); - var newValue = defaults(); - - if (Condition == null || Condition(newValue)) - Add(rootkey, key, newValue); - - return newValue; - } - - return default; - } - - protected virtual bool FitsCondition(object cached) => cached != null && cached is T; - - protected virtual T ReturnCached(object objectCache) => (T)objectCache; - - protected string BuildKey(string key, string rootkey) => $"{BaseKey}-{rootkey}-{key}"; - - protected abstract object GetObjectFromCache(string fullKey); - - [Conditional("DEBUG")] - protected virtual void OnHit(string fullKey) => Debug.Print("cache hit:{0}", fullKey); - - [Conditional("DEBUG")] - protected virtual void OnMiss(string fullKey) => Debug.Print("cache miss:{0}", fullKey); + var key = string.Format("func {0} {2}.{1}({3})", @default.Method.ReturnType, @default.Method.Name, + @default.Method.DeclaringType.FullName, + string.Join(",", + @default.Method.GetGenericArguments().Select(x => x.FullName).ToArray + ())); + return Get(key, @default); } + + public virtual T Get(string rootkey, string key, Func<T> defaults) + { + var fullKey = BuildKey(key, rootkey); + var objectCache = GetObjectFromCache(fullKey); + + if (FitsCondition(objectCache)) + { + OnHit(fullKey); + + return ReturnCached(objectCache); + } + + if (defaults != null) + { + OnMiss(fullKey); + var newValue = defaults(); + + if (Condition == null || Condition(newValue)) + Add(rootkey, key, newValue); + + return newValue; + } + + return default; + } + + protected virtual bool FitsCondition(object cached) => cached != null && cached is T; + + protected virtual T ReturnCached(object objectCache) => (T)objectCache; + + protected string BuildKey(string key, string rootkey) => $"{BaseKey}-{rootkey}-{key}"; + + protected abstract object GetObjectFromCache(string fullKey); + + [Conditional("DEBUG")] + protected virtual void OnHit(string fullKey) => Debug.Print("cache hit:{0}", fullKey); + + [Conditional("DEBUG")] + protected virtual void OnMiss(string fullKey) => Debug.Print("cache miss:{0}", fullKey); } \ No newline at end of file diff --git a/common/ASC.Common/Collections/HttpRequestDictionary.cs b/common/ASC.Common/Collections/HttpRequestDictionary.cs index cf5b89307b..3c0ddcf883 100644 --- a/common/ASC.Common/Collections/HttpRequestDictionary.cs +++ b/common/ASC.Common/Collections/HttpRequestDictionary.cs @@ -23,57 +23,56 @@ * */ -namespace ASC.Collections -{ - public sealed class HttpRequestDictionary<T> : CachedDictionaryBase<T> - { - private readonly HttpContext _httpContext; - - public HttpRequestDictionary(HttpContext httpContext, string baseKey) - { - Condition = (T) => true; - BaseKey = baseKey; - _httpContext = httpContext; - } - - public override void Reset(string rootKey, string key) - { - if (_httpContext != null) - { - var builtkey = BuildKey(key, rootKey); - _httpContext.Items[builtkey] = null; - } - } - - public override void Add(string rootkey, string key, T newValue) - { - if (_httpContext != null) - { - var builtkey = BuildKey(key, rootkey); - _httpContext.Items[builtkey] = new CachedItem(newValue); - } - } - - protected override object GetObjectFromCache(string fullKey) => _httpContext?.Items[fullKey]; - - protected override bool FitsCondition(object cached) => cached is CachedItem; - - protected override T ReturnCached(object objectCache) => ((CachedItem)objectCache).Value; - - protected override void OnHit(string fullKey) { } - - protected override void OnMiss(string fullKey) { } +namespace ASC.Collections; - protected override void InsertRootKey(string rootKey) - { - //We can't expire in HtppContext in such way - } +public sealed class HttpRequestDictionary<T> : CachedDictionaryBase<T> +{ + private readonly HttpContext _httpContext; - private class CachedItem - { - internal T Value { get; set; } - - internal CachedItem(T value) => Value = value; - } - } + public HttpRequestDictionary(HttpContext httpContext, string baseKey) + { + Condition = (T) => true; + BaseKey = baseKey; + _httpContext = httpContext; + } + + public override void Reset(string rootKey, string key) + { + if (_httpContext != null) + { + var builtkey = BuildKey(key, rootKey); + _httpContext.Items[builtkey] = null; + } + } + + public override void Add(string rootkey, string key, T newValue) + { + if (_httpContext != null) + { + var builtkey = BuildKey(key, rootkey); + _httpContext.Items[builtkey] = new CachedItem(newValue); + } + } + + protected override object GetObjectFromCache(string fullKey) => _httpContext?.Items[fullKey]; + + protected override bool FitsCondition(object cached) => cached is CachedItem; + + protected override T ReturnCached(object objectCache) => ((CachedItem)objectCache).Value; + + protected override void OnHit(string fullKey) { } + + protected override void OnMiss(string fullKey) { } + + protected override void InsertRootKey(string rootKey) + { + //We can't expire in HtppContext in such way + } + + private class CachedItem + { + internal T Value { get; set; } + + internal CachedItem(T value) => Value = value; + } } \ No newline at end of file diff --git a/common/ASC.Common/DIHelper.cs b/common/ASC.Common/DIHelper.cs index c23b6ae2d2..b03d2df7b1 100644 --- a/common/ASC.Common/DIHelper.cs +++ b/common/ASC.Common/DIHelper.cs @@ -1,370 +1,369 @@ -namespace ASC.Common +namespace ASC.Common; + +public enum DIAttributeEnum { - public enum DIAttributeEnum + Singletone, + Scope, + Transient +} + +public class TransientAttribute : DIAttribute +{ + public override DIAttributeEnum DIAttributeEnum => DIAttributeEnum.Transient; + + public TransientAttribute() { } + + public TransientAttribute(Type service) : base(service) { } + + public TransientAttribute(Type service, Type implementation) : base(service, implementation) { } + + public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) { - Singletone, - Scope, - Transient + if (implementation != null) services.AddTransient(service, implementation); + + else services.AddTransient(service); + } +} + +public class ScopeAttribute : DIAttribute +{ + public override DIAttributeEnum DIAttributeEnum => DIAttributeEnum.Scope; + + public ScopeAttribute() { } + + public ScopeAttribute(Type service) : base(service) { } + + public ScopeAttribute(Type service, Type implementation) : base(service, implementation) { } + + public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) + { + if (implementation != null) services.AddScoped(service, implementation); + + else services.AddScoped(service); + } +} + +public class SingletoneAttribute : DIAttribute +{ + public override DIAttributeEnum DIAttributeEnum => DIAttributeEnum.Singletone; + + public SingletoneAttribute() { } + + public SingletoneAttribute(Type service) : base(service) { } + + public SingletoneAttribute(Type service, Type implementation) : base(service, implementation) { } + + public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) + { + if (implementation != null) services.AddSingleton(service, implementation); + + else services.AddSingleton(service); + } +} + +public abstract class DIAttribute : Attribute +{ + public abstract DIAttributeEnum DIAttributeEnum { get; } + public Type Implementation { get; } + public Type Service { get; } + public Type Additional { get; set; } + + public DIAttribute() { } + + public DIAttribute(Type service) => Service = service; + + public DIAttribute(Type service, Type implementation) + { + Implementation = implementation; + Service = service; } - public class TransientAttribute : DIAttribute + public abstract void TryAdd(IServiceCollection services, Type service, Type implementation = null); +} + +public class DIHelper +{ + public Dictionary<DIAttributeEnum, List<string>> Services { get; set; } + public List<string> Added { get; set; } + public List<string> Configured { get; set; } + public IServiceCollection ServiceCollection { get; private set; } + + public DIHelper() { - public override DIAttributeEnum DIAttributeEnum => DIAttributeEnum.Transient; - - public TransientAttribute() { } - - public TransientAttribute(Type service) : base(service) { } - - public TransientAttribute(Type service, Type implementation) : base(service, implementation) { } - - public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) - { - if (implementation != null) services.AddTransient(service, implementation); - - else services.AddTransient(service); - } - } - - public class ScopeAttribute : DIAttribute - { - public override DIAttributeEnum DIAttributeEnum => DIAttributeEnum.Scope; - - public ScopeAttribute() { } - - public ScopeAttribute(Type service) : base(service) { } - - public ScopeAttribute(Type service, Type implementation) : base(service, implementation) { } - - public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) - { - if (implementation != null) services.AddScoped(service, implementation); - - else services.AddScoped(service); - } - } - - public class SingletoneAttribute : DIAttribute - { - public override DIAttributeEnum DIAttributeEnum => DIAttributeEnum.Singletone; - - public SingletoneAttribute() { } - - public SingletoneAttribute(Type service) : base(service) { } - - public SingletoneAttribute(Type service, Type implementation) : base(service, implementation) { } - - public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) - { - if (implementation != null) services.AddSingleton(service, implementation); - - else services.AddSingleton(service); - } - } - - public abstract class DIAttribute : Attribute - { - public abstract DIAttributeEnum DIAttributeEnum { get; } - public Type Implementation { get; } - public Type Service { get; } - public Type Additional { get; set; } - - public DIAttribute() { } - - public DIAttribute(Type service) => Service = service; - - public DIAttribute(Type service, Type implementation) - { - Implementation = implementation; - Service = service; - } - - public abstract void TryAdd(IServiceCollection services, Type service, Type implementation = null); - } - - public class DIHelper - { - public Dictionary<DIAttributeEnum, List<string>> Services { get; set; } - public List<string> Added { get; set; } - public List<string> Configured { get; set; } - public IServiceCollection ServiceCollection { get; private set; } - - public DIHelper() - { - Services = new Dictionary<DIAttributeEnum, List<string>>() + Services = new Dictionary<DIAttributeEnum, List<string>>() { { DIAttributeEnum.Singletone, new List<string>() }, { DIAttributeEnum.Scope, new List<string>() }, { DIAttributeEnum.Transient, new List<string>() } }; - Added = new List<string>(); - Configured = new List<string>(); + Added = new List<string>(); + Configured = new List<string>(); + } + + public DIHelper(IServiceCollection serviceCollection) : this() => ServiceCollection = serviceCollection; + + public void Configure(IServiceCollection serviceCollection) => ServiceCollection = serviceCollection; + + public void RegisterProducts(IConfiguration configuration, string path) + { + var types = AutofacExtension.FindAndLoad(configuration, path); + + foreach (var t in types.Select(Type.GetType).Where(r => r != null)) + TryAdd(t); + } + + public bool TryAdd<TService>() where TService : class => TryAdd(typeof(TService)); + + public bool TryAdd<TService, TImplementation>() where TService : class => TryAdd(typeof(TService), typeof(TImplementation)); + + public bool TryAdd(Type service, Type implementation = null) + { + if (service.IsInterface && service.IsGenericType && implementation == null && + (service.GetGenericTypeDefinition() == typeof(IOptionsSnapshot<>) || + service.GetGenericTypeDefinition() == typeof(IOptions<>) || + service.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) + )) + { + service = service.GetGenericArguments().FirstOrDefault(); + + if (service == null) return false; } - public DIHelper(IServiceCollection serviceCollection) : this() => ServiceCollection = serviceCollection; + var serviceName = $"{service}{implementation}"; - public void Configure(IServiceCollection serviceCollection) => ServiceCollection = serviceCollection; + if (Added.Contains(serviceName)) return false; - public void RegisterProducts(IConfiguration configuration, string path) + Added.Add(serviceName); + + var di = service.IsGenericType && ( + service.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || + service.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || + service.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) + ) && implementation != null ? implementation.GetCustomAttribute<DIAttribute>() : service.GetCustomAttribute<DIAttribute>(); + + var isnew = false; + + if (di != null) { - var types = AutofacExtension.FindAndLoad(configuration, path); - - foreach (var t in types.Select(Type.GetType).Where(r => r != null)) - TryAdd(t); - } - - public bool TryAdd<TService>() where TService : class => TryAdd(typeof(TService)); - - public bool TryAdd<TService, TImplementation>() where TService : class => TryAdd(typeof(TService), typeof(TImplementation)); - - public bool TryAdd(Type service, Type implementation = null) - { - if (service.IsInterface && service.IsGenericType && implementation == null && - (service.GetGenericTypeDefinition() == typeof(IOptionsSnapshot<>) || - service.GetGenericTypeDefinition() == typeof(IOptions<>) || - service.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) - )) + if (di.Additional != null) { - service = service.GetGenericArguments().FirstOrDefault(); - - if (service == null) return false; + var m = di.Additional.GetMethod("Register", BindingFlags.Public | BindingFlags.Static); + m.Invoke(null, new[] { this }); } - var serviceName = $"{service}{implementation}"; - - if (Added.Contains(serviceName)) return false; - - Added.Add(serviceName); - - var di = service.IsGenericType && ( - service.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || - service.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || - service.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) - ) && implementation != null ? implementation.GetCustomAttribute<DIAttribute>() : service.GetCustomAttribute<DIAttribute>(); - - var isnew = false; - - if (di != null) + if (!service.IsInterface || implementation != null) { - if (di.Additional != null) - { - var m = di.Additional.GetMethod("Register", BindingFlags.Public | BindingFlags.Static); - m.Invoke(null, new[] { this }); - } + isnew = implementation != null ? Register(service, implementation) : Register(service); + if (!isnew) return false; + } - if (!service.IsInterface || implementation != null) + if (service.IsInterface && implementation == null || !service.IsInterface) + { + if (di.Service != null) { - isnew = implementation != null ? Register(service, implementation) : Register(service); - if (!isnew) return false; - } + var a = di.Service.GetInterfaces().FirstOrDefault(x => x.IsGenericType && ( + x.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || + x.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || + x.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) + )); - if (service.IsInterface && implementation == null || !service.IsInterface) - { - if (di.Service != null) + if (a != null) { - var a = di.Service.GetInterfaces().FirstOrDefault(x => x.IsGenericType && ( - x.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || - x.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || - x.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) - )); - - if (a != null) + if (!a.ContainsGenericParameters) { - if (!a.ContainsGenericParameters) + var b = a.GetGenericArguments(); + + foreach (var g in b) { - var b = a.GetGenericArguments(); - - foreach (var g in b) + if (g != service) { - if (g != service) - { - TryAdd(g); + TryAdd(g); - if (service.IsInterface && di.Implementation == null) TryAdd(service, g); - } + if (service.IsInterface && di.Implementation == null) TryAdd(service, g); } - - TryAdd(a, di.Service); } - else - { - Type c = null; - var a1 = a.GetGenericTypeDefinition(); - var b = a.GetGenericArguments().FirstOrDefault(); - if (b != null && b.IsGenericType) - { - var b1 = b.GetGenericTypeDefinition().MakeGenericType(service.GetGenericArguments()); - - TryAdd(b1); - c = a1.MakeGenericType(b1); - } - else - { - c = a1.MakeGenericType(service.GetGenericArguments()); - } - - TryAdd(c, di.Service.MakeGenericType(service.GetGenericArguments())); - //a, di.Service - } + TryAdd(a, di.Service); } else { - if (di.Implementation == null) + Type c = null; + var a1 = a.GetGenericTypeDefinition(); + var b = a.GetGenericArguments().FirstOrDefault(); + + if (b != null && b.IsGenericType) { - isnew = Register(service, di.Service); - TryAdd(di.Service); - } - else Register(di.Service); - } - } + var b1 = b.GetGenericTypeDefinition().MakeGenericType(service.GetGenericArguments()); - if (di.Implementation != null) - { - var a = di.Implementation.GetInterfaces().FirstOrDefault(x => x.IsGenericType && - (x.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || - x.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || - x.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>)) - ); - if (a != null) - { - if (!a.ContainsGenericParameters) - { - var b = a.GetGenericArguments(); - - foreach (var g in b) - { - if (g != service) - { - //TryAdd(g); - if (service.IsInterface && implementation == null) TryAdd(service, g); - } - } - - TryAdd(a, di.Implementation); + TryAdd(b1); + c = a1.MakeGenericType(b1); } else { - Type c = null; - var a1 = a.GetGenericTypeDefinition(); - var b = a.GetGenericArguments().FirstOrDefault(); - - if (b != null && b.IsGenericType) - { - var b1 = b.GetGenericTypeDefinition().MakeGenericType(service.GetGenericArguments()); - - TryAdd(b1); - c = a1.MakeGenericType(b1); - } - else c = a1.MakeGenericType(service.GetGenericArguments()); - - TryAdd(c, di.Implementation.MakeGenericType(service.GetGenericArguments())); - //a, di.Service + c = a1.MakeGenericType(service.GetGenericArguments()); } - } - else isnew = TryAdd(service, di.Implementation); + TryAdd(c, di.Service.MakeGenericType(service.GetGenericArguments())); + //a, di.Service + } + } + else + { + if (di.Implementation == null) + { + isnew = Register(service, di.Service); + TryAdd(di.Service); + } + else Register(di.Service); } } - } - if (isnew) - { - ConstructorInfo[] props = null; - - if (!service.IsInterface) props = service.GetConstructors(); - - else if (implementation != null) props = implementation.GetConstructors(); - - else if (di.Service != null) props = di.Service.GetConstructors(); - - if (props != null) + if (di.Implementation != null) { - var par = props.SelectMany(r => r.GetParameters()).Distinct(); + var a = di.Implementation.GetInterfaces().FirstOrDefault(x => x.IsGenericType && + (x.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || + x.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || + x.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>)) + ); + if (a != null) + { + if (!a.ContainsGenericParameters) + { + var b = a.GetGenericArguments(); - foreach (var p1 in par) - TryAdd(p1.ParameterType); + foreach (var g in b) + { + if (g != service) + { + //TryAdd(g); + if (service.IsInterface && implementation == null) TryAdd(service, g); + } + } + + TryAdd(a, di.Implementation); + } + else + { + Type c = null; + var a1 = a.GetGenericTypeDefinition(); + var b = a.GetGenericArguments().FirstOrDefault(); + + if (b != null && b.IsGenericType) + { + var b1 = b.GetGenericTypeDefinition().MakeGenericType(service.GetGenericArguments()); + + TryAdd(b1); + c = a1.MakeGenericType(b1); + } + else c = a1.MakeGenericType(service.GetGenericArguments()); + + TryAdd(c, di.Implementation.MakeGenericType(service.GetGenericArguments())); + //a, di.Service + } + } + + else isnew = TryAdd(service, di.Implementation); } } - - return isnew; } - public DIHelper TryAddSingleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class + if (isnew) { - var serviceName = $"{typeof(TService)}"; + ConstructorInfo[] props = null; - if (!Services[DIAttributeEnum.Singletone].Contains(serviceName)) + if (!service.IsInterface) props = service.GetConstructors(); + + else if (implementation != null) props = implementation.GetConstructors(); + + else if (di.Service != null) props = di.Service.GetConstructors(); + + if (props != null) { - Services[DIAttributeEnum.Singletone].Add(serviceName); - ServiceCollection.TryAddSingleton(implementationFactory); - } + var par = props.SelectMany(r => r.GetParameters()).Distinct(); - return this; + foreach (var p1 in par) + TryAdd(p1.ParameterType); + } } - public DIHelper TryAddSingleton<TService, TImplementation>() where TService : class where TImplementation : class, TService - { - var serviceName = $"{typeof(TService)}{typeof(TImplementation)}"; - - if (!Services[DIAttributeEnum.Singletone].Contains(serviceName)) - { - Services[DIAttributeEnum.Singletone].Add(serviceName); - ServiceCollection.TryAddSingleton<TService, TImplementation>(); - } - - return this; - } - - public DIHelper Configure<TOptions>(Action<TOptions> configureOptions) where TOptions : class - { - var serviceName = $"{typeof(TOptions)}"; - - if (!Configured.Contains(serviceName)) - { - Configured.Add(serviceName); - ServiceCollection.Configure(configureOptions); - } - - return this; - } - - public DIHelper Configure<TOptions>(string name, Action<TOptions> configureOptions) where TOptions : class - { - var serviceName = $"{typeof(TOptions)}{name}"; - - if (!Configured.Contains(serviceName)) - { - Configured.Add(serviceName); - ServiceCollection.Configure(name, configureOptions); - } - - return this; - } - - private bool Register(Type service, Type implementation = null) - { - if (service.IsSubclassOf(typeof(ControllerBase)) || service.GetInterfaces().Contains(typeof(IResourceFilter)) - || service.GetInterfaces().Contains(typeof(IDictionary<string, string>))) - return true; - - var c = service.IsGenericType && ( - service.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || - service.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || - service.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) - ) && implementation != null ? implementation.GetCustomAttribute<DIAttribute>() : service.GetCustomAttribute<DIAttribute>(); - - var serviceName = $"{service}{implementation}"; - - if (!Services[c.DIAttributeEnum].Contains(serviceName)) - { - c.TryAdd(ServiceCollection, service, implementation); - Services[c.DIAttributeEnum].Add(serviceName); - - return true; - } - - return false; - } + return isnew; } -} \ No newline at end of file + + public DIHelper TryAddSingleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class + { + var serviceName = $"{typeof(TService)}"; + + if (!Services[DIAttributeEnum.Singletone].Contains(serviceName)) + { + Services[DIAttributeEnum.Singletone].Add(serviceName); + ServiceCollection.TryAddSingleton(implementationFactory); + } + + return this; + } + + public DIHelper TryAddSingleton<TService, TImplementation>() where TService : class where TImplementation : class, TService + { + var serviceName = $"{typeof(TService)}{typeof(TImplementation)}"; + + if (!Services[DIAttributeEnum.Singletone].Contains(serviceName)) + { + Services[DIAttributeEnum.Singletone].Add(serviceName); + ServiceCollection.TryAddSingleton<TService, TImplementation>(); + } + + return this; + } + + public DIHelper Configure<TOptions>(Action<TOptions> configureOptions) where TOptions : class + { + var serviceName = $"{typeof(TOptions)}"; + + if (!Configured.Contains(serviceName)) + { + Configured.Add(serviceName); + ServiceCollection.Configure(configureOptions); + } + + return this; + } + + public DIHelper Configure<TOptions>(string name, Action<TOptions> configureOptions) where TOptions : class + { + var serviceName = $"{typeof(TOptions)}{name}"; + + if (!Configured.Contains(serviceName)) + { + Configured.Add(serviceName); + ServiceCollection.Configure(name, configureOptions); + } + + return this; + } + + private bool Register(Type service, Type implementation = null) + { + if (service.IsSubclassOf(typeof(ControllerBase)) || service.GetInterfaces().Contains(typeof(IResourceFilter)) + || service.GetInterfaces().Contains(typeof(IDictionary<string, string>))) + return true; + + var c = service.IsGenericType && ( + service.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || + service.GetGenericTypeDefinition() == typeof(IPostConfigureOptions<>) || + service.GetGenericTypeDefinition() == typeof(IOptionsMonitor<>) + ) && implementation != null ? implementation.GetCustomAttribute<DIAttribute>() : service.GetCustomAttribute<DIAttribute>(); + + var serviceName = $"{service}{implementation}"; + + if (!Services[c.DIAttributeEnum].Contains(serviceName)) + { + c.TryAdd(ServiceCollection, service, implementation); + Services[c.DIAttributeEnum].Add(serviceName); + + return true; + } + + return false; + } +} diff --git a/common/ASC.Common/Data/StreamExtension.cs b/common/ASC.Common/Data/StreamExtension.cs index f7ca7990c7..58007997cb 100644 --- a/common/ASC.Common/Data/StreamExtension.cs +++ b/common/ASC.Common/Data/StreamExtension.cs @@ -22,6 +22,8 @@ * Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks. * */ + +namespace ASC.Common.Data; public static class StreamExtension { diff --git a/common/ASC.Common/Data/TempPath.cs b/common/ASC.Common/Data/TempPath.cs index 102424fe0c..f7d53c36e5 100644 --- a/common/ASC.Common/Data/TempPath.cs +++ b/common/ASC.Common/Data/TempPath.cs @@ -14,60 +14,59 @@ * */ -namespace System.IO +namespace System.IO; + +[Singletone] +public class TempPath { - [Singletone] - public class TempPath + private readonly string _tempFolder; + + public TempPath(IConfiguration configuration) { - private readonly string _tempFolder; + string rootFolder = AppContext.BaseDirectory; - public TempPath(IConfiguration configuration) + if (string.IsNullOrEmpty(rootFolder)) + rootFolder = Assembly.GetEntryAssembly().Location; + + _tempFolder = configuration["temp"] ?? Path.Combine("..", "Data", "temp"); + + if (!Path.IsPathRooted(_tempFolder)) + _tempFolder = Path.GetFullPath(Path.Combine(rootFolder, _tempFolder)); + + if (!Directory.Exists(_tempFolder)) Directory.CreateDirectory(_tempFolder); + } + + public string GetTempPath() => _tempFolder; + + public string GetTempFileName() + { + FileStream f = null; + string path; + var count = 0; + + do { - string rootFolder = AppContext.BaseDirectory; + path = Path.Combine(_tempFolder, Path.GetRandomFileName()); - if (string.IsNullOrEmpty(rootFolder)) - rootFolder = Assembly.GetEntryAssembly().Location; - - _tempFolder = configuration["temp"] ?? Path.Combine("..", "Data", "temp"); - - if (!Path.IsPathRooted(_tempFolder)) - _tempFolder = Path.GetFullPath(Path.Combine(rootFolder, _tempFolder)); - - if (!Directory.Exists(_tempFolder)) Directory.CreateDirectory(_tempFolder); - } - - public string GetTempPath() => _tempFolder; - - public string GetTempFileName() - { - FileStream f = null; - string path; - var count = 0; - - do + try { - path = Path.Combine(_tempFolder, Path.GetRandomFileName()); + using (f = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read)) + { + return path; + } + } + catch (IOException ex) + { + if (ex.HResult != -2147024816 || count++ > 65536) + throw; + } + catch (UnauthorizedAccessException ex) + { + if (count++ > 65536) + throw new IOException(ex.Message, ex); + } + } while (f == null); - try - { - using (f = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read)) - { - return path; - } - } - catch (IOException ex) - { - if (ex.HResult != -2147024816 || count++ > 65536) - throw; - } - catch (UnauthorizedAccessException ex) - { - if (count++ > 65536) - throw new IOException(ex.Message, ex); - } - } while (f == null); - - return path; - } + return path; } } \ No newline at end of file diff --git a/common/ASC.Common/Data/TempStream.cs b/common/ASC.Common/Data/TempStream.cs index e4aad4f075..b80f2f89bc 100644 --- a/common/ASC.Common/Data/TempStream.cs +++ b/common/ASC.Common/Data/TempStream.cs @@ -14,33 +14,32 @@ * */ -namespace ASC.Common +namespace ASC.Common; + +[Singletone] +public class TempStream { - [Singletone] - public class TempStream + private readonly TempPath _tempPath; + + public TempStream(TempPath tempPath) => _tempPath = tempPath; + + public Stream GetBuffered(Stream srcStream) { - private readonly TempPath _tempPath; + if (srcStream == null) throw new ArgumentNullException(nameof(srcStream)); - public TempStream(TempPath tempPath) => _tempPath = tempPath; - - public Stream GetBuffered(Stream srcStream) + if (!srcStream.CanSeek || srcStream.CanTimeout) { - if (srcStream == null) throw new ArgumentNullException(nameof(srcStream)); + //Buffer it + var memStream = Create(); + srcStream.CopyTo(memStream); + memStream.Position = 0; - if (!srcStream.CanSeek || srcStream.CanTimeout) - { - //Buffer it - var memStream = Create(); - srcStream.CopyTo(memStream); - memStream.Position = 0; - - return memStream; - } - - return srcStream; + return memStream; } - public Stream Create() => new FileStream(_tempPath.GetTempFileName(), FileMode.OpenOrCreate, - FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose); + return srcStream; } + + public Stream Create() => new FileStream(_tempPath.GetTempFileName(), FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose); } \ No newline at end of file diff --git a/common/ASC.Common/DependencyInjection/AutofacExtension.cs b/common/ASC.Common/DependencyInjection/AutofacExtension.cs index afcf57449d..2f4cb4c895 100644 --- a/common/ASC.Common/DependencyInjection/AutofacExtension.cs +++ b/common/ASC.Common/DependencyInjection/AutofacExtension.cs @@ -1,135 +1,134 @@ -namespace ASC.Common.DependencyInjection +namespace ASC.Common.DependencyInjection; + +internal class AutofacComponent { - internal class AutofacComponent - { - public string Type { get; set; } - public IEnumerable<AutofacService> Services { get; set; } - } + public string Type { get; set; } + public IEnumerable<AutofacService> Services { get; set; } +} - internal class AutofacService - { - public string Type { get; set; } - } +internal class AutofacService +{ + public string Type { get; set; } +} - public static class AutofacExtension +public static class AutofacExtension +{ + public static void Register(this ContainerBuilder builder, IConfiguration configuration, + bool loadproducts = true, bool loadconsumers = true, params string[] intern) { - public static void Register(this ContainerBuilder builder, IConfiguration configuration, - bool loadproducts = true, bool loadconsumers = true, params string[] intern) - { - var modules = new List<(bool, string)> + var modules = new List<(bool, string)> { (true, "autofac.json") }; - if (loadproducts) - modules.Add((true, "autofac.products.json")); + if (loadproducts) + modules.Add((true, "autofac.products.json")); - if (loadconsumers) - modules.Add((true, "autofac.consumers.json")); + if (loadconsumers) + modules.Add((true, "autofac.consumers.json")); - if (intern != null) - modules.AddRange(intern.Select(r => (false, r))); + if (intern != null) + modules.AddRange(intern.Select(r => (false, r))); - foreach (var p in modules) - { - var config = new ConfigurationBuilder(); - - if (p.Item1) config.SetBasePath(configuration["pathToConf"]); - - config.AddJsonFile(p.Item2); - - var root = config.Build(); - var module = new ConfigurationModule(root); - builder.RegisterModule(module); - } - - return; - } - - public static List<string> FindAndLoad(IConfiguration configuration, string currentDir, string section = "autofac.products.json") + foreach (var p in modules) { var config = new ConfigurationBuilder(); - config.SetBasePath(configuration["pathToConf"]); - config.AddJsonFile(section); + + if (p.Item1) config.SetBasePath(configuration["pathToConf"]); + + config.AddJsonFile(p.Item2); + var root = config.Build(); - - var sectionSettings = root.GetSection("components"); - - if (sectionSettings == null) return new List<string>(); - - var folder = configuration["core:products:folder"]; - var subfolder = configuration["core:products:subfolder"]; - string productsDir; - - if (!Path.IsPathRooted(folder)) - { - if (currentDir.EndsWith(CrossPlatform.PathCombine(Path.GetFileName(folder), Assembly.GetEntryAssembly().GetName().Name, subfolder))) - productsDir = Path.GetFullPath(CrossPlatform.PathCombine("..", "..")); - - else productsDir = Path.GetFullPath(CrossPlatform.PathCombine(currentDir, folder)); - } - - else productsDir = folder; - - var cs = new List<AutofacComponent>(); - sectionSettings.Bind(cs); - - var types = new List<string>(); - - foreach (var component in cs) - { - try - { - LoadAssembly(component.Type); - types.Add(component.Type); - } - catch (System.Exception) - { - //TODO - } - } - - return types; - - void LoadAssembly(string type) - { - var dll = type.Substring(type.IndexOf(",") + 1).Trim(); - var path = GetFullPath(dll); - - if (!string.IsNullOrEmpty(path)) - AssemblyLoadContext.Default.Resolving += new Resolver(path).Resolving; - } - - string GetFullPath(string n) - { - var productPath = CrossPlatform.PathCombine(productsDir, n, subfolder); - - return GetPath(CrossPlatform.PathCombine(productPath, "bin"), n, SearchOption.AllDirectories) - ?? GetPath(productPath, n, SearchOption.TopDirectoryOnly); - } - - static string GetPath(string dirPath, string dll, SearchOption searchOption) - { - if (!Directory.Exists(dirPath)) return null; - - return Directory.GetFiles(dirPath, $"{dll}.dll", searchOption).FirstOrDefault(); - } + var module = new ConfigurationModule(root); + builder.RegisterModule(module); } + + return; } - class Resolver + public static List<string> FindAndLoad(IConfiguration configuration, string currentDir, string section = "autofac.products.json") { - private readonly string _resolvePath; + var config = new ConfigurationBuilder(); + config.SetBasePath(configuration["pathToConf"]); + config.AddJsonFile(section); + var root = config.Build(); - public Resolver(string assemblyPath) => _resolvePath = assemblyPath; + var sectionSettings = root.GetSection("components"); - public Assembly Resolving(AssemblyLoadContext context, AssemblyName assemblyName) + if (sectionSettings == null) return new List<string>(); + + var folder = configuration["core:products:folder"]; + var subfolder = configuration["core:products:subfolder"]; + string productsDir; + + if (!Path.IsPathRooted(folder)) { - var path = CrossPlatform.PathCombine(Path.GetDirectoryName(_resolvePath), $"{assemblyName.Name}.dll"); + if (currentDir.EndsWith(CrossPlatform.PathCombine(Path.GetFileName(folder), Assembly.GetEntryAssembly().GetName().Name, subfolder))) + productsDir = Path.GetFullPath(CrossPlatform.PathCombine("..", "..")); - if (!File.Exists(path)) return null; - - return context.LoadFromAssemblyPath(path); + else productsDir = Path.GetFullPath(CrossPlatform.PathCombine(currentDir, folder)); } + + else productsDir = folder; + + var cs = new List<AutofacComponent>(); + sectionSettings.Bind(cs); + + var types = new List<string>(); + + foreach (var component in cs) + { + try + { + LoadAssembly(component.Type); + types.Add(component.Type); + } + catch (System.Exception) + { + //TODO + } + } + + return types; + + void LoadAssembly(string type) + { + var dll = type.Substring(type.IndexOf(",") + 1).Trim(); + var path = GetFullPath(dll); + + if (!string.IsNullOrEmpty(path)) + AssemblyLoadContext.Default.Resolving += new Resolver(path).Resolving; + } + + string GetFullPath(string n) + { + var productPath = CrossPlatform.PathCombine(productsDir, n, subfolder); + + return GetPath(CrossPlatform.PathCombine(productPath, "bin"), n, SearchOption.AllDirectories) + ?? GetPath(productPath, n, SearchOption.TopDirectoryOnly); + } + + static string GetPath(string dirPath, string dll, SearchOption searchOption) + { + if (!Directory.Exists(dirPath)) return null; + + return Directory.GetFiles(dirPath, $"{dll}.dll", searchOption).FirstOrDefault(); + } + } +} + +class Resolver +{ + private readonly string _resolvePath; + + public Resolver(string assemblyPath) => _resolvePath = assemblyPath; + + public Assembly Resolving(AssemblyLoadContext context, AssemblyName assemblyName) + { + var path = CrossPlatform.PathCombine(Path.GetDirectoryName(_resolvePath), $"{assemblyName.Name}.dll"); + + if (!File.Exists(path)) return null; + + return context.LoadFromAssemblyPath(path); } } \ No newline at end of file diff --git a/common/ASC.Common/Geolocation/IPGeolocationInfo.cs b/common/ASC.Common/Geolocation/IPGeolocationInfo.cs index 7ec1a796d3..674230a7d4 100644 --- a/common/ASC.Common/Geolocation/IPGeolocationInfo.cs +++ b/common/ASC.Common/Geolocation/IPGeolocationInfo.cs @@ -23,24 +23,23 @@ * */ -namespace ASC.Geolocation -{ - public class IPGeolocationInfo - { - public string Key { get; set; } - public string City { get; set; } - public double TimezoneOffset { get; set; } - public string TimezoneName { get; set; } - public string IPStart { get; set; } - public string IPEnd { get; set; } - - public readonly static IPGeolocationInfo Default = new IPGeolocationInfo - { - Key = string.Empty, - IPStart = string.Empty, - IPEnd = string.Empty, - City = string.Empty, - TimezoneName = string.Empty, - }; - } -} \ No newline at end of file +namespace ASC.Geolocation; + +public class IPGeolocationInfo +{ + public string Key { get; set; } + public string City { get; set; } + public double TimezoneOffset { get; set; } + public string TimezoneName { get; set; } + public string IPStart { get; set; } + public string IPEnd { get; set; } + + public readonly static IPGeolocationInfo Default = new IPGeolocationInfo + { + Key = string.Empty, + IPStart = string.Empty, + IPEnd = string.Empty, + City = string.Empty, + TimezoneName = string.Empty, + }; +} diff --git a/common/ASC.Common/GlobalUsings.cs b/common/ASC.Common/GlobalUsings.cs index faae11b0f8..1cf21ba438 100644 --- a/common/ASC.Common/GlobalUsings.cs +++ b/common/ASC.Common/GlobalUsings.cs @@ -21,6 +21,8 @@ global using System.Threading.Tasks; global using System.Web; global using System.Xml.Linq; global using System.Xml.XPath; +global using System.ServiceModel; +global using System.Runtime.Serialization; global using ARSoft.Tools.Net; global using ARSoft.Tools.Net.Dns; diff --git a/common/ASC.Common/Logging/EFLoggerFactory.cs b/common/ASC.Common/Logging/EFLoggerFactory.cs index 13697538e1..b3db84d929 100644 --- a/common/ASC.Common/Logging/EFLoggerFactory.cs +++ b/common/ASC.Common/Logging/EFLoggerFactory.cs @@ -1,79 +1,78 @@ using ILogger = Microsoft.Extensions.Logging.ILogger; using LogLevel = Microsoft.Extensions.Logging.LogLevel; -namespace ASC.Common.Logging +namespace ASC.Common.Logging; + +[Singletone] +public class EFLoggerFactory : ILoggerFactory { - [Singletone] - public class EFLoggerFactory : ILoggerFactory + private readonly Lazy<ILogger> _logger; + private readonly ILoggerProvider _loggerProvider; + + public EFLoggerFactory(EFLoggerProvider loggerProvider) { - private readonly Lazy<ILogger> _logger; - private readonly ILoggerProvider _loggerProvider; - - public EFLoggerFactory(EFLoggerProvider loggerProvider) - { - _loggerProvider = loggerProvider; - _logger = new Lazy<ILogger>(() => _loggerProvider.CreateLogger("")); - } - - public void AddProvider(ILoggerProvider provider) - { - //LoggerProvider = provider; - } - - public ILogger CreateLogger(string categoryName) => _logger.Value; - - public void Dispose() { } + _loggerProvider = loggerProvider; + _logger = new Lazy<ILogger>(() => _loggerProvider.CreateLogger("")); } - [Singletone] - public class EFLoggerProvider : ILoggerProvider + public void AddProvider(ILoggerProvider provider) { - private readonly IOptionsMonitor<ILog> _option; - - public EFLoggerProvider(IOptionsMonitor<ILog> option) => _option = option; - - public ILogger CreateLogger(string categoryName) => new EFLogger(_option.Get("ASC.SQL")); - - public void Dispose() { } + //LoggerProvider = provider; } - public class EFLogger : ILogger + public ILogger CreateLogger(string categoryName) => _logger.Value; + + public void Dispose() { } +} + +[Singletone] +public class EFLoggerProvider : ILoggerProvider +{ + private readonly IOptionsMonitor<ILog> _option; + + public EFLoggerProvider(IOptionsMonitor<ILog> option) => _option = option; + + public ILogger CreateLogger(string categoryName) => new EFLogger(_option.Get("ASC.SQL")); + + public void Dispose() { } +} + +public class EFLogger : ILogger +{ + public ILog CustomLogger { get; } + + public EFLogger(ILog customLogger) => CustomLogger = customLogger; + + public IDisposable BeginScope<TState>(TState state) { return null; } + + public bool IsEnabled(LogLevel logLevel) { - public ILog CustomLogger { get; } - - public EFLogger(ILog customLogger) => CustomLogger = customLogger; - - public IDisposable BeginScope<TState>(TState state) { return null; } - - public bool IsEnabled(LogLevel logLevel) + return logLevel switch { - return logLevel switch - { - LogLevel.Trace => CustomLogger.IsTraceEnabled, - LogLevel.Information => CustomLogger.IsInfoEnabled, - LogLevel.None => false, + LogLevel.Trace => CustomLogger.IsTraceEnabled, + LogLevel.Information => CustomLogger.IsInfoEnabled, + LogLevel.None => false, - LogLevel.Debug => CustomLogger.IsDebugEnabled, - LogLevel.Warning => CustomLogger.IsWarnEnabled, - LogLevel.Error => CustomLogger.IsErrorEnabled, - LogLevel.Critical => CustomLogger.IsErrorEnabled, + LogLevel.Debug => CustomLogger.IsDebugEnabled, + LogLevel.Warning => CustomLogger.IsWarnEnabled, + LogLevel.Error => CustomLogger.IsErrorEnabled, + LogLevel.Critical => CustomLogger.IsErrorEnabled, - _ => true, - }; - } + _ => true, + }; + } - public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) + public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) + { + switch (eventId.Id) { - switch (eventId.Id) - { - //case 20000: - // CustomLogger.Debug(formatter(state, exception)); - // break; - case 20101: - var keyValuePairs = state as IEnumerable<KeyValuePair<string, object>>; - CustomLogger.DebugWithProps("", keyValuePairs); - break; - } + //case 20000: + // CustomLogger.Debug(formatter(state, exception)); + // break; + case 20101: + var keyValuePairs = state as IEnumerable<KeyValuePair<string, object>>; + CustomLogger.DebugWithProps("", keyValuePairs); + break; } } -} \ No newline at end of file +} diff --git a/common/ASC.Common/Logging/Log.cs b/common/ASC.Common/Logging/Log.cs index 0ab91773b0..c7b580ff86 100644 --- a/common/ASC.Common/Logging/Log.cs +++ b/common/ASC.Common/Logging/Log.cs @@ -25,720 +25,719 @@ using LogLevel = NLog.LogLevel; -namespace ASC.Common.Logging +namespace ASC.Common.Logging; + +[Singletone(typeof(ConfigureLogNLog), Additional = typeof(LogNLogExtension))] +public interface ILog { - [Singletone(typeof(ConfigureLogNLog), Additional = typeof(LogNLogExtension))] - public interface ILog - { - bool IsDebugEnabled { get; } - bool IsInfoEnabled { get; } - bool IsWarnEnabled { get; } - bool IsErrorEnabled { get; } - bool IsFatalEnabled { get; } - bool IsTraceEnabled { get; } - - void Trace(object message); - void TraceFormat(string message, object arg0); - - void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props); - void Debug(object message); - void Debug(object message, Exception exception); - void DebugFormat(string format, params object[] args); - void DebugFormat(string format, object arg0); - void DebugFormat(string format, object arg0, object arg1); - void DebugFormat(string format, object arg0, object arg1, object arg2); - void DebugFormat(IFormatProvider provider, string format, params object[] args); - - - void Info(object message); - void Info(string message, Exception exception); - void InfoFormat(string format, params object[] args); - void InfoFormat(string format, object arg0); - void InfoFormat(string format, object arg0, object arg1); - void InfoFormat(string format, object arg0, object arg1, object arg2); - void InfoFormat(IFormatProvider provider, string format, params object[] args); - - void Warn(object message); - void Warn(object message, Exception exception); - void WarnFormat(string format, params object[] args); - void WarnFormat(string format, object arg0); - void WarnFormat(string format, object arg0, object arg1); - void WarnFormat(string format, object arg0, object arg1, object arg2); - void WarnFormat(IFormatProvider provider, string format, params object[] args); - - void Error(object message); - void Error(object message, Exception exception); - void ErrorFormat(string format, params object[] args); - void ErrorFormat(string format, object arg0); - void ErrorFormat(string format, object arg0, object arg1); - void ErrorFormat(string format, object arg0, object arg1, object arg2); - void ErrorFormat(IFormatProvider provider, string format, params object[] args); - - void Fatal(object message); - void Fatal(string message, Exception exception); - void FatalFormat(string format, params object[] args); - void FatalFormat(string format, object arg0); - void FatalFormat(string format, object arg0, object arg1); - void FatalFormat(string format, object arg0, object arg1, object arg2); - void FatalFormat(IFormatProvider provider, string format, params object[] args); - - string LogDirectory { get; } - string Name { get; set; } + bool IsDebugEnabled { get; } + bool IsInfoEnabled { get; } + bool IsWarnEnabled { get; } + bool IsErrorEnabled { get; } + bool IsFatalEnabled { get; } + bool IsTraceEnabled { get; } - void Configure(string name); - } - - public class Log : ILog - { - public string Name { get; set; } - public bool IsDebugEnabled { get; private set; } - public bool IsInfoEnabled { get; private set; } - public bool IsWarnEnabled { get; private set; } - public bool IsErrorEnabled { get; private set; } - public bool IsFatalEnabled { get; private set; } - public bool IsTraceEnabled { get; private set; } - public string LogDirectory => log4net.GlobalContext.Properties["LogDirectory"].ToString(); + void Trace(object message); + void TraceFormat(string message, object arg0); - private log4net.ILog _logger; + void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props); + void Debug(object message); + void Debug(object message, Exception exception); + void DebugFormat(string format, params object[] args); + void DebugFormat(string format, object arg0); + void DebugFormat(string format, object arg0, object arg1); + void DebugFormat(string format, object arg0, object arg1, object arg2); + void DebugFormat(IFormatProvider provider, string format, params object[] args); - public Log(string name) => Configure(name); - - static Log() => XmlConfigurator.Configure(log4net.LogManager.GetRepository(Assembly.GetCallingAssembly())); - public void Configure(string name) - { - _logger = log4net.LogManager.GetLogger(Assembly.GetCallingAssembly(), name); - - IsDebugEnabled = _logger.IsDebugEnabled; - IsInfoEnabled = _logger.IsInfoEnabled; - IsWarnEnabled = _logger.IsWarnEnabled; - IsErrorEnabled = _logger.IsErrorEnabled; - IsFatalEnabled = _logger.IsFatalEnabled; - IsTraceEnabled = _logger.Logger.IsEnabledFor(Level.Trace); - } - - public void Trace(object message) - { - if (IsTraceEnabled) _logger.Logger.Log(GetType(), Level.Trace, message, null); - } - - public void TraceFormat(string message, object arg0) - { - if (IsTraceEnabled) _logger.Logger.Log(GetType(), Level.Trace, string.Format(message, arg0), null); - } - - public void Debug(object message) - { - if (IsDebugEnabled) _logger.Debug(message); - } - - public void Debug(object message, Exception exception) - { - if (IsDebugEnabled) _logger.Debug(message, exception); - } - - public void DebugFormat(string format, params object[] args) - { - if (IsDebugEnabled) _logger.DebugFormat(format, args); - } - - public void DebugFormat(string format, object arg0) - { - if (IsDebugEnabled) _logger.DebugFormat(format, arg0); - } - - public void DebugFormat(string format, object arg0, object arg1) - { - if (IsDebugEnabled) _logger.DebugFormat(format, arg0, arg1); - } - - public void DebugFormat(string format, object arg0, object arg1, object arg2) - { - if (IsDebugEnabled) _logger.DebugFormat(format, arg0, arg1, arg2); - } - - public void DebugFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsDebugEnabled) _logger.DebugFormat(provider, format, args); - } - - public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) - { - if (!IsDebugEnabled) return; - - foreach (var p in props) - { - log4net.ThreadContext.Properties[p.Key] = p.Value; - } - - _logger.Debug(message); - } - - - public void Info(object message) - { - if (IsInfoEnabled) _logger.Info(message); - } - - public void Info(string message, Exception exception) - { - if (IsInfoEnabled) _logger.Info(message, exception); - } - - public void InfoFormat(string format, params object[] args) - { - if (IsInfoEnabled) _logger.InfoFormat(format, args); - } - - public void InfoFormat(string format, object arg0) - { - if (IsInfoEnabled) _logger.InfoFormat(format, arg0); - } - - public void InfoFormat(string format, object arg0, object arg1) - { - if (IsInfoEnabled) _logger.InfoFormat(format, arg0, arg1); - } - - public void InfoFormat(string format, object arg0, object arg1, object arg2) - { - if (IsInfoEnabled) _logger.InfoFormat(format, arg0, arg1, arg2); - } - - public void InfoFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsInfoEnabled) _logger.InfoFormat(provider, format, args); - } - - - public void Warn(object message) - { - if (IsWarnEnabled) _logger.Warn(message); - } - - public void Warn(object message, Exception exception) - { - if (IsWarnEnabled) _logger.Warn(message, exception); - } - - public void WarnFormat(string format, params object[] args) - { - if (IsWarnEnabled) _logger.WarnFormat(format, args); - } - - public void WarnFormat(string format, object arg0) - { - if (IsWarnEnabled) _logger.WarnFormat(format, arg0); - } - - public void WarnFormat(string format, object arg0, object arg1) - { - if (IsWarnEnabled) _logger.WarnFormat(format, arg0, arg1); - } - - public void WarnFormat(string format, object arg0, object arg1, object arg2) - { - if (IsWarnEnabled) _logger.WarnFormat(format, arg0, arg1, arg2); - } - - public void WarnFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsWarnEnabled) _logger.WarnFormat(provider, format, args); - } - - - public void Error(object message) - { - if (IsErrorEnabled) _logger.Error(message); - } - - public void Error(object message, Exception exception) - { - if (IsErrorEnabled) _logger.Error(message, exception); - } - - public void ErrorFormat(string format, params object[] args) - { - if (IsErrorEnabled) _logger.ErrorFormat(format, args); - } - - public void ErrorFormat(string format, object arg0) - { - if (IsErrorEnabled) _logger.ErrorFormat(format, arg0); - } - - public void ErrorFormat(string format, object arg0, object arg1) - { - if (IsErrorEnabled) _logger.ErrorFormat(format, arg0, arg1); - } - - public void ErrorFormat(string format, object arg0, object arg1, object arg2) - { - if (IsErrorEnabled) _logger.ErrorFormat(format, arg0, arg1, arg2); - } - - public void ErrorFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsErrorEnabled) _logger.ErrorFormat(provider, format, args); - } - - - public void Fatal(object message) - { - if (IsFatalEnabled) _logger.Fatal(message); - } - - public void Fatal(string message, Exception exception) - { - if (IsFatalEnabled) _logger.Fatal(message, exception); - } - - public void FatalFormat(string format, params object[] args) - { - if (IsFatalEnabled) _logger.FatalFormat(format, args); - } - - public void FatalFormat(string format, object arg0) - { - if (IsFatalEnabled) _logger.FatalFormat(format, arg0); - } - - public void FatalFormat(string format, object arg0, object arg1) - { - if (IsFatalEnabled) _logger.FatalFormat(format, arg0, arg1); - } - - public void FatalFormat(string format, object arg0, object arg1, object arg2) - { - if (IsFatalEnabled) _logger.FatalFormat(format, arg0, arg1, arg2); - } - - public void FatalFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsFatalEnabled) _logger.FatalFormat(provider, format, args); - } - - public void DebugWithProps(string message, KeyValuePair<string, object> prop1, KeyValuePair<string, object> prop2, KeyValuePair<string, object> prop3) - { - if (!IsDebugEnabled) return; - - AddProp(prop1); - AddProp(prop2); - AddProp(prop3); - - _logger.Debug(message); - - static void AddProp(KeyValuePair<string, object> p) - { - log4net.ThreadContext.Properties[p.Key] = p.Value; - } - } - } - - public class NLogSettings - { - public string Name { get; set; } - public string Dir { get; set; } - } + void Info(object message); + void Info(string message, Exception exception); + void InfoFormat(string format, params object[] args); + void InfoFormat(string format, object arg0); + void InfoFormat(string format, object arg0, object arg1); + void InfoFormat(string format, object arg0, object arg1, object arg2); + void InfoFormat(IFormatProvider provider, string format, params object[] args); - [Singletone] - public class ConfigureLogNLog : IConfigureNamedOptions<LogNLog> + void Warn(object message); + void Warn(object message, Exception exception); + void WarnFormat(string format, params object[] args); + void WarnFormat(string format, object arg0); + void WarnFormat(string format, object arg0, object arg1); + void WarnFormat(string format, object arg0, object arg1, object arg2); + void WarnFormat(IFormatProvider provider, string format, params object[] args); + + void Error(object message); + void Error(object message, Exception exception); + void ErrorFormat(string format, params object[] args); + void ErrorFormat(string format, object arg0); + void ErrorFormat(string format, object arg0, object arg1); + void ErrorFormat(string format, object arg0, object arg1, object arg2); + void ErrorFormat(IFormatProvider provider, string format, params object[] args); + + void Fatal(object message); + void Fatal(string message, Exception exception); + void FatalFormat(string format, params object[] args); + void FatalFormat(string format, object arg0); + void FatalFormat(string format, object arg0, object arg1); + void FatalFormat(string format, object arg0, object arg1, object arg2); + void FatalFormat(IFormatProvider provider, string format, params object[] args); + + string LogDirectory { get; } + string Name { get; set; } + + void Configure(string name); +} + +public class Log : ILog +{ + public string Name { get; set; } + public bool IsDebugEnabled { get; private set; } + public bool IsInfoEnabled { get; private set; } + public bool IsWarnEnabled { get; private set; } + public bool IsErrorEnabled { get; private set; } + public bool IsFatalEnabled { get; private set; } + public bool IsTraceEnabled { get; private set; } + public string LogDirectory => log4net.GlobalContext.Properties["LogDirectory"].ToString(); + + private log4net.ILog _logger; + + public Log(string name) => Configure(name); + + static Log() => XmlConfigurator.Configure(log4net.LogManager.GetRepository(Assembly.GetCallingAssembly())); + + public void Configure(string name) { - private readonly IConfiguration _configuration; - private readonly ConfigurationExtension _configurationExtension; - - public ConfigureLogNLog(IConfiguration configuration, ConfigurationExtension configurationExtension, IHostEnvironment hostingEnvironment) - { - _configuration = configuration; - _configurationExtension = configurationExtension; + _logger = log4net.LogManager.GetLogger(Assembly.GetCallingAssembly(), name); - - LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(CrossPlatform.PathCombine(_configuration["pathToConf"], "nlog.config")); - LogManager.ThrowConfigExceptions = false; - - var settings = _configurationExtension.GetSetting<NLogSettings>("log"); - - if (!string.IsNullOrEmpty(settings.Name)) - LogManager.Configuration.Variables["name"] = settings.Name; - - if (!string.IsNullOrEmpty(settings.Dir)) - LogManager.Configuration.Variables["dir"] = CrossPlatform.PathCombine(hostingEnvironment.ContentRootPath, settings.Dir) - .TrimEnd('/').TrimEnd('\\') + Path.DirectorySeparatorChar; - - NLog.Targets.Target.Register<SelfCleaningTarget>("SelfCleaning"); - } - - public void Configure(LogNLog options) => options.Configure("ASC"); - - public void Configure(string name, LogNLog options) - { - if (string.IsNullOrEmpty(name)) Configure(options); - - else options.Configure(name); - } - } - - public class LogNLog : ILog - { - public bool IsDebugEnabled { get; private set; } - public bool IsInfoEnabled { get; private set; } - public bool IsWarnEnabled { get; private set; } - public bool IsErrorEnabled { get; private set; } - public bool IsFatalEnabled { get; private set; } - public bool IsTraceEnabled { get; private set; } - public string LogDirectory => LogManager.Configuration.Variables["dir"].Text; - public string Name - { - get => _name; - - set - { - _name = value; - Logger = LogManager.GetLogger(_name); - } - } - - private NLog.ILogger Logger - { - get => _logger; - - set - { - _logger = value; - IsDebugEnabled = _logger.IsDebugEnabled; - IsInfoEnabled = _logger.IsInfoEnabled; - IsWarnEnabled = _logger.IsWarnEnabled; - IsErrorEnabled = _logger.IsErrorEnabled; - IsFatalEnabled = _logger.IsFatalEnabled; - IsTraceEnabled = _logger.IsEnabled(LogLevel.Trace); - } - } - - private NLog.ILogger _logger; - private string _name; - - public void Configure(string name) => Name = name; - - public void Trace(object message) - { - if (IsTraceEnabled) Logger.Log(LogLevel.Trace, message); - } - - public void TraceFormat(string message, object arg0) - { - if (IsTraceEnabled) Logger.Log(LogLevel.Trace, string.Format(message, arg0)); - } - - public void Debug(object message) - { - if (IsDebugEnabled) Logger.Debug(message); - } - - public void Debug(object message, Exception exception) - { - if (IsDebugEnabled) Logger.Debug(exception, "{0}", message); - } - - public void DebugFormat(string format, params object[] args) - { - if (IsDebugEnabled) Logger.Debug(format, args); - } - - public void DebugFormat(string format, object arg0) - { - if (IsDebugEnabled) Logger.Debug(format, arg0); - } - - public void DebugFormat(string format, object arg0, object arg1) - { - if (IsDebugEnabled) Logger.Debug(format, arg0, arg1); - } - - public void DebugFormat(string format, object arg0, object arg1, object arg2) - { - if (IsDebugEnabled) Logger.Debug(format, arg0, arg1, arg2); - } - - public void DebugFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsDebugEnabled) Logger.Debug(provider, format, args); - } - - public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) - { - if (!IsDebugEnabled) return; - - var theEvent = new LogEventInfo { Message = message, LoggerName = Name, Level = LogLevel.Debug }; - - foreach (var p in props) - { - theEvent.Properties[p.Key] = p.Value; - } - - Logger.Log(theEvent); - } - - public void Info(object message) - { - if (IsInfoEnabled) Logger.Info(message); - } - - public void Info(string message, Exception exception) - { - if (IsInfoEnabled) Logger.Info(exception, message); - } - - public void InfoFormat(string format, params object[] args) - { - if (IsInfoEnabled) Logger.Info(format, args); - } - - public void InfoFormat(string format, object arg0) - { - if (IsInfoEnabled) Logger.Info(format, arg0); - } - - public void InfoFormat(string format, object arg0, object arg1) - { - if (IsInfoEnabled) Logger.Info(format, arg0, arg1); - } - - public void InfoFormat(string format, object arg0, object arg1, object arg2) - { - if (IsInfoEnabled) Logger.Info(format, arg0, arg1, arg2); - } - - public void InfoFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsInfoEnabled) Logger.Info(provider, format, args); - } - - - public void Warn(object message) - { - if (IsWarnEnabled) Logger.Warn(message); - } - - public void Warn(object message, Exception exception) - { - if (IsWarnEnabled) Logger.Warn(exception, "{0}", message); - } - - public void WarnFormat(string format, params object[] args) - { - if (IsWarnEnabled) Logger.Warn(format, args); - } - - public void WarnFormat(string format, object arg0) - { - if (IsWarnEnabled) Logger.Warn(format, arg0); - } - - public void WarnFormat(string format, object arg0, object arg1) - { - if (IsWarnEnabled) Logger.Warn(format, arg0, arg1); - } - - public void WarnFormat(string format, object arg0, object arg1, object arg2) - { - if (IsWarnEnabled) Logger.Warn(format, arg0, arg1, arg2); - } - - public void WarnFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsWarnEnabled) Logger.Warn(provider, format, args); - } - - - public void Error(object message) - { - if (IsErrorEnabled) Logger.Error(message); - } - - public void Error(object message, Exception exception) - { - if (IsErrorEnabled) Logger.Error(exception, "{0}", message); - } - - public void ErrorFormat(string format, params object[] args) - { - if (IsErrorEnabled) Logger.Error(format, args); - } - - public void ErrorFormat(string format, object arg0) - { - if (IsErrorEnabled) Logger.Error(format, arg0); - } - - public void ErrorFormat(string format, object arg0, object arg1) - { - if (IsErrorEnabled) Logger.Error(format, arg0, arg1); - } - - public void ErrorFormat(string format, object arg0, object arg1, object arg2) - { - if (IsErrorEnabled) Logger.Error(format, arg0, arg1, arg2); - } - - public void ErrorFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsErrorEnabled) Logger.Error(provider, format, args); - } - - - public void Fatal(object message) - { - if (IsFatalEnabled) Logger.Fatal(message); - } - - public void Fatal(string message, Exception exception) - { - if (IsFatalEnabled) Logger.Fatal(exception, message); - } - - public void FatalFormat(string format, params object[] args) - { - if (IsFatalEnabled) Logger.Fatal(format, args); - } - - public void FatalFormat(string format, object arg0) - { - if (IsFatalEnabled) Logger.Fatal(format, arg0); - } - - public void FatalFormat(string format, object arg0, object arg1) - { - if (IsFatalEnabled) Logger.Fatal(format, arg0, arg1); - } - - public void FatalFormat(string format, object arg0, object arg1, object arg2) - { - if (IsFatalEnabled) Logger.Fatal(format, arg0, arg1, arg2); - } - - public void FatalFormat(IFormatProvider provider, string format, params object[] args) - { - if (IsFatalEnabled) Logger.Fatal(provider, format, args); - } - } - - public class NullLog : ILog - { - public bool IsDebugEnabled { get; set; } - public bool IsInfoEnabled { get; set; } - public bool IsWarnEnabled { get; set; } - public bool IsErrorEnabled { get; set; } - public bool IsFatalEnabled { get; set; } - public bool IsTraceEnabled { get; set; } - public string Name { get; set; } - public string LogDirectory => string.Empty; - - public void Trace(object message) { } - - public void TraceFormat(string message, object arg0) { } - - public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) { } - - public void Debug(object message) { } - - public void Debug(object message, Exception exception) { } - - public void DebugFormat(string format, params object[] args) { } - - public void DebugFormat(string format, object arg0) { } - - public void DebugFormat(string format, object arg0, object arg1) { } - - public void DebugFormat(string format, object arg0, object arg1, object arg2) { } - - public void DebugFormat(IFormatProvider provider, string format, params object[] args) { } - - public void Info(object message) { } - - public void Info(string message, Exception exception) { } - - public void InfoFormat(string format, params object[] args) { } - - public void InfoFormat(string format, object arg0) { } - - public void InfoFormat(string format, object arg0, object arg1) { } - - public void InfoFormat(string format, object arg0, object arg1, object arg2) { } - - public void InfoFormat(IFormatProvider provider, string format, params object[] args) { } - - public void Warn(object message) { } - - public void Warn(object message, Exception exception) { } - - public void WarnFormat(string format, params object[] args) { } - - public void WarnFormat(string format, object arg0) { } - - public void WarnFormat(string format, object arg0, object arg1) { } - - public void WarnFormat(string format, object arg0, object arg1, object arg2) { } - - public void WarnFormat(IFormatProvider provider, string format, params object[] args) { } - - public void Error(object message) { } - - public void Error(object message, Exception exception) { } - - public void ErrorFormat(string format, params object[] args) { } - - public void ErrorFormat(string format, object arg0) { } - - public void ErrorFormat(string format, object arg0, object arg1) { } - - public void ErrorFormat(string format, object arg0, object arg1, object arg2) { } - - public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { } - - public void Fatal(object message) { } - - public void Fatal(string message, Exception exception) { } - - public void FatalFormat(string format, params object[] args) { } - - public void FatalFormat(string format, object arg0) { } - - public void FatalFormat(string format, object arg0, object arg1) { } - - public void FatalFormat(string format, object arg0, object arg1, object arg2) { } - - public void FatalFormat(IFormatProvider provider, string format, params object[] args) { } - - public void Configure(string name) { } - } - - [Singletone] - public class LogManager<T> : OptionsMonitor<T> where T : class, ILog, new() - { - public LogManager(IOptionsFactory<T> factory, - IEnumerable<IOptionsChangeTokenSource<T>> sources, - IOptionsMonitorCache<T> cache) - : base(factory, sources, cache) { } - - public override T Get(string name) - { - var log = base.Get(name); - - if (string.IsNullOrEmpty(log?.Name)) log = CurrentValue; - - return log; - } - } - - public class LoggerExtension<T> where T : class, ILog, new() - { - public static void RegisterLog(DIHelper services) => - services.TryAdd(typeof(IOptionsMonitor<ILog>), typeof(LogManager<T>)); + IsDebugEnabled = _logger.IsDebugEnabled; + IsInfoEnabled = _logger.IsInfoEnabled; + IsWarnEnabled = _logger.IsWarnEnabled; + IsErrorEnabled = _logger.IsErrorEnabled; + IsFatalEnabled = _logger.IsFatalEnabled; + IsTraceEnabled = _logger.Logger.IsEnabledFor(Level.Trace); } - public class LogNLogExtension : LoggerExtension<LogNLog> + public void Trace(object message) { - public static void Register(DIHelper services) => - RegisterLog(services); - } + if (IsTraceEnabled) _logger.Logger.Log(GetType(), Level.Trace, message, null); + } + + public void TraceFormat(string message, object arg0) + { + if (IsTraceEnabled) _logger.Logger.Log(GetType(), Level.Trace, string.Format(message, arg0), null); + } + + public void Debug(object message) + { + if (IsDebugEnabled) _logger.Debug(message); + } + + public void Debug(object message, Exception exception) + { + if (IsDebugEnabled) _logger.Debug(message, exception); + } + + public void DebugFormat(string format, params object[] args) + { + if (IsDebugEnabled) _logger.DebugFormat(format, args); + } + + public void DebugFormat(string format, object arg0) + { + if (IsDebugEnabled) _logger.DebugFormat(format, arg0); + } + + public void DebugFormat(string format, object arg0, object arg1) + { + if (IsDebugEnabled) _logger.DebugFormat(format, arg0, arg1); + } + + public void DebugFormat(string format, object arg0, object arg1, object arg2) + { + if (IsDebugEnabled) _logger.DebugFormat(format, arg0, arg1, arg2); + } + + public void DebugFormat(IFormatProvider provider, string format, params object[] args) + { + if (IsDebugEnabled) _logger.DebugFormat(provider, format, args); + } + + public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) + { + if (!IsDebugEnabled) return; + + foreach (var p in props) + { + log4net.ThreadContext.Properties[p.Key] = p.Value; + } + + _logger.Debug(message); + } + + + public void Info(object message) + { + if (IsInfoEnabled) _logger.Info(message); + } + + public void Info(string message, Exception exception) + { + if (IsInfoEnabled) _logger.Info(message, exception); + } + + public void InfoFormat(string format, params object[] args) + { + if (IsInfoEnabled) _logger.InfoFormat(format, args); + } + + public void InfoFormat(string format, object arg0) + { + if (IsInfoEnabled) _logger.InfoFormat(format, arg0); + } + + public void InfoFormat(string format, object arg0, object arg1) + { + if (IsInfoEnabled) _logger.InfoFormat(format, arg0, arg1); + } + + public void InfoFormat(string format, object arg0, object arg1, object arg2) + { + if (IsInfoEnabled) _logger.InfoFormat(format, arg0, arg1, arg2); + } + + public void InfoFormat(IFormatProvider provider, string format, params object[] args) + { + if (IsInfoEnabled) _logger.InfoFormat(provider, format, args); + } + + + public void Warn(object message) + { + if (IsWarnEnabled) _logger.Warn(message); + } + + public void Warn(object message, Exception exception) + { + if (IsWarnEnabled) _logger.Warn(message, exception); + } + + public void WarnFormat(string format, params object[] args) + { + if (IsWarnEnabled) _logger.WarnFormat(format, args); + } + + public void WarnFormat(string format, object arg0) + { + if (IsWarnEnabled) _logger.WarnFormat(format, arg0); + } + + public void WarnFormat(string format, object arg0, object arg1) + { + if (IsWarnEnabled) _logger.WarnFormat(format, arg0, arg1); + } + + public void WarnFormat(string format, object arg0, object arg1, object arg2) + { + if (IsWarnEnabled) _logger.WarnFormat(format, arg0, arg1, arg2); + } + + public void WarnFormat(IFormatProvider provider, string format, params object[] args) + { + if (IsWarnEnabled) _logger.WarnFormat(provider, format, args); + } + + + public void Error(object message) + { + if (IsErrorEnabled) _logger.Error(message); + } + + public void Error(object message, Exception exception) + { + if (IsErrorEnabled) _logger.Error(message, exception); + } + + public void ErrorFormat(string format, params object[] args) + { + if (IsErrorEnabled) _logger.ErrorFormat(format, args); + } + + public void ErrorFormat(string format, object arg0) + { + if (IsErrorEnabled) _logger.ErrorFormat(format, arg0); + } + + public void ErrorFormat(string format, object arg0, object arg1) + { + if (IsErrorEnabled) _logger.ErrorFormat(format, arg0, arg1); + } + + public void ErrorFormat(string format, object arg0, object arg1, object arg2) + { + if (IsErrorEnabled) _logger.ErrorFormat(format, arg0, arg1, arg2); + } + + public void ErrorFormat(IFormatProvider provider, string format, params object[] args) + { + if (IsErrorEnabled) _logger.ErrorFormat(provider, format, args); + } + + + public void Fatal(object message) + { + if (IsFatalEnabled) _logger.Fatal(message); + } + + public void Fatal(string message, Exception exception) + { + if (IsFatalEnabled) _logger.Fatal(message, exception); + } + + public void FatalFormat(string format, params object[] args) + { + if (IsFatalEnabled) _logger.FatalFormat(format, args); + } + + public void FatalFormat(string format, object arg0) + { + if (IsFatalEnabled) _logger.FatalFormat(format, arg0); + } + + public void FatalFormat(string format, object arg0, object arg1) + { + if (IsFatalEnabled) _logger.FatalFormat(format, arg0, arg1); + } + + public void FatalFormat(string format, object arg0, object arg1, object arg2) + { + if (IsFatalEnabled) _logger.FatalFormat(format, arg0, arg1, arg2); + } + + public void FatalFormat(IFormatProvider provider, string format, params object[] args) + { + if (IsFatalEnabled) _logger.FatalFormat(provider, format, args); + } + + public void DebugWithProps(string message, KeyValuePair<string, object> prop1, KeyValuePair<string, object> prop2, KeyValuePair<string, object> prop3) + { + if (!IsDebugEnabled) return; + + AddProp(prop1); + AddProp(prop2); + AddProp(prop3); + + _logger.Debug(message); + + static void AddProp(KeyValuePair<string, object> p) + { + log4net.ThreadContext.Properties[p.Key] = p.Value; + } + } +} + +public class NLogSettings +{ + public string Name { get; set; } + public string Dir { get; set; } +} + +[Singletone] +public class ConfigureLogNLog : IConfigureNamedOptions<LogNLog> +{ + private readonly IConfiguration _configuration; + private readonly ConfigurationExtension _configurationExtension; + + public ConfigureLogNLog(IConfiguration configuration, ConfigurationExtension configurationExtension, IHostEnvironment hostingEnvironment) + { + _configuration = configuration; + _configurationExtension = configurationExtension; + + + LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(CrossPlatform.PathCombine(_configuration["pathToConf"], "nlog.config")); + LogManager.ThrowConfigExceptions = false; + + var settings = _configurationExtension.GetSetting<NLogSettings>("log"); + + if (!string.IsNullOrEmpty(settings.Name)) + LogManager.Configuration.Variables["name"] = settings.Name; + + if (!string.IsNullOrEmpty(settings.Dir)) + LogManager.Configuration.Variables["dir"] = CrossPlatform.PathCombine(hostingEnvironment.ContentRootPath, settings.Dir) + .TrimEnd('/').TrimEnd('\\') + Path.DirectorySeparatorChar; + + NLog.Targets.Target.Register<SelfCleaningTarget>("SelfCleaning"); + } + + public void Configure(LogNLog options) => options.Configure("ASC"); + + public void Configure(string name, LogNLog options) + { + if (string.IsNullOrEmpty(name)) Configure(options); + + else options.Configure(name); + } +} + +public class LogNLog : ILog +{ + public bool IsDebugEnabled { get; private set; } + public bool IsInfoEnabled { get; private set; } + public bool IsWarnEnabled { get; private set; } + public bool IsErrorEnabled { get; private set; } + public bool IsFatalEnabled { get; private set; } + public bool IsTraceEnabled { get; private set; } + public string LogDirectory => LogManager.Configuration.Variables["dir"].Text; + public string Name + { + get => _name; + + set + { + _name = value; + Logger = LogManager.GetLogger(_name); + } + } + + private NLog.ILogger Logger + { + get => _logger; + + set + { + _logger = value; + IsDebugEnabled = _logger.IsDebugEnabled; + IsInfoEnabled = _logger.IsInfoEnabled; + IsWarnEnabled = _logger.IsWarnEnabled; + IsErrorEnabled = _logger.IsErrorEnabled; + IsFatalEnabled = _logger.IsFatalEnabled; + IsTraceEnabled = _logger.IsEnabled(LogLevel.Trace); + } + } + + private NLog.ILogger _logger; + private string _name; + + public void Configure(string name) => Name = name; + + public void Trace(object message) + { + if (IsTraceEnabled) Logger.Log(LogLevel.Trace, message); + } + + public void TraceFormat(string message, object arg0) + { + if (IsTraceEnabled) Logger.Log(LogLevel.Trace, string.Format(message, arg0)); + } + + public void Debug(object message) + { + if (IsDebugEnabled) Logger.Debug(message); + } + + public void Debug(object message, Exception exception) + { + if (IsDebugEnabled) Logger.Debug(exception, "{0}", message); + } + + public void DebugFormat(string format, params object[] args) + { + if (IsDebugEnabled) Logger.Debug(format, args); + } + + public void DebugFormat(string format, object arg0) + { + if (IsDebugEnabled) Logger.Debug(format, arg0); + } + + public void DebugFormat(string format, object arg0, object arg1) + { + if (IsDebugEnabled) Logger.Debug(format, arg0, arg1); + } + + public void DebugFormat(string format, object arg0, object arg1, object arg2) + { + if (IsDebugEnabled) Logger.Debug(format, arg0, arg1, arg2); + } + + public void DebugFormat(IFormatProvider provider, string format, params object[] args) + { + if (IsDebugEnabled) Logger.Debug(provider, format, args); + } + + public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) + { + if (!IsDebugEnabled) return; + + var theEvent = new LogEventInfo { Message = message, LoggerName = Name, Level = LogLevel.Debug }; + + foreach (var p in props) + { + theEvent.Properties[p.Key] = p.Value; + } + + Logger.Log(theEvent); + } + + public void Info(object message) + { + if (IsInfoEnabled) Logger.Info(message); + } + + public void Info(string message, Exception exception) + { + if (IsInfoEnabled) Logger.Info(exception, message); + } + + public void InfoFormat(string format, params object[] args) + { + if (IsInfoEnabled) Logger.Info(format, args); + } + + public void InfoFormat(string format, object arg0) + { + if (IsInfoEnabled) Logger.Info(format, arg0); + } + + public void InfoFormat(string format, object arg0, object arg1) + { + if (IsInfoEnabled) Logger.Info(format, arg0, arg1); + } + + public void InfoFormat(string format, object arg0, object arg1, object arg2) + { + if (IsInfoEnabled) Logger.Info(format, arg0, arg1, arg2); + } + + public void InfoFormat(IFormatProvider provider, string format, params object[] args) + { + if (IsInfoEnabled) Logger.Info(provider, format, args); + } + + + public void Warn(object message) + { + if (IsWarnEnabled) Logger.Warn(message); + } + + public void Warn(object message, Exception exception) + { + if (IsWarnEnabled) Logger.Warn(exception, "{0}", message); + } + + public void WarnFormat(string format, params object[] args) + { + if (IsWarnEnabled) Logger.Warn(format, args); + } + + public void WarnFormat(string format, object arg0) + { + if (IsWarnEnabled) Logger.Warn(format, arg0); + } + + public void WarnFormat(string format, object arg0, object arg1) + { + if (IsWarnEnabled) Logger.Warn(format, arg0, arg1); + } + + public void WarnFormat(string format, object arg0, object arg1, object arg2) + { + if (IsWarnEnabled) Logger.Warn(format, arg0, arg1, arg2); + } + + public void WarnFormat(IFormatProvider provider, string format, params object[] args) + { + if (IsWarnEnabled) Logger.Warn(provider, format, args); + } + + + public void Error(object message) + { + if (IsErrorEnabled) Logger.Error(message); + } + + public void Error(object message, Exception exception) + { + if (IsErrorEnabled) Logger.Error(exception, "{0}", message); + } + + public void ErrorFormat(string format, params object[] args) + { + if (IsErrorEnabled) Logger.Error(format, args); + } + + public void ErrorFormat(string format, object arg0) + { + if (IsErrorEnabled) Logger.Error(format, arg0); + } + + public void ErrorFormat(string format, object arg0, object arg1) + { + if (IsErrorEnabled) Logger.Error(format, arg0, arg1); + } + + public void ErrorFormat(string format, object arg0, object arg1, object arg2) + { + if (IsErrorEnabled) Logger.Error(format, arg0, arg1, arg2); + } + + public void ErrorFormat(IFormatProvider provider, string format, params object[] args) + { + if (IsErrorEnabled) Logger.Error(provider, format, args); + } + + + public void Fatal(object message) + { + if (IsFatalEnabled) Logger.Fatal(message); + } + + public void Fatal(string message, Exception exception) + { + if (IsFatalEnabled) Logger.Fatal(exception, message); + } + + public void FatalFormat(string format, params object[] args) + { + if (IsFatalEnabled) Logger.Fatal(format, args); + } + + public void FatalFormat(string format, object arg0) + { + if (IsFatalEnabled) Logger.Fatal(format, arg0); + } + + public void FatalFormat(string format, object arg0, object arg1) + { + if (IsFatalEnabled) Logger.Fatal(format, arg0, arg1); + } + + public void FatalFormat(string format, object arg0, object arg1, object arg2) + { + if (IsFatalEnabled) Logger.Fatal(format, arg0, arg1, arg2); + } + + public void FatalFormat(IFormatProvider provider, string format, params object[] args) + { + if (IsFatalEnabled) Logger.Fatal(provider, format, args); + } +} + +public class NullLog : ILog +{ + public bool IsDebugEnabled { get; set; } + public bool IsInfoEnabled { get; set; } + public bool IsWarnEnabled { get; set; } + public bool IsErrorEnabled { get; set; } + public bool IsFatalEnabled { get; set; } + public bool IsTraceEnabled { get; set; } + public string Name { get; set; } + public string LogDirectory => string.Empty; + + public void Trace(object message) { } + + public void TraceFormat(string message, object arg0) { } + + public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) { } + + public void Debug(object message) { } + + public void Debug(object message, Exception exception) { } + + public void DebugFormat(string format, params object[] args) { } + + public void DebugFormat(string format, object arg0) { } + + public void DebugFormat(string format, object arg0, object arg1) { } + + public void DebugFormat(string format, object arg0, object arg1, object arg2) { } + + public void DebugFormat(IFormatProvider provider, string format, params object[] args) { } + + public void Info(object message) { } + + public void Info(string message, Exception exception) { } + + public void InfoFormat(string format, params object[] args) { } + + public void InfoFormat(string format, object arg0) { } + + public void InfoFormat(string format, object arg0, object arg1) { } + + public void InfoFormat(string format, object arg0, object arg1, object arg2) { } + + public void InfoFormat(IFormatProvider provider, string format, params object[] args) { } + + public void Warn(object message) { } + + public void Warn(object message, Exception exception) { } + + public void WarnFormat(string format, params object[] args) { } + + public void WarnFormat(string format, object arg0) { } + + public void WarnFormat(string format, object arg0, object arg1) { } + + public void WarnFormat(string format, object arg0, object arg1, object arg2) { } + + public void WarnFormat(IFormatProvider provider, string format, params object[] args) { } + + public void Error(object message) { } + + public void Error(object message, Exception exception) { } + + public void ErrorFormat(string format, params object[] args) { } + + public void ErrorFormat(string format, object arg0) { } + + public void ErrorFormat(string format, object arg0, object arg1) { } + + public void ErrorFormat(string format, object arg0, object arg1, object arg2) { } + + public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { } + + public void Fatal(object message) { } + + public void Fatal(string message, Exception exception) { } + + public void FatalFormat(string format, params object[] args) { } + + public void FatalFormat(string format, object arg0) { } + + public void FatalFormat(string format, object arg0, object arg1) { } + + public void FatalFormat(string format, object arg0, object arg1, object arg2) { } + + public void FatalFormat(IFormatProvider provider, string format, params object[] args) { } + + public void Configure(string name) { } +} + +[Singletone] +public class LogManager<T> : OptionsMonitor<T> where T : class, ILog, new() +{ + public LogManager(IOptionsFactory<T> factory, + IEnumerable<IOptionsChangeTokenSource<T>> sources, + IOptionsMonitorCache<T> cache) + : base(factory, sources, cache) { } + + public override T Get(string name) + { + var log = base.Get(name); + + if (string.IsNullOrEmpty(log?.Name)) log = CurrentValue; + + return log; + } +} + +public class LoggerExtension<T> where T : class, ILog, new() +{ + public static void RegisterLog(DIHelper services) => + services.TryAdd(typeof(IOptionsMonitor<ILog>), typeof(LogManager<T>)); +} + +public class LogNLogExtension : LoggerExtension<LogNLog> +{ + public static void Register(DIHelper services) => + RegisterLog(services); } diff --git a/common/ASC.Common/Logging/SelfCleaningAppender.cs b/common/ASC.Common/Logging/SelfCleaningAppender.cs index c76727263d..90c346d64c 100644 --- a/common/ASC.Common/Logging/SelfCleaningAppender.cs +++ b/common/ASC.Common/Logging/SelfCleaningAppender.cs @@ -23,85 +23,84 @@ * */ -namespace ASC.Common.Logging -{ - public class SelfCleaningAppender : RollingFileAppender - { - private static DateTime _lastCleanDate; - - private static int? _cleanPeriod; +namespace ASC.Common.Logging; - protected override void Append(LoggingEvent loggingEvent) - { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) - { - _lastCleanDate = DateTime.UtcNow.Date; - Clean(); - } +public class SelfCleaningAppender : RollingFileAppender +{ + private static DateTime _lastCleanDate; - base.Append(loggingEvent); + private static int? _cleanPeriod; + + protected override void Append(LoggingEvent loggingEvent) + { + if (DateTime.UtcNow.Date > _lastCleanDate.Date) + { + _lastCleanDate = DateTime.UtcNow.Date; + Clean(); } - protected override void Append(LoggingEvent[] loggingEvents) - { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) - { - _lastCleanDate = DateTime.UtcNow.Date; - Clean(); - } + base.Append(loggingEvent); + } - base.Append(loggingEvents); + protected override void Append(LoggingEvent[] loggingEvents) + { + if (DateTime.UtcNow.Date > _lastCleanDate.Date) + { + _lastCleanDate = DateTime.UtcNow.Date; + Clean(); } - - private static int GetCleanPeriod() - { - if (_cleanPeriod != null) - return _cleanPeriod.Value; - - const string key = "CleanPeriod"; - - var value = 30; - - var repo = log4net.LogManager.GetRepository(Assembly.GetCallingAssembly()); - - if (repo != null && repo.Properties.GetKeys().Contains(key)) - int.TryParse(repo.Properties[key].ToString(), out value); - - _cleanPeriod = value; - - return value; - } - - private void Clean() - { - try - { - if (string.IsNullOrEmpty(File)) - return; - var fileInfo = new FileInfo(File); - - if (!fileInfo.Exists) - return; - - var directory = fileInfo.Directory; - - if (directory == null || !directory.Exists) - return; - - var files = directory.GetFiles(); - - var cleanPeriod = GetCleanPeriod(); - - foreach (var file in files.Where(file => (DateTime.UtcNow.Date - file.CreationTimeUtc.Date).Days > cleanPeriod)) - { - file.Delete(); - } - } - catch (Exception err) - { - LogLog.Error(GetType(), err.Message, err); - } - } - } -} \ No newline at end of file + base.Append(loggingEvents); + } + + private static int GetCleanPeriod() + { + if (_cleanPeriod != null) + return _cleanPeriod.Value; + + const string key = "CleanPeriod"; + + var value = 30; + + var repo = log4net.LogManager.GetRepository(Assembly.GetCallingAssembly()); + + if (repo != null && repo.Properties.GetKeys().Contains(key)) + int.TryParse(repo.Properties[key].ToString(), out value); + + _cleanPeriod = value; + + return value; + } + + private void Clean() + { + try + { + if (string.IsNullOrEmpty(File)) + return; + + var fileInfo = new FileInfo(File); + + if (!fileInfo.Exists) + return; + + var directory = fileInfo.Directory; + + if (directory == null || !directory.Exists) + return; + + var files = directory.GetFiles(); + + var cleanPeriod = GetCleanPeriod(); + + foreach (var file in files.Where(file => (DateTime.UtcNow.Date - file.CreationTimeUtc.Date).Days > cleanPeriod)) + { + file.Delete(); + } + } + catch (Exception err) + { + LogLog.Error(GetType(), err.Message, err); + } + } +} diff --git a/common/ASC.Common/Logging/SelfCleaningTarget.cs b/common/ASC.Common/Logging/SelfCleaningTarget.cs index 9bb2aca696..1a3fe0a3b0 100644 --- a/common/ASC.Common/Logging/SelfCleaningTarget.cs +++ b/common/ASC.Common/Logging/SelfCleaningTarget.cs @@ -25,116 +25,115 @@ using LogLevel = NLog.LogLevel; -namespace ASC.Common.Logging -{ - [Target("SelfCleaning")] - public class SelfCleaningTarget : FileTarget - { - private static DateTime _lastCleanDate; - - private static int? _cleanPeriod; +namespace ASC.Common.Logging; - protected override void Write(IList<AsyncLogEventInfo> logEvents) - { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) - { - _lastCleanDate = DateTime.UtcNow.Date; - Clean(); - } +[Target("SelfCleaning")] +public class SelfCleaningTarget : FileTarget +{ + private static DateTime _lastCleanDate; - var buffer = new List<AsyncLogEventInfo>(); + private static int? _cleanPeriod; - foreach (var logEvent in logEvents) + protected override void Write(IList<AsyncLogEventInfo> logEvents) + { + if (DateTime.UtcNow.Date > _lastCleanDate.Date) + { + _lastCleanDate = DateTime.UtcNow.Date; + Clean(); + } + + var buffer = new List<AsyncLogEventInfo>(); + + foreach (var logEvent in logEvents) + { + buffer.Add(logEvent); + if (buffer.Count < 10) continue; + base.Write(buffer); + buffer.Clear(); + } + + base.Write(buffer); + } + + protected override void Write(LogEventInfo logEvent) + { + if (DateTime.UtcNow.Date > _lastCleanDate.Date) + { + _lastCleanDate = DateTime.UtcNow.Date; + Clean(); + } + + base.Write(logEvent); + } + + private static int GetCleanPeriod() + { + if (_cleanPeriod != null) + return _cleanPeriod.Value; + + var value = 30; + + const string key = "cleanPeriod"; + + if (LogManager.Configuration.Variables.Keys.Contains(key)) + { + var variable = LogManager.Configuration.Variables[key]; + + if (variable != null && !string.IsNullOrEmpty(variable.Text)) + int.TryParse(variable.Text, out value); + } + + _cleanPeriod = value; + + return value; + } + + private void Clean() + { + var filePath = string.Empty; + var dirPath = string.Empty; + + try + { + if (FileName == null) + return; + + filePath = ((NLog.Layouts.SimpleLayout)FileName).Text; + + if (string.IsNullOrEmpty(filePath)) + return; + + dirPath = Path.GetDirectoryName(filePath); + + if (string.IsNullOrEmpty(dirPath)) + return; + + if (!Path.IsPathRooted(dirPath)) + dirPath = CrossPlatform.PathCombine(AppDomain.CurrentDomain.BaseDirectory, dirPath); + + var directory = new DirectoryInfo(dirPath); + + if (!directory.Exists) + return; + + var files = directory.GetFiles(); + + var cleanPeriod = GetCleanPeriod(); + + foreach (var file in files.Where(file => (DateTime.UtcNow.Date - file.CreationTimeUtc.Date).Days > cleanPeriod)) { - buffer.Add(logEvent); - if (buffer.Count < 10) continue; - base.Write(buffer); - buffer.Clear(); + file.Delete(); } - - base.Write(buffer); } - - protected override void Write(LogEventInfo logEvent) - { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) - { - _lastCleanDate = DateTime.UtcNow.Date; - Clean(); - } - - base.Write(logEvent); - } - - private static int GetCleanPeriod() - { - if (_cleanPeriod != null) - return _cleanPeriod.Value; - - var value = 30; - - const string key = "cleanPeriod"; - - if (LogManager.Configuration.Variables.Keys.Contains(key)) - { - var variable = LogManager.Configuration.Variables[key]; - - if (variable != null && !string.IsNullOrEmpty(variable.Text)) - int.TryParse(variable.Text, out value); - } - - _cleanPeriod = value; - - return value; - } - - private void Clean() - { - var filePath = string.Empty; - var dirPath = string.Empty; - - try - { - if (FileName == null) - return; - - filePath = ((NLog.Layouts.SimpleLayout)FileName).Text; - - if (string.IsNullOrEmpty(filePath)) - return; - - dirPath = Path.GetDirectoryName(filePath); - - if (string.IsNullOrEmpty(dirPath)) - return; - - if (!Path.IsPathRooted(dirPath)) - dirPath = CrossPlatform.PathCombine(AppDomain.CurrentDomain.BaseDirectory, dirPath); - - var directory = new DirectoryInfo(dirPath); - - if (!directory.Exists) - return; - - var files = directory.GetFiles(); - - var cleanPeriod = GetCleanPeriod(); - - foreach (var file in files.Where(file => (DateTime.UtcNow.Date - file.CreationTimeUtc.Date).Days > cleanPeriod)) - { - file.Delete(); - } - } - catch (Exception err) - { - base.Write(new LogEventInfo - { - Exception = err, - Level = LogLevel.Error, - Message = string.Format("file: {0}, dir: {1}, mess: {2}", filePath, dirPath, err.Message), - LoggerName = "SelfCleaningTarget" - }); - } + catch (Exception err) + { + base.Write(new LogEventInfo + { + Exception = err, + Level = LogLevel.Error, + Message = string.Format("file: {0}, dir: {1}, mess: {2}", filePath, dirPath, err.Message), + LoggerName = "SelfCleaningTarget" + }); } - } -} \ No newline at end of file + } +} diff --git a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs index 0789930f33..e51115490b 100644 --- a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs +++ b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs @@ -23,64 +23,63 @@ * */ -namespace ASC.Common.Logging -{ - public class SpecialFolderPathConverter : PatternConverter - { - protected override void Convert(TextWriter writer, object state) - { - if (string.IsNullOrEmpty(Option)) return; - - try - { - var result = string.Empty; - const string CMD_LINE = "CommandLine:"; - - if (Option.StartsWith(CMD_LINE)) - { - var args = Environment.CommandLine.Split(' '); - for (var i = 0; i < args.Length - 1; i++) - { - if (args[i].Equals(Option.Substring(CMD_LINE.Length), StringComparison.InvariantCultureIgnoreCase)) - result = args[i + 1]; - } - } - else - { - var repo = log4net.LogManager.GetRepository(Assembly.GetCallingAssembly()); - if (repo != null) - { - var realKey = Option; - foreach (var key in repo.Properties.GetKeys()) - { - if (Path.DirectorySeparatorChar == '/' && key == "UNIX:" + Option) - realKey = "UNIX:" + Option; - - if (Path.DirectorySeparatorChar == '\\' && key == "WINDOWS:" + Option) - realKey = "WINDOWS:" + Option; - } - - var val = repo.Properties[realKey]; - if (val is PatternString patternString) - { - patternString.ActivateOptions(); - patternString.Format(writer); - } - - else if (val != null) result = val.ToString(); - } - } - - if (!string.IsNullOrEmpty(result)) - { - result = result.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar); - writer.Write(result); - } - } - catch (Exception err) - { - LogLog.Error(GetType(), "Can not convert " + Option, err); - } - } - } -} \ No newline at end of file +namespace ASC.Common.Logging; + +public class SpecialFolderPathConverter : PatternConverter +{ + protected override void Convert(TextWriter writer, object state) + { + if (string.IsNullOrEmpty(Option)) return; + + try + { + var result = string.Empty; + const string CMD_LINE = "CommandLine:"; + + if (Option.StartsWith(CMD_LINE)) + { + var args = Environment.CommandLine.Split(' '); + for (var i = 0; i < args.Length - 1; i++) + { + if (args[i].Equals(Option.Substring(CMD_LINE.Length), StringComparison.InvariantCultureIgnoreCase)) + result = args[i + 1]; + } + } + else + { + var repo = log4net.LogManager.GetRepository(Assembly.GetCallingAssembly()); + if (repo != null) + { + var realKey = Option; + foreach (var key in repo.Properties.GetKeys()) + { + if (Path.DirectorySeparatorChar == '/' && key == "UNIX:" + Option) + realKey = "UNIX:" + Option; + + if (Path.DirectorySeparatorChar == '\\' && key == "WINDOWS:" + Option) + realKey = "WINDOWS:" + Option; + } + + var val = repo.Properties[realKey]; + if (val is PatternString patternString) + { + patternString.ActivateOptions(); + patternString.Format(writer); + } + + else if (val != null) result = val.ToString(); + } + } + + if (!string.IsNullOrEmpty(result)) + { + result = result.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar); + writer.Write(result); + } + } + catch (Exception err) + { + LogLog.Error(GetType(), "Can not convert " + Option, err); + } + } +} diff --git a/common/ASC.Common/Mapping/IMapFrom.cs b/common/ASC.Common/Mapping/IMapFrom.cs index 9e309b6263..bd96a3f229 100644 --- a/common/ASC.Common/Mapping/IMapFrom.cs +++ b/common/ASC.Common/Mapping/IMapFrom.cs @@ -23,10 +23,9 @@ * */ -namespace ASC.Common.Mapping +namespace ASC.Common.Mapping; + +public interface IMapFrom<T> { - public interface IMapFrom<T> - { - void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType()); - } -} \ No newline at end of file + void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType()); +} diff --git a/common/ASC.Common/Mapping/MappingProfile.cs b/common/ASC.Common/Mapping/MappingProfile.cs index 0df22a5cf8..d90d4991bd 100644 --- a/common/ASC.Common/Mapping/MappingProfile.cs +++ b/common/ASC.Common/Mapping/MappingProfile.cs @@ -23,30 +23,29 @@ * */ -namespace ASC.Common.Mapping +namespace ASC.Common.Mapping; + +public class MappingProfile : Profile { - public class MappingProfile : Profile + public MappingProfile() => Array.ForEach(AppDomain.CurrentDomain.GetAssemblies(), a => ApplyMappingsFromAssembly(a)); + + private void ApplyMappingsFromAssembly(Assembly assembly) { - public MappingProfile() => Array.ForEach(AppDomain.CurrentDomain.GetAssemblies(), a => ApplyMappingsFromAssembly(a)); + if (!assembly.GetName().Name.StartsWith("ASC.")) return; - private void ApplyMappingsFromAssembly(Assembly assembly) + var types = assembly.GetExportedTypes() + .Where(t => t.GetInterfaces().Any(i => + i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>))) + .ToList(); + + foreach (var type in types) { - if (!assembly.GetName().Name.StartsWith("ASC.")) return; + var instance = Activator.CreateInstance(type); - var types = assembly.GetExportedTypes() - .Where(t => t.GetInterfaces().Any(i => - i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>))) - .ToList(); + var methodInfo = type.GetMethod("Mapping") + ?? type.GetInterface("IMapFrom`1").GetMethod("Mapping"); - foreach (var type in types) - { - var instance = Activator.CreateInstance(type); - - var methodInfo = type.GetMethod("Mapping") - ?? type.GetInterface("IMapFrom`1").GetMethod("Mapping"); - - methodInfo?.Invoke(instance, new object[] { this }); - } + methodInfo?.Invoke(instance, new object[] { this }); } } -} \ No newline at end of file +} diff --git a/common/ASC.Common/Module/BaseWcfClient.cs b/common/ASC.Common/Module/BaseWcfClient.cs index 3fa222fb21..f94a1e47aa 100644 --- a/common/ASC.Common/Module/BaseWcfClient.cs +++ b/common/ASC.Common/Module/BaseWcfClient.cs @@ -23,35 +23,31 @@ * */ +namespace ASC.Common.Module; -using System.ServiceModel; - -namespace ASC.Common.Module +public class BaseWcfClient<TService> : ClientBase<TService>, IDisposable where TService : class { - public class BaseWcfClient<TService> : ClientBase<TService>, IDisposable where TService : class - { - public BaseWcfClient() { } + public BaseWcfClient() { } - void IDisposable.Dispose() + void IDisposable.Dispose() + { + // msdn recommendation to close wcf client + try { - // msdn recommendation to close wcf client - try - { - //Close(); - } - catch (CommunicationException) - { - Abort(); - } - catch (TimeoutException) - { - Abort(); - } - catch (Exception) - { - Abort(); - throw; - } + //Close(); + } + catch (CommunicationException) + { + Abort(); + } + catch (TimeoutException) + { + Abort(); + } + catch (Exception) + { + Abort(); + throw; } } } \ No newline at end of file diff --git a/common/ASC.Common/Module/IServiceController.cs b/common/ASC.Common/Module/IServiceController.cs index 90f40098cd..c7d571ba08 100644 --- a/common/ASC.Common/Module/IServiceController.cs +++ b/common/ASC.Common/Module/IServiceController.cs @@ -24,12 +24,11 @@ */ -namespace ASC.Common.Module -{ - public interface IServiceController - { - void Start(); +namespace ASC.Common.Module; - void Stop(); - } -} \ No newline at end of file +public interface IServiceController +{ + void Start(); + + void Stop(); +} diff --git a/common/ASC.Common/Notify/AWSEmail.cs b/common/ASC.Common/Notify/AWSEmail.cs deleted file mode 100644 index 947993753a..0000000000 --- a/common/ASC.Common/Notify/AWSEmail.cs +++ /dev/null @@ -1,192 +0,0 @@ -/* - * - * (c) Copyright Ascensio System Limited 2010-2018 - * - * This program is freeware. You can redistribute it and/or modify it under the terms of the GNU - * General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html). - * In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that - * Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights. - * - * THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR - * FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html - * - * You can contact Ascensio System SIA by email at sales@onlyoffice.com - * - * The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display - * Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3. - * - * Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains - * relevant author attributions when distributing the software. If the display of the logo in its graphic - * form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE" - * in every copy of the program you distribute. - * Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks. - * -*/ - - -using System; -using System.Configuration; -using System.IO; -using System.Linq; -using System.Net.Mail; -using System.Text; -using System.Threading; -using ASC.Common.Utils; -using Amazon.SimpleEmail; -using Amazon.SimpleEmail.Model; -using log4net; - -namespace ASC.Common.Notify -{ - public class AWSEmail - { - public enum SendStatus - { - Ok, - Failed, - QuotaLimit - } - - private readonly AmazonSimpleEmailServiceClient _emailService; - private readonly ILog _log = LogHolder.Log("ASC.Notify.AmazonSES"); - - //Static fields - private static readonly TimeSpan RefreshTimeout; - private static DateTime _lastRefresh; - private static DateTime _lastSend; - private static TimeSpan _sendWindow = TimeSpan.MinValue; - private static GetSendQuotaResult _quota; - private static readonly object SynchRoot = new object(); - - - static AWSEmail() - { - RefreshTimeout = TimeSpan.FromMinutes(30); - if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ses.refreshTimeout"])) - { - TimeSpan.TryParse(ConfigurationManager.AppSettings["ses.refreshTimeout"], out RefreshTimeout); - } - _lastRefresh = DateTime.UtcNow - RefreshTimeout;//Set to refresh on first send - } - - public AWSEmail() - { - var accessKey = ConfigurationManager.AppSettings["ses.accessKey"]; - var secretKey = ConfigurationManager.AppSettings["ses.secretKey"]; - - _emailService = new AmazonSimpleEmailServiceClient(accessKey, secretKey); - - - } - - public SendStatus SendEmail(MailMessage mailMessage) - { - //Check if we need to query stats - RefreshQuotaIfNeeded(); - if (_quota != null) - { - lock (SynchRoot) - { - if (_quota.Max24HourSend <= _quota.SentLast24Hours) - { - //Quota exceeded - //Queu next refresh to +24 hours - _lastRefresh = DateTime.UtcNow.AddHours(24); - _log.WarnFormat("quota limit reached. setting next check to: {0}", _lastRefresh); - return SendStatus.QuotaLimit; - } - } - } - - - - var destination = new Destination - { - ToAddresses = mailMessage.To.Select(adresses => adresses.Address).ToList(), - BccAddresses = mailMessage.Bcc.Select(adresses => adresses.Address).ToList(), - CcAddresses = mailMessage.CC.Select(adresses => adresses.Address).ToList(), - - }; - - var body = new Body(new Content(mailMessage.Body) { Charset = Encoding.UTF8.WebName }); - - if (mailMessage.AlternateViews.Count > 0) - { - //Get html body - foreach (var alternateView in mailMessage.AlternateViews) - { - if ("text/html".Equals(alternateView.ContentType.MediaType, StringComparison.OrdinalIgnoreCase)) - { - var stream = alternateView.ContentStream; - var buf = new byte[stream.Length]; - stream.Read(buf, 0, buf.Length); - stream.Seek(0, SeekOrigin.Begin);//NOTE:seek to begin to keep HTML body - body.Html = new Content(Encoding.UTF8.GetString(buf)) { Charset = Encoding.UTF8.WebName }; - break; - } - } - } - - var message = new Message(new Content(mailMessage.Subject), body); - - var seRequest = new SendEmailRequest(mailMessage.From.ToEncodedStringEx(), destination, message); - if (mailMessage.ReplyTo != null) - seRequest.ReplyToAddresses.Add(mailMessage.ReplyTo.Address); - - ThrottleIfNeeded(); - - var response = _emailService.SendEmail(seRequest); - _lastSend = DateTime.UtcNow; - return response != null ? SendStatus.Ok : SendStatus.Failed; - } - - private void ThrottleIfNeeded() - { - //Check last send and throttle if needed - if (_sendWindow != TimeSpan.MinValue) - { - if (DateTime.UtcNow - _lastSend <= _sendWindow) - //Possible BUG: at high frequncies maybe bug with to little differences - { - //This means that time passed from last send is less then message per second - _log.DebugFormat("send rate doesn't fit in send window. sleeping for:{0}", _sendWindow); - Thread.Sleep(_sendWindow); - } - } - } - - private void RefreshQuotaIfNeeded() - { - if (!IsRefreshNeeded()) return; - - lock (SynchRoot) - { - if (IsRefreshNeeded())//Double check - { - _log.DebugFormat("refreshing qouta. interval: {0} Last refresh was at: {1}", RefreshTimeout, - _lastRefresh); - - //Do quota refresh - _lastRefresh = DateTime.UtcNow.AddMinutes(1); - try - { - var quotaRequest = new GetSendQuotaRequest(); - _quota = _emailService.GetSendQuota(quotaRequest).GetSendQuotaResult; - _sendWindow = TimeSpan.FromSeconds(1.0 / _quota.MaxSendRate); - _log.DebugFormat("quota: {0}/{1} at {2} mps. send window:{3}", _quota.SentLast24Hours, - _quota.Max24HourSend, _quota.MaxSendRate, _sendWindow); - } - catch (Exception e) - { - _log.Error("error refreshing quota", e); - } - } - } - } - - private static bool IsRefreshNeeded() - { - return (DateTime.UtcNow - _lastRefresh) > RefreshTimeout || _quota == null; - } - } -} diff --git a/common/ASC.Common/Security/AscRandom.cs b/common/ASC.Common/Security/AscRandom.cs index 97071e2942..0458ba4054 100644 --- a/common/ASC.Common/Security/AscRandom.cs +++ b/common/ASC.Common/Security/AscRandom.cs @@ -23,90 +23,89 @@ * */ -namespace ASC.Common.Security -{ - public class AscRandom : Random +namespace ASC.Common.Security; + +public class AscRandom : Random +{ + private const int Mbig = int.MaxValue; + private const int Mseed = 161803398; + private const int Mz = 0; + + private int _inext; + private int _inextp; + private readonly int[] _seeds; + + public AscRandom() : this(Environment.TickCount) { } + + public AscRandom(int seed) { - private const int Mbig = int.MaxValue; - private const int Mseed = 161803398; - private const int Mz = 0; - - private int _inext; - private int _inextp; - private readonly int[] _seeds; - - public AscRandom() : this(Environment.TickCount) { } - - public AscRandom(int seed) - { - _seeds = new int[56]; - var num4 = (seed == int.MinValue) ? int.MaxValue : Math.Abs(seed); - var num2 = 161803398 - num4; - _seeds[^1] = num2; - var num3 = 1; - - for (var i = 1; i < _seeds.Length - 1; i++) - { - var index = (21 * i) % (_seeds.Length - 1); - _seeds[index] = num3; - num3 = num2 - num3; - - if (num3 < 0) num3 += int.MaxValue; - - num2 = _seeds[index]; + _seeds = new int[56]; + var num4 = (seed == int.MinValue) ? int.MaxValue : Math.Abs(seed); + var num2 = 161803398 - num4; + _seeds[^1] = num2; + var num3 = 1; + + for (var i = 1; i < _seeds.Length - 1; i++) + { + var index = (21 * i) % (_seeds.Length - 1); + _seeds[index] = num3; + num3 = num2 - num3; + + if (num3 < 0) num3 += int.MaxValue; + + num2 = _seeds[index]; + } + + for (var j = 1; j < 5; j++) + { + for (var k = 1; k < _seeds.Length; k++) + { + _seeds[k] -= _seeds[1 + ((k + 30) % (_seeds.Length - 1))]; + + if (_seeds[k] < 0) _seeds[k] += int.MaxValue; } - - for (var j = 1; j < 5; j++) - { - for (var k = 1; k < _seeds.Length; k++) - { - _seeds[k] -= _seeds[1 + ((k + 30) % (_seeds.Length - 1))]; - - if (_seeds[k] < 0) _seeds[k] += int.MaxValue; - } - } - - _inext = 0; - _inextp = 21; - } - - public override int Next(int maxValue) - { - if (maxValue < 0) throw new ArgumentOutOfRangeException(nameof(maxValue)); - - return (int)(InternalSample() * 4.6566128752457969E-10 * maxValue); - } - - public override void NextBytes(byte[] buffer) - { - if (buffer == null) throw new ArgumentNullException(nameof(buffer)); - - for (var i = 0; i < buffer.Length; i++) - { - buffer[i] = (byte)(InternalSample() % (byte.MaxValue + 1)); - } - } - - private int InternalSample() - { - var inext = this._inext; - var inextp = this._inextp; - - if (++inext >= _seeds.Length - 1) inext = 1; - - if (++inextp >= _seeds.Length - 1) inextp = 1; - - var num = _seeds[inext] - _seeds[inextp]; - - if (num == int.MaxValue) num--; - - if (num < 0) num += int.MaxValue; - - _seeds[inext] = num; - this._inext = inext; - this._inextp = inextp; - - return num; - } - } -} \ No newline at end of file + } + + _inext = 0; + _inextp = 21; + } + + public override int Next(int maxValue) + { + if (maxValue < 0) throw new ArgumentOutOfRangeException(nameof(maxValue)); + + return (int)(InternalSample() * 4.6566128752457969E-10 * maxValue); + } + + public override void NextBytes(byte[] buffer) + { + if (buffer == null) throw new ArgumentNullException(nameof(buffer)); + + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte)(InternalSample() % (byte.MaxValue + 1)); + } + } + + private int InternalSample() + { + var inext = _inext; + var inextp = _inextp; + + if (++inext >= _seeds.Length - 1) inext = 1; + + if (++inextp >= _seeds.Length - 1) inextp = 1; + + var num = _seeds[inext] - _seeds[inextp]; + + if (num == int.MaxValue) num--; + + if (num < 0) num += int.MaxValue; + + _seeds[inext] = num; + _inext = inext; + _inextp = inextp; + + return num; + } +} diff --git a/common/ASC.Common/Security/Authentication/Account.cs b/common/ASC.Common/Security/Authentication/Account.cs index 4bfbe88248..71ba28d655 100644 --- a/common/ASC.Common/Security/Authentication/Account.cs +++ b/common/ASC.Common/Security/Authentication/Account.cs @@ -23,29 +23,28 @@ * */ -namespace ASC.Common.Security.Authentication +namespace ASC.Common.Security.Authentication; + +[Serializable] +public class Account : IAccount { - [Serializable] - public class Account : IAccount + public Guid ID { get; private set; } + public string Name { get; private set; } + public virtual bool IsAuthenticated { get; private set; } + public string AuthenticationType => "ASC"; + + public Account(Guid id, string name, bool authenticated) { - public Guid ID { get; private set; } - public string Name { get; private set; } - public virtual bool IsAuthenticated { get; private set; } - public string AuthenticationType => "ASC"; - - public Account(Guid id, string name, bool authenticated) - { - ID = id; - Name = name; - IsAuthenticated = authenticated; - } - - public object Clone() => MemberwiseClone(); - - public override bool Equals(object obj) => obj is IAccount a && ID.Equals(a.ID); - - public override int GetHashCode() => ID.GetHashCode(); - - public override string ToString() => Name; + ID = id; + Name = name; + IsAuthenticated = authenticated; } -} \ No newline at end of file + + public object Clone() => MemberwiseClone(); + + public override bool Equals(object obj) => obj is IAccount a && ID.Equals(a.ID); + + public override int GetHashCode() => ID.GetHashCode(); + + public override string ToString() => Name; +} diff --git a/common/ASC.Common/Security/Authentication/IAccount.cs b/common/ASC.Common/Security/Authentication/IAccount.cs index 57d69487b3..21bedd12c9 100644 --- a/common/ASC.Common/Security/Authentication/IAccount.cs +++ b/common/ASC.Common/Security/Authentication/IAccount.cs @@ -23,7 +23,6 @@ * */ -namespace ASC.Common.Security.Authentication -{ - public interface IAccount : ISubject, ICloneable { } -} \ No newline at end of file +namespace ASC.Common.Security.Authentication; + +public interface IAccount : ISubject, ICloneable { } diff --git a/common/ASC.Common/Security/Authentication/ISystemAccount.cs b/common/ASC.Common/Security/Authentication/ISystemAccount.cs index f94f27b71c..903c4037f3 100644 --- a/common/ASC.Common/Security/Authentication/ISystemAccount.cs +++ b/common/ASC.Common/Security/Authentication/ISystemAccount.cs @@ -24,7 +24,6 @@ */ -namespace ASC.Common.Security.Authentication -{ - public interface ISystemAccount : IAccount { } -} \ No newline at end of file +namespace ASC.Common.Security.Authentication; + +public interface ISystemAccount : IAccount { } diff --git a/common/ASC.Common/Security/Authentication/IUserAccount.cs b/common/ASC.Common/Security/Authentication/IUserAccount.cs index a3a211dd3e..6455841227 100644 --- a/common/ASC.Common/Security/Authentication/IUserAccount.cs +++ b/common/ASC.Common/Security/Authentication/IUserAccount.cs @@ -24,14 +24,13 @@ */ -namespace ASC.Common.Security.Authentication +namespace ASC.Common.Security.Authentication; + +public interface IUserAccount : IAccount { - public interface IUserAccount : IAccount - { - string Email { get; } - string FirstName { get; } - string LastName { get; } - string Title { get; } - int Tenant { get; } - } -} \ No newline at end of file + string Email { get; } + string FirstName { get; } + string LastName { get; } + string Title { get; } + int Tenant { get; } +} diff --git a/common/ASC.Common/Security/Authentication/SystemAccount.cs b/common/ASC.Common/Security/Authentication/SystemAccount.cs index 4f44704bff..6c05ccb503 100644 --- a/common/ASC.Common/Security/Authentication/SystemAccount.cs +++ b/common/ASC.Common/Security/Authentication/SystemAccount.cs @@ -23,12 +23,11 @@ * */ -namespace ASC.Common.Security.Authentication +namespace ASC.Common.Security.Authentication; + +[Serializable] +public class SystemAccount : Account, ISystemAccount { - [Serializable] - public class SystemAccount : Account, ISystemAccount - { - public SystemAccount(Guid id, string name, bool authenticated) - : base(id, name, authenticated) { } - } -} \ No newline at end of file + public SystemAccount(Guid id, string name, bool authenticated) + : base(id, name, authenticated) { } +} diff --git a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs index d1c577b170..b815fe550b 100644 --- a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs +++ b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs @@ -24,102 +24,95 @@ */ -#region usings +namespace ASC.Common.Security.Authorizing; -using System.Runtime.Serialization; - -#endregion - -namespace ASC.Common.Security.Authorizing +[Serializable] +public class AuthorizingException : Exception { - [Serializable] - public class AuthorizingException : Exception + public ISubject Subject { get; internal set; } + public IAction[] Actions { get; internal set; } + public override string Message => _message; + + private readonly string _message; + + public AuthorizingException(string message) + : base(message) { } + + public AuthorizingException(ISubject subject, IAction[] actions) { - public ISubject Subject { get; internal set; } - public IAction[] Actions { get; internal set; } - public override string Message => _message; - - private readonly string _message; + if (actions == null || actions.Length == 0) throw new ArgumentNullException(nameof(actions)); - public AuthorizingException(string message) - : base(message) { } + Subject = subject ?? throw new ArgumentNullException(nameof(subject)); + Actions = actions; + var sactions = ""; - public AuthorizingException(ISubject subject, IAction[] actions) - { - if (actions == null || actions.Length == 0) throw new ArgumentNullException(nameof(actions)); + Array.ForEach(actions, action => { sactions += action.ToString() + ", "; }); - Subject = subject ?? throw new ArgumentNullException(nameof(subject)); - Actions = actions; - var sactions = ""; - - Array.ForEach(actions, action => { sactions += action.ToString() + ", "; }); - - _message = string.Format( - "\"{0}\" access denied \"{1}\"", - subject, - sactions - ); - } - - public AuthorizingException(ISubject subject, IAction[] actions, ISubject[] denySubjects, IAction[] denyActions) => - _message = FormatErrorMessage(subject, actions, denySubjects, denyActions); - - protected AuthorizingException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - _message = info.GetValue("_Message", typeof(string)) as string; - Subject = info.GetValue("Subject", typeof(ISubject)) as ISubject; - Actions = info.GetValue("Actions", typeof(IAction[])) as IAction[]; - } - - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("Subject", Subject, typeof(ISubject)); - info.AddValue("_Message", _message, typeof(string)); - info.AddValue("Actions", Actions, typeof(IAction[])); - base.GetObjectData(info, context); - } - - internal static string FormatErrorMessage(ISubject subject, IAction[] actions, ISubject[] denySubjects, - IAction[] denyActions) - { - if (subject == null) throw new ArgumentNullException(nameof(subject)); - if (actions == null || actions.Length == 0) throw new ArgumentNullException(nameof(actions)); - if (denySubjects == null || denySubjects.Length == 0) throw new ArgumentNullException(nameof(denySubjects)); - if (denyActions == null || denyActions.Length == 0) throw new ArgumentNullException(nameof(denyActions)); - if (actions.Length != denySubjects.Length || actions.Length != denyActions.Length) - throw new ArgumentException(); - - var reasons = ""; - for (var i = 0; i < actions.Length; i++) - { - var reason = ""; - - if (denySubjects[i] != null && denyActions[i] != null) - reason = string.Format("{0}:{1} access denied {2}.", - actions[i].Name, - (denySubjects[i] is IRole ? "role:" : "") + denySubjects[i].Name, - denyActions[i].Name - ); - else reason = string.Format("{0}: access denied.", actions[i].Name); - - if (i != actions.Length - 1) - reason += ", "; - - reasons += reason; - } - var sactions = ""; - - Array.ForEach(actions, action => { sactions += action.ToString() + ", "; }); - - var message = string.Format( - "\"{0}\" access denied \"{1}\". Cause: {2}.", - (subject is IRole ? "role:" : "") + subject.Name, - sactions, - reasons - ); - - return message; - } + _message = string.Format( + "\"{0}\" access denied \"{1}\"", + subject, + sactions + ); } -} \ No newline at end of file + + public AuthorizingException(ISubject subject, IAction[] actions, ISubject[] denySubjects, IAction[] denyActions) => + _message = FormatErrorMessage(subject, actions, denySubjects, denyActions); + + protected AuthorizingException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + _message = info.GetValue("_Message", typeof(string)) as string; + Subject = info.GetValue("Subject", typeof(ISubject)) as ISubject; + Actions = info.GetValue("Actions", typeof(IAction[])) as IAction[]; + } + + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue("Subject", Subject, typeof(ISubject)); + info.AddValue("_Message", _message, typeof(string)); + info.AddValue("Actions", Actions, typeof(IAction[])); + base.GetObjectData(info, context); + } + + internal static string FormatErrorMessage(ISubject subject, IAction[] actions, ISubject[] denySubjects, + IAction[] denyActions) + { + if (subject == null) throw new ArgumentNullException(nameof(subject)); + if (actions == null || actions.Length == 0) throw new ArgumentNullException(nameof(actions)); + if (denySubjects == null || denySubjects.Length == 0) throw new ArgumentNullException(nameof(denySubjects)); + if (denyActions == null || denyActions.Length == 0) throw new ArgumentNullException(nameof(denyActions)); + if (actions.Length != denySubjects.Length || actions.Length != denyActions.Length) + throw new ArgumentException(); + + var reasons = ""; + for (var i = 0; i < actions.Length; i++) + { + var reason = ""; + + if (denySubjects[i] != null && denyActions[i] != null) + reason = string.Format("{0}:{1} access denied {2}.", + actions[i].Name, + (denySubjects[i] is IRole ? "role:" : "") + denySubjects[i].Name, + denyActions[i].Name + ); + else reason = string.Format("{0}: access denied.", actions[i].Name); + + if (i != actions.Length - 1) + reason += ", "; + + reasons += reason; + } + var sactions = ""; + + Array.ForEach(actions, action => { sactions += action.ToString() + ", "; }); + + var message = string.Format( + "\"{0}\" access denied \"{1}\". Cause: {2}.", + (subject is IRole ? "role:" : "") + subject.Name, + sactions, + reasons + ); + + return message; + } +} diff --git a/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs b/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs index a82b16340a..87eade24d5 100644 --- a/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs +++ b/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs @@ -24,17 +24,16 @@ */ -namespace ASC.Common.Security.Authorizing +namespace ASC.Common.Security.Authorizing; + +public static class AzObjectIdHelper { - public static class AzObjectIdHelper + private static readonly string separator = "|"; + + public static string GetFullObjectId(ISecurityObjectId objectId) { - private static readonly string separator = "|"; + if (objectId == null) return null; - public static string GetFullObjectId(ISecurityObjectId objectId) - { - if (objectId == null) return null; - - return $"{objectId.ObjectType.FullName}{separator}{objectId.SecurityId}"; - } + return $"{objectId.ObjectType.FullName}{separator}{objectId.SecurityId}"; } -} \ No newline at end of file +} diff --git a/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs b/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs index fc5b310bc1..505f09863f 100644 --- a/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs +++ b/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs @@ -23,63 +23,56 @@ * */ +namespace ASC.Common.Security.Authorizing; -#region usings - - -#endregion - -namespace ASC.Common.Security.Authorizing +public class AzObjectSecurityProviderHelper { - public class AzObjectSecurityProviderHelper + public ISecurityObjectId CurrentObjectId { get; private set; } + public bool ObjectRolesSupported => _currSecObjProvider != null && _currSecObjProvider.ObjectRolesSupported; + + private readonly SecurityCallContext _callContext; + private readonly bool _currObjIdAsProvider; + private ISecurityObjectProvider _currSecObjProvider; + + public AzObjectSecurityProviderHelper(ISecurityObjectId objectId, ISecurityObjectProvider secObjProvider) { - public ISecurityObjectId CurrentObjectId { get; private set; } - public bool ObjectRolesSupported => _currSecObjProvider != null && _currSecObjProvider.ObjectRolesSupported; + _currObjIdAsProvider = false; + CurrentObjectId = objectId ?? throw new ArgumentNullException(nameof(objectId)); + _currSecObjProvider = secObjProvider; - private readonly SecurityCallContext _callContext; - private readonly bool _currObjIdAsProvider; - private ISecurityObjectProvider _currSecObjProvider; - - public AzObjectSecurityProviderHelper(ISecurityObjectId objectId, ISecurityObjectProvider secObjProvider) + if (_currSecObjProvider == null && CurrentObjectId is ISecurityObjectProvider securityObjectProvider) { - _currObjIdAsProvider = false; - CurrentObjectId = objectId ?? throw new ArgumentNullException(nameof(objectId)); - _currSecObjProvider = secObjProvider; - - if (_currSecObjProvider == null && CurrentObjectId is ISecurityObjectProvider securityObjectProvider) - { - _currObjIdAsProvider = true; - _currSecObjProvider = securityObjectProvider; - } - - _callContext = new SecurityCallContext(); + _currObjIdAsProvider = true; + _currSecObjProvider = securityObjectProvider; } - public IEnumerable<IRole> GetObjectRoles(ISubject account) + _callContext = new SecurityCallContext(); + } + + public IEnumerable<IRole> GetObjectRoles(ISubject account) + { + var roles = _currSecObjProvider.GetObjectRoles(account, CurrentObjectId, _callContext); + + foreach (var role in roles) { - var roles = _currSecObjProvider.GetObjectRoles(account, CurrentObjectId, _callContext); - - foreach (var role in roles) - { - if (!_callContext.RolesList.Contains(role)) _callContext.RolesList.Add(role); - } - - return roles; + if (!_callContext.RolesList.Contains(role)) _callContext.RolesList.Add(role); } - public bool NextInherit() - { - if (_currSecObjProvider == null || !_currSecObjProvider.InheritSupported) return false; + return roles; + } - CurrentObjectId = _currSecObjProvider.InheritFrom(CurrentObjectId); + public bool NextInherit() + { + if (_currSecObjProvider == null || !_currSecObjProvider.InheritSupported) return false; - if (CurrentObjectId == null) return false; + CurrentObjectId = _currSecObjProvider.InheritFrom(CurrentObjectId); - if (_currObjIdAsProvider) _currSecObjProvider = CurrentObjectId as ISecurityObjectProvider; + if (CurrentObjectId == null) return false; - _callContext.ObjectsStack.Insert(0, CurrentObjectId); + if (_currObjIdAsProvider) _currSecObjProvider = CurrentObjectId as ISecurityObjectProvider; - return _currSecObjProvider != null; - } + _callContext.ObjectsStack.Insert(0, CurrentObjectId); + + return _currSecObjProvider != null; } } \ No newline at end of file diff --git a/common/ASC.Common/Security/Authorizing/Constants.cs b/common/ASC.Common/Security/Authorizing/Constants.cs index bd415c11e9..3c3cb37bd3 100644 --- a/common/ASC.Common/Security/Authorizing/Constants.cs +++ b/common/ASC.Common/Security/Authorizing/Constants.cs @@ -23,24 +23,23 @@ * */ -namespace ASC.Common.Security.Authorizing +namespace ASC.Common.Security.Authorizing; + +public sealed class Constants { - public sealed class Constants - { - public static readonly Role Admin = new Role(new Guid("cd84e66b-b803-40fc-99f9-b2969a54a1de"), "Admin"); + public static readonly Role Admin = new Role(new Guid("cd84e66b-b803-40fc-99f9-b2969a54a1de"), "Admin"); - public static readonly Role Everyone = new Role(new Guid("c5cc67d1-c3e8-43c0-a3ad-3928ae3e5b5e"), "Everyone"); + public static readonly Role Everyone = new Role(new Guid("c5cc67d1-c3e8-43c0-a3ad-3928ae3e5b5e"), "Everyone"); - public static readonly Role User = new Role(new Guid("abef62db-11a8-4673-9d32-ef1d8af19dc0"), "User"); + public static readonly Role User = new Role(new Guid("abef62db-11a8-4673-9d32-ef1d8af19dc0"), "User"); - public static readonly Role Visitor = new Role(new Guid("aced04fa-dd96-4b35-af3e-346bf1eb972d"), "Visitor"); + public static readonly Role Visitor = new Role(new Guid("aced04fa-dd96-4b35-af3e-346bf1eb972d"), "Visitor"); - public static readonly Role Member = new Role(new Guid("ba74ca02-873f-43dc-8470-8620c156bc67"), "Member"); + public static readonly Role Member = new Role(new Guid("ba74ca02-873f-43dc-8470-8620c156bc67"), "Member"); - public static readonly Role Owner = new Role(new Guid("bba32183-a14d-48ed-9d39-c6b4d8925fbf"), "Owner"); + public static readonly Role Owner = new Role(new Guid("bba32183-a14d-48ed-9d39-c6b4d8925fbf"), "Owner"); - public static readonly Role Self = new Role(new Guid("5d5b7260-f7f7-49f1-a1c9-95fbb6a12604"), "Self"); - } -} \ No newline at end of file + public static readonly Role Self = new Role(new Guid("5d5b7260-f7f7-49f1-a1c9-95fbb6a12604"), "Self"); +} diff --git a/common/ASC.Common/Security/Authorizing/Domain/Ace.cs b/common/ASC.Common/Security/Authorizing/Domain/Ace.cs index b945dcdaa9..e92e64ce83 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Ace.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Ace.cs @@ -23,18 +23,17 @@ * */ -namespace ASC.Common.Security.Authorizing -{ - [Serializable] - public class Ace - { - public Guid ActionId { get; set; } - public AceType Reaction { get; set; } +namespace ASC.Common.Security.Authorizing; - public Ace(Guid actionId, AceType reaction) - { - ActionId = actionId; - Reaction = reaction; - } - } -} \ No newline at end of file +[Serializable] +public class Ace +{ + public Guid ActionId { get; set; } + public AceType Reaction { get; set; } + + public Ace(Guid actionId, AceType reaction) + { + ActionId = actionId; + Reaction = reaction; + } +} diff --git a/common/ASC.Common/Security/Authorizing/Domain/AceType.cs b/common/ASC.Common/Security/Authorizing/Domain/AceType.cs index e01ed60b1c..d320336078 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/AceType.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/AceType.cs @@ -24,11 +24,10 @@ */ -namespace ASC.Common.Security.Authorizing +namespace ASC.Common.Security.Authorizing; + +public enum AceType { - public enum AceType - { - Allow, - Deny, - } -} \ No newline at end of file + Allow, + Deny, +} diff --git a/common/ASC.Common/Security/Authorizing/Domain/Action.cs b/common/ASC.Common/Security/Authorizing/Domain/Action.cs index 896f9ad730..067286393b 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Action.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Action.cs @@ -23,33 +23,32 @@ * */ -namespace ASC.Common.Security.Authorizing +namespace ASC.Common.Security.Authorizing; + +[Serializable] +public class Action : IAction { - [Serializable] - public class Action : IAction + public Guid ID { get; private set; } + public string Name { get; private set; } + public bool AdministratorAlwaysAllow { get; private set; } + public bool Conjunction { get; private set; } + + public Action(Guid id, string name) + : this(id, name, true, true) { } + + public Action(Guid id, string name, bool administratorAlwaysAllow, bool conjunction) { - public Guid ID { get; private set; } - public string Name { get; private set; } - public bool AdministratorAlwaysAllow { get; private set; } - public bool Conjunction { get; private set; } + if (id == Guid.Empty) throw new ArgumentNullException(nameof(id)); - public Action(Guid id, string name) - : this(id, name, true, true) { } - - public Action(Guid id, string name, bool administratorAlwaysAllow, bool conjunction) - { - if (id == Guid.Empty) throw new ArgumentNullException(nameof(id)); - - ID = id; - Name = name; - AdministratorAlwaysAllow = administratorAlwaysAllow; - Conjunction = conjunction; - } - - public override int GetHashCode() => ID.GetHashCode(); - - public override bool Equals(object obj) => obj is Action a && a.ID == ID; - - public override string ToString() => Name; + ID = id; + Name = name; + AdministratorAlwaysAllow = administratorAlwaysAllow; + Conjunction = conjunction; } -} \ No newline at end of file + + public override int GetHashCode() => ID.GetHashCode(); + + public override bool Equals(object obj) => obj is Action a && a.ID == ID; + + public override string ToString() => Name; +} diff --git a/common/ASC.Common/Security/Authorizing/Domain/Role.cs b/common/ASC.Common/Security/Authorizing/Domain/Role.cs index 228c06c58f..50fbb28835 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Role.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Role.cs @@ -23,36 +23,35 @@ * */ -namespace ASC.Common.Security.Authorizing +namespace ASC.Common.Security.Authorizing; + +[Serializable] +public sealed class Role : IRole { - [Serializable] - public sealed class Role : IRole + public const string Everyone = "Everyone"; + public const string Visitors = "Visitors"; + public const string Users = "Users"; + public const string Administrators = "Administrators"; + public const string System = "System"; + + public Guid ID { get; internal set; } + public string Name { get; internal set; } + public string AuthenticationType => "ASC"; + public bool IsAuthenticated => false; + + + public Role(Guid id, string name) { - public const string Everyone = "Everyone"; - public const string Visitors = "Visitors"; - public const string Users = "Users"; - public const string Administrators = "Administrators"; - public const string System = "System"; + if (id == Guid.Empty) throw new ArgumentException(nameof(id)); + if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); - public Guid ID { get; internal set; } - public string Name { get; internal set; } - public string AuthenticationType => "ASC"; - public bool IsAuthenticated => false; - - - public Role(Guid id, string name) - { - if (id == Guid.Empty) throw new ArgumentException(nameof(id)); - if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); - - ID = id; - Name = name; - } - - public override int GetHashCode() => ID.GetHashCode(); - - public override bool Equals(object obj) => obj is Role r && r.ID == ID; - - public override string ToString() => $"Role: {Name}"; + ID = id; + Name = name; } -} \ No newline at end of file + + public override int GetHashCode() => ID.GetHashCode(); + + public override bool Equals(object obj) => obj is Role r && r.ID == ID; + + public override string ToString() => $"Role: {Name}"; +} diff --git a/common/ASC.Common/Security/Authorizing/Interfaces/IAction.cs b/common/ASC.Common/Security/Authorizing/Interfaces/IAction.cs index 0303b5ee73..60f95a9f65 100644 --- a/common/ASC.Common/Security/Authorizing/Interfaces/IAction.cs +++ b/common/ASC.Common/Security/Authorizing/Interfaces/IAction.cs @@ -23,13 +23,12 @@ * */ -namespace ASC.Common.Security.Authorizing +namespace ASC.Common.Security.Authorizing; + +public interface IAction { - public interface IAction - { - Guid ID { get; } - string Name { get; } - bool AdministratorAlwaysAllow { get; } - bool Conjunction { get; } - } -} \ No newline at end of file + Guid ID { get; } + string Name { get; } + bool AdministratorAlwaysAllow { get; } + bool Conjunction { get; } +} diff --git a/common/ASC.Common/Security/Authorizing/Interfaces/IRole.cs b/common/ASC.Common/Security/Authorizing/Interfaces/IRole.cs index 30c1c06042..52553eb0af 100644 --- a/common/ASC.Common/Security/Authorizing/Interfaces/IRole.cs +++ b/common/ASC.Common/Security/Authorizing/Interfaces/IRole.cs @@ -24,7 +24,6 @@ */ -namespace ASC.Common.Security.Authorizing -{ - public interface IRole : ISubject { } -} \ No newline at end of file +namespace ASC.Common.Security.Authorizing; + +public interface IRole : ISubject { } diff --git a/common/ASC.Common/Security/Authorizing/Interfaces/ISubject.cs b/common/ASC.Common/Security/Authorizing/Interfaces/ISubject.cs index 5a691ea36e..cd8f33633b 100644 --- a/common/ASC.Common/Security/Authorizing/Interfaces/ISubject.cs +++ b/common/ASC.Common/Security/Authorizing/Interfaces/ISubject.cs @@ -23,10 +23,9 @@ * */ -namespace ASC.Common.Security.Authorizing +namespace ASC.Common.Security.Authorizing; + +public interface ISubject : IIdentity { - public interface ISubject : IIdentity - { - Guid ID { get; } - } -} \ No newline at end of file + Guid ID { get; } +} diff --git a/common/ASC.Common/Security/Cryptography/HashAlg.cs b/common/ASC.Common/Security/Cryptography/HashAlg.cs index 75105cf436..0925f9da0e 100644 --- a/common/ASC.Common/Security/Cryptography/HashAlg.cs +++ b/common/ASC.Common/Security/Cryptography/HashAlg.cs @@ -24,13 +24,12 @@ */ -namespace ASC.Security.Cryptography +namespace ASC.Security.Cryptography; + +public enum HashAlg { - public enum HashAlg - { - MD5, - SHA1, - SHA256, - SHA512 - } -} \ No newline at end of file + MD5, + SHA1, + SHA256, + SHA512 +} diff --git a/common/ASC.Common/Security/Cryptography/Hasher.cs b/common/ASC.Common/Security/Cryptography/Hasher.cs index c95ef80f5a..ed2961f49c 100644 --- a/common/ASC.Common/Security/Cryptography/Hasher.cs +++ b/common/ASC.Common/Security/Cryptography/Hasher.cs @@ -23,92 +23,91 @@ * */ -namespace ASC.Security.Cryptography -{ - public sealed class Hasher - { - private const HashAlg DefaultAlg = HashAlg.SHA256; - - public static byte[] Hash(string data, HashAlg hashAlg) => ComputeHash(data, hashAlg); - - public static byte[] Hash(string data) => Hash(data, DefaultAlg); - - public static byte[] Hash(byte[] data, HashAlg hashAlg) => ComputeHash(data, hashAlg); - - public static byte[] Hash(byte[] data) => Hash(data, DefaultAlg); - - public static string Base64Hash(string data, HashAlg hashAlg) => ComputeHash64(data, hashAlg); - - public static string Base64Hash(string data) => Base64Hash(data, DefaultAlg); - - public static string Base64Hash(byte[] data, HashAlg hashAlg) => ComputeHash64(data, hashAlg); - - public static string Base64Hash(byte[] data) => Base64Hash(data, DefaultAlg); - public static bool EqualHash(byte[] dataToCompare, byte[] hash) => EqualHash(dataToCompare, hash, DefaultAlg); - - public static bool EqualHash(string dataToCompare, string hash, HashAlg hashAlg) => EqualHash(S2B(dataToCompare), S642B(hash), hashAlg); - - public static bool EqualHash(string dataToCompare, string hash) => EqualHash(dataToCompare, hash, DefaultAlg); +namespace ASC.Security.Cryptography; - public static bool EqualHash(byte[] dataToCompare, byte[] hash, HashAlg hashAlg) - { - return string.Equals( - ComputeHash64(dataToCompare, hashAlg), - B2S64(hash) - ); - } - - private static HashAlgorithm GetAlg(HashAlg hashAlg) - { - return hashAlg switch - { - HashAlg.MD5 => MD5.Create(), - HashAlg.SHA1 => SHA1.Create(), - HashAlg.SHA256 => SHA256.Create(), - HashAlg.SHA512 => SHA512.Create(), - _ => SHA256.Create() - }; - } - - private static byte[] S2B(string str) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - return Encoding.UTF8.GetBytes(str); - } - - private static string B2S(byte[] data) - { - if (data == null) throw new ArgumentNullException(nameof(data)); - - return Encoding.UTF8.GetString(data); - } - - private static byte[] S642B(string str) - { - if (str == null) throw new ArgumentNullException(nameof(str)); - - return Convert.FromBase64String(str); - } - - private static string B2S64(byte[] data) - { - if (data == null) throw new ArgumentNullException(nameof(data)); - - return Convert.ToBase64String(data); - } - - private static byte[] ComputeHash(byte[] data, HashAlg hashAlg) +public sealed class Hasher +{ + private const HashAlg DefaultAlg = HashAlg.SHA256; + + public static byte[] Hash(string data, HashAlg hashAlg) => ComputeHash(data, hashAlg); + + public static byte[] Hash(string data) => Hash(data, DefaultAlg); + + public static byte[] Hash(byte[] data, HashAlg hashAlg) => ComputeHash(data, hashAlg); + + public static byte[] Hash(byte[] data) => Hash(data, DefaultAlg); + + public static string Base64Hash(string data, HashAlg hashAlg) => ComputeHash64(data, hashAlg); + + public static string Base64Hash(string data) => Base64Hash(data, DefaultAlg); + + public static string Base64Hash(byte[] data, HashAlg hashAlg) => ComputeHash64(data, hashAlg); + + public static string Base64Hash(byte[] data) => Base64Hash(data, DefaultAlg); + public static bool EqualHash(byte[] dataToCompare, byte[] hash) => EqualHash(dataToCompare, hash, DefaultAlg); + + public static bool EqualHash(string dataToCompare, string hash, HashAlg hashAlg) => EqualHash(S2B(dataToCompare), S642B(hash), hashAlg); + + public static bool EqualHash(string dataToCompare, string hash) => EqualHash(dataToCompare, hash, DefaultAlg); + + public static bool EqualHash(byte[] dataToCompare, byte[] hash, HashAlg hashAlg) + { + return string.Equals( + ComputeHash64(dataToCompare, hashAlg), + B2S64(hash) + ); + } + + private static HashAlgorithm GetAlg(HashAlg hashAlg) + { + return hashAlg switch { - using var alg = GetAlg(hashAlg); - - return alg.ComputeHash(data); - } - - private static byte[] ComputeHash(string data, HashAlg hashAlg) => ComputeHash(S2B(data), hashAlg); - - private static string ComputeHash64(byte[] data, HashAlg hashAlg) => B2S64(ComputeHash(data, hashAlg)); - - private static string ComputeHash64(string data, HashAlg hashAlg) => ComputeHash64(S2B(data), hashAlg); - } -} \ No newline at end of file + HashAlg.MD5 => MD5.Create(), + HashAlg.SHA1 => SHA1.Create(), + HashAlg.SHA256 => SHA256.Create(), + HashAlg.SHA512 => SHA512.Create(), + _ => SHA256.Create() + }; + } + + private static byte[] S2B(string str) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + return Encoding.UTF8.GetBytes(str); + } + + private static string B2S(byte[] data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + + return Encoding.UTF8.GetString(data); + } + + private static byte[] S642B(string str) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + + return Convert.FromBase64String(str); + } + + private static string B2S64(byte[] data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + + return Convert.ToBase64String(data); + } + + private static byte[] ComputeHash(byte[] data, HashAlg hashAlg) + { + using var alg = GetAlg(hashAlg); + + return alg.ComputeHash(data); + } + + private static byte[] ComputeHash(string data, HashAlg hashAlg) => ComputeHash(S2B(data), hashAlg); + + private static string ComputeHash64(byte[] data, HashAlg hashAlg) => B2S64(ComputeHash(data, hashAlg)); + + private static string ComputeHash64(string data, HashAlg hashAlg) => ComputeHash64(S2B(data), hashAlg); +} diff --git a/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs b/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs index a79906198b..4f8f93f717 100644 --- a/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs +++ b/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs @@ -23,51 +23,50 @@ * */ -namespace ASC.Security.Cryptography +namespace ASC.Security.Cryptography; + +[Singletone] +public class InstanceCrypto { - [Singletone] - public class InstanceCrypto + private readonly byte[] _eKey; + + public InstanceCrypto(MachinePseudoKeys machinePseudoKeys) => + _eKey = machinePseudoKeys.GetMachineConstant(32); + + public string Encrypt(string data) => + Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(data))); + + public byte[] Encrypt(byte[] data) { - private readonly byte[] _eKey; + using var hasher = Aes.Create(); + hasher.Key = _eKey; + hasher.IV = new byte[hasher.BlockSize >> 3]; - public InstanceCrypto(MachinePseudoKeys machinePseudoKeys) => - _eKey = machinePseudoKeys.GetMachineConstant(32); + using var ms = new MemoryStream(); + using var ss = new CryptoStream(ms, hasher.CreateEncryptor(), CryptoStreamMode.Write); + using var plainTextStream = new MemoryStream(data); - public string Encrypt(string data) => - Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(data))); + plainTextStream.CopyTo(ss); + ss.FlushFinalBlock(); + hasher.Clear(); - public byte[] Encrypt(byte[] data) - { - using var hasher = Aes.Create(); - hasher.Key = _eKey; - hasher.IV = new byte[hasher.BlockSize >> 3]; - - using var ms = new MemoryStream(); - using var ss = new CryptoStream(ms, hasher.CreateEncryptor(), CryptoStreamMode.Write); - using var plainTextStream = new MemoryStream(data); - - plainTextStream.CopyTo(ss); - ss.FlushFinalBlock(); - hasher.Clear(); - - return ms.ToArray(); - } - - public string Decrypt(string data) => Decrypt(Convert.FromBase64String(data)); - - public string Decrypt(byte[] data) - { - using var hasher = Aes.Create(); - hasher.Key = _eKey; - hasher.IV = new byte[hasher.BlockSize >> 3]; - - using var msDecrypt = new MemoryStream(data); - using var csDecrypt = new CryptoStream(msDecrypt, hasher.CreateDecryptor(), CryptoStreamMode.Read); - using var srDecrypt = new StreamReader(csDecrypt); - - // Read the decrypted bytes from the decrypting stream - // and place them in a string. - return srDecrypt.ReadToEnd(); - } + return ms.ToArray(); } -} \ No newline at end of file + + public string Decrypt(string data) => Decrypt(Convert.FromBase64String(data)); + + public string Decrypt(byte[] data) + { + using var hasher = Aes.Create(); + hasher.Key = _eKey; + hasher.IV = new byte[hasher.BlockSize >> 3]; + + using var msDecrypt = new MemoryStream(data); + using var csDecrypt = new CryptoStream(msDecrypt, hasher.CreateDecryptor(), CryptoStreamMode.Read); + using var srDecrypt = new StreamReader(csDecrypt); + + // Read the decrypted bytes from the decrypting stream + // and place them in a string. + return srDecrypt.ReadToEnd(); + } +} diff --git a/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs b/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs index 0c1117b0c1..7b386c0eca 100644 --- a/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs +++ b/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs @@ -23,42 +23,41 @@ * */ -namespace ASC.Security.Cryptography +namespace ASC.Security.Cryptography; + +[Singletone] +public class MachinePseudoKeys { - [Singletone] - public class MachinePseudoKeys + private readonly byte[] _confKey = null; + + public MachinePseudoKeys(IConfiguration configuration) { - private readonly byte[] _confKey = null; + var key = configuration["core:machinekey"]; - public MachinePseudoKeys(IConfiguration configuration) - { - var key = configuration["core:machinekey"]; + if (string.IsNullOrEmpty(key)) key = configuration["asc:common.machinekey"]; - if (string.IsNullOrEmpty(key)) key = configuration["asc:common.machinekey"]; - - if (!string.IsNullOrEmpty(key)) _confKey = Encoding.UTF8.GetBytes(key); - } - - - public byte[] GetMachineConstant() - { - if (_confKey != null) return _confKey; - - var path = typeof(MachinePseudoKeys).Assembly.Location; - var fi = new FileInfo(path); - - return BitConverter.GetBytes(fi.CreationTime.ToOADate()); - } - - public byte[] GetMachineConstant(int bytesCount) - { - var cnst = Enumerable.Repeat<byte>(0, sizeof(int)).Concat(GetMachineConstant()).ToArray(); - var icnst = BitConverter.ToInt32(cnst, cnst.Length - sizeof(int)); - var rnd = new AscRandom(icnst); - var buff = new byte[bytesCount]; - rnd.NextBytes(buff); - - return buff; - } + if (!string.IsNullOrEmpty(key)) _confKey = Encoding.UTF8.GetBytes(key); } -} \ No newline at end of file + + + public byte[] GetMachineConstant() + { + if (_confKey != null) return _confKey; + + var path = typeof(MachinePseudoKeys).Assembly.Location; + var fi = new FileInfo(path); + + return BitConverter.GetBytes(fi.CreationTime.ToOADate()); + } + + public byte[] GetMachineConstant(int bytesCount) + { + var cnst = Enumerable.Repeat<byte>(0, sizeof(int)).Concat(GetMachineConstant()).ToArray(); + var icnst = BitConverter.ToInt32(cnst, cnst.Length - sizeof(int)); + var rnd = new AscRandom(icnst); + var buff = new byte[bytesCount]; + rnd.NextBytes(buff); + + return buff; + } +} diff --git a/common/ASC.Common/Security/Cryptography/PasswordHasher.cs b/common/ASC.Common/Security/Cryptography/PasswordHasher.cs index 0573a44db7..5ec25eeabe 100644 --- a/common/ASC.Common/Security/Cryptography/PasswordHasher.cs +++ b/common/ASC.Common/Security/Cryptography/PasswordHasher.cs @@ -23,54 +23,53 @@ * */ -namespace ASC.Security.Cryptography +namespace ASC.Security.Cryptography; + +[Singletone] +public class PasswordHasher { - [Singletone] - public class PasswordHasher + public int Size { get; private set; } + public int Iterations { get; private set; } + public string Salt { get; private set; } + + public PasswordHasher(IConfiguration configuration, MachinePseudoKeys machinePseudoKeys) { - public int Size { get; private set; } - public int Iterations { get; private set; } - public string Salt { get; private set; } + if (!int.TryParse(configuration["core:password:size"], out var size)) size = 256; + Size = size; - public PasswordHasher(IConfiguration configuration, MachinePseudoKeys machinePseudoKeys) + if (!int.TryParse(configuration["core.password.iterations"], out var iterations)) iterations = 100000; + Iterations = iterations; + + Salt = (configuration["core:password:salt"] ?? "").Trim(); + if (string.IsNullOrEmpty(Salt)) { - if (!int.TryParse(configuration["core:password:size"], out var size)) size = 256; - Size = size; + var salt = Hasher.Hash("{9450BEF7-7D9F-4E4F-A18A-971D8681722D}", HashAlg.SHA256); - if (!int.TryParse(configuration["core.password.iterations"], out var iterations)) iterations = 100000; - Iterations = iterations; - - Salt = (configuration["core:password:salt"] ?? "").Trim(); - if (string.IsNullOrEmpty(Salt)) - { - var salt = Hasher.Hash("{9450BEF7-7D9F-4E4F-A18A-971D8681722D}", HashAlg.SHA256); - - var PasswordHashSaltBytes = KeyDerivation.Pbkdf2( - Encoding.UTF8.GetString(machinePseudoKeys.GetMachineConstant()), - salt, - KeyDerivationPrf.HMACSHA256, - Iterations, - Size / 8); - Salt = BitConverter.ToString(PasswordHashSaltBytes).Replace("-", string.Empty).ToLower(); - } - } - - public string GetClientPassword(string password) - { - if (string.IsNullOrWhiteSpace(password)) password = Guid.NewGuid().ToString(); - - var salt = new UTF8Encoding(false).GetBytes(Salt); - - var hashBytes = KeyDerivation.Pbkdf2( - password, - salt, - KeyDerivationPrf.HMACSHA256, - Iterations, - Size / 8); - - var hash = BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLower(); - - return hash; + var PasswordHashSaltBytes = KeyDerivation.Pbkdf2( + Encoding.UTF8.GetString(machinePseudoKeys.GetMachineConstant()), + salt, + KeyDerivationPrf.HMACSHA256, + Iterations, + Size / 8); + Salt = BitConverter.ToString(PasswordHashSaltBytes).Replace("-", string.Empty).ToLower(); } } -} \ No newline at end of file + + public string GetClientPassword(string password) + { + if (string.IsNullOrWhiteSpace(password)) password = Guid.NewGuid().ToString(); + + var salt = new UTF8Encoding(false).GetBytes(Salt); + + var hashBytes = KeyDerivation.Pbkdf2( + password, + salt, + KeyDerivationPrf.HMACSHA256, + Iterations, + Size / 8); + + var hash = BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLower(); + + return hash; + } +} diff --git a/common/ASC.Common/Security/ISecurityObject.cs b/common/ASC.Common/Security/ISecurityObject.cs index 3f1e612d21..a960498a28 100644 --- a/common/ASC.Common/Security/ISecurityObject.cs +++ b/common/ASC.Common/Security/ISecurityObject.cs @@ -24,7 +24,6 @@ */ -namespace ASC.Common.Security -{ - public interface ISecurityObject : ISecurityObjectId, ISecurityObjectProvider { } -} \ No newline at end of file +namespace ASC.Common.Security; + +public interface ISecurityObject : ISecurityObjectId, ISecurityObjectProvider { } diff --git a/common/ASC.Common/Security/ISecurityObjectId.cs b/common/ASC.Common/Security/ISecurityObjectId.cs index 46feb8a967..1af91ed6ce 100644 --- a/common/ASC.Common/Security/ISecurityObjectId.cs +++ b/common/ASC.Common/Security/ISecurityObjectId.cs @@ -24,11 +24,10 @@ */ -namespace ASC.Common.Security +namespace ASC.Common.Security; + +public interface ISecurityObjectId { - public interface ISecurityObjectId - { - object SecurityId { get; } - Type ObjectType { get; } - } -} \ No newline at end of file + object SecurityId { get; } + Type ObjectType { get; } +} diff --git a/common/ASC.Common/Security/ISecurityObjectProvider.cs b/common/ASC.Common/Security/ISecurityObjectProvider.cs index abf8b557ce..bafcda4054 100644 --- a/common/ASC.Common/Security/ISecurityObjectProvider.cs +++ b/common/ASC.Common/Security/ISecurityObjectProvider.cs @@ -24,14 +24,13 @@ */ -namespace ASC.Common.Security -{ - public interface ISecurityObjectProvider - { - bool InheritSupported { get; } - bool ObjectRolesSupported { get; } - - ISecurityObjectId InheritFrom(ISecurityObjectId objectId); - IEnumerable<IRole> GetObjectRoles(ISubject account, ISecurityObjectId objectId, SecurityCallContext callContext); - } -} \ No newline at end of file +namespace ASC.Common.Security; + +public interface ISecurityObjectProvider +{ + bool InheritSupported { get; } + bool ObjectRolesSupported { get; } + + ISecurityObjectId InheritFrom(ISecurityObjectId objectId); + IEnumerable<IRole> GetObjectRoles(ISubject account, ISecurityObjectId objectId, SecurityCallContext callContext); +} diff --git a/common/ASC.Common/Security/SecurityCallContext.cs b/common/ASC.Common/Security/SecurityCallContext.cs index 979fd38064..f34f3c7e83 100644 --- a/common/ASC.Common/Security/SecurityCallContext.cs +++ b/common/ASC.Common/Security/SecurityCallContext.cs @@ -23,18 +23,17 @@ * */ -namespace ASC.Common.Security -{ - public class SecurityCallContext +namespace ASC.Common.Security; + +public class SecurityCallContext +{ + public object UserData { get; set; } + public List<ISecurityObjectId> ObjectsStack { get; private set; } + public List<IRole> RolesList { get; private set; } + + public SecurityCallContext() { - public object UserData { get; set; } - public List<ISecurityObjectId> ObjectsStack { get; private set; } - public List<IRole> RolesList { get; private set; } - - public SecurityCallContext() - { - ObjectsStack = new List<ISecurityObjectId>(); - RolesList = new List<IRole>(); - } - } -} \ No newline at end of file + ObjectsStack = new List<ISecurityObjectId>(); + RolesList = new List<IRole>(); + } +} diff --git a/common/ASC.Common/Security/SecurityObjectId.cs b/common/ASC.Common/Security/SecurityObjectId.cs index c9a1c0a3fa..d6e8209a80 100644 --- a/common/ASC.Common/Security/SecurityObjectId.cs +++ b/common/ASC.Common/Security/SecurityObjectId.cs @@ -23,24 +23,23 @@ * */ -namespace ASC.Common.Security -{ - [DebuggerDisplay("ObjectType: {ObjectType.Name}, SecurityId: {SecurityId}")] - public class SecurityObjectId : ISecurityObjectId - { - public object SecurityId { get; private set; } - public Type ObjectType { get; private set; } - - public SecurityObjectId(object id, Type objType) - { - SecurityId = id; - ObjectType = objType ?? throw new ArgumentNullException(nameof(objType)); - } - - public override int GetHashCode() => AzObjectIdHelper.GetFullObjectId(this).GetHashCode(); - - public override bool Equals(object obj) => - obj is SecurityObjectId other && - Equals(AzObjectIdHelper.GetFullObjectId(other), AzObjectIdHelper.GetFullObjectId(this)); - } -} \ No newline at end of file +namespace ASC.Common.Security; + +[DebuggerDisplay("ObjectType: {ObjectType.Name}, SecurityId: {SecurityId}")] +public class SecurityObjectId : ISecurityObjectId +{ + public object SecurityId { get; private set; } + public Type ObjectType { get; private set; } + + public SecurityObjectId(object id, Type objType) + { + SecurityId = id; + ObjectType = objType ?? throw new ArgumentNullException(nameof(objType)); + } + + public override int GetHashCode() => AzObjectIdHelper.GetFullObjectId(this).GetHashCode(); + + public override bool Equals(object obj) => + obj is SecurityObjectId other && + Equals(AzObjectIdHelper.GetFullObjectId(other), AzObjectIdHelper.GetFullObjectId(this)); +} diff --git a/common/ASC.Common/Threading/DistributedTask.cs b/common/ASC.Common/Threading/DistributedTask.cs index 639e5a3b13..d5e3c8d000 100644 --- a/common/ASC.Common/Threading/DistributedTask.cs +++ b/common/ASC.Common/Threading/DistributedTask.cs @@ -25,73 +25,72 @@ using JsonSerializer = System.Text.Json.JsonSerializer; -namespace ASC.Common.Threading -{ - public class DistributedTask - { - public Action<DistributedTask> Publication { get; set; } - public int InstanceId - { - get => DistributedTaskCache.InstanceId; - set => DistributedTaskCache.InstanceId = value; - } - public string Id - { - get => DistributedTaskCache.Id; - protected set => DistributedTaskCache.Id = value?.ToString() ?? ""; - } - public DistributedTaskStatus Status - { - get => Enum.Parse<DistributedTaskStatus>(DistributedTaskCache.Status); - set => DistributedTaskCache.Status = value.ToString(); - } - public Exception Exception - { - get => new Exception(DistributedTaskCache.Exception); - set => DistributedTaskCache.Exception = value?.ToString() ?? ""; - } - protected internal DistributedTaskCache DistributedTaskCache { get; internal set; } - - public DistributedTask() - { - DistributedTaskCache = new DistributedTaskCache - { - Id = Guid.NewGuid().ToString() - }; - } - - public DistributedTask(DistributedTaskCache distributedTaskCache) => - DistributedTaskCache = distributedTaskCache; - - public T GetProperty<T>(string name) - { - var prop = DistributedTaskCache.Props.FirstOrDefault(r => r.Key == name); +namespace ASC.Common.Threading; - if (prop == null) return default; - - return JsonSerializer.Deserialize<T>(prop.Value); - } - - public void SetProperty(string name, object value) +public class DistributedTask +{ + public Action<DistributedTask> Publication { get; set; } + public int InstanceId + { + get => DistributedTaskCache.InstanceId; + set => DistributedTaskCache.InstanceId = value; + } + public string Id + { + get => DistributedTaskCache.Id; + protected set => DistributedTaskCache.Id = value?.ToString() ?? ""; + } + public DistributedTaskStatus Status + { + get => Enum.Parse<DistributedTaskStatus>(DistributedTaskCache.Status); + set => DistributedTaskCache.Status = value.ToString(); + } + public Exception Exception + { + get => new Exception(DistributedTaskCache.Exception); + set => DistributedTaskCache.Exception = value?.ToString() ?? ""; + } + protected internal DistributedTaskCache DistributedTaskCache { get; internal set; } + + public DistributedTask() + { + DistributedTaskCache = new DistributedTaskCache { - var prop = new DistributedTaskCache.Types.DistributedTaskCacheProp() - { - Key = name, - Value = JsonSerializer.Serialize(value) - }; + Id = Guid.NewGuid().ToString() + }; + } - var current = DistributedTaskCache.Props.SingleOrDefault(r => r.Key == name); + public DistributedTask(DistributedTaskCache distributedTaskCache) => + DistributedTaskCache = distributedTaskCache; - if (current != null) DistributedTaskCache.Props.Remove(current); - - if (value != null) DistributedTaskCache.Props.Add(prop); - } - - public void PublishChanges() - { - if (Publication == null) throw new InvalidOperationException("Publication not found."); - - Publication(this); - } - } -} \ No newline at end of file + public T GetProperty<T>(string name) + { + var prop = DistributedTaskCache.Props.FirstOrDefault(r => r.Key == name); + + if (prop == null) return default; + + return JsonSerializer.Deserialize<T>(prop.Value); + } + + public void SetProperty(string name, object value) + { + var prop = new DistributedTaskCache.Types.DistributedTaskCacheProp() + { + Key = name, + Value = JsonSerializer.Serialize(value) + }; + + var current = DistributedTaskCache.Props.SingleOrDefault(r => r.Key == name); + + if (current != null) DistributedTaskCache.Props.Remove(current); + + if (value != null) DistributedTaskCache.Props.Add(prop); + } + + public void PublishChanges() + { + if (Publication == null) throw new InvalidOperationException("Publication not found."); + + Publication(this); + } +} diff --git a/common/ASC.Common/Threading/DistributedTaskProgress.cs b/common/ASC.Common/Threading/DistributedTaskProgress.cs index 2c451ccac4..4e1c1012bf 100644 --- a/common/ASC.Common/Threading/DistributedTaskProgress.cs +++ b/common/ASC.Common/Threading/DistributedTaskProgress.cs @@ -1,39 +1,38 @@ -namespace ASC.Common.Threading +namespace ASC.Common.Threading; + +[Transient] +public class DistributedTaskProgress : DistributedTask { - [Transient] - public class DistributedTaskProgress : DistributedTask + public double Percentage { - public double Percentage - { - get => Math.Min(100.0, Math.Max(0, DistributedTaskCache.Percentage)); - set => DistributedTaskCache.Percentage = value; - } - public bool IsCompleted - { - get => DistributedTaskCache.IsCompleted; - set => DistributedTaskCache.IsCompleted = value; - } - protected int StepCount - { - get => DistributedTaskCache.StepCount; - set => DistributedTaskCache.StepCount = value; - } - - public void RunJob() - { - Percentage = 0; - Status = DistributedTaskStatus.Running; - - DoJob(); - } - - protected virtual void DoJob() { } - - protected void StepDone() - { - if (StepCount > 0) Percentage += 100.0 / StepCount; - - PublishChanges(); - } + get => Math.Min(100.0, Math.Max(0, DistributedTaskCache.Percentage)); + set => DistributedTaskCache.Percentage = value; } -} \ No newline at end of file + public bool IsCompleted + { + get => DistributedTaskCache.IsCompleted; + set => DistributedTaskCache.IsCompleted = value; + } + protected int StepCount + { + get => DistributedTaskCache.StepCount; + set => DistributedTaskCache.StepCount = value; + } + + public void RunJob() + { + Percentage = 0; + Status = DistributedTaskStatus.Running; + + DoJob(); + } + + protected virtual void DoJob() { } + + protected void StepDone() + { + if (StepCount > 0) Percentage += 100.0 / StepCount; + + PublishChanges(); + } +} diff --git a/common/ASC.Common/Threading/DistributedTaskQueue.cs b/common/ASC.Common/Threading/DistributedTaskQueue.cs index 214d712df1..ce95eb3638 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -23,267 +23,266 @@ * */ -namespace ASC.Common.Threading +namespace ASC.Common.Threading; + +[Singletone] +public class DistributedTaskCacheNotify { - [Singletone] - public class DistributedTaskCacheNotify + public ConcurrentDictionary<string, CancellationTokenSource> Cancelations { get; } + public ICache Cache { get; } + + private readonly IEventBus<DistributedTaskCancelation> _eventBusNotify; + private readonly IEventBus<DistributedTaskCache> _eventBusCache; + + public DistributedTaskCacheNotify( + IEventBus<DistributedTaskCancelation> eventBusNotify, + IEventBus<DistributedTaskCache> eventBusCache, + ICache cache) { - public ConcurrentDictionary<string, CancellationTokenSource> Cancelations { get; } - public ICache Cache { get; } + Cancelations = new ConcurrentDictionary<string, CancellationTokenSource>(); - private readonly IEventBus<DistributedTaskCancelation> _eventBusNotify; - private readonly IEventBus<DistributedTaskCache> _eventBusCache; + Cache = cache; - public DistributedTaskCacheNotify( - IEventBus<DistributedTaskCancelation> eventBusNotify, - IEventBus<DistributedTaskCache> eventBusCache, - ICache cache) + _eventBusNotify = eventBusNotify; + + eventBusNotify.Subscribe((c) => { - Cancelations = new ConcurrentDictionary<string, CancellationTokenSource>(); + if (Cancelations.TryGetValue(c.Id, out var s)) s.Cancel(); - Cache = cache; + }, EventType.Remove); - _eventBusNotify = eventBusNotify; + _eventBusCache = eventBusCache; - eventBusNotify.Subscribe((c) => - { - if (Cancelations.TryGetValue(c.Id, out var s)) s.Cancel(); - - }, EventType.Remove); + eventBusCache.Subscribe((c) => + { + Cache.HashSet(c.Key, c.Id, (DistributedTaskCache)null); + }, EventType.Remove); - _eventBusCache = eventBusCache; - - eventBusCache.Subscribe((c) => - { - Cache.HashSet(c.Key, c.Id, (DistributedTaskCache)null); - }, EventType.Remove); - - eventBusCache.Subscribe((c) => - { - Cache.HashSet(c.Key, c.Id, c); - }, EventType.InsertOrUpdate); - } - - public void CancelTask(string id) => - _eventBusNotify.Publish(new DistributedTaskCancelation() { Id = id }, EventType.Remove); - - public void SetTask(DistributedTask task) => - _eventBusCache.Publish(task.DistributedTaskCache, EventType.InsertOrUpdate); - - public void RemoveTask(string id, string key) => - _eventBusCache.Publish(new DistributedTaskCache() { Id = id, Key = key }, EventType.Remove); + eventBusCache.Subscribe((c) => + { + Cache.HashSet(c.Key, c.Id, c); + }, EventType.InsertOrUpdate); } - [Singletone(typeof(ConfigureDistributedTaskQueue))] - public class DistributedTaskQueueOptionsManager : OptionsManager<DistributedTaskQueue> - { - public DistributedTaskQueueOptionsManager(IOptionsFactory<DistributedTaskQueue> factory) : base(factory) { } + public void CancelTask(string id) => + _eventBusNotify.Publish(new DistributedTaskCancelation() { Id = id }, EventType.Remove); - public DistributedTaskQueue Get<T>() where T : DistributedTask => Get(typeof(T).FullName); - } + public void SetTask(DistributedTask task) => + _eventBusCache.Publish(task.DistributedTaskCache, EventType.InsertOrUpdate); - [Scope] - public class ConfigureDistributedTaskQueue : IConfigureNamedOptions<DistributedTaskQueue> + public void RemoveTask(string id, string key) => + _eventBusCache.Publish(new DistributedTaskCache() { Id = id, Key = key }, EventType.Remove); +} + +[Singletone(typeof(ConfigureDistributedTaskQueue))] +public class DistributedTaskQueueOptionsManager : OptionsManager<DistributedTaskQueue> +{ + public DistributedTaskQueueOptionsManager(IOptionsFactory<DistributedTaskQueue> factory) : base(factory) { } + + public DistributedTaskQueue Get<T>() where T : DistributedTask => Get(typeof(T).FullName); +} + +[Scope] +public class ConfigureDistributedTaskQueue : IConfigureNamedOptions<DistributedTaskQueue> +{ + private DistributedTaskCacheNotify DistributedTaskCacheNotify { get; } + public IServiceProvider ServiceProvider { get; } + + public ConfigureDistributedTaskQueue(DistributedTaskCacheNotify distributedTaskCacheNotify, IServiceProvider serviceProvider) { - private DistributedTaskCacheNotify DistributedTaskCacheNotify { get; } - public IServiceProvider ServiceProvider { get; } - - public ConfigureDistributedTaskQueue(DistributedTaskCacheNotify distributedTaskCacheNotify, IServiceProvider serviceProvider) - { - DistributedTaskCacheNotify = distributedTaskCacheNotify; - ServiceProvider = serviceProvider; - } - - public void Configure(DistributedTaskQueue queue) - { - queue.DistributedTaskCacheNotify = DistributedTaskCacheNotify; - queue.ServiceProvider = ServiceProvider; - } - - public void Configure(string name, DistributedTaskQueue options) - { - Configure(options); - options.Name = name; - } - } - - public class DistributedTaskQueue - { - public IServiceProvider ServiceProvider { get; set; } - public DistributedTaskCacheNotify DistributedTaskCacheNotify { get; set; } - public string Name - { - get => _name; - set => _name = value + GetType().Name; - } - public int MaxThreadsCount - { - set => Scheduler = value <= 0 - ? TaskScheduler.Default - : new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, value).ConcurrentScheduler; - } - - public static readonly int InstanceId; - - private TaskScheduler Scheduler { get; set; } = TaskScheduler.Default; - private ICache Cache => DistributedTaskCacheNotify.Cache; - private ConcurrentDictionary<string, CancellationTokenSource> Cancelations => - DistributedTaskCacheNotify.Cancelations; - - private string _name; - - static DistributedTaskQueue() => InstanceId = Process.GetCurrentProcess().Id; - - - public void QueueTask(DistributedTaskProgress taskProgress) => - QueueTask((a, b) => taskProgress.RunJob(), taskProgress); - - public void QueueTask(Action<DistributedTask, CancellationToken> action, DistributedTask distributedTask = null) - { - if (distributedTask == null) distributedTask = new DistributedTask(); - - distributedTask.InstanceId = InstanceId; - - var cancelation = new CancellationTokenSource(); - var token = cancelation.Token; - Cancelations[distributedTask.Id] = cancelation; - - var task = new Task(() => { action(distributedTask, token); }, token, TaskCreationOptions.LongRunning); - - task.ConfigureAwait(false) - .GetAwaiter() - .OnCompleted(() => OnCompleted(task, distributedTask.Id)); - - distributedTask.Status = DistributedTaskStatus.Running; - - if (distributedTask.Publication == null) - distributedTask.Publication = GetPublication(); - - distributedTask.PublishChanges(); - - task.Start(Scheduler); - } - - public IEnumerable<DistributedTask> GetTasks() - { - var tasks = Cache.HashGetAll<DistributedTaskCache>(_name).Values.Select(r => new DistributedTask(r)).ToList(); - - tasks.ForEach(t => - { - if (t.Publication == null) t.Publication = GetPublication(); - }); - - return tasks; - } - - public IEnumerable<T> GetTasks<T>() where T : DistributedTask - { - var tasks = Cache.HashGetAll<DistributedTaskCache>(_name).Values.Select(r => - { - var result = ServiceProvider.GetService<T>(); - result.DistributedTaskCache = r; - - return result; - }).ToList(); - - tasks.ForEach(t => - { - if (t.Publication == null) t.Publication = GetPublication(); - }); - - return tasks; - } - - public T GetTask<T>(string id) where T : DistributedTask - { - var cache = Cache.HashGet<DistributedTaskCache>(_name, id); - if (cache != null) - { - using var scope = ServiceProvider.CreateScope(); - var task = scope.ServiceProvider.GetService<T>(); - task.DistributedTaskCache = cache; - - if (task != null && task.Publication == null) - task.Publication = GetPublication(); - - return task; - } - - return null; - } - - public DistributedTask GetTask(string id) - { - var cache = Cache.HashGet<DistributedTaskCache>(_name, id); - if (cache != null) - { - var task = new DistributedTask(); - task.DistributedTaskCache = cache; - - if (task != null && task.Publication == null) task.Publication = GetPublication(); - - return task; - } - - return null; - } - - public void SetTask(DistributedTask task) => DistributedTaskCacheNotify.SetTask(task); - - public void RemoveTask(string id) => DistributedTaskCacheNotify.RemoveTask(id, _name); - - public void CancelTask(string id) => DistributedTaskCacheNotify.CancelTask(id); - - private void OnCompleted(Task task, string id) - { - var distributedTask = GetTask(id); - if (distributedTask != null) - { - distributedTask.Status = DistributedTaskStatus.Completed; - distributedTask.Exception = task.Exception; - - if (task.IsFaulted) distributedTask.Status = DistributedTaskStatus.Failted; - - if (task.IsCanceled) distributedTask.Status = DistributedTaskStatus.Canceled; - - Cancelations.TryRemove(id, out _); - - distributedTask.PublishChanges(); - } - } - - private Action<DistributedTask> GetPublication() - { - return (t) => - { - if (t.DistributedTaskCache != null) t.DistributedTaskCache.Key = _name; - - DistributedTaskCacheNotify.SetTask(t); - }; - } + DistributedTaskCacheNotify = distributedTaskCacheNotify; + ServiceProvider = serviceProvider; } - public static class DistributedTaskQueueExtention - { - public static DIHelper AddDistributedTaskQueueService<T>(this DIHelper services, int maxThreadsCount) where T : DistributedTask + public void Configure(DistributedTaskQueue queue) + { + queue.DistributedTaskCacheNotify = DistributedTaskCacheNotify; + queue.ServiceProvider = ServiceProvider; + } + + public void Configure(string name, DistributedTaskQueue options) + { + Configure(options); + options.Name = name; + } +} + +public class DistributedTaskQueue +{ + public IServiceProvider ServiceProvider { get; set; } + public DistributedTaskCacheNotify DistributedTaskCacheNotify { get; set; } + public string Name + { + get => _name; + set => _name = value + GetType().Name; + } + public int MaxThreadsCount + { + set => Scheduler = value <= 0 + ? TaskScheduler.Default + : new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, value).ConcurrentScheduler; + } + + public static readonly int InstanceId; + + private TaskScheduler Scheduler { get; set; } = TaskScheduler.Default; + private ICache Cache => DistributedTaskCacheNotify.Cache; + private ConcurrentDictionary<string, CancellationTokenSource> Cancelations => + DistributedTaskCacheNotify.Cancelations; + + private string _name; + + static DistributedTaskQueue() => InstanceId = Process.GetCurrentProcess().Id; + + + public void QueueTask(DistributedTaskProgress taskProgress) => + QueueTask((a, b) => taskProgress.RunJob(), taskProgress); + + public void QueueTask(Action<DistributedTask, CancellationToken> action, DistributedTask distributedTask = null) + { + if (distributedTask == null) distributedTask = new DistributedTask(); + + distributedTask.InstanceId = InstanceId; + + var cancelation = new CancellationTokenSource(); + var token = cancelation.Token; + Cancelations[distributedTask.Id] = cancelation; + + var task = new Task(() => { action(distributedTask, token); }, token, TaskCreationOptions.LongRunning); + + task.ConfigureAwait(false) + .GetAwaiter() + .OnCompleted(() => OnCompleted(task, distributedTask.Id)); + + distributedTask.Status = DistributedTaskStatus.Running; + + if (distributedTask.Publication == null) + distributedTask.Publication = GetPublication(); + + distributedTask.PublishChanges(); + + task.Start(Scheduler); + } + + public IEnumerable<DistributedTask> GetTasks() + { + var tasks = Cache.HashGetAll<DistributedTaskCache>(_name).Values.Select(r => new DistributedTask(r)).ToList(); + + tasks.ForEach(t => { - services.TryAdd<DistributedTaskCacheNotify>(); - services.TryAdd<DistributedTaskQueueOptionsManager>(); - services.TryAdd<DistributedTaskQueue>(); + if (t.Publication == null) t.Publication = GetPublication(); + }); - var type = typeof(T); + return tasks; + } - if (!type.IsAbstract) services.TryAdd<T>(); + public IEnumerable<T> GetTasks<T>() where T : DistributedTask + { + var tasks = Cache.HashGetAll<DistributedTaskCache>(_name).Values.Select(r => + { + var result = ServiceProvider.GetService<T>(); + result.DistributedTaskCache = r; - services.TryAddSingleton<IConfigureOptions<DistributedTaskQueue>, ConfigureDistributedTaskQueue>(); + return result; + }).ToList(); - _ = services.Configure<DistributedTaskQueue>(type.Name, r => - { - r.MaxThreadsCount = maxThreadsCount; + tasks.ForEach(t => + { + if (t.Publication == null) t.Publication = GetPublication(); + }); + + return tasks; + } + + public T GetTask<T>(string id) where T : DistributedTask + { + var cache = Cache.HashGet<DistributedTaskCache>(_name, id); + if (cache != null) + { + using var scope = ServiceProvider.CreateScope(); + var task = scope.ServiceProvider.GetService<T>(); + task.DistributedTaskCache = cache; + + if (task != null && task.Publication == null) + task.Publication = GetPublication(); + + return task; + } + + return null; + } + + public DistributedTask GetTask(string id) + { + var cache = Cache.HashGet<DistributedTaskCache>(_name, id); + if (cache != null) + { + var task = new DistributedTask(); + task.DistributedTaskCache = cache; + + if (task != null && task.Publication == null) task.Publication = GetPublication(); + + return task; + } + + return null; + } + + public void SetTask(DistributedTask task) => DistributedTaskCacheNotify.SetTask(task); + + public void RemoveTask(string id) => DistributedTaskCacheNotify.RemoveTask(id, _name); + + public void CancelTask(string id) => DistributedTaskCacheNotify.CancelTask(id); + + private void OnCompleted(Task task, string id) + { + var distributedTask = GetTask(id); + if (distributedTask != null) + { + distributedTask.Status = DistributedTaskStatus.Completed; + distributedTask.Exception = task.Exception; + + if (task.IsFaulted) distributedTask.Status = DistributedTaskStatus.Failted; + + if (task.IsCanceled) distributedTask.Status = DistributedTaskStatus.Canceled; + + Cancelations.TryRemove(id, out _); + + distributedTask.PublishChanges(); + } + } + + private Action<DistributedTask> GetPublication() + { + return (t) => + { + if (t.DistributedTaskCache != null) t.DistributedTaskCache.Key = _name; + + DistributedTaskCacheNotify.SetTask(t); + }; + } +} + +public static class DistributedTaskQueueExtention +{ + public static DIHelper AddDistributedTaskQueueService<T>(this DIHelper services, int maxThreadsCount) where T : DistributedTask + { + services.TryAdd<DistributedTaskCacheNotify>(); + services.TryAdd<DistributedTaskQueueOptionsManager>(); + services.TryAdd<DistributedTaskQueue>(); + + var type = typeof(T); + + if (!type.IsAbstract) services.TryAdd<T>(); + + services.TryAddSingleton<IConfigureOptions<DistributedTaskQueue>, ConfigureDistributedTaskQueue>(); + + _ = services.Configure<DistributedTaskQueue>(type.Name, r => + { + r.MaxThreadsCount = maxThreadsCount; //r.errorCount = 1; }); - return services; - } + return services; } -} +} diff --git a/common/ASC.Common/Threading/DistributedTaskStatus.cs b/common/ASC.Common/Threading/DistributedTaskStatus.cs index 34e5d626e7..872ceac323 100644 --- a/common/ASC.Common/Threading/DistributedTaskStatus.cs +++ b/common/ASC.Common/Threading/DistributedTaskStatus.cs @@ -24,14 +24,13 @@ */ -namespace ASC.Common.Threading +namespace ASC.Common.Threading; + +public enum DistributedTaskStatus { - public enum DistributedTaskStatus - { - Created, - Running, - Completed, - Canceled, - Failted - } -} \ No newline at end of file + Created, + Running, + Completed, + Canceled, + Failted +} diff --git a/common/ASC.Common/Threading/Progress/IProgressItem.cs b/common/ASC.Common/Threading/Progress/IProgressItem.cs index 57c7ecd9fa..b9c77dfb0f 100644 --- a/common/ASC.Common/Threading/Progress/IProgressItem.cs +++ b/common/ASC.Common/Threading/Progress/IProgressItem.cs @@ -23,16 +23,15 @@ * */ -namespace ASC.Common.Threading.Progress -{ - public interface IProgressItem : ICloneable - { - string Id { get; } - DistributedTaskStatus Status { get; set; } - object Error { get; set; } - double Percentage { get; set; } - bool IsCompleted { get; set; } +namespace ASC.Common.Threading.Progress; - void RunJob(); - } -} \ No newline at end of file +public interface IProgressItem : ICloneable +{ + string Id { get; } + DistributedTaskStatus Status { get; set; } + object Error { get; set; } + double Percentage { get; set; } + bool IsCompleted { get; set; } + + void RunJob(); +} diff --git a/common/ASC.Common/Utils/ConfigurationManager.cs b/common/ASC.Common/Utils/ConfigurationManager.cs index d5c8caa0e2..1fdcf4e920 100644 --- a/common/ASC.Common/Utils/ConfigurationManager.cs +++ b/common/ASC.Common/Utils/ConfigurationManager.cs @@ -1,65 +1,64 @@ -namespace ASC.Common.Utils +namespace ASC.Common.Utils; + +public class ConnectionStringCollection : IEnumerable<ConnectionStringSettings> { - public class ConnectionStringCollection : IEnumerable<ConnectionStringSettings> + private List<ConnectionStringSettings> _data; + + public ConnectionStringSettings this[string name] => _data.FirstOrDefault(r => r.Name == name); + + public ConnectionStringCollection(IEnumerable<ConnectionStringSettings> data) => _data = data.ToList(); + + public IEnumerator<ConnectionStringSettings> GetEnumerator() => _data.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} + +[Singletone] +public class ConfigurationExtension +{ + public string this[string key] { - private List<ConnectionStringSettings> _data; - - public ConnectionStringSettings this[string name] => _data.FirstOrDefault(r => r.Name == name); - - public ConnectionStringCollection(IEnumerable<ConnectionStringSettings> data) => _data = data.ToList(); - - public IEnumerator<ConnectionStringSettings> GetEnumerator() => _data.GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + get => _configuration[key]; + set => _configuration[key] = value; } - [Singletone] - public class ConfigurationExtension + private readonly IConfiguration _configuration; + private readonly Lazy<ConnectionStringCollection> _connectionStringSettings; + + public ConfigurationExtension(IConfiguration configuration) { - public string this[string key] - { - get => _configuration[key]; - set => _configuration[key] = value; - } - - private readonly IConfiguration _configuration; - private readonly Lazy<ConnectionStringCollection> _connectionStringSettings; - - public ConfigurationExtension(IConfiguration configuration) - { - _configuration = configuration; - _connectionStringSettings = new Lazy<ConnectionStringCollection>(new ConnectionStringCollection(GetSettings<ConnectionStringSettings>("ConnectionStrings"))); - } - - public IEnumerable<T> GetSettings<T>(string section) where T : new() - { - var result = new List<T>(); - - var sectionSettings = _configuration.GetSection(section); - - foreach (var ch in sectionSettings.GetChildren()) - { - var cs = new T(); - ch.Bind(cs); - result.Add(cs); - } - - return result; - } - - public T GetSetting<T>(string section) where T : new() => GetSetting(section, new T()); - - public T GetSetting<T>(string section, T instance) - { - var sectionSettings = _configuration.GetSection(section); - - sectionSettings.Bind(instance); - - return instance; - } - - public ConnectionStringCollection GetConnectionStrings() => _connectionStringSettings.Value; - - public ConnectionStringSettings GetConnectionStrings(string key) => GetConnectionStrings()[key]; + _configuration = configuration; + _connectionStringSettings = new Lazy<ConnectionStringCollection>(new ConnectionStringCollection(GetSettings<ConnectionStringSettings>("ConnectionStrings"))); } -} \ No newline at end of file + + public IEnumerable<T> GetSettings<T>(string section) where T : new() + { + var result = new List<T>(); + + var sectionSettings = _configuration.GetSection(section); + + foreach (var ch in sectionSettings.GetChildren()) + { + var cs = new T(); + ch.Bind(cs); + result.Add(cs); + } + + return result; + } + + public T GetSetting<T>(string section) where T : new() => GetSetting(section, new T()); + + public T GetSetting<T>(string section, T instance) + { + var sectionSettings = _configuration.GetSection(section); + + sectionSettings.Bind(instance); + + return instance; + } + + public ConnectionStringCollection GetConnectionStrings() => _connectionStringSettings.Value; + + public ConnectionStringSettings GetConnectionStrings(string key) => GetConnectionStrings()[key]; +} diff --git a/common/ASC.Common/Utils/CrossPlatformUtils.cs b/common/ASC.Common/Utils/CrossPlatformUtils.cs index 807aef7d77..b26ac4ddfc 100644 --- a/common/ASC.Common/Utils/CrossPlatformUtils.cs +++ b/common/ASC.Common/Utils/CrossPlatformUtils.cs @@ -23,30 +23,29 @@ * */ -namespace ASC.Common.Utils +namespace ASC.Common.Utils; + +public static class CrossPlatform { - public static class CrossPlatform + private static char[] _pathSplitCharacters = new char[] { '/', '\\' }; + + public static string PathCombine(string basePath, params string[] additional) { - private static char[] _pathSplitCharacters = new char[] { '/', '\\' }; + var splits = additional.Select(s => s.Split(_pathSplitCharacters)).ToArray(); + var totalLength = splits.Sum(arr => arr.Length); + var segments = new string[totalLength + 1]; + segments[0] = basePath; + var i = 0; - public static string PathCombine(string basePath, params string[] additional) + foreach (var split in splits) { - var splits = additional.Select(s => s.Split(_pathSplitCharacters)).ToArray(); - var totalLength = splits.Sum(arr => arr.Length); - var segments = new string[totalLength + 1]; - segments[0] = basePath; - var i = 0; - - foreach (var split in splits) + foreach (var value in split) { - foreach (var value in split) - { - i++; - segments[i] = value; - } + i++; + segments[i] = value; } + } - return Path.Combine(segments); - } + return Path.Combine(segments); } -} \ No newline at end of file +} diff --git a/common/ASC.Common/Utils/DnsLookup.cs b/common/ASC.Common/Utils/DnsLookup.cs index e444ac9a46..d73f29c101 100644 --- a/common/ASC.Common/Utils/DnsLookup.cs +++ b/common/ASC.Common/Utils/DnsLookup.cs @@ -23,224 +23,223 @@ * */ -namespace ASC.Common.Utils -{ - public class DnsLookup - { - private readonly IDnsResolver _sDnsResolver; - private readonly DnsClient _dnsClient; - - public DnsLookup() - { - _dnsClient = DnsClient.Default; - _sDnsResolver = new DnsStubResolver(_dnsClient); - } - - /// <summary> - /// Get domain MX records - /// </summary> - /// <param name="domainName">domain name</param> - /// <exception cref="ArgumentNullException">if domainName is empty</exception> - /// <exception cref="ArgumentException">if domainName is invalid</exception> - /// <returns>list of MxRecord</returns> - public List<MxRecord> GetDomainMxRecords(string domainName) - { - if (string.IsNullOrEmpty(domainName)) - throw new ArgumentNullException(nameof(domainName)); - - var mxRecords = DnsResolve<MxRecord>(domainName, RecordType.Mx); - - return mxRecords; - } - - /// <summary> - /// Check existance of MX record in domain DNS - /// </summary> - /// <param name="domainName">domain name</param> - /// <param name="mxRecord">MX record value</param> - /// <exception cref="ArgumentNullException">if domainName is empty</exception> - /// <exception cref="ArgumentException">if domainName is invalid</exception> - /// <returns>true if exists and vice versa</returns> - public bool IsDomainMxRecordExists(string domainName, string mxRecord) - { - if (string.IsNullOrEmpty(domainName)) - throw new ArgumentNullException(nameof(domainName)); - - if (string.IsNullOrEmpty(mxRecord)) - throw new ArgumentNullException(nameof(mxRecord)); - - var mxDomain = DomainName.Parse(mxRecord); - - var records = GetDomainMxRecords(domainName); - - return records.Any( - mx => mx.ExchangeDomainName.Equals(mxDomain)); - } - - /// <summary> - /// Check domain existance - /// </summary> - /// <param name="domainName"></param> - /// <exception cref="ArgumentNullException">if domainName is empty</exception> - /// <exception cref="ArgumentException">if domainName is invalid</exception> - /// <exception cref="SystemException">if DNS request failed</exception> - /// <returns>true if any DNS record exists and vice versa</returns> - public bool IsDomainExists(string domainName) - { - if (string.IsNullOrEmpty(domainName)) - throw new ArgumentNullException(nameof(domainName)); - - var dnsMessage = GetDnsMessage(domainName); - - return dnsMessage.AnswerRecords.Any(); - } - - /// <summary> - /// Get domain A records - /// </summary> - /// <param name="domainName">domain name</param> - /// <exception cref="ArgumentNullException">if domainName is empty</exception> - /// <exception cref="ArgumentException">if domainName is invalid</exception> - /// <returns>list of ARecord</returns> - public List<ARecord> GetDomainARecords(string domainName) - { - if (string.IsNullOrEmpty(domainName)) - throw new ArgumentNullException(nameof(domainName)); - - var aRecords = DnsResolve<ARecord>(domainName, RecordType.A); - - return aRecords; - } - - /// <summary> - /// Get domain IP addresses list - /// </summary> - /// <param name="domainName">domain name</param> - /// <exception cref="ArgumentNullException">if domainName is empty</exception> - /// <exception cref="ArgumentException">if domainName is invalid</exception> - /// <returns>list of IPAddress</returns> - public List<IPAddress> GetDomainIPs(string domainName) - { - if (string.IsNullOrEmpty(domainName)) - throw new ArgumentNullException(nameof(domainName)); - - var addresses = _sDnsResolver.ResolveHost(domainName); - - return addresses; - } - - /// <summary> - /// Get domain TXT records - /// </summary> - /// <param name="domainName">domain name</param> - /// <exception cref="ArgumentNullException">if domainName is empty</exception> - /// <exception cref="ArgumentException">if domainName is invalid</exception> - /// <returns>list of TxtRecord</returns> - public List<TxtRecord> GetDomainTxtRecords(string domainName) - { - if (string.IsNullOrEmpty(domainName)) - throw new ArgumentNullException(nameof(domainName)); - - var txtRecords = DnsResolve<TxtRecord>(domainName, RecordType.Txt); - - return txtRecords; - } - - /// <summary> - /// Check existance of TXT record in domain DNS - /// </summary> - /// <param name="domainName">domain name</param> - /// <param name="recordValue">TXT record value</param> - /// <exception cref="ArgumentNullException">if domainName is empty</exception> - /// <exception cref="ArgumentException">if domainName is invalid</exception> - /// <returns>true if exists and vice versa</returns> - public bool IsDomainTxtRecordExists(string domainName, string recordValue) - { - var txtRecords = GetDomainTxtRecords(domainName); - - return - txtRecords.Any( - txtRecord => - txtRecord.TextData.Trim('\"').Equals(recordValue, StringComparison.InvariantCultureIgnoreCase)); - } - - /// <summary> - /// Check existance of DKIM record in domain DNS - /// </summary> - /// <param name="domainName">domain name</param> - /// <param name="dkimSelector">DKIM selector (example is "dkim")</param> - /// <param name="dkimValue">DKIM record value</param> - /// <exception cref="ArgumentNullException">if domainName is empty</exception> - /// <exception cref="ArgumentException">if domainName is invalid</exception> - /// <returns>true if exists and vice versa</returns> - public bool IsDomainDkimRecordExists(string domainName, string dkimSelector, string dkimValue) - { - var dkimRecordName = dkimSelector + "._domainkey." + domainName; - - var txtRecords = GetDomainTxtRecords(dkimRecordName); - - return txtRecords.Any(txtRecord => txtRecord.TextData.Trim('\"').Equals(dkimValue)); - } - - /// <summary> - /// Check existance Domain in PTR record - /// </summary> - /// <param name="ipAddress">IP address for PTR check</param> - /// <param name="domainName">PTR domain name</param> - /// <exception cref="ArgumentNullException">if domainName or ipAddress is empty/null</exception> - /// <exception cref="ArgumentException">if domainName is invalid</exception> - /// <returns>true if exists and vice versa</returns> - public bool IsDomainPtrRecordExists(IPAddress ipAddress, string domainName) - { - if (string.IsNullOrEmpty(domainName)) - throw new ArgumentNullException(nameof(domainName)); - - if (ipAddress == null) - throw new ArgumentNullException(nameof(ipAddress)); - - var domain = DomainName.Parse(domainName); - - var ptrDomain = _sDnsResolver.ResolvePtr(ipAddress); - - return ptrDomain.Equals(domain); - } - - /// <summary> - /// Check existance Domain in PTR record - /// </summary> - /// <param name="ipAddress">IP address for PTR check</param> - /// <param name="domainName">PTR domain name</param> - /// <exception cref="ArgumentNullException">if domainName or ipAddress is empty/null</exception> - /// <exception cref="ArgumentException">if domainName is invalid</exception> - /// <exception cref="FormatException">if ipAddress is invalid</exception> - /// <returns>true if exists and vice versa</returns> - public bool IsDomainPtrRecordExists(string ipAddress, string domainName) => - IsDomainPtrRecordExists(IPAddress.Parse(ipAddress), domainName); - - private DnsMessage GetDnsMessage(string domainName, RecordType? type = null) - { - if (string.IsNullOrEmpty(domainName)) - throw new ArgumentNullException(nameof(domainName)); - - var domain = DomainName.Parse(domainName); - - var dnsMessage = type.HasValue ? _dnsClient.Resolve(domain, type.Value) : _dnsClient.Resolve(domain); - - if ((dnsMessage == null) || - ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain))) - throw new SystemException(); // DNS request failed - - return dnsMessage; - } - - private List<T> DnsResolve<T>(string domainName, RecordType type) - { - if (string.IsNullOrEmpty(domainName)) - throw new ArgumentNullException(nameof(domainName)); - - var dnsMessage = GetDnsMessage(domainName, type); - - return dnsMessage.AnswerRecords.Where(r => r.RecordType == type).Cast<T>().ToList(); - } - } -} \ No newline at end of file +namespace ASC.Common.Utils; + +public class DnsLookup +{ + private readonly IDnsResolver _sDnsResolver; + private readonly DnsClient _dnsClient; + + public DnsLookup() + { + _dnsClient = DnsClient.Default; + _sDnsResolver = new DnsStubResolver(_dnsClient); + } + + /// <summary> + /// Get domain MX records + /// </summary> + /// <param name="domainName">domain name</param> + /// <exception cref="ArgumentNullException">if domainName is empty</exception> + /// <exception cref="ArgumentException">if domainName is invalid</exception> + /// <returns>list of MxRecord</returns> + public List<MxRecord> GetDomainMxRecords(string domainName) + { + if (string.IsNullOrEmpty(domainName)) + throw new ArgumentNullException(nameof(domainName)); + + var mxRecords = DnsResolve<MxRecord>(domainName, RecordType.Mx); + + return mxRecords; + } + + /// <summary> + /// Check existance of MX record in domain DNS + /// </summary> + /// <param name="domainName">domain name</param> + /// <param name="mxRecord">MX record value</param> + /// <exception cref="ArgumentNullException">if domainName is empty</exception> + /// <exception cref="ArgumentException">if domainName is invalid</exception> + /// <returns>true if exists and vice versa</returns> + public bool IsDomainMxRecordExists(string domainName, string mxRecord) + { + if (string.IsNullOrEmpty(domainName)) + throw new ArgumentNullException(nameof(domainName)); + + if (string.IsNullOrEmpty(mxRecord)) + throw new ArgumentNullException(nameof(mxRecord)); + + var mxDomain = DomainName.Parse(mxRecord); + + var records = GetDomainMxRecords(domainName); + + return records.Any( + mx => mx.ExchangeDomainName.Equals(mxDomain)); + } + + /// <summary> + /// Check domain existance + /// </summary> + /// <param name="domainName"></param> + /// <exception cref="ArgumentNullException">if domainName is empty</exception> + /// <exception cref="ArgumentException">if domainName is invalid</exception> + /// <exception cref="SystemException">if DNS request failed</exception> + /// <returns>true if any DNS record exists and vice versa</returns> + public bool IsDomainExists(string domainName) + { + if (string.IsNullOrEmpty(domainName)) + throw new ArgumentNullException(nameof(domainName)); + + var dnsMessage = GetDnsMessage(domainName); + + return dnsMessage.AnswerRecords.Any(); + } + + /// <summary> + /// Get domain A records + /// </summary> + /// <param name="domainName">domain name</param> + /// <exception cref="ArgumentNullException">if domainName is empty</exception> + /// <exception cref="ArgumentException">if domainName is invalid</exception> + /// <returns>list of ARecord</returns> + public List<ARecord> GetDomainARecords(string domainName) + { + if (string.IsNullOrEmpty(domainName)) + throw new ArgumentNullException(nameof(domainName)); + + var aRecords = DnsResolve<ARecord>(domainName, RecordType.A); + + return aRecords; + } + + /// <summary> + /// Get domain IP addresses list + /// </summary> + /// <param name="domainName">domain name</param> + /// <exception cref="ArgumentNullException">if domainName is empty</exception> + /// <exception cref="ArgumentException">if domainName is invalid</exception> + /// <returns>list of IPAddress</returns> + public List<IPAddress> GetDomainIPs(string domainName) + { + if (string.IsNullOrEmpty(domainName)) + throw new ArgumentNullException(nameof(domainName)); + + var addresses = _sDnsResolver.ResolveHost(domainName); + + return addresses; + } + + /// <summary> + /// Get domain TXT records + /// </summary> + /// <param name="domainName">domain name</param> + /// <exception cref="ArgumentNullException">if domainName is empty</exception> + /// <exception cref="ArgumentException">if domainName is invalid</exception> + /// <returns>list of TxtRecord</returns> + public List<TxtRecord> GetDomainTxtRecords(string domainName) + { + if (string.IsNullOrEmpty(domainName)) + throw new ArgumentNullException(nameof(domainName)); + + var txtRecords = DnsResolve<TxtRecord>(domainName, RecordType.Txt); + + return txtRecords; + } + + /// <summary> + /// Check existance of TXT record in domain DNS + /// </summary> + /// <param name="domainName">domain name</param> + /// <param name="recordValue">TXT record value</param> + /// <exception cref="ArgumentNullException">if domainName is empty</exception> + /// <exception cref="ArgumentException">if domainName is invalid</exception> + /// <returns>true if exists and vice versa</returns> + public bool IsDomainTxtRecordExists(string domainName, string recordValue) + { + var txtRecords = GetDomainTxtRecords(domainName); + + return + txtRecords.Any( + txtRecord => + txtRecord.TextData.Trim('\"').Equals(recordValue, StringComparison.InvariantCultureIgnoreCase)); + } + + /// <summary> + /// Check existance of DKIM record in domain DNS + /// </summary> + /// <param name="domainName">domain name</param> + /// <param name="dkimSelector">DKIM selector (example is "dkim")</param> + /// <param name="dkimValue">DKIM record value</param> + /// <exception cref="ArgumentNullException">if domainName is empty</exception> + /// <exception cref="ArgumentException">if domainName is invalid</exception> + /// <returns>true if exists and vice versa</returns> + public bool IsDomainDkimRecordExists(string domainName, string dkimSelector, string dkimValue) + { + var dkimRecordName = dkimSelector + "._domainkey." + domainName; + + var txtRecords = GetDomainTxtRecords(dkimRecordName); + + return txtRecords.Any(txtRecord => txtRecord.TextData.Trim('\"').Equals(dkimValue)); + } + + /// <summary> + /// Check existance Domain in PTR record + /// </summary> + /// <param name="ipAddress">IP address for PTR check</param> + /// <param name="domainName">PTR domain name</param> + /// <exception cref="ArgumentNullException">if domainName or ipAddress is empty/null</exception> + /// <exception cref="ArgumentException">if domainName is invalid</exception> + /// <returns>true if exists and vice versa</returns> + public bool IsDomainPtrRecordExists(IPAddress ipAddress, string domainName) + { + if (string.IsNullOrEmpty(domainName)) + throw new ArgumentNullException(nameof(domainName)); + + if (ipAddress == null) + throw new ArgumentNullException(nameof(ipAddress)); + + var domain = DomainName.Parse(domainName); + + var ptrDomain = _sDnsResolver.ResolvePtr(ipAddress); + + return ptrDomain.Equals(domain); + } + + /// <summary> + /// Check existance Domain in PTR record + /// </summary> + /// <param name="ipAddress">IP address for PTR check</param> + /// <param name="domainName">PTR domain name</param> + /// <exception cref="ArgumentNullException">if domainName or ipAddress is empty/null</exception> + /// <exception cref="ArgumentException">if domainName is invalid</exception> + /// <exception cref="FormatException">if ipAddress is invalid</exception> + /// <returns>true if exists and vice versa</returns> + public bool IsDomainPtrRecordExists(string ipAddress, string domainName) => + IsDomainPtrRecordExists(IPAddress.Parse(ipAddress), domainName); + + private DnsMessage GetDnsMessage(string domainName, RecordType? type = null) + { + if (string.IsNullOrEmpty(domainName)) + throw new ArgumentNullException(nameof(domainName)); + + var domain = DomainName.Parse(domainName); + + var dnsMessage = type.HasValue ? _dnsClient.Resolve(domain, type.Value) : _dnsClient.Resolve(domain); + + if ((dnsMessage == null) || + ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain))) + throw new SystemException(); // DNS request failed + + return dnsMessage; + } + + private List<T> DnsResolve<T>(string domainName, RecordType type) + { + if (string.IsNullOrEmpty(domainName)) + throw new ArgumentNullException(nameof(domainName)); + + var dnsMessage = GetDnsMessage(domainName, type); + + return dnsMessage.AnswerRecords.Where(r => r.RecordType == type).Cast<T>().ToList(); + } +} diff --git a/common/ASC.Common/Utils/HtmlUtil.cs b/common/ASC.Common/Utils/HtmlUtil.cs index b26d82c8cf..2d4bb297e0 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -23,84 +23,83 @@ * */ -namespace ASC.Common.Utils +namespace ASC.Common.Utils; + +public static class HtmlUtil { - public static class HtmlUtil + private static readonly Regex _tagReplacer + = new Regex("<[^>]*>", RegexOptions.Multiline | RegexOptions.Compiled); + + private static readonly Regex _commentsReplacer + = new Regex("<!--(?s).*?-->", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); + + private static readonly Regex _xssReplacer + = new Regex(@"<\s*(style|script)[^>]*>(.*?)<\s*/\s*(style|script)>", RegexOptions.IgnoreCase + | RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Singleline); + + private static readonly Regex _worder = + new Regex(@"\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + + public static string GetText(string html, int maxLength = 0, string endBlockTemplate = "...") { - private static readonly Regex _tagReplacer - = new Regex("<[^>]*>", RegexOptions.Multiline | RegexOptions.Compiled); + var unformatedText = string.Empty; - private static readonly Regex _commentsReplacer - = new Regex("<!--(?s).*?-->", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - - private static readonly Regex _xssReplacer - = new Regex(@"<\s*(style|script)[^>]*>(.*?)<\s*/\s*(style|script)>", RegexOptions.IgnoreCase - | RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Singleline); - - private static readonly Regex _worder = - new Regex(@"\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - - - public static string GetText(string html, int maxLength = 0, string endBlockTemplate = "...") + if (!string.IsNullOrEmpty(html)) { - var unformatedText = string.Empty; + html = _xssReplacer.Replace(html, string.Empty); //Clean malicious tags. <script> <style> - if (!string.IsNullOrEmpty(html)) + if (string.IsNullOrEmpty(html)) return html; + + unformatedText = _tagReplacer.Replace(html, string.Empty); + + if (!string.IsNullOrEmpty(unformatedText)) { - html = _xssReplacer.Replace(html, string.Empty); //Clean malicious tags. <script> <style> - - if (string.IsNullOrEmpty(html)) return html; - - unformatedText = _tagReplacer.Replace(html, string.Empty); + // kill comments + unformatedText = _commentsReplacer.Replace(unformatedText, string.Empty); + unformatedText = unformatedText.Trim(); if (!string.IsNullOrEmpty(unformatedText)) { - // kill comments - unformatedText = _commentsReplacer.Replace(unformatedText, string.Empty); - unformatedText = unformatedText.Trim(); + if (maxLength == 0 || unformatedText.Length < maxLength) + return HttpUtility.HtmlDecode(unformatedText); - if (!string.IsNullOrEmpty(unformatedText)) - { - if (maxLength == 0 || unformatedText.Length < maxLength) - return HttpUtility.HtmlDecode(unformatedText); + //Set maximum length with end block + maxLength = Math.Max(0, maxLength - endBlockTemplate.Length); + var startIndex = Math.Max(0, Math.Min(unformatedText.Length - 1, maxLength)); + var countToScan = Math.Max(0, startIndex - 1); - //Set maximum length with end block - maxLength = Math.Max(0, maxLength - endBlockTemplate.Length); - var startIndex = Math.Max(0, Math.Min(unformatedText.Length - 1, maxLength)); - var countToScan = Math.Max(0, startIndex - 1); + var lastSpaceIndex = unformatedText.LastIndexOf(' ', startIndex, countToScan); - var lastSpaceIndex = unformatedText.LastIndexOf(' ', startIndex, countToScan); + unformatedText = lastSpaceIndex > 0 && lastSpaceIndex < unformatedText.Length + ? unformatedText.Remove(lastSpaceIndex) + : unformatedText.Substring(0, maxLength); - unformatedText = lastSpaceIndex > 0 && lastSpaceIndex < unformatedText.Length - ? unformatedText.Remove(lastSpaceIndex) - : unformatedText.Substring(0, maxLength); - - if (!string.IsNullOrEmpty(endBlockTemplate)) - unformatedText += endBlockTemplate; - } + if (!string.IsNullOrEmpty(endBlockTemplate)) + unformatedText += endBlockTemplate; } } - - return HttpUtility.HtmlDecode(unformatedText);//TODO:!!! } - public static string ToPlainText(string html) => GetText(html); - - /// <summary> - /// The function highlight all words in htmlText by searchText. - /// </summary> - /// <param name="searchText">the space separated string</param> - /// <param name="htmlText">html for highlight</param> - /// <param name="withoutLink"></param> - /// <returns>highlighted html</returns> - public static string SearchTextHighlight(string searchText, string htmlText, bool withoutLink = false) - { - if (string.IsNullOrEmpty(searchText) || string.IsNullOrEmpty(htmlText)) return htmlText; - - var regexpstr = _worder.Matches(searchText).Cast<Match>().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); - var wordsFinder = new Regex(Regex.Escape(regexpstr), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline); - - return wordsFinder.Replace(htmlText, m => string.Format("<span class='searchTextHighlight{1}'>{0}</span>", m.Value, withoutLink ? " bold" : string.Empty)); - } + return HttpUtility.HtmlDecode(unformatedText);//TODO:!!! } -} \ No newline at end of file + + public static string ToPlainText(string html) => GetText(html); + + /// <summary> + /// The function highlight all words in htmlText by searchText. + /// </summary> + /// <param name="searchText">the space separated string</param> + /// <param name="htmlText">html for highlight</param> + /// <param name="withoutLink"></param> + /// <returns>highlighted html</returns> + public static string SearchTextHighlight(string searchText, string htmlText, bool withoutLink = false) + { + if (string.IsNullOrEmpty(searchText) || string.IsNullOrEmpty(htmlText)) return htmlText; + + var regexpstr = _worder.Matches(searchText).Cast<Match>().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); + var wordsFinder = new Regex(Regex.Escape(regexpstr), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline); + + return wordsFinder.Replace(htmlText, m => string.Format("<span class='searchTextHighlight{1}'>{0}</span>", m.Value, withoutLink ? " bold" : string.Empty)); + } +} diff --git a/common/ASC.Common/Utils/HttpRequestExtensions.cs b/common/ASC.Common/Utils/HttpRequestExtensions.cs index 24135aeff6..b343be9753 100644 --- a/common/ASC.Common/Utils/HttpRequestExtensions.cs +++ b/common/ASC.Common/Utils/HttpRequestExtensions.cs @@ -26,168 +26,167 @@ using HttpContext = Microsoft.AspNetCore.Http.HttpContext; -namespace System.Web -{ - public static class HttpRequestExtensions - { - public static readonly string UrlRewriterHeader = "X-REWRITER-URL"; - - public static Uri GetUrlRewriter(this HttpRequest request) => - request != null ? GetUrlRewriter(request.Headers, request) : null; - - public static Uri Url(this HttpRequest request) => - request != null ? new Uri(request.GetDisplayUrl()) : null; - - /*public static Uri GetUrlRewriter(this HttpRequestBase request) - { - return request != null ? GetUrlRewriter(request.Headers, request.Url) : null; - }*/ - - public static Uri GetUrlRewriter(IHeaderDictionary headers, HttpRequest request) - { - if (headers != null) - { - var h = headers[UrlRewriterHeader]; - var rewriterUri = !string.IsNullOrEmpty(h) ? ParseRewriterUrl(h) : null; - - if (request != null && rewriterUri != null) - { - var result = new UriBuilder() - { - Scheme = rewriterUri.Scheme, - Host = rewriterUri.Host, - Port = rewriterUri.Port - }; +namespace System.Web; - result.Query = request.QueryString.Value; - result.Path = request.Path.Value; - - return result.Uri; - } - } +public static class HttpRequestExtensions +{ + public static readonly string UrlRewriterHeader = "X-REWRITER-URL"; - if (request != null && request.Query != null) - { - var h = request.Query[UrlRewriterHeader]; - var rewriterUri = !string.IsNullOrEmpty(h) ? ParseRewriterUrl(h) : null; - if (rewriterUri != null) - { - var result = new UriBuilder() - { - Scheme = rewriterUri.Scheme, - Host = rewriterUri.Host, - Port = rewriterUri.Port - }; - result.Query = request.QueryString.Value; - result.Path = request.Path.Value; - - return result.Uri; - } - } - - return request.Url(); - } - - public static Uri PushRewritenUri(this HttpContext context) => - context != null ? PushRewritenUri(context, GetUrlRewriter(context.Request)) : null; - - public static Uri PushRewritenUri(this HttpContext context, Uri rewrittenUri) - { - Uri oldUri = null; - - if (context != null) - { - var request = context.Request; - - var url = new Uri(request.GetDisplayUrl()); - - if (url != rewrittenUri) - { - var requestUri = url; - try - { - //Push it - request.Headers.SetCommaSeparatedValues("HTTPS", rewrittenUri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) ? "on" : "off"); - request.Headers.SetCommaSeparatedValues("SERVER_NAME", rewrittenUri.Host); - request.Headers.SetCommaSeparatedValues("SERVER_PORT", - rewrittenUri.Port.ToString(CultureInfo.InvariantCulture)); - - if (rewrittenUri.IsDefaultPort) - request.Headers.SetCommaSeparatedValues("HTTP_HOST", - rewrittenUri.Host); - - else request.Headers.SetCommaSeparatedValues("HTTP_HOST", - rewrittenUri.Host + ":" + requestUri.Port); - //Hack: - typeof(HttpRequest).InvokeMember("_url", - BindingFlags.NonPublic | BindingFlags.SetField | - BindingFlags.Instance, - null, request, - new object[] { null }); - oldUri = requestUri; - context.Items["oldUri"] = oldUri; - - } - catch (Exception) { } - } - } - - return oldUri; - } - - public static Uri PopRewritenUri(this HttpContext context) - { - if (context != null && context.Items["oldUri"] != null) - { - var rewriteTo = context.Items["oldUri"] as Uri; - - if (rewriteTo != null) return PushRewritenUri(context, rewriteTo); - } - - return null; - } - - public static bool DesktopApp(this HttpRequest request) + public static Uri GetUrlRewriter(this HttpRequest request) => + request != null ? GetUrlRewriter(request.Headers, request) : null; + + public static Uri Url(this HttpRequest request) => + request != null ? new Uri(request.GetDisplayUrl()) : null; + + /*public static Uri GetUrlRewriter(this HttpRequestBase request) + { + return request != null ? GetUrlRewriter(request.Headers, request.Url) : null; + }*/ + + public static Uri GetUrlRewriter(IHeaderDictionary headers, HttpRequest request) + { + if (headers != null) { - return request != null - && (!string.IsNullOrEmpty(request.Query["desktop"]) - || !string.IsNullOrEmpty(request.Headers[HeaderNames.UserAgent]) && request.Headers[HeaderNames.UserAgent].ToString().Contains("AscDesktopEditor")); - } - - public static bool SailfishApp(this HttpRequest request) - { - return request != null - && (!string.IsNullOrEmpty(request.Headers["sailfish"]) - || !string.IsNullOrEmpty(request.Headers[HeaderNames.UserAgent]) && request.Headers[HeaderNames.UserAgent].ToString().Contains("SailfishOS")); - } + var h = headers[UrlRewriterHeader]; + var rewriterUri = !string.IsNullOrEmpty(h) ? ParseRewriterUrl(h) : null; - public static string GetUserHostAddress(this HttpRequest request) => - request.HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString(); - - private static Uri ParseRewriterUrl(string s) - { - if (string.IsNullOrEmpty(s)) return null; - - const StringComparison cmp = StringComparison.OrdinalIgnoreCase; - - if (0 < s.Length && (s.StartsWith("0", cmp))) - s = Uri.UriSchemeHttp + s.Substring(1); - - else if (3 < s.Length && s.StartsWith("OFF", cmp)) - s = Uri.UriSchemeHttp + s.Substring(3); - - else if (0 < s.Length && (s.StartsWith("1", cmp))) - s = Uri.UriSchemeHttps + s.Substring(1); - - else if (2 < s.Length && s.StartsWith("ON", cmp)) - s = Uri.UriSchemeHttps + s.Substring(2); - - else if (s.StartsWith(Uri.UriSchemeHttp + "%3A%2F%2F", cmp) || s.StartsWith(Uri.UriSchemeHttps + "%3A%2F%2F", cmp)) - s = HttpUtility.UrlDecode(s); - - Uri.TryCreate(s, UriKind.Absolute, out var result); - - return result; - } - } -} \ No newline at end of file + if (request != null && rewriterUri != null) + { + var result = new UriBuilder() + { + Scheme = rewriterUri.Scheme, + Host = rewriterUri.Host, + Port = rewriterUri.Port + }; + + result.Query = request.QueryString.Value; + result.Path = request.Path.Value; + + return result.Uri; + } + } + + if (request != null && request.Query != null) + { + var h = request.Query[UrlRewriterHeader]; + var rewriterUri = !string.IsNullOrEmpty(h) ? ParseRewriterUrl(h) : null; + if (rewriterUri != null) + { + var result = new UriBuilder() + { + Scheme = rewriterUri.Scheme, + Host = rewriterUri.Host, + Port = rewriterUri.Port + }; + result.Query = request.QueryString.Value; + result.Path = request.Path.Value; + + return result.Uri; + } + } + + return request.Url(); + } + + public static Uri PushRewritenUri(this HttpContext context) => + context != null ? PushRewritenUri(context, GetUrlRewriter(context.Request)) : null; + + public static Uri PushRewritenUri(this HttpContext context, Uri rewrittenUri) + { + Uri oldUri = null; + + if (context != null) + { + var request = context.Request; + + var url = new Uri(request.GetDisplayUrl()); + + if (url != rewrittenUri) + { + var requestUri = url; + try + { + //Push it + request.Headers.SetCommaSeparatedValues("HTTPS", rewrittenUri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) ? "on" : "off"); + request.Headers.SetCommaSeparatedValues("SERVER_NAME", rewrittenUri.Host); + request.Headers.SetCommaSeparatedValues("SERVER_PORT", + rewrittenUri.Port.ToString(CultureInfo.InvariantCulture)); + + if (rewrittenUri.IsDefaultPort) + request.Headers.SetCommaSeparatedValues("HTTP_HOST", + rewrittenUri.Host); + + else request.Headers.SetCommaSeparatedValues("HTTP_HOST", + rewrittenUri.Host + ":" + requestUri.Port); + //Hack: + typeof(HttpRequest).InvokeMember("_url", + BindingFlags.NonPublic | BindingFlags.SetField | + BindingFlags.Instance, + null, request, + new object[] { null }); + oldUri = requestUri; + context.Items["oldUri"] = oldUri; + + } + catch (Exception) { } + } + } + + return oldUri; + } + + public static Uri PopRewritenUri(this HttpContext context) + { + if (context != null && context.Items["oldUri"] != null) + { + var rewriteTo = context.Items["oldUri"] as Uri; + + if (rewriteTo != null) return PushRewritenUri(context, rewriteTo); + } + + return null; + } + + public static bool DesktopApp(this HttpRequest request) + { + return request != null + && (!string.IsNullOrEmpty(request.Query["desktop"]) + || !string.IsNullOrEmpty(request.Headers[HeaderNames.UserAgent]) && request.Headers[HeaderNames.UserAgent].ToString().Contains("AscDesktopEditor")); + } + + public static bool SailfishApp(this HttpRequest request) + { + return request != null + && (!string.IsNullOrEmpty(request.Headers["sailfish"]) + || !string.IsNullOrEmpty(request.Headers[HeaderNames.UserAgent]) && request.Headers[HeaderNames.UserAgent].ToString().Contains("SailfishOS")); + } + + public static string GetUserHostAddress(this HttpRequest request) => + request.HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString(); + + private static Uri ParseRewriterUrl(string s) + { + if (string.IsNullOrEmpty(s)) return null; + + const StringComparison cmp = StringComparison.OrdinalIgnoreCase; + + if (0 < s.Length && (s.StartsWith("0", cmp))) + s = Uri.UriSchemeHttp + s.Substring(1); + + else if (3 < s.Length && s.StartsWith("OFF", cmp)) + s = Uri.UriSchemeHttp + s.Substring(3); + + else if (0 < s.Length && (s.StartsWith("1", cmp))) + s = Uri.UriSchemeHttps + s.Substring(1); + + else if (2 < s.Length && s.StartsWith("ON", cmp)) + s = Uri.UriSchemeHttps + s.Substring(2); + + else if (s.StartsWith(Uri.UriSchemeHttp + "%3A%2F%2F", cmp) || s.StartsWith(Uri.UriSchemeHttps + "%3A%2F%2F", cmp)) + s = HttpUtility.UrlDecode(s); + + Uri.TryCreate(s, UriKind.Absolute, out var result); + + return result; + } +} diff --git a/common/ASC.Common/Utils/JsonWebToken.cs b/common/ASC.Common/Utils/JsonWebToken.cs index 44d312b0c8..5d67de1e47 100644 --- a/common/ASC.Common/Utils/JsonWebToken.cs +++ b/common/ASC.Common/Utils/JsonWebToken.cs @@ -27,70 +27,69 @@ using Formatting = Newtonsoft.Json.Formatting; using IJsonSerializer = JWT.IJsonSerializer; -namespace ASC.Web.Core.Files +namespace ASC.Web.Core.Files; + +public class JsonWebToken { - public class JsonWebToken + public static string Encode(object payload, string key) { - public static string Encode(object payload, string key) + var (serializer, algorithm, urlEncoder) = GetSettings(); + var encoder = new JwtEncoder(algorithm, serializer, urlEncoder); + + return encoder.Encode(payload, key); + } + + public static string Decode(string token, string key, bool verify = true, bool baseSerializer = false) + { + var (serializer, algorithm, urlEncoder) = GetSettings(baseSerializer); + + var provider = new UtcDateTimeProvider(); + IJwtValidator validator = new JwtValidator(serializer, provider); + + var decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); + + return decoder.Decode(token, key, verify); + } + + private static (IJsonSerializer, IJwtAlgorithm, IBase64UrlEncoder) GetSettings(bool baseSerializer = false) + { + return (baseSerializer ? (IJsonSerializer)new JsonNetSerializer() : new JwtSerializer(), new HMACSHA256Algorithm(), new JwtBase64UrlEncoder()); + } +} + +public class JwtSerializer : IJsonSerializer +{ + private class CamelCaseExceptDictionaryKeysResolver : CamelCasePropertyNamesContractResolver + { + protected override JsonDictionaryContract CreateDictionaryContract(Type objectType) { - var (serializer, algorithm, urlEncoder) = GetSettings(); - var encoder = new JwtEncoder(algorithm, serializer, urlEncoder); + var contract = base.CreateDictionaryContract(objectType); - return encoder.Encode(payload, key); - } + contract.DictionaryKeyResolver = propertyName => propertyName; - public static string Decode(string token, string key, bool verify = true, bool baseSerializer = false) - { - var (serializer, algorithm, urlEncoder) = GetSettings(baseSerializer); - - var provider = new UtcDateTimeProvider(); - IJwtValidator validator = new JwtValidator(serializer, provider); - - var decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); - - return decoder.Decode(token, key, verify); - } - - private static (IJsonSerializer, IJwtAlgorithm, IBase64UrlEncoder) GetSettings(bool baseSerializer = false) - { - return (baseSerializer ? (IJsonSerializer)new JsonNetSerializer() : new JwtSerializer(), new HMACSHA256Algorithm(), new JwtBase64UrlEncoder()); + return contract; } } - public class JwtSerializer : IJsonSerializer + public string Serialize(object obj) { - private class CamelCaseExceptDictionaryKeysResolver : CamelCasePropertyNamesContractResolver + var settings = new JsonSerializerSettings { - protected override JsonDictionaryContract CreateDictionaryContract(Type objectType) - { - var contract = base.CreateDictionaryContract(objectType); + ContractResolver = new CamelCaseExceptDictionaryKeysResolver(), + NullValueHandling = NullValueHandling.Ignore, + }; - contract.DictionaryKeyResolver = propertyName => propertyName; - - return contract; - } - } - - public string Serialize(object obj) - { - var settings = new JsonSerializerSettings - { - ContractResolver = new CamelCaseExceptDictionaryKeysResolver(), - NullValueHandling = NullValueHandling.Ignore, - }; - - return JsonConvert.SerializeObject(obj, Formatting.Indented, settings); - } - - public T Deserialize<T>(string json) - { - var settings = new JsonSerializerSettings - { - ContractResolver = new CamelCaseExceptDictionaryKeysResolver(), - NullValueHandling = NullValueHandling.Ignore, - }; - - return JsonConvert.DeserializeObject<T>(json, settings); - } + return JsonConvert.SerializeObject(obj, Formatting.Indented, settings); } -} \ No newline at end of file + + public T Deserialize<T>(string json) + { + var settings = new JsonSerializerSettings + { + ContractResolver = new CamelCaseExceptDictionaryKeysResolver(), + NullValueHandling = NullValueHandling.Ignore, + }; + + return JsonConvert.DeserializeObject<T>(json, settings); + } +} diff --git a/common/ASC.Common/Utils/MailAddressUtils.cs b/common/ASC.Common/Utils/MailAddressUtils.cs index d8ae27b86f..cedd9926dc 100644 --- a/common/ASC.Common/Utils/MailAddressUtils.cs +++ b/common/ASC.Common/Utils/MailAddressUtils.cs @@ -23,40 +23,39 @@ * */ -namespace ASC.Common.Utils +namespace ASC.Common.Utils; + +public static class MailAddressUtils { - public static class MailAddressUtils + public static MailAddress Create(string address) { - public static MailAddress Create(string address) + if (!string.IsNullOrEmpty(address)) { - if (!string.IsNullOrEmpty(address)) - { - var firstPos = address.IndexOf('"'); - var lastPos = address.LastIndexOf('"'); + var firstPos = address.IndexOf('"'); + var lastPos = address.LastIndexOf('"'); - if (firstPos != -1 && firstPos < lastPos && address.IndexOf('"', firstPos + 1, lastPos - firstPos - 1) != -1) - address = new StringBuilder(address).Replace("\"", string.Empty, firstPos + 1, lastPos - firstPos - 1).ToString(); - } - - return new MailAddress(address); + if (firstPos != -1 && firstPos < lastPos && address.IndexOf('"', firstPos + 1, lastPos - firstPos - 1) != -1) + address = new StringBuilder(address).Replace("\"", string.Empty, firstPos + 1, lastPos - firstPos - 1).ToString(); } - public static MailAddress Create(string address, string displayName) - { - if (!string.IsNullOrEmpty(displayName)) - { - displayName = displayName.Replace("\"", string.Empty); - - if (125 < displayName.Length) - displayName = displayName.Substring(0, 125); - } - - return Create(ToSmtpAddress(address, displayName)); - } - - public static string ToEncodedString(this MailAddress m) => - ToSmtpAddress(m.Address, MimeHeaderUtils.EncodeMime(m.DisplayName)); - - private static string ToSmtpAddress(string address, string displayName) => $"\"{displayName}\" <{address}>"; + return new MailAddress(address); } -} \ No newline at end of file + + public static MailAddress Create(string address, string displayName) + { + if (!string.IsNullOrEmpty(displayName)) + { + displayName = displayName.Replace("\"", string.Empty); + + if (125 < displayName.Length) + displayName = displayName.Substring(0, 125); + } + + return Create(ToSmtpAddress(address, displayName)); + } + + public static string ToEncodedString(this MailAddress m) => + ToSmtpAddress(m.Address, MimeHeaderUtils.EncodeMime(m.DisplayName)); + + private static string ToSmtpAddress(string address, string displayName) => $"\"{displayName}\" <{address}>"; +} diff --git a/common/ASC.Common/Utils/MimeHeaderUtils.cs b/common/ASC.Common/Utils/MimeHeaderUtils.cs index 3afa3c3378..ae9417d13e 100644 --- a/common/ASC.Common/Utils/MimeHeaderUtils.cs +++ b/common/ASC.Common/Utils/MimeHeaderUtils.cs @@ -23,46 +23,45 @@ * */ -namespace ASC.Common.Utils +namespace ASC.Common.Utils; + +public static class MimeHeaderUtils { - public static class MimeHeaderUtils + public static string EncodeMime(string mimeHeaderValue) => + EncodeMime(mimeHeaderValue, Encoding.UTF8, false); + + public static string EncodeMime(string mimeHeaderValue, Encoding charset, bool split) { - public static string EncodeMime(string mimeHeaderValue) => - EncodeMime(mimeHeaderValue, Encoding.UTF8, false); - - public static string EncodeMime(string mimeHeaderValue, Encoding charset, bool split) + if (MustEncode(mimeHeaderValue)) { - if (MustEncode(mimeHeaderValue)) + var result = new StringBuilder(); + var data = charset.GetBytes(mimeHeaderValue); + var maxEncodedTextSize = split ? 75 - ("=?" + charset.WebName + "?" + "B"/*Base64 encode*/ + "?" + "?=").Length : int.MaxValue; + + result.Append("=?" + charset.WebName + "?B?"); + var stored = 0; + var base64 = Convert.ToBase64String(data); + + for (var i = 0; i < base64.Length; i += 4) { - var result = new StringBuilder(); - var data = charset.GetBytes(mimeHeaderValue); - var maxEncodedTextSize = split ? 75 - ("=?" + charset.WebName + "?" + "B"/*Base64 encode*/ + "?" + "?=").Length : int.MaxValue; - - result.Append("=?" + charset.WebName + "?B?"); - var stored = 0; - var base64 = Convert.ToBase64String(data); - - for (var i = 0; i < base64.Length; i += 4) + // Encoding buffer full, create new encoded-word. + if (stored + 4 > maxEncodedTextSize) { - // Encoding buffer full, create new encoded-word. - if (stored + 4 > maxEncodedTextSize) - { - result.Append("?=\r\n =?" + charset.WebName + "?B?"); - stored = 0; - } - - result.Append(base64, i, 4); - stored += 4; + result.Append("?=\r\n =?" + charset.WebName + "?B?"); + stored = 0; } - result.Append("?="); - - return result.ToString(); + result.Append(base64, i, 4); + stored += 4; } - return mimeHeaderValue; - } - public static bool MustEncode(string text) => - !string.IsNullOrEmpty(text) && text.Any(c => c > 127); + result.Append("?="); + + return result.ToString(); + } + return mimeHeaderValue; } -} \ No newline at end of file + + public static bool MustEncode(string text) => + !string.IsNullOrEmpty(text) && text.Any(c => c > 127); +} diff --git a/common/ASC.Common/Utils/RandomString.cs b/common/ASC.Common/Utils/RandomString.cs index c2baef5bbe..f48ea20dc7 100644 --- a/common/ASC.Common/Utils/RandomString.cs +++ b/common/ASC.Common/Utils/RandomString.cs @@ -23,22 +23,21 @@ * */ -namespace ASC.Common.Utils +namespace ASC.Common.Utils; + +public static class RandomString { - public static class RandomString + public static string Generate(int length) { - public static string Generate(int length) + const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + var res = new StringBuilder(); + var rnd = new Random(); + + while (0 < length--) { - const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - var res = new StringBuilder(); - var rnd = new Random(); - - while (0 < length--) - { - res.Append(valid[rnd.Next(valid.Length)]); - } - - return res.ToString(); + res.Append(valid[rnd.Next(valid.Length)]); } + + return res.ToString(); } -} \ No newline at end of file +} diff --git a/common/ASC.Common/Utils/Signature.cs b/common/ASC.Common/Utils/Signature.cs index e8023c2b81..7ed82a4cbf 100644 --- a/common/ASC.Common/Utils/Signature.cs +++ b/common/ASC.Common/Utils/Signature.cs @@ -23,56 +23,55 @@ * */ -namespace ASC.Common.Utils +namespace ASC.Common.Utils; + +[Singletone] +public class Signature { - [Singletone] - public class Signature + private readonly MachinePseudoKeys _machinePseudoKeys; + + public Signature(MachinePseudoKeys machinePseudoKeys) => _machinePseudoKeys = machinePseudoKeys; + + public string Create<T>(T obj) => + Create(obj, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant())); + + public static string Create<T>(T obj, string secret) { - private readonly MachinePseudoKeys _machinePseudoKeys; + var str = JsonConvert.SerializeObject(obj); + var payload = GetHashBase64(str + secret) + "?" + str; - public Signature(MachinePseudoKeys machinePseudoKeys) => _machinePseudoKeys = machinePseudoKeys; - - public string Create<T>(T obj) => - Create(obj, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant())); - - public static string Create<T>(T obj, string secret) - { - var str = JsonConvert.SerializeObject(obj); - var payload = GetHashBase64(str + secret) + "?" + str; - - return WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(payload)); - } - - public T Read<T>(string signature) => - Read<T>(signature, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant())); - - public static T Read<T>(string signature, string secret) - { - try - { - var rightSignature = signature.Replace("\"", ""); - var payloadParts = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(rightSignature)).Split('?'); - - if (GetHashBase64(payloadParts[1] + secret) == payloadParts[0]) - return JsonConvert.DeserializeObject<T>(payloadParts[1]); //Sig correct - } - catch (Exception) { } - - return default; - } - - private static string GetHashBase64(string str) - { - using var sha256 = SHA256.Create(); - - return Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))); - } - - private static string GetHashBase64MD5(string str) - { - using var md5 = MD5.Create(); - - return Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(str))); - } + return WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(payload)); } -} \ No newline at end of file + + public T Read<T>(string signature) => + Read<T>(signature, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant())); + + public static T Read<T>(string signature, string secret) + { + try + { + var rightSignature = signature.Replace("\"", ""); + var payloadParts = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(rightSignature)).Split('?'); + + if (GetHashBase64(payloadParts[1] + secret) == payloadParts[0]) + return JsonConvert.DeserializeObject<T>(payloadParts[1]); //Sig correct + } + catch (Exception) { } + + return default; + } + + private static string GetHashBase64(string str) + { + using var sha256 = SHA256.Create(); + + return Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))); + } + + private static string GetHashBase64MD5(string str) + { + using var md5 = MD5.Create(); + + return Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(str))); + } +} diff --git a/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs b/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs index 3fd424640c..ea0b1c3dbe 100644 --- a/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs +++ b/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs @@ -23,286 +23,285 @@ * */ -namespace ASC.Common.Utils +namespace ASC.Common.Utils; + +[Singletone] +public class TimeZoneConverter { - [Singletone] - public class TimeZoneConverter + private TimeZoneInfo _defaultTimeZone; + private IEnumerable<MapZone> _mapZones; + private bool _customMode; + private bool _isMono; + private Dictionary<string, string> _translations; + private readonly IConfiguration _configuration; + private readonly ILog _logger; + + public TimeZoneConverter(IConfiguration configuration, IOptionsMonitor<ILog> option) { - private TimeZoneInfo _defaultTimeZone; - private IEnumerable<MapZone> _mapZones; - private bool _customMode; - private bool _isMono; - private Dictionary<string, string> _translations; - private readonly IConfiguration _configuration; - private readonly ILog _logger; - - public TimeZoneConverter(IConfiguration configuration, IOptionsMonitor<ILog> option) - { - _logger = option.CurrentValue; - _configuration = configuration; - InitMapZones(); - InitTranslations(); + _logger = option.CurrentValue; + _configuration = configuration; + InitMapZones(); + InitTranslations(); + } + + public string GetTimeZoneDisplayName(TimeZoneInfo tz) + { + var displayName = GetTimeZoneName(tz); + if (!displayName.StartsWith("(UTC") && !displayName.StartsWith("UTC")) + { + if (tz.BaseUtcOffset != TimeSpan.Zero) + { + var offSet = tz.BaseUtcOffset < TimeSpan.Zero ? "-" : "+"; + var name = tz.BaseUtcOffset.ToString(@"hh\:mm"); + displayName = $"(UTC{offSet}{name}) {displayName}"; + } + else displayName = "(UTC) " + displayName; } - public string GetTimeZoneDisplayName(TimeZoneInfo tz) + return displayName; + } + + public string OlsonTzId2WindowsTzId(string olsonTimeZoneId, bool defaultIfNoMatch = true) + { + var mapZone = GetMapZoneByWindowsTzId(olsonTimeZoneId); + + if (mapZone != null) + return olsonTimeZoneId; //already Windows + + mapZone = GetMapZoneByOlsonTzId(olsonTimeZoneId); + + if (mapZone != null) + return mapZone.WindowsTimeZoneId; + + _logger.Error($"OlsonTimeZone {olsonTimeZoneId} not found"); + + return defaultIfNoMatch ? "UTC" : null; + } + + public string WindowsTzId2OlsonTzId(string windowsTimeZoneId, bool defaultIfNoMatch = true) + { + var mapZone = GetMapZoneByOlsonTzId(windowsTimeZoneId); + + if (mapZone != null) + return windowsTimeZoneId; //already Olson + + mapZone = GetMapZoneByWindowsTzId(windowsTimeZoneId); + + if (mapZone != null) + return mapZone.OlsonTimeZoneId; + + _logger.Error($"WindowsTimeZone {windowsTimeZoneId} not found"); + + return defaultIfNoMatch ? "Etc/GMT" : null; + } + + public TimeZoneInfo GetTimeZone(string timeZoneId, bool defaultIfNoMatch = true) + { + var defaultTimezone = GetTimeZoneDefault(); + + if (string.IsNullOrEmpty(timeZoneId)) + return defaultIfNoMatch ? defaultTimezone : null; + + try { - var displayName = GetTimeZoneName(tz); - if (!displayName.StartsWith("(UTC") && !displayName.StartsWith("UTC")) + return TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); + } + catch (TimeZoneNotFoundException) + { + try { - if (tz.BaseUtcOffset != TimeSpan.Zero) - { - var offSet = tz.BaseUtcOffset < TimeSpan.Zero ? "-" : "+"; - var name = tz.BaseUtcOffset.ToString(@"hh\:mm"); - displayName = $"(UTC{offSet}{name}) {displayName}"; - } - else displayName = "(UTC) " + displayName; + var mapZone = GetMapZoneByOlsonTzId(timeZoneId); + + if (mapZone != null) + return TimeZoneInfo.FindSystemTimeZoneById(mapZone.WindowsTimeZoneId); + + mapZone = GetMapZoneByWindowsTzId(timeZoneId); + + if (mapZone != null) + return TimeZoneInfo.FindSystemTimeZoneById(mapZone.OlsonTimeZoneId); + + _logger.InfoFormat("TimeZone {0} not found", timeZoneId); + + return defaultIfNoMatch ? GetTimeZoneByOffset(timeZoneId) ?? defaultTimezone : null; + } + catch (Exception error) + { + _logger.Error(error); + + return defaultIfNoMatch ? defaultTimezone : null; + } + } + catch (Exception error) + { + _logger.Error(error); + + return defaultIfNoMatch ? defaultTimezone : null; + } + } + + + private MapZone GetMapZoneByOlsonTzId(string olsonTimeZoneId) + { + return _mapZones.FirstOrDefault(x => + x.OlsonTimeZoneId.Equals(olsonTimeZoneId, StringComparison.CurrentCultureIgnoreCase)); + } + + private MapZone GetMapZoneByWindowsTzId(string windowsTimeZoneId) + { + return _mapZones.FirstOrDefault(x => + x.WindowsTimeZoneId.Equals(windowsTimeZoneId, StringComparison.CurrentCultureIgnoreCase) && + x.Territory.Equals("001", StringComparison.CurrentCultureIgnoreCase)); + } + + private TimeZoneInfo GetTimeZoneByOffset(string timeZoneId) + { + var systemTimeZones = TimeZoneInfo.GetSystemTimeZones(); + + var timeZone = systemTimeZones.FirstOrDefault(tz => + tz.DisplayName == timeZoneId || + tz.StandardName == timeZoneId || + tz.DaylightName == timeZoneId); + + if (timeZone != null) return timeZone; + + var regex = new Regex(@"[+-][0-9]{2}:[0-9]{2}\b"); + + var offsetStr = regex.Match(timeZoneId).Value.TrimStart('+'); + + if (string.IsNullOrEmpty(offsetStr)) return null; + + + if (!TimeSpan.TryParse(offsetStr, out var offset)) + return null; + + return systemTimeZones.FirstOrDefault(tz => tz.BaseUtcOffset == offset); + } + + private void InitMapZones() + { + try + { + var assembly = Assembly.GetExecutingAssembly(); + + using var stream = assembly.GetManifestResourceStream("ASC.Common.Utils.TimeZoneConverter.windowsZones.xml"); + + var xml = XElement.Load(stream); + + _mapZones = from row in xml.XPathSelectElements("*/mapTimezones/mapZone") + let olsonTimeZones = row.Attribute("type").Value.Split(' ') + from olsonTimeZone in olsonTimeZones + select new MapZone + { + OlsonTimeZoneId = olsonTimeZone, + WindowsTimeZoneId = row.Attribute("other").Value, + Territory = row.Attribute("territory").Value + }; + + _mapZones = _mapZones.ToList(); + } + catch (Exception error) + { + _mapZones = new MapZone[0]; + _logger.Error(error); + } + } + + private void InitTranslations() + { + try + { + _customMode = _configuration["core:custom-mode"] == "true"; + + if (!_customMode) + { + _translations = new Dictionary<string, string>(); + return; } - return displayName; + var assembly = Assembly.GetExecutingAssembly(); + + using var stream = assembly.GetManifestResourceStream("ASC.Common.Utils.TimeZoneConverter.timeZoneNames.xml"); + + var xml = XElement.Load(stream); + _translations = (from row in xml.XPathSelectElements("*/zone") + select new KeyValuePair<string, string>(row.Attribute("type").Value, row.Value) + ).ToDictionary(item => item.Key, item => item.Value); } - - public string OlsonTzId2WindowsTzId(string olsonTimeZoneId, bool defaultIfNoMatch = true) - { - var mapZone = GetMapZoneByWindowsTzId(olsonTimeZoneId); - - if (mapZone != null) - return olsonTimeZoneId; //already Windows - - mapZone = GetMapZoneByOlsonTzId(olsonTimeZoneId); - - if (mapZone != null) - return mapZone.WindowsTimeZoneId; - - _logger.Error($"OlsonTimeZone {olsonTimeZoneId} not found"); - - return defaultIfNoMatch ? "UTC" : null; - } - - public string WindowsTzId2OlsonTzId(string windowsTimeZoneId, bool defaultIfNoMatch = true) - { - var mapZone = GetMapZoneByOlsonTzId(windowsTimeZoneId); - - if (mapZone != null) - return windowsTimeZoneId; //already Olson - - mapZone = GetMapZoneByWindowsTzId(windowsTimeZoneId); - - if (mapZone != null) - return mapZone.OlsonTimeZoneId; - - _logger.Error($"WindowsTimeZone {windowsTimeZoneId} not found"); - - return defaultIfNoMatch ? "Etc/GMT" : null; - } - - public TimeZoneInfo GetTimeZone(string timeZoneId, bool defaultIfNoMatch = true) + catch (Exception error) { - var defaultTimezone = GetTimeZoneDefault(); - - if (string.IsNullOrEmpty(timeZoneId)) - return defaultIfNoMatch ? defaultTimezone : null; - - try - { - return TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); - } - catch (TimeZoneNotFoundException) - { - try - { - var mapZone = GetMapZoneByOlsonTzId(timeZoneId); - - if (mapZone != null) - return TimeZoneInfo.FindSystemTimeZoneById(mapZone.WindowsTimeZoneId); - - mapZone = GetMapZoneByWindowsTzId(timeZoneId); - - if (mapZone != null) - return TimeZoneInfo.FindSystemTimeZoneById(mapZone.OlsonTimeZoneId); - - _logger.InfoFormat("TimeZone {0} not found", timeZoneId); - - return defaultIfNoMatch ? GetTimeZoneByOffset(timeZoneId) ?? defaultTimezone : null; - } - catch (Exception error) - { - _logger.Error(error); - - return defaultIfNoMatch ? defaultTimezone : null; - } - } - catch (Exception error) - { - _logger.Error(error); - - return defaultIfNoMatch ? defaultTimezone : null; - } + _translations = new Dictionary<string, string>(); + _logger.Error(error); } + } + public string GetTimeZoneName(TimeZoneInfo timeZone) + { + if (!_customMode) + return _isMono ? timeZone.Id : timeZone.DisplayName; - private MapZone GetMapZoneByOlsonTzId(string olsonTimeZoneId) - { - return _mapZones.FirstOrDefault(x => - x.OlsonTimeZoneId.Equals(olsonTimeZoneId, StringComparison.CurrentCultureIgnoreCase)); - } - - private MapZone GetMapZoneByWindowsTzId(string windowsTimeZoneId) - { - return _mapZones.FirstOrDefault(x => - x.WindowsTimeZoneId.Equals(windowsTimeZoneId, StringComparison.CurrentCultureIgnoreCase) && - x.Territory.Equals("001", StringComparison.CurrentCultureIgnoreCase)); - } - - private TimeZoneInfo GetTimeZoneByOffset(string timeZoneId) - { - var systemTimeZones = TimeZoneInfo.GetSystemTimeZones(); - - var timeZone = systemTimeZones.FirstOrDefault(tz => - tz.DisplayName == timeZoneId || - tz.StandardName == timeZoneId || - tz.DaylightName == timeZoneId); - - if (timeZone != null) return timeZone; - - var regex = new Regex(@"[+-][0-9]{2}:[0-9]{2}\b"); - - var offsetStr = regex.Match(timeZoneId).Value.TrimStart('+'); - - if (string.IsNullOrEmpty(offsetStr)) return null; - - - if (!TimeSpan.TryParse(offsetStr, out var offset)) - return null; - - return systemTimeZones.FirstOrDefault(tz => tz.BaseUtcOffset == offset); - } + return _translations.ContainsKey(timeZone.Id) ? _translations[timeZone.Id] : timeZone.DisplayName; + } - private void InitMapZones() - { - try - { - var assembly = Assembly.GetExecutingAssembly(); - - using var stream = assembly.GetManifestResourceStream("ASC.Common.Utils.TimeZoneConverter.windowsZones.xml"); - - var xml = XElement.Load(stream); - - _mapZones = from row in xml.XPathSelectElements("*/mapTimezones/mapZone") - let olsonTimeZones = row.Attribute("type").Value.Split(' ') - from olsonTimeZone in olsonTimeZones - select new MapZone - { - OlsonTimeZoneId = olsonTimeZone, - WindowsTimeZoneId = row.Attribute("other").Value, - Territory = row.Attribute("territory").Value - }; - - _mapZones = _mapZones.ToList(); - } - catch (Exception error) - { - _mapZones = new MapZone[0]; - _logger.Error(error); - } - } - - private void InitTranslations() - { - try - { - _customMode = _configuration["core:custom-mode"] == "true"; - - if (!_customMode) - { - _translations = new Dictionary<string, string>(); - return; - } - - var assembly = Assembly.GetExecutingAssembly(); - - using var stream = assembly.GetManifestResourceStream("ASC.Common.Utils.TimeZoneConverter.timeZoneNames.xml"); - - var xml = XElement.Load(stream); - _translations = (from row in xml.XPathSelectElements("*/zone") - select new KeyValuePair<string, string>(row.Attribute("type").Value, row.Value) - ).ToDictionary(item => item.Key, item => item.Value); - } - catch (Exception error) - { - _translations = new Dictionary<string, string>(); - _logger.Error(error); - } - } - - public string GetTimeZoneName(TimeZoneInfo timeZone) - { - if (!_customMode) - return _isMono ? timeZone.Id : timeZone.DisplayName; - - return _translations.ContainsKey(timeZone.Id) ? _translations[timeZone.Id] : timeZone.DisplayName; - } + private TimeZoneInfo GetTimeZoneDefault() + { + if (_defaultTimeZone == null) + { + try + { + var tz = TimeZoneInfo.Local; + if (Path.DirectorySeparatorChar == '/') + { + if (tz.StandardName == "UTC" || tz.StandardName == "UCT") + tz = TimeZoneInfo.Utc; + else + { + var id = string.Empty; - private TimeZoneInfo GetTimeZoneDefault() - { - if (_defaultTimeZone == null) - { - try - { - var tz = TimeZoneInfo.Local; - if (Path.DirectorySeparatorChar == '/') - { - if (tz.StandardName == "UTC" || tz.StandardName == "UCT") - tz = TimeZoneInfo.Utc; - else - { - var id = string.Empty; - - if (File.Exists("/etc/timezone")) + if (File.Exists("/etc/timezone")) + { + _isMono = true; + id = File.ReadAllText("/etc/timezone").Trim(); + } + + if (string.IsNullOrEmpty(id)) + { + var psi = new ProcessStartInfo { - _isMono = true; - id = File.ReadAllText("/etc/timezone").Trim(); - } - - if (string.IsNullOrEmpty(id)) - { - var psi = new ProcessStartInfo - { - FileName = "/bin/bash", - Arguments = "date +%Z", - RedirectStandardOutput = true, - UseShellExecute = false, - }; - - using var p = Process.Start(psi); + FileName = "/bin/bash", + Arguments = "date +%Z", + RedirectStandardOutput = true, + UseShellExecute = false, + }; - if (p.WaitForExit(1000)) - id = p.StandardOutput.ReadToEnd(); + using var p = Process.Start(psi); - p.Close(); - } - - if (!string.IsNullOrEmpty(id)) - tz = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(z => z.Id == id) ?? tz; - } + if (p.WaitForExit(1000)) + id = p.StandardOutput.ReadToEnd(); + + p.Close(); + } + + if (!string.IsNullOrEmpty(id)) + tz = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(z => z.Id == id) ?? tz; } - - _defaultTimeZone = tz; - } - catch (Exception) - { - // ignore - _defaultTimeZone = TimeZoneInfo.Utc; - } - } - - return _defaultTimeZone; + } + + _defaultTimeZone = tz; + } + catch (Exception) + { + // ignore + _defaultTimeZone = TimeZoneInfo.Utc; + } } - - private class MapZone - { - public string OlsonTimeZoneId { get; set; } - public string WindowsTimeZoneId { get; set; } - public string Territory { get; set; } - } - } -} \ No newline at end of file + + return _defaultTimeZone; + } + + private class MapZone + { + public string OlsonTimeZoneId { get; set; } + public string WindowsTimeZoneId { get; set; } + public string Territory { get; set; } + } +} diff --git a/common/ASC.Common/Utils/VelocityFormatter.cs b/common/ASC.Common/Utils/VelocityFormatter.cs index 7cda1af784..19b96032b1 100644 --- a/common/ASC.Common/Utils/VelocityFormatter.cs +++ b/common/ASC.Common/Utils/VelocityFormatter.cs @@ -23,63 +23,62 @@ * */ -namespace ASC.Common.Utils -{ - public class TextLoader : ResourceLoader - { - public override void Init(Commons.Collections.ExtendedProperties configuration) - { - //nothing to configure - } - - public override Stream GetResourceStream(string source) => - new MemoryStream(Encoding.UTF8.GetBytes(source)); - - public override long GetLastModified(NVelocity.Runtime.Resource.Resource resource) => 1; - - public override bool IsSourceModified(NVelocity.Runtime.Resource.Resource resource) => false; - } - - public class VelocityFormatter - { - private static bool initialized; - private static readonly ConcurrentDictionary<string, Template> patterns = new ConcurrentDictionary<string, Template>(); - - public static string FormatText(string templateText, IDictionary<string, object> values) - { - var nvelocityContext = new VelocityContext(); - - foreach (var tagValue in values) - nvelocityContext.Put(tagValue.Key, tagValue.Value); - - return FormatText(templateText, nvelocityContext); - } - - public static string FormatText(string templateText, VelocityContext context) - { - if (!initialized) - { - var properties = new Commons.Collections.ExtendedProperties(); - properties.AddProperty("resource.loader", "custom"); - properties.AddProperty("custom.resource.loader.class", "ASC.Common.Utils.TextLoader; ASC.Common"); - properties.AddProperty("input.encoding", Encoding.UTF8.WebName); - properties.AddProperty("output.encoding", Encoding.UTF8.WebName); - Velocity.Init(properties); - initialized = true; - } - - using var writer = new StringWriter(); - var key = templateText.GetHashCode().ToString(); +namespace ASC.Common.Utils; - if (!patterns.TryGetValue(key, out var template)) - { - template = Velocity.GetTemplate(templateText); - patterns.TryAdd(key, template); - } +public class TextLoader : ResourceLoader +{ + public override void Init(Commons.Collections.ExtendedProperties configuration) + { + //nothing to configure + } - template.Merge(context, writer); + public override Stream GetResourceStream(string source) => + new MemoryStream(Encoding.UTF8.GetBytes(source)); - return writer.GetStringBuilder().ToString(); - } - } -} \ No newline at end of file + public override long GetLastModified(NVelocity.Runtime.Resource.Resource resource) => 1; + + public override bool IsSourceModified(NVelocity.Runtime.Resource.Resource resource) => false; +} + +public class VelocityFormatter +{ + private static bool _initialized; + private static readonly ConcurrentDictionary<string, Template> _patterns = new ConcurrentDictionary<string, Template>(); + + public static string FormatText(string templateText, IDictionary<string, object> values) + { + var nvelocityContext = new VelocityContext(); + + foreach (var tagValue in values) + nvelocityContext.Put(tagValue.Key, tagValue.Value); + + return FormatText(templateText, nvelocityContext); + } + + public static string FormatText(string templateText, VelocityContext context) + { + if (!_initialized) + { + var properties = new Commons.Collections.ExtendedProperties(); + properties.AddProperty("resource.loader", "custom"); + properties.AddProperty("custom.resource.loader.class", "ASC.Common.Utils.TextLoader; ASC.Common"); + properties.AddProperty("input.encoding", Encoding.UTF8.WebName); + properties.AddProperty("output.encoding", Encoding.UTF8.WebName); + Velocity.Init(properties); + _initialized = true; + } + + using var writer = new StringWriter(); + var key = templateText.GetHashCode().ToString(); + + if (!_patterns.TryGetValue(key, out var template)) + { + template = Velocity.GetTemplate(templateText); + _patterns.TryAdd(key, template); + } + + template.Merge(context, writer); + + return writer.GetStringBuilder().ToString(); + } +} diff --git a/common/ASC.Common/Utils/Wildcard.cs b/common/ASC.Common/Utils/Wildcard.cs index 418a28f822..3c516e68d5 100644 --- a/common/ASC.Common/Utils/Wildcard.cs +++ b/common/ASC.Common/Utils/Wildcard.cs @@ -24,82 +24,81 @@ */ -namespace ASC.Common.Utils +namespace ASC.Common.Utils; + +public static class Wildcard { - public static class Wildcard + public static bool WildcardMatch(this string input, string pattern) => + WildcardMatch(input, pattern, true); + + public static bool WildcardMatch(this string input, string pattern, bool ignoreCase) { - public static bool WildcardMatch(this string input, string pattern) => - WildcardMatch(input, pattern, true); + if (!string.IsNullOrEmpty(input)) return IsMatch(pattern, input, ignoreCase); - public static bool WildcardMatch(this string input, string pattern, bool ignoreCase) + return false; + } + + public static bool IsMatch(string pattern, string input) => + IsMatch(pattern, input, true); + + public static bool IsMatch(string pattern, string input, bool ignoreCase) + { + var offsetInput = 0; + var isAsterix = false; + int i; + + for (i = 0; i < pattern.Length;) { - if (!string.IsNullOrEmpty(input)) return IsMatch(pattern, input, ignoreCase); - - return false; - } - - public static bool IsMatch(string pattern, string input) => - IsMatch(pattern, input, true); - - public static bool IsMatch(string pattern, string input, bool ignoreCase) - { - var offsetInput = 0; - var isAsterix = false; - int i; - - for (i = 0; i < pattern.Length;) + switch (pattern[i]) { - switch (pattern[i]) - { - case '?': - isAsterix = false; - offsetInput++; - break; - case '*': - isAsterix = true; + case '?': + isAsterix = false; + offsetInput++; + break; + case '*': + isAsterix = true; - while (i < pattern.Length && - pattern[i] == '*') - { - i++; - } + while (i < pattern.Length && + pattern[i] == '*') + { + i++; + } - if (i >= pattern.Length) - return true; + if (i >= pattern.Length) + return true; - continue; - default: - if (offsetInput >= input.Length) + continue; + default: + if (offsetInput >= input.Length) + return false; + + if ((ignoreCase + ? char.ToLower(input[offsetInput]) + : input[offsetInput]) + != + (ignoreCase + ? char.ToLower(pattern[i]) + : pattern[i])) + { + if (!isAsterix) return false; - if ((ignoreCase - ? char.ToLower(input[offsetInput]) - : input[offsetInput]) - != - (ignoreCase - ? char.ToLower(pattern[i]) - : pattern[i])) - { - if (!isAsterix) - return false; - - offsetInput++; - - continue; - } offsetInput++; - break; - } - i++; + + continue; + } + offsetInput++; + break; } - - if (i > input.Length) - return false; - - while (i < pattern.Length && pattern[i] == '*') - ++i; - - return (offsetInput == input.Length); + i++; } + + if (i > input.Length) + return false; + + while (i < pattern.Length && pattern[i] == '*') + ++i; + + return (offsetInput == input.Length); } -} \ No newline at end of file +} diff --git a/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs b/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs index ce25ebeb8a..bf7ec58f2d 100644 --- a/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs +++ b/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs @@ -23,36 +23,35 @@ * */ -namespace ASC.Common.Web +namespace ASC.Common.Web; + +public abstract class AbstractHttpAsyncHandler // : IHttpAsyncHandler, IReadOnlySessionState { - public abstract class AbstractHttpAsyncHandler // : IHttpAsyncHandler, IReadOnlySessionState + public bool IsReusable => false; + + private Action<HttpContext> _processRequest; + private IPrincipal _principal; + private CultureInfo _culture; + + public void ProcessRequest(HttpContext context) { - public bool IsReusable => false; - - private Action<Microsoft.AspNetCore.Http.HttpContext> _processRequest; - private IPrincipal _principal; - private CultureInfo _culture; - - public void ProcessRequest(Microsoft.AspNetCore.Http.HttpContext context) - { - Thread.CurrentThread.CurrentCulture = _culture; - Thread.CurrentThread.CurrentUICulture = _culture; - Thread.CurrentPrincipal = _principal; - //HttpContext.Current = context; - OnProcessRequest(context); - } - - public IAsyncResult BeginProcessRequest(Microsoft.AspNetCore.Http.HttpContext context, AsyncCallback cb, object extraData) - { - _culture = Thread.CurrentThread.CurrentCulture; - _principal = Thread.CurrentPrincipal; - _processRequest = ProcessRequest; - - return _processRequest.BeginInvoke(context, cb, extraData); - } - - public void EndProcessRequest(IAsyncResult result) => _processRequest.EndInvoke(result); - - public abstract void OnProcessRequest(Microsoft.AspNetCore.Http.HttpContext context); + Thread.CurrentThread.CurrentCulture = _culture; + Thread.CurrentThread.CurrentUICulture = _culture; + Thread.CurrentPrincipal = _principal; + //HttpContext.Current = context; + OnProcessRequest(context); } -} \ No newline at end of file + + public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) + { + _culture = Thread.CurrentThread.CurrentCulture; + _principal = Thread.CurrentPrincipal; + _processRequest = ProcessRequest; + + return _processRequest.BeginInvoke(context, cb, extraData); + } + + public void EndProcessRequest(IAsyncResult result) => _processRequest.EndInvoke(result); + + public abstract void OnProcessRequest(HttpContext context); +} diff --git a/common/ASC.Common/Web/DisposableHttpContext.cs b/common/ASC.Common/Web/DisposableHttpContext.cs index c623ed89b8..c42c086f48 100644 --- a/common/ASC.Common/Web/DisposableHttpContext.cs +++ b/common/ASC.Common/Web/DisposableHttpContext.cs @@ -23,66 +23,59 @@ * */ +namespace ASC.Common.Web; -#region usings - - -#endregion - -namespace ASC.Common.Web +public class DisposableHttpContext : IDisposable { - public class DisposableHttpContext : IDisposable + private const string Key = "disposable.key"; + + public object this[string key] { - private const string Key = "disposable.key"; - - public object this[string key] + get => Items.ContainsKey(key) ? Items[key] : null; + set { - get => Items.ContainsKey(key) ? Items[key] : null; - set - { - if (value == null) throw new ArgumentNullException(); - if (!(value is IDisposable)) throw new ArgumentException("Only IDisposable may be added!"); - Items[key] = (IDisposable)value; - } + if (value == null) throw new ArgumentNullException(); + if (!(value is IDisposable)) throw new ArgumentException("Only IDisposable may be added!"); + Items[key] = (IDisposable)value; } + } - private readonly Microsoft.AspNetCore.Http.HttpContext _context; - private bool _isDisposed; - - public DisposableHttpContext(Microsoft.AspNetCore.Http.HttpContext ctx) => - _context = ctx ?? throw new ArgumentNullException(nameof(ctx)); - - private Dictionary<string, IDisposable> Items + private Dictionary<string, IDisposable> Items + { + get { - get + var table = (Dictionary<string, IDisposable>)_context.Items[Key]; + + if (table == null) { - var table = (Dictionary<string, IDisposable>)_context.Items[Key]; - - if (table == null) - { - table = new Dictionary<string, IDisposable>(1); - _context.Items.Add(Key, table); - } - - return table; + table = new Dictionary<string, IDisposable>(1); + _context.Items.Add(Key, table); } + + return table; } + } - public void Dispose() + private readonly HttpContext _context; + private bool _isDisposed; + + public DisposableHttpContext(HttpContext ctx) => + _context = ctx ?? throw new ArgumentNullException(nameof(ctx)); + + public void Dispose() + { + if (!_isDisposed) { - if (!_isDisposed) + foreach (var item in Items.Values) { - foreach (var item in Items.Values) + try { - try - { - item.Dispose(); - } - catch { } + item.Dispose(); } - - _isDisposed = true; + catch { } } + + _isDisposed = true; } } } \ No newline at end of file diff --git a/common/ASC.Common/Web/HttpException.cs b/common/ASC.Common/Web/HttpException.cs index e247167569..8de8e38b4c 100644 --- a/common/ASC.Common/Web/HttpException.cs +++ b/common/ASC.Common/Web/HttpException.cs @@ -1,20 +1,19 @@ -namespace ASC.Common.Web +namespace ASC.Common.Web; + +public class HttpException : Exception { - public class HttpException : Exception - { - public int StatusCode { get; } + public int StatusCode { get; } - public HttpException(int httpStatusCode) => StatusCode = httpStatusCode; + public HttpException(int httpStatusCode) => StatusCode = httpStatusCode; - public HttpException(HttpStatusCode httpStatusCode) => StatusCode = (int)httpStatusCode; + public HttpException(HttpStatusCode httpStatusCode) => StatusCode = (int)httpStatusCode; - public HttpException(int httpStatusCode, string message) : base(message) => StatusCode = httpStatusCode; + public HttpException(int httpStatusCode, string message) : base(message) => StatusCode = httpStatusCode; - public HttpException(HttpStatusCode httpStatusCode, string message) : base(message) => StatusCode = (int)httpStatusCode; + public HttpException(HttpStatusCode httpStatusCode, string message) : base(message) => StatusCode = (int)httpStatusCode; - public HttpException(int httpStatusCode, string message, Exception inner) : base(message, inner) => StatusCode = httpStatusCode; + public HttpException(int httpStatusCode, string message, Exception inner) : base(message, inner) => StatusCode = httpStatusCode; - public HttpException(HttpStatusCode httpStatusCode, string message, Exception inner) : base(message, inner) => - StatusCode = (int)httpStatusCode; - } -} \ No newline at end of file + public HttpException(HttpStatusCode httpStatusCode, string message, Exception inner) : base(message, inner) => + StatusCode = (int)httpStatusCode; +} diff --git a/common/ASC.Common/Web/ItemNotFoundException.cs b/common/ASC.Common/Web/ItemNotFoundException.cs index 2e1fe6a3c6..584231f028 100644 --- a/common/ASC.Common/Web/ItemNotFoundException.cs +++ b/common/ASC.Common/Web/ItemNotFoundException.cs @@ -1,12 +1,11 @@ -namespace ASC.Common.Web +namespace ASC.Common.Web; + +[Serializable] +public class ItemNotFoundException : HttpException { - [Serializable] - public class ItemNotFoundException : HttpException - { - public ItemNotFoundException() : base(404, "Not found") { } + public ItemNotFoundException() : base(404, "Not found") { } - public ItemNotFoundException(string message) : base(404, message) { } + public ItemNotFoundException(string message) : base(404, message) { } - public ItemNotFoundException(string message, Exception inner) : base(404, message, inner) { } - } -} \ No newline at end of file + public ItemNotFoundException(string message, Exception inner) : base(404, message, inner) { } +} diff --git a/common/ASC.Common/Web/MimeMapping.cs b/common/ASC.Common/Web/MimeMapping.cs index c684f241b3..7ebd83b1f7 100644 --- a/common/ASC.Common/Web/MimeMapping.cs +++ b/common/ASC.Common/Web/MimeMapping.cs @@ -23,832 +23,831 @@ * */ -namespace ASC.Common.Web -{ - public static class MimeMapping - { - private static readonly Hashtable _extensionToMimeMappingTable = new Hashtable(200, StringComparer.CurrentCultureIgnoreCase); - private static readonly IDictionary<string, IList<string>> _mimeSynonyms = new Dictionary<string, IList<string>>(); - - static MimeMapping() - { - AddMimeMapping(".323", "text/h323"); - AddMimeMapping(".3dm", "x-world/x-3dmf"); - AddMimeMapping(".3dmf", "x-world/x-3dmf"); - AddMimeMapping(".a", "application/octet-stream"); - AddMimeMapping(".aab", "application/x-authorware-bin"); - AddMimeMapping(".aac", "audio/x-aac"); - AddMimeMapping(".aam", "application/x-authorware-map"); - AddMimeMapping(".aas", "application/x-authorware-seg"); - AddMimeMapping(".abc", "text/vnd.abc"); - AddMimeMapping(".acgi", "text/html"); - AddMimeMapping(".acx", "application/internet-property-stream"); - AddMimeMapping(".afl", "video/animaflex"); - AddMimeMapping(".ai", "application/postscript"); - AddMimeMapping(".aif", "audio/aiff"); - AddMimeMapping(".aif", "audio/x-aiff"); - AddMimeMapping(".aifc", "audio/aiff"); - AddMimeMapping(".aifc", "audio/x-aiff"); - AddMimeMapping(".aiff", "audio/aiff"); - AddMimeMapping(".aiff", "audio/x-aiff"); - AddMimeMapping(".aim", "application/x-aim"); - AddMimeMapping(".aip", "text/x-audiosoft-intra"); - AddMimeMapping(".ani", "application/x-navi-animation"); - AddMimeMapping(".aos", "application/x-nokia-9000-communicator-add-on-software"); - AddMimeMapping(".application", "application/x-ms-application"); - AddMimeMapping(".aps", "application/mime"); - AddMimeMapping(".arc", "application/octet-stream"); - AddMimeMapping(".arj", "application/arj"); - AddMimeMapping(".arj", "application/octet-stream"); - AddMimeMapping(".art", "image/x-jg"); - AddMimeMapping(".asf", "video/x-ms-asf"); - AddMimeMapping(".asm", "text/x-asm"); - AddMimeMapping(".asp", "text/asp"); - AddMimeMapping(".asr", "video/x-ms-asf"); - AddMimeMapping(".asx", "application/x-mplayer2"); - AddMimeMapping(".asx", "video/x-ms-asf"); - AddMimeMapping(".asx", "video/x-ms-asf-plugin"); - AddMimeMapping(".au", "audio/basic"); - AddMimeMapping(".au", "audio/x-au"); - AddMimeMapping(".avi", "video/avi"); - AddMimeMapping(".avi", "application/x-troff-msvideo"); - AddMimeMapping(".avi", "video/msvideo"); - AddMimeMapping(".avi", "video/x-msvideo"); - AddMimeMapping(".avs", "video/avs-video"); - AddMimeMapping(".axs", "application/olescript"); - AddMimeMapping(".bas", "text/plain"); - AddMimeMapping(".bcpio", "application/x-bcpio"); - AddMimeMapping(".bin", "application/octet-stream"); - AddMimeMapping(".bin", "application/mac-binary"); - AddMimeMapping(".bin", "application/macbinary"); - AddMimeMapping(".bin", "application/x-binary"); - AddMimeMapping(".bin", "application/x-macbinary"); - AddMimeMapping(".bm", "image/bmp"); - AddMimeMapping(".bmp", "image/bmp"); - AddMimeMapping(".bmp", "image/x-windows-bmp"); - AddMimeMapping(".bmp", "image/x-ms-bmp"); - AddMimeMapping(".boo", "application/book"); - AddMimeMapping(".book", "application/book"); - AddMimeMapping(".boz", "application/x-bzip2"); - AddMimeMapping(".bsh", "application/x-bsh"); - AddMimeMapping(".bz", "application/x-bzip"); - AddMimeMapping(".bz2", "application/x-bzip2"); - AddMimeMapping(".c", "text/plain"); - AddMimeMapping(".c", "text/x-c"); - AddMimeMapping(".c++", "text/plain"); - AddMimeMapping(".cat", "application/vnd.ms-pki.seccat"); - AddMimeMapping(".cat", "application/vndms-pkiseccat"); - AddMimeMapping(".cc", "text/plain"); - AddMimeMapping(".cc", "text/x-c"); - AddMimeMapping(".ccad", "application/clariscad"); - AddMimeMapping(".cco", "application/x-cocoa"); - AddMimeMapping(".cdf", "application/cdf"); - AddMimeMapping(".cdf", "application/x-cdf"); - AddMimeMapping(".cdf", "application/x-netcdf"); - AddMimeMapping(".cer", "application/pkix-cert"); - AddMimeMapping(".cer", "application/x-x509-ca-cert"); - AddMimeMapping(".cha", "application/x-chat"); - AddMimeMapping(".chat", "application/x-chat"); - AddMimeMapping(".class", "application/java"); - AddMimeMapping(".class", "application/java-byte-code"); - AddMimeMapping(".class", "application/x-java-class"); - AddMimeMapping(".clp", "application/x-msclip"); - AddMimeMapping(".cmx", "image/x-cmx"); - AddMimeMapping(".cod", "image/cis-cod"); - AddMimeMapping(".com", "application/octet-stream"); - AddMimeMapping(".com", "text/plain"); - AddMimeMapping(".conf", "text/plain"); - AddMimeMapping(".cpio", "application/x-cpio"); - AddMimeMapping(".cpp", "text/x-c"); - AddMimeMapping(".cpt", "application/mac-compactpro"); - AddMimeMapping(".cpt", "application/x-compactpro"); - AddMimeMapping(".cpt", "application/x-cpt"); - AddMimeMapping(".crd", "application/x-mscardfile"); - AddMimeMapping(".crl", "application/pkcs-crl"); - AddMimeMapping(".crl", "application/pkix-crl"); - AddMimeMapping(".crt", "application/pkix-cert"); - AddMimeMapping(".crt", "application/x-x509-ca-cert"); - AddMimeMapping(".crt", "application/x-x509-user-cert"); - AddMimeMapping(".csh", "application/x-csh"); - AddMimeMapping(".csh", "text/x-script.csh"); - AddMimeMapping(".css", "text/css"); - AddMimeMapping(".css", "application/x-pointplus"); - AddMimeMapping(".csv", "text/csv"); - AddMimeMapping(".cxx", "text/plain"); - AddMimeMapping(".dcr", "application/x-director"); - AddMimeMapping(".deepv", "application/x-deepv"); - AddMimeMapping(".def", "text/plain"); - AddMimeMapping(".deploy", "application/octet-stream"); - AddMimeMapping(".der", "application/x-x509-ca-cert"); - AddMimeMapping(".dib", "image/bmp"); - AddMimeMapping(".dif", "video/x-dv"); - AddMimeMapping(".dir", "application/x-director"); - AddMimeMapping(".disco", "text/xml"); - AddMimeMapping(".djvu", "image/vnd.djvu"); - AddMimeMapping(".dll", "application/octet-stream"); - AddMimeMapping(".dll", "application/x-msdownload"); - AddMimeMapping(".dl", "video/dl"); - AddMimeMapping(".dl", "video/x-dl"); - AddMimeMapping(".doc", "application/msword"); - AddMimeMapping(".docm", "application/vnd.ms-word.document.macroEnabled.12"); - AddMimeMapping(".doct", "application/doct"); - AddMimeMapping(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); - AddMimeMapping(".docxf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); - AddMimeMapping(".docxf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.docxf"); - AddMimeMapping(".dot", "application/msword"); - AddMimeMapping(".dotm", "application/vnd.ms-word.template.macroEnabled.12"); - AddMimeMapping(".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"); - AddMimeMapping(".dp", "application/commonground"); - AddMimeMapping(".drw", "application/drafting"); - AddMimeMapping(".dump", "application/octet-stream"); - AddMimeMapping(".dv", "video/x-dv"); - AddMimeMapping(".dvi", "application/x-dvi"); - AddMimeMapping(".dwf", "drawing/x-dwf (old)"); - AddMimeMapping(".dwf", "model/vnd.dwf"); - AddMimeMapping(".dwg", "application/acad"); - AddMimeMapping(".dwg", "image/vnd.dwg"); - AddMimeMapping(".dwg", "image/x-dwg"); - AddMimeMapping(".dxf", "application/dxf"); - AddMimeMapping(".dxf", "image/vnd.dwg"); - AddMimeMapping(".dxf", "image/x-dwg"); - AddMimeMapping(".dxr", "application/x-director"); - AddMimeMapping(".el", "text/x-script.elisp"); - AddMimeMapping(".elc", "application/x-bytecode.elisp (compiled elisp)"); - AddMimeMapping(".elc", "application/x-elc"); - AddMimeMapping(".env", "application/x-envoy"); - AddMimeMapping(".eml", "message/rfc822"); - AddMimeMapping(".eps", "application/postscript"); - AddMimeMapping(".epub", "application/epub+zip"); - AddMimeMapping(".es", "application/x-esrehber"); - AddMimeMapping(".etx", "text/x-setext"); - AddMimeMapping(".evy", "application/envoy"); - AddMimeMapping(".evy", "application/x-envoy"); - AddMimeMapping(".exe", "application/octet-stream"); - AddMimeMapping(".f", "text/plain"); - AddMimeMapping(".f", "text/x-fortran"); - AddMimeMapping(".f4v", "video/x-f4v"); - AddMimeMapping(".f77", "text/x-fortran"); - AddMimeMapping(".f90", "text/plain"); - AddMimeMapping(".f90", "text/x-fortran"); - AddMimeMapping(".fb2", "text/xml"); - AddMimeMapping(".fdf", "application/vnd.fdf"); - AddMimeMapping(".fif", "application/fractals"); - AddMimeMapping(".fif", "image/fif"); - AddMimeMapping(".flac", "audio/flac"); - AddMimeMapping(".fli", "video/fli"); - AddMimeMapping(".fli", "video/x-fli"); - AddMimeMapping(".flo", "image/florian"); - AddMimeMapping(".flr", "x-world/x-vrml"); - AddMimeMapping(".flx", "text/vnd.fmi.flexstor"); - AddMimeMapping(".fmf", "video/x-atomic3d-feature"); - AddMimeMapping(".fodp", "application/vnd.oasis.opendocument.presentation"); - AddMimeMapping(".fods", "application/vnd.oasis.opendocument.spreadsheet"); - AddMimeMapping(".fodt", "application/vnd.oasis.opendocument.text"); - AddMimeMapping(".for", "text/plain"); - AddMimeMapping(".for", "text/x-fortran"); - AddMimeMapping(".fpx", "image/vnd.fpx"); - AddMimeMapping(".fpx", "image/vnd.net-fpx"); - AddMimeMapping(".frl", "application/freeloader"); - AddMimeMapping(".funk", "audio/make"); - AddMimeMapping(".g", "text/plain"); - AddMimeMapping(".g3", "image/g3fax"); - AddMimeMapping(".gdoc", "application/vnd.google-apps.document"); - AddMimeMapping(".gdraw", "application/vnd.google-apps.drawing"); - AddMimeMapping(".gif", "image/gif"); - AddMimeMapping(".gl", "video/gl"); - AddMimeMapping(".gl", "video/x-gl"); - AddMimeMapping(".gsd", "audio/x-gsm"); - AddMimeMapping(".gsheet", "application/vnd.google-apps.spreadsheet"); - AddMimeMapping(".gslides", "application/vnd.google-apps.presentation"); - AddMimeMapping(".gsm", "audio/x-gsm"); - AddMimeMapping(".gsp", "application/x-gsp"); - AddMimeMapping(".gss", "application/x-gss"); - AddMimeMapping(".gtar", "application/x-gtar"); - AddMimeMapping(".gz", "application/x-gzip"); - AddMimeMapping(".gz", "application/x-compressed"); - AddMimeMapping(".gzip", "application/x-gzip"); - AddMimeMapping(".gzip", "multipart/x-gzip"); - AddMimeMapping(".h", "text/plain"); - AddMimeMapping(".h", "text/x-h"); - AddMimeMapping(".hdf", "application/x-hdf"); - AddMimeMapping(".help", "application/x-helpfile"); - AddMimeMapping(".hgl", "application/vnd.hp-hpgl"); - AddMimeMapping(".hh", "text/plain"); - AddMimeMapping(".hh", "text/x-h"); - AddMimeMapping(".hlb", "text/x-script"); - AddMimeMapping(".hlp", "application/hlp"); - AddMimeMapping(".hlp", "application/x-helpfile"); - AddMimeMapping(".hlp", "application/x-winhelp"); - AddMimeMapping(".hpg", "application/vnd.hp-hpgl"); - AddMimeMapping(".hpgl", "application/vnd.hp-hpgl"); - AddMimeMapping(".hqx", "application/binhex"); - AddMimeMapping(".hqx", "application/binhex4"); - AddMimeMapping(".hqx", "application/mac-binhex"); - AddMimeMapping(".hqx", "application/mac-binhex40"); - AddMimeMapping(".hqx", "application/x-binhex40"); - AddMimeMapping(".hqx", "application/x-mac-binhex40"); - AddMimeMapping(".hta", "application/hta"); - AddMimeMapping(".htc", "text/x-component"); - AddMimeMapping(".htm", "text/html"); - AddMimeMapping(".html", "text/html"); - AddMimeMapping(".htmls", "text/html"); - AddMimeMapping(".htt", "text/webviewhtml"); - AddMimeMapping(".htx", "text/html"); - AddMimeMapping(".ice", "x-conference/x-cooltalk"); - AddMimeMapping(".ico", "image/x-icon"); - AddMimeMapping(".idc", "text/plain"); - AddMimeMapping(".ief", "image/ief"); - AddMimeMapping(".iefs", "image/ief"); - AddMimeMapping(".iii", "application/x-iphone"); - AddMimeMapping(".iges", "application/iges"); - AddMimeMapping(".iges", "model/iges"); - AddMimeMapping(".igs", "application/iges"); - AddMimeMapping(".igs", "model/iges"); - AddMimeMapping(".ima", "application/x-ima"); - AddMimeMapping(".imap", "application/x-httpd-imap"); - AddMimeMapping(".inf", "application/inf"); - AddMimeMapping(".ins", "application/x-internett-signup"); - AddMimeMapping(".ip", "application/x-ip2"); - AddMimeMapping(".isp", "application/x-internet-signup"); - AddMimeMapping(".isu", "video/x-isvideo"); - AddMimeMapping(".it", "audio/it"); - AddMimeMapping(".iv", "application/x-inventor"); - AddMimeMapping(".ivf", "video/x-ivf"); - AddMimeMapping(".ivr", "i-world/i-vrml"); - AddMimeMapping(".ivy", "application/x-livescreen"); - AddMimeMapping(".jam", "audio/x-jam"); - AddMimeMapping(".jav", "text/plain"); - AddMimeMapping(".jav", "text/x-java-source"); - AddMimeMapping(".java", "text/plain"); - AddMimeMapping(".java", "text/x-java-source"); - AddMimeMapping(".jcm", "application/x-java-commerce"); - AddMimeMapping(".jfif", "image/jpeg"); - AddMimeMapping(".jfif", "image/pjpeg"); - AddMimeMapping(".jfif-tbnl", "image/jpeg"); - AddMimeMapping(".jpeg", "image/jpeg"); - AddMimeMapping(".jpe", "image/jpeg"); - AddMimeMapping(".jpe", "image/pjpeg"); - AddMimeMapping(".jpeg", "image/pjpeg"); - AddMimeMapping(".jpg", "image/jpeg"); - AddMimeMapping(".jpg", "image/pjpeg"); - AddMimeMapping(".jps", "image/x-jps"); - AddMimeMapping(".json", "application/json"); - AddMimeMapping(".js", "text/javascript"); - AddMimeMapping(".js", "application/javascript"); - AddMimeMapping(".js", "application/x-javascript"); - AddMimeMapping(".js", "application/ecmascript"); - AddMimeMapping(".js", "text/ecmascript"); - AddMimeMapping(".jut", "image/jutvision"); - AddMimeMapping(".kar", "audio/midi"); - AddMimeMapping(".kar", "music/x-karaoke"); - AddMimeMapping(".ksh", "application/x-ksh"); - AddMimeMapping(".ksh", "text/x-script.ksh"); - AddMimeMapping(".la", "audio/nspaudio"); - AddMimeMapping(".la", "audio/x-nspaudio"); - AddMimeMapping(".lam", "audio/x-liveaudio"); - AddMimeMapping(".latex", "application/x-latex"); - AddMimeMapping(".less", "text/css"); - AddMimeMapping(".lha", "application/lha"); - AddMimeMapping(".lha", "application/octet-stream"); - AddMimeMapping(".lha", "application/x-lha"); - AddMimeMapping(".lhx", "application/octet-stream"); - AddMimeMapping(".list", "text/plain"); - AddMimeMapping(".lma", "audio/nspaudio"); - AddMimeMapping(".lma", "audio/x-nspaudio"); - AddMimeMapping(".log", "text/plain"); - AddMimeMapping(".lsf", "video/x-la-asf"); - AddMimeMapping(".lsp", "application/x-lisp"); - AddMimeMapping(".lsp", "text/x-script.lisp"); - AddMimeMapping(".lst", "text/plain"); - AddMimeMapping(".lsx", "text/x-la-asf"); - AddMimeMapping(".ltx", "application/x-latex"); - AddMimeMapping(".lzh", "application/octet-stream"); - AddMimeMapping(".lzh", "application/x-lzh"); - AddMimeMapping(".lzx", "application/lzx"); - AddMimeMapping(".lzx", "application/octet-stream"); - AddMimeMapping(".lzx", "application/x-lzx"); - AddMimeMapping(".m", "text/plain"); - AddMimeMapping(".m", "text/x-m"); - AddMimeMapping(".m13", "application/x-msmediaview"); - AddMimeMapping(".m14", "application/x-msmediaview"); - AddMimeMapping(".m1v", "video/mpeg"); - AddMimeMapping(".m2a", "audio/mpeg"); - AddMimeMapping(".m2v", "video/mpeg"); - AddMimeMapping(".m3u", "audio/x-mpequrl"); - AddMimeMapping(".m4a", "audio/m4a"); - AddMimeMapping(".m4a", "audio/x-m4a"); - AddMimeMapping(".m4v", "video/mp4"); - AddMimeMapping(".m4v", "video/mpeg4"); - AddMimeMapping(".m4v", "video/x-m4v"); - AddMimeMapping(".man", "application/x-troff-man"); - AddMimeMapping(".manifest", "application/x-ms-manifest"); - AddMimeMapping(".map", "application/x-navimap"); - AddMimeMapping(".mar", "text/plain"); - AddMimeMapping(".mbd", "application/mbedlet"); - AddMimeMapping(".mdb", "application/x-msaccess"); - AddMimeMapping(".mc$", "application/x-magic-cap-package-1.0"); - AddMimeMapping(".mcd", "application/mcad"); - AddMimeMapping(".mcd", "application/x-mathcad"); - AddMimeMapping(".mcf", "image/vasa"); - AddMimeMapping(".mcf", "text/mcf"); - AddMimeMapping(".mcp", "application/netmc"); - AddMimeMapping(".me", "application/x-troff-me"); - AddMimeMapping(".mht", "message/rfc822"); - AddMimeMapping(".mhtml", "message/rfc822"); - AddMimeMapping(".mid", "application/x-midi"); - AddMimeMapping(".mid", "audio/midi"); - AddMimeMapping(".mid", "audio/x-mid"); - AddMimeMapping(".mid", "audio/x-midi"); - AddMimeMapping(".mid", "music/crescendo"); - AddMimeMapping(".mid", "x-music/x-midi"); - AddMimeMapping(".midi", "application/x-midi"); - AddMimeMapping(".midi", "audio/midi"); - AddMimeMapping(".midi", "audio/x-mid"); - AddMimeMapping(".midi", "audio/x-midi"); - AddMimeMapping(".midi", "music/crescendo"); - AddMimeMapping(".midi", "x-music/x-midi"); - AddMimeMapping(".mif", "application/x-frame"); - AddMimeMapping(".mif", "application/x-mif"); - AddMimeMapping(".mime", "message/rfc822"); - AddMimeMapping(".mime", "www/mime"); - AddMimeMapping(".mjf", "audio/x-vnd.audioexplosion.mjuicemediafile"); - AddMimeMapping(".mjpg", "video/x-motion-jpeg"); - AddMimeMapping(".mm", "application/base64"); - AddMimeMapping(".mm", "application/x-meme"); - AddMimeMapping(".mme", "application/base64"); - AddMimeMapping(".mny", "application/x-msmoney"); - AddMimeMapping(".mod", "audio/mod"); - AddMimeMapping(".mod", "audio/x-mod"); - AddMimeMapping(".moov", "video/quicktime"); - AddMimeMapping(".mov", "video/quicktime"); - AddMimeMapping(".movie", "video/x-sgi-movie"); - AddMimeMapping(".mp2", "audio/mpeg"); - AddMimeMapping(".mp2", "audio/x-mpeg"); - AddMimeMapping(".mp2", "video/mpeg"); - AddMimeMapping(".mp2", "video/x-mpeg"); - AddMimeMapping(".mp2", "video/x-mpeq2a"); - AddMimeMapping(".mp3", "audio/mpeg3"); - AddMimeMapping(".mp3", "audio/x-mpeg-3"); - AddMimeMapping(".mp3", "video/mpeg"); - AddMimeMapping(".mp3", "video/x-mpeg"); - AddMimeMapping(".mp4", "video/mp4"); - AddMimeMapping(".mpa", "audio/mpeg"); - AddMimeMapping(".mpa", "video/mpeg"); - AddMimeMapping(".mpc", "application/x-project"); - AddMimeMapping(".mpe", "video/mpeg"); - AddMimeMapping(".mpeg", "video/mpeg"); - AddMimeMapping(".mpg", "audio/mpeg"); - AddMimeMapping(".mpg", "video/mpeg"); - AddMimeMapping(".mpga", "audio/mpeg"); - AddMimeMapping(".mpp", "application/vnd.ms-project"); - AddMimeMapping(".mpt", "application/x-project"); - AddMimeMapping(".mpv", "application/x-project"); - AddMimeMapping(".mpv2", "video/mpeg"); - AddMimeMapping(".mpx", "application/x-project"); - AddMimeMapping(".mrc", "application/marc"); - AddMimeMapping(".ms", "application/x-troff-ms"); - AddMimeMapping(".mv", "video/x-sgi-movie"); - AddMimeMapping(".mvb", "application/x-msmediaview"); - AddMimeMapping(".my", "audio/make"); - AddMimeMapping(".mzz", "application/x-vnd.audioexplosion.mzz"); - AddMimeMapping(".nap", "image/naplps"); - AddMimeMapping(".naplps", "image/naplps"); - AddMimeMapping(".nc", "application/x-netcdf"); - AddMimeMapping(".ncm", "application/vnd.nokia.configuration-message"); - AddMimeMapping(".nif", "image/x-niff"); - AddMimeMapping(".niff", "image/x-niff"); - AddMimeMapping(".nix", "application/x-mix-transfer"); - AddMimeMapping(".nsc", "application/x-conference"); - AddMimeMapping(".nvd", "application/x-navidoc"); - AddMimeMapping(".nws", "message/rfc822"); - AddMimeMapping(".o", "application/octet-stream"); - AddMimeMapping(".oda", "application/oda"); - AddMimeMapping(".odp", "application/vnd.oasis.opendocument.presentation"); - AddMimeMapping(".ods", "application/vnd.oasis.opendocument.spreadsheet"); - AddMimeMapping(".odt", "application/vnd.oasis.opendocument.text"); - AddMimeMapping(".oform", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); - AddMimeMapping(".oform", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.oform"); - AddMimeMapping(".oga", "audio/ogg"); - AddMimeMapping(".ogg", "video/ogg"); - AddMimeMapping(".ogg", "audio/ogg"); - AddMimeMapping(".ogv", "video/ogg"); - AddMimeMapping(".omc", "application/x-omc"); - AddMimeMapping(".omcd", "application/x-omcdatamaker"); - AddMimeMapping(".omcr", "application/x-omcregerator"); - AddMimeMapping(".otp", "application/vnd.oasis.opendocument.presentation-template"); - AddMimeMapping(".ots", "application/vnd.oasis.opendocument.spreadsheet-template"); - AddMimeMapping(".ott", "application/vnd.oasis.opendocument.text-template"); - AddMimeMapping(".p", "text/x-pascal"); - AddMimeMapping(".p10", "application/pkcs10"); - AddMimeMapping(".p10", "application/x-pkcs10"); - AddMimeMapping(".p12", "application/pkcs-12"); - AddMimeMapping(".p12", "application/x-pkcs12"); - AddMimeMapping(".p7a", "application/x-pkcs7-signature"); - AddMimeMapping(".p7b", "application/x-pkcs7-certificates"); - AddMimeMapping(".p7c", "application/pkcs7-mime"); - AddMimeMapping(".p7c", "application/x-pkcs7-mime"); - AddMimeMapping(".p7m", "application/pkcs7-mime"); - AddMimeMapping(".p7m", "application/x-pkcs7-mime"); - AddMimeMapping(".p7r", "application/x-pkcs7-certreqresp"); - AddMimeMapping(".p7s", "application/pkcs7-signature"); - AddMimeMapping(".part", "application/pro_eng"); - AddMimeMapping(".pas", "text/pascal"); - AddMimeMapping(".pbm", "image/x-portable-bitmap"); - AddMimeMapping(".pcl", "application/vnd.hp-pcl"); - AddMimeMapping(".pcl", "application/x-pcl"); - AddMimeMapping(".pct", "image/x-pict"); - AddMimeMapping(".pcx", "image/x-pcx"); - AddMimeMapping(".pdb", "chemical/x-pdb"); - AddMimeMapping(".pdf", "application/pdf"); - AddMimeMapping(".pfunk", "audio/make"); - AddMimeMapping(".pfunk", "audio/make.my.funk"); - AddMimeMapping(".pfx", "application/x-pkcs12"); - AddMimeMapping(".pgm", "image/x-portable-graymap"); - AddMimeMapping(".pgm", "image/x-portable-greymap"); - AddMimeMapping(".pic", "image/pict"); - AddMimeMapping(".pict", "image/pict"); - AddMimeMapping(".pkg", "application/x-newton-compatible-pkg"); - AddMimeMapping(".pko", "application/vnd.ms-pki.pko"); - AddMimeMapping(".pko", "application/vndms-pkipko"); - AddMimeMapping(".pl", "text/plain"); - AddMimeMapping(".pl", "text/x-script.perl"); - AddMimeMapping(".plx", "application/x-pixclscript"); - AddMimeMapping(".pm", "image/x-xpixmap"); - AddMimeMapping(".pm", "text/x-script.perl-module"); - AddMimeMapping(".pm4", "application/x-pagemaker"); - AddMimeMapping(".pm5", "application/x-pagemaker"); - AddMimeMapping(".pma", "application/x-perfmon"); - AddMimeMapping(".pmc", "application/x-perfmon"); - AddMimeMapping(".pml", "application/x-perfmon"); - AddMimeMapping(".pmr", "application/x-perfmon"); - AddMimeMapping(".pmw", "application/x-perfmon"); - AddMimeMapping(".png", "image/png"); - AddMimeMapping(".pnm", "application/x-portable-anymap"); - AddMimeMapping(".pnm", "image/x-portable-anymap"); - AddMimeMapping(".pot", "application/mspowerpoint"); - AddMimeMapping(".pot", "application/vnd.ms-powerpoint"); - AddMimeMapping(".potm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"); - AddMimeMapping(".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"); - AddMimeMapping(".pov", "model/x-pov"); - AddMimeMapping(".ppa", "application/vnd.ms-powerpoint"); - AddMimeMapping(".ppm", "image/x-portable-pixmap"); - AddMimeMapping(".pps", "application/mspowerpoint"); - AddMimeMapping(".pps", "application/vnd.ms-powerpoint"); - AddMimeMapping(".ppsm", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"); - AddMimeMapping(".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"); - AddMimeMapping(".ppt", "application/vnd.ms-powerpoint"); - AddMimeMapping(".ppt", "application/mspowerpoint"); - AddMimeMapping(".ppt", "application/powerpoint"); - AddMimeMapping(".ppt", "application/x-mspowerpoint"); - AddMimeMapping(".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"); - AddMimeMapping(".pptt", "application/pptt"); - AddMimeMapping(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); - AddMimeMapping(".ppz", "application/mspowerpoint"); - AddMimeMapping(".pre", "application/x-freelance"); - AddMimeMapping(".prf", "application/pics-rules"); - AddMimeMapping(".prt", "application/pro_eng"); - AddMimeMapping(".ps", "application/postscript"); - AddMimeMapping(".psd", "application/octet-stream"); - AddMimeMapping(".pub", "application/x-mspublisher"); - AddMimeMapping(".pvu", "paleovu/x-pv"); - AddMimeMapping(".pwz", "application/vnd.ms-powerpoint"); - AddMimeMapping(".py", "text/x-script.phyton"); - AddMimeMapping(".pyc", "applicaiton/x-bytecode.python"); - AddMimeMapping(".qcp", "audio/vnd.qcelp"); - AddMimeMapping(".qd3", "x-world/x-3dmf"); - AddMimeMapping(".qd3d", "x-world/x-3dmf"); - AddMimeMapping(".qif", "image/x-quicktime"); - AddMimeMapping(".qt", "video/quicktime"); - AddMimeMapping(".qtc", "video/x-qtc"); - AddMimeMapping(".qti", "image/x-quicktime"); - AddMimeMapping(".qtif", "image/x-quicktime"); - AddMimeMapping(".ra", "audio/x-pn-realaudio"); - AddMimeMapping(".ra", "audio/x-pn-realaudio-plugin"); - AddMimeMapping(".ra", "audio/x-realaudio"); - AddMimeMapping(".ram", "audio/x-pn-realaudio"); - AddMimeMapping(".ras", "application/x-cmu-raster"); - AddMimeMapping(".ras", "image/cmu-raster"); - AddMimeMapping(".ras", "image/x-cmu-raster"); - AddMimeMapping(".rast", "image/cmu-raster"); - AddMimeMapping(".rexx", "text/x-script.rexx"); - AddMimeMapping(".rf", "image/vnd.rn-realflash"); - AddMimeMapping(".rgb", "image/x-rgb"); - AddMimeMapping(".rm", "application/vnd.rn-realmedia"); - AddMimeMapping(".rm", "audio/x-pn-realaudio"); - AddMimeMapping(".rmi", "audio/mid"); - AddMimeMapping(".rmm", "audio/x-pn-realaudio"); - AddMimeMapping(".rmp", "audio/x-pn-realaudio"); - AddMimeMapping(".rmp", "audio/x-pn-realaudio-plugin"); - AddMimeMapping(".rng", "application/ringing-tones"); - AddMimeMapping(".rng", "application/vnd.nokia.ringing-tone"); - AddMimeMapping(".rnx", "application/vnd.rn-realplayer"); - AddMimeMapping(".roff", "application/x-troff"); - AddMimeMapping(".rp", "image/vnd.rn-realpix"); - AddMimeMapping(".rpm", "audio/x-pn-realaudio-plugin"); - AddMimeMapping(".rt", "text/richtext"); - AddMimeMapping(".rt", "text/vnd.rn-realtext"); - AddMimeMapping(".rtf", "application/rtf"); - AddMimeMapping(".rtf", "application/x-rtf"); - AddMimeMapping(".rtf", "text/richtext"); - AddMimeMapping(".rtx", "application/rtf"); - AddMimeMapping(".rtx", "text/richtext"); - AddMimeMapping(".rv", "video/vnd.rn-realvideo"); - AddMimeMapping(".s", "text/x-asm"); - AddMimeMapping(".s3m", "audio/s3m"); - AddMimeMapping(".saveme", "application/octet-stream"); - AddMimeMapping(".sbk", "application/x-tbook"); - AddMimeMapping(".scd", "application/x-msschedule"); - AddMimeMapping(".scm", "application/x-lotusscreencam"); - AddMimeMapping(".scm", "text/x-script.guile"); - AddMimeMapping(".scm", "text/x-script.scheme"); - AddMimeMapping(".scm", "video/x-scm"); - AddMimeMapping(".sct", "text/scriptlet"); - AddMimeMapping(".sdml", "text/plain"); - AddMimeMapping(".sdp", "application/sdp"); - AddMimeMapping(".sdp", "application/x-sdp"); - AddMimeMapping(".sdr", "application/sounder"); - AddMimeMapping(".sea", "application/sea"); - AddMimeMapping(".sea", "application/x-sea"); - AddMimeMapping(".set", "application/set"); - AddMimeMapping(".setpay", "application/set-payment-initiation"); - AddMimeMapping(".setreg", "application/set-registration-initiation"); - AddMimeMapping(".sgm", "text/sgml"); - AddMimeMapping(".sgm", "text/x-sgml"); - AddMimeMapping(".sgml", "text/sgml"); - AddMimeMapping(".sgml", "text/x-sgml"); - AddMimeMapping(".sh", "application/x-bsh"); - AddMimeMapping(".sh", "application/x-sh"); - AddMimeMapping(".sh", "application/x-shar"); - AddMimeMapping(".sh", "text/x-script.sh"); - AddMimeMapping(".shar", "application/x-bsh"); - AddMimeMapping(".shar", "application/x-shar"); - AddMimeMapping(".shtml", "text/html"); - AddMimeMapping(".shtml", "text/x-server-parsed-html"); - AddMimeMapping(".sid", "audio/x-psid"); - AddMimeMapping(".sit", "application/x-sit"); - AddMimeMapping(".sit", "application/x-stuffit"); - AddMimeMapping(".skd", "application/x-koan"); - AddMimeMapping(".skm", "application/x-koan"); - AddMimeMapping(".skp", "application/x-koan"); - AddMimeMapping(".skt", "application/x-koan"); - AddMimeMapping(".sl", "application/x-seelogo"); - AddMimeMapping(".smi", "application/smil"); - AddMimeMapping(".smil", "application/smil"); - AddMimeMapping(".snd", "audio/basic"); - AddMimeMapping(".snd", "audio/x-adpcm"); - AddMimeMapping(".sol", "application/solids"); - AddMimeMapping(".spc", "application/x-pkcs7-certificates"); - AddMimeMapping(".spc", "text/x-speech"); - AddMimeMapping(".spl", "application/futuresplash"); - AddMimeMapping(".spr", "application/x-sprite"); - AddMimeMapping(".sprite", "application/x-sprite"); - AddMimeMapping(".src", "application/x-wais-source"); - AddMimeMapping(".ssi", "text/x-server-parsed-html"); - AddMimeMapping(".ssm", "application/streamingmedia"); - AddMimeMapping(".sst", "application/vnd.ms-pki.certstore"); - AddMimeMapping(".sst", "application/vndms-pkicertstore"); - AddMimeMapping(".step", "application/step"); - AddMimeMapping(".stl", "application/sla"); - AddMimeMapping(".stl", "application/vnd.ms-pki.stl"); - AddMimeMapping(".stl", "application/x-navistyle"); - AddMimeMapping(".stl", "application/vndms-pkistl"); - AddMimeMapping(".stm", "text/html"); - AddMimeMapping(".stp", "application/step"); - AddMimeMapping(".sv4cpio", "application/x-sv4cpio"); - AddMimeMapping(".sv4crc", "application/x-sv4crc"); - AddMimeMapping(".svf", "image/vnd.dwg"); - AddMimeMapping(".svf", "image/x-dwg"); - AddMimeMapping(".svr", "application/x-world"); - AddMimeMapping(".svr", "x-world/x-svr"); - AddMimeMapping(".svg", "image/svg+xml"); - AddMimeMapping(".svgt", "image/svg+xml"); - AddMimeMapping(".swf", "application/x-shockwave-flash"); - AddMimeMapping(".t", "application/x-troff"); - AddMimeMapping(".talk", "text/x-speech"); - AddMimeMapping(".tar", "application/x-tar"); - AddMimeMapping(".tbk", "application/toolbook"); - AddMimeMapping(".tbk", "application/x-tbook"); - AddMimeMapping(".tcl", "application/x-tcl"); - AddMimeMapping(".tcl", "text/x-script.tcl"); - AddMimeMapping(".tcsh", "text/x-script.tcsh"); - AddMimeMapping(".tex", "application/x-tex"); - AddMimeMapping(".texi", "application/x-texinfo"); - AddMimeMapping(".texinfo", "application/x-texinfo"); - AddMimeMapping(".text", "application/plain"); - AddMimeMapping(".text", "text/plain"); - AddMimeMapping(".tgz", "application/x-compressed"); - AddMimeMapping(".tgz", "application/gnutar"); - AddMimeMapping(".tif", "image/tiff"); - AddMimeMapping(".tif", "image/x-tiff"); - AddMimeMapping(".tiff", "image/tiff"); - AddMimeMapping(".tiff", "image/x-tiff"); - AddMimeMapping(".tr", "application/x-troff"); - AddMimeMapping(".trm", "application/x-msterminal"); - AddMimeMapping(".tsi", "audio/tsp-audio"); - AddMimeMapping(".tsp", "application/dsptype"); - AddMimeMapping(".tsp", "audio/tsplayer"); - AddMimeMapping(".tsv", "text/tab-separated-values"); - AddMimeMapping(".turbot", "image/florian"); - AddMimeMapping(".txt", "text/plain"); - AddMimeMapping(".uil", "text/x-uil"); - AddMimeMapping(".uls", "text/iuls"); - AddMimeMapping(".uni", "text/uri-list"); - AddMimeMapping(".unis", "text/uri-list"); - AddMimeMapping(".unv", "application/i-deas"); - AddMimeMapping(".uri", "text/uri-list"); - AddMimeMapping(".uris", "text/uri-list"); - AddMimeMapping(".ustar", "application/x-ustar"); - AddMimeMapping(".ustar", "multipart/x-ustar"); - AddMimeMapping(".uu", "application/octet-stream"); - AddMimeMapping(".uu", "text/x-uuencode"); - AddMimeMapping(".uue", "text/x-uuencode"); - AddMimeMapping(".vcd", "application/x-cdlink"); - AddMimeMapping(".vcf", "text/x-vcard"); - AddMimeMapping(".vcs", "text/x-vcalendar"); - AddMimeMapping(".vda", "application/vda"); - AddMimeMapping(".vdo", "video/vdo"); - AddMimeMapping(".vew", "application/groupwise"); - AddMimeMapping(".viv", "video/vivo"); - AddMimeMapping(".viv", "video/vnd.vivo"); - AddMimeMapping(".vivo", "video/vivo"); - AddMimeMapping(".vivo", "video/vnd.vivo"); - AddMimeMapping(".vmd", "application/vocaltec-media-desc"); - AddMimeMapping(".vmf", "application/vocaltec-media-file"); - AddMimeMapping(".voc", "audio/voc"); - AddMimeMapping(".voc", "audio/x-voc"); - AddMimeMapping(".vos", "video/vosaic"); - AddMimeMapping(".vox", "audio/voxware"); - AddMimeMapping(".vqe", "audio/x-twinvq-plugin"); - AddMimeMapping(".vqf", "audio/x-twinvq"); - AddMimeMapping(".vql", "audio/x-twinvq-plugin"); - AddMimeMapping(".vrml", "application/x-vrml"); - AddMimeMapping(".vrml", "model/vrml"); - AddMimeMapping(".vrml", "x-world/x-vrml"); - AddMimeMapping(".vrt", "x-world/x-vrt"); - AddMimeMapping(".vsd", "application/x-visio"); - AddMimeMapping(".vst", "application/x-visio"); - AddMimeMapping(".vsw", "application/x-visio"); - AddMimeMapping(".w60", "application/wordperfect6.0"); - AddMimeMapping(".w61", "application/wordperfect6.1"); - AddMimeMapping(".w6w", "application/msword"); - AddMimeMapping(".wav", "audio/wav"); - AddMimeMapping(".wav", "audio/x-wav"); - AddMimeMapping(".wb1", "application/x-qpro"); - AddMimeMapping(".wbmp", "image/vnd.wap.wbmp"); - AddMimeMapping(".wcm", "application/vnd.ms-works"); - AddMimeMapping(".wdb", "application/vnd.ms-works"); - AddMimeMapping(".web", "application/vnd.xara"); - AddMimeMapping(".webm", "video/webm"); - AddMimeMapping(".webp", "image/webp"); - AddMimeMapping(".wiz", "application/msword"); - AddMimeMapping(".wk1", "application/x-123"); - AddMimeMapping(".wks", "application/vnd.ms-works"); - AddMimeMapping(".wmf", "windows/metafile"); - AddMimeMapping(".wmf", "application/x-msmetafile"); - AddMimeMapping(".wml", "text/vnd.wap.wml"); - AddMimeMapping(".wmlc", "application/vnd.wap.wmlc"); - AddMimeMapping(".wmls", "text/vnd.wap.wmlscript"); - AddMimeMapping(".wmlsc", "application/vnd.wap.wmlscriptc"); - AddMimeMapping(".woff2", "application/font-woff2"); - AddMimeMapping(".word", "application/msword"); - AddMimeMapping(".wp", "application/wordperfect"); - AddMimeMapping(".wp5", "application/wordperfect"); - AddMimeMapping(".wp5", "application/wordperfect6.0"); - AddMimeMapping(".wp6", "application/wordperfect"); - AddMimeMapping(".wpd", "application/wordperfect"); - AddMimeMapping(".wpd", "application/x-wpwin"); - AddMimeMapping(".wps", "application/vnd.ms-works"); - AddMimeMapping(".wq1", "application/x-lotus"); - AddMimeMapping(".wri", "application/mswrite"); - AddMimeMapping(".wri", "application/x-wri"); - AddMimeMapping(".wri", "application/x-mswrite"); - AddMimeMapping(".wrl", "application/x-world"); - AddMimeMapping(".wrl", "model/vrml"); - AddMimeMapping(".wrl", "x-world/x-vrml"); - AddMimeMapping(".wrz", "model/vrml"); - AddMimeMapping(".wrz", "x-world/x-vrml"); - AddMimeMapping(".wsc", "text/scriplet"); - AddMimeMapping(".wsdl", "text/xml"); - AddMimeMapping(".wsrc", "application/x-wais-source"); - AddMimeMapping(".wtk", "application/x-wintalk"); - AddMimeMapping(".x-png", "image/png"); - AddMimeMapping(".xaf", "x-world/x-vrml"); - AddMimeMapping(".xbm", "image/x-xbitmap"); - AddMimeMapping(".xbm", "image/x-xbm"); - AddMimeMapping(".xbm", "image/xbm"); - AddMimeMapping(".xdr", "video/x-amt-demorun"); - AddMimeMapping(".xgz", "xgl/drawing"); - AddMimeMapping(".xif", "image/vnd.xiff"); - AddMimeMapping(".xl", "application/excel"); - AddMimeMapping(".xla", "application/excel"); - AddMimeMapping(".xla", "application/x-excel"); - AddMimeMapping(".xla", "application/x-msexcel"); - AddMimeMapping(".xla", "application/vnd.ms-excel"); - AddMimeMapping(".xlb", "application/excel"); - AddMimeMapping(".xlb", "application/vnd.ms-excel"); - AddMimeMapping(".xlb", "application/x-excel"); - AddMimeMapping(".xlc", "application/excel"); - AddMimeMapping(".xlc", "application/vnd.ms-excel"); - AddMimeMapping(".xlc", "application/x-excel"); - AddMimeMapping(".xld", "application/excel"); - AddMimeMapping(".xld", "application/x-excel"); - AddMimeMapping(".xlk", "application/excel"); - AddMimeMapping(".xlk", "application/x-excel"); - AddMimeMapping(".xll", "application/excel"); - AddMimeMapping(".xll", "application/vnd.ms-excel"); - AddMimeMapping(".xll", "application/x-excel"); - AddMimeMapping(".xlm", "application/excel"); - AddMimeMapping(".xlm", "application/vnd.ms-excel"); - AddMimeMapping(".xlm", "application/x-excel"); - AddMimeMapping(".xls", "application/vnd.ms-excel"); - AddMimeMapping(".xls", "application/excel"); - AddMimeMapping(".xls", "application/x-excel"); - AddMimeMapping(".xls", "application/x-msexcel"); - AddMimeMapping(".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"); - AddMimeMapping(".xlsm", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - AddMimeMapping(".xlst", "application/xlst"); - AddMimeMapping(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - AddMimeMapping(".xlt", "application/excel"); - AddMimeMapping(".xlt", "application/x-excel"); - AddMimeMapping(".xlt", "application/vnd.ms-excel"); - AddMimeMapping(".xltm", "application/vnd.ms-excel.template.macroEnabled.12"); - AddMimeMapping(".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"); - AddMimeMapping(".xlv", "application/excel"); - AddMimeMapping(".xlv", "application/x-excel"); - AddMimeMapping(".xlw", "application/excel"); - AddMimeMapping(".xlw", "application/vnd.ms-excel"); - AddMimeMapping(".xlw", "application/x-excel"); - AddMimeMapping(".xlw", "application/x-msexcel"); - AddMimeMapping(".xm", "audio/xm"); - AddMimeMapping(".xml", "application/xml"); - AddMimeMapping(".xml", "text/xml"); - AddMimeMapping(".xmz", "xgl/movie"); - AddMimeMapping(".xof", "x-world/x-vrml"); - AddMimeMapping(".xpix", "application/x-vnd.ls-xpix"); - AddMimeMapping(".xpm", "image/x-xpixmap"); - AddMimeMapping(".xpm", "image/xpm"); - AddMimeMapping(".xps", "application/vnd.ms-xpsdocument"); - AddMimeMapping(".xsd", "text/xml"); - AddMimeMapping(".xsl", "text/xml"); - AddMimeMapping(".xsr", "video/x-amt-showrun"); - AddMimeMapping(".xwd", "image/x-xwd"); - AddMimeMapping(".xwd", "image/x-xwindowdump"); - AddMimeMapping(".xyz", "chemical/x-pdb"); - AddMimeMapping(".z", "application/x-compress"); - AddMimeMapping(".z", "application/x-compressed"); - AddMimeMapping(".zip", "application/zip"); - AddMimeMapping(".zip", "application/x-compressed"); - AddMimeMapping(".zip", "application/x-zip-compressed"); - AddMimeSynonym("application/x-zip-compressed", "application/zip"); - AddMimeMapping(".zip", "multipart/x-zip"); - AddMimeMapping(".zoo", "application/octet-stream"); - AddMimeMapping(".zsh", "text/x-script.zsh"); - AddMimeMapping(".*", "application/octet-stream"); +namespace ASC.Common.Web; + +public static class MimeMapping +{ + private static readonly Hashtable _extensionToMimeMappingTable = new Hashtable(200, StringComparer.CurrentCultureIgnoreCase); + private static readonly IDictionary<string, IList<string>> _mimeSynonyms = new Dictionary<string, IList<string>>(); + + static MimeMapping() + { + AddMimeMapping(".323", "text/h323"); + AddMimeMapping(".3dm", "x-world/x-3dmf"); + AddMimeMapping(".3dmf", "x-world/x-3dmf"); + AddMimeMapping(".a", "application/octet-stream"); + AddMimeMapping(".aab", "application/x-authorware-bin"); + AddMimeMapping(".aac", "audio/x-aac"); + AddMimeMapping(".aam", "application/x-authorware-map"); + AddMimeMapping(".aas", "application/x-authorware-seg"); + AddMimeMapping(".abc", "text/vnd.abc"); + AddMimeMapping(".acgi", "text/html"); + AddMimeMapping(".acx", "application/internet-property-stream"); + AddMimeMapping(".afl", "video/animaflex"); + AddMimeMapping(".ai", "application/postscript"); + AddMimeMapping(".aif", "audio/aiff"); + AddMimeMapping(".aif", "audio/x-aiff"); + AddMimeMapping(".aifc", "audio/aiff"); + AddMimeMapping(".aifc", "audio/x-aiff"); + AddMimeMapping(".aiff", "audio/aiff"); + AddMimeMapping(".aiff", "audio/x-aiff"); + AddMimeMapping(".aim", "application/x-aim"); + AddMimeMapping(".aip", "text/x-audiosoft-intra"); + AddMimeMapping(".ani", "application/x-navi-animation"); + AddMimeMapping(".aos", "application/x-nokia-9000-communicator-add-on-software"); + AddMimeMapping(".application", "application/x-ms-application"); + AddMimeMapping(".aps", "application/mime"); + AddMimeMapping(".arc", "application/octet-stream"); + AddMimeMapping(".arj", "application/arj"); + AddMimeMapping(".arj", "application/octet-stream"); + AddMimeMapping(".art", "image/x-jg"); + AddMimeMapping(".asf", "video/x-ms-asf"); + AddMimeMapping(".asm", "text/x-asm"); + AddMimeMapping(".asp", "text/asp"); + AddMimeMapping(".asr", "video/x-ms-asf"); + AddMimeMapping(".asx", "application/x-mplayer2"); + AddMimeMapping(".asx", "video/x-ms-asf"); + AddMimeMapping(".asx", "video/x-ms-asf-plugin"); + AddMimeMapping(".au", "audio/basic"); + AddMimeMapping(".au", "audio/x-au"); + AddMimeMapping(".avi", "video/avi"); + AddMimeMapping(".avi", "application/x-troff-msvideo"); + AddMimeMapping(".avi", "video/msvideo"); + AddMimeMapping(".avi", "video/x-msvideo"); + AddMimeMapping(".avs", "video/avs-video"); + AddMimeMapping(".axs", "application/olescript"); + AddMimeMapping(".bas", "text/plain"); + AddMimeMapping(".bcpio", "application/x-bcpio"); + AddMimeMapping(".bin", "application/octet-stream"); + AddMimeMapping(".bin", "application/mac-binary"); + AddMimeMapping(".bin", "application/macbinary"); + AddMimeMapping(".bin", "application/x-binary"); + AddMimeMapping(".bin", "application/x-macbinary"); + AddMimeMapping(".bm", "image/bmp"); + AddMimeMapping(".bmp", "image/bmp"); + AddMimeMapping(".bmp", "image/x-windows-bmp"); + AddMimeMapping(".bmp", "image/x-ms-bmp"); + AddMimeMapping(".boo", "application/book"); + AddMimeMapping(".book", "application/book"); + AddMimeMapping(".boz", "application/x-bzip2"); + AddMimeMapping(".bsh", "application/x-bsh"); + AddMimeMapping(".bz", "application/x-bzip"); + AddMimeMapping(".bz2", "application/x-bzip2"); + AddMimeMapping(".c", "text/plain"); + AddMimeMapping(".c", "text/x-c"); + AddMimeMapping(".c++", "text/plain"); + AddMimeMapping(".cat", "application/vnd.ms-pki.seccat"); + AddMimeMapping(".cat", "application/vndms-pkiseccat"); + AddMimeMapping(".cc", "text/plain"); + AddMimeMapping(".cc", "text/x-c"); + AddMimeMapping(".ccad", "application/clariscad"); + AddMimeMapping(".cco", "application/x-cocoa"); + AddMimeMapping(".cdf", "application/cdf"); + AddMimeMapping(".cdf", "application/x-cdf"); + AddMimeMapping(".cdf", "application/x-netcdf"); + AddMimeMapping(".cer", "application/pkix-cert"); + AddMimeMapping(".cer", "application/x-x509-ca-cert"); + AddMimeMapping(".cha", "application/x-chat"); + AddMimeMapping(".chat", "application/x-chat"); + AddMimeMapping(".class", "application/java"); + AddMimeMapping(".class", "application/java-byte-code"); + AddMimeMapping(".class", "application/x-java-class"); + AddMimeMapping(".clp", "application/x-msclip"); + AddMimeMapping(".cmx", "image/x-cmx"); + AddMimeMapping(".cod", "image/cis-cod"); + AddMimeMapping(".com", "application/octet-stream"); + AddMimeMapping(".com", "text/plain"); + AddMimeMapping(".conf", "text/plain"); + AddMimeMapping(".cpio", "application/x-cpio"); + AddMimeMapping(".cpp", "text/x-c"); + AddMimeMapping(".cpt", "application/mac-compactpro"); + AddMimeMapping(".cpt", "application/x-compactpro"); + AddMimeMapping(".cpt", "application/x-cpt"); + AddMimeMapping(".crd", "application/x-mscardfile"); + AddMimeMapping(".crl", "application/pkcs-crl"); + AddMimeMapping(".crl", "application/pkix-crl"); + AddMimeMapping(".crt", "application/pkix-cert"); + AddMimeMapping(".crt", "application/x-x509-ca-cert"); + AddMimeMapping(".crt", "application/x-x509-user-cert"); + AddMimeMapping(".csh", "application/x-csh"); + AddMimeMapping(".csh", "text/x-script.csh"); + AddMimeMapping(".css", "text/css"); + AddMimeMapping(".css", "application/x-pointplus"); + AddMimeMapping(".csv", "text/csv"); + AddMimeMapping(".cxx", "text/plain"); + AddMimeMapping(".dcr", "application/x-director"); + AddMimeMapping(".deepv", "application/x-deepv"); + AddMimeMapping(".def", "text/plain"); + AddMimeMapping(".deploy", "application/octet-stream"); + AddMimeMapping(".der", "application/x-x509-ca-cert"); + AddMimeMapping(".dib", "image/bmp"); + AddMimeMapping(".dif", "video/x-dv"); + AddMimeMapping(".dir", "application/x-director"); + AddMimeMapping(".disco", "text/xml"); + AddMimeMapping(".djvu", "image/vnd.djvu"); + AddMimeMapping(".dll", "application/octet-stream"); + AddMimeMapping(".dll", "application/x-msdownload"); + AddMimeMapping(".dl", "video/dl"); + AddMimeMapping(".dl", "video/x-dl"); + AddMimeMapping(".doc", "application/msword"); + AddMimeMapping(".docm", "application/vnd.ms-word.document.macroEnabled.12"); + AddMimeMapping(".doct", "application/doct"); + AddMimeMapping(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + AddMimeMapping(".docxf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + AddMimeMapping(".docxf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.docxf"); + AddMimeMapping(".dot", "application/msword"); + AddMimeMapping(".dotm", "application/vnd.ms-word.template.macroEnabled.12"); + AddMimeMapping(".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"); + AddMimeMapping(".dp", "application/commonground"); + AddMimeMapping(".drw", "application/drafting"); + AddMimeMapping(".dump", "application/octet-stream"); + AddMimeMapping(".dv", "video/x-dv"); + AddMimeMapping(".dvi", "application/x-dvi"); + AddMimeMapping(".dwf", "drawing/x-dwf (old)"); + AddMimeMapping(".dwf", "model/vnd.dwf"); + AddMimeMapping(".dwg", "application/acad"); + AddMimeMapping(".dwg", "image/vnd.dwg"); + AddMimeMapping(".dwg", "image/x-dwg"); + AddMimeMapping(".dxf", "application/dxf"); + AddMimeMapping(".dxf", "image/vnd.dwg"); + AddMimeMapping(".dxf", "image/x-dwg"); + AddMimeMapping(".dxr", "application/x-director"); + AddMimeMapping(".el", "text/x-script.elisp"); + AddMimeMapping(".elc", "application/x-bytecode.elisp (compiled elisp)"); + AddMimeMapping(".elc", "application/x-elc"); + AddMimeMapping(".env", "application/x-envoy"); + AddMimeMapping(".eml", "message/rfc822"); + AddMimeMapping(".eps", "application/postscript"); + AddMimeMapping(".epub", "application/epub+zip"); + AddMimeMapping(".es", "application/x-esrehber"); + AddMimeMapping(".etx", "text/x-setext"); + AddMimeMapping(".evy", "application/envoy"); + AddMimeMapping(".evy", "application/x-envoy"); + AddMimeMapping(".exe", "application/octet-stream"); + AddMimeMapping(".f", "text/plain"); + AddMimeMapping(".f", "text/x-fortran"); + AddMimeMapping(".f4v", "video/x-f4v"); + AddMimeMapping(".f77", "text/x-fortran"); + AddMimeMapping(".f90", "text/plain"); + AddMimeMapping(".f90", "text/x-fortran"); + AddMimeMapping(".fb2", "text/xml"); + AddMimeMapping(".fdf", "application/vnd.fdf"); + AddMimeMapping(".fif", "application/fractals"); + AddMimeMapping(".fif", "image/fif"); + AddMimeMapping(".flac", "audio/flac"); + AddMimeMapping(".fli", "video/fli"); + AddMimeMapping(".fli", "video/x-fli"); + AddMimeMapping(".flo", "image/florian"); + AddMimeMapping(".flr", "x-world/x-vrml"); + AddMimeMapping(".flx", "text/vnd.fmi.flexstor"); + AddMimeMapping(".fmf", "video/x-atomic3d-feature"); + AddMimeMapping(".fodp", "application/vnd.oasis.opendocument.presentation"); + AddMimeMapping(".fods", "application/vnd.oasis.opendocument.spreadsheet"); + AddMimeMapping(".fodt", "application/vnd.oasis.opendocument.text"); + AddMimeMapping(".for", "text/plain"); + AddMimeMapping(".for", "text/x-fortran"); + AddMimeMapping(".fpx", "image/vnd.fpx"); + AddMimeMapping(".fpx", "image/vnd.net-fpx"); + AddMimeMapping(".frl", "application/freeloader"); + AddMimeMapping(".funk", "audio/make"); + AddMimeMapping(".g", "text/plain"); + AddMimeMapping(".g3", "image/g3fax"); + AddMimeMapping(".gdoc", "application/vnd.google-apps.document"); + AddMimeMapping(".gdraw", "application/vnd.google-apps.drawing"); + AddMimeMapping(".gif", "image/gif"); + AddMimeMapping(".gl", "video/gl"); + AddMimeMapping(".gl", "video/x-gl"); + AddMimeMapping(".gsd", "audio/x-gsm"); + AddMimeMapping(".gsheet", "application/vnd.google-apps.spreadsheet"); + AddMimeMapping(".gslides", "application/vnd.google-apps.presentation"); + AddMimeMapping(".gsm", "audio/x-gsm"); + AddMimeMapping(".gsp", "application/x-gsp"); + AddMimeMapping(".gss", "application/x-gss"); + AddMimeMapping(".gtar", "application/x-gtar"); + AddMimeMapping(".gz", "application/x-gzip"); + AddMimeMapping(".gz", "application/x-compressed"); + AddMimeMapping(".gzip", "application/x-gzip"); + AddMimeMapping(".gzip", "multipart/x-gzip"); + AddMimeMapping(".h", "text/plain"); + AddMimeMapping(".h", "text/x-h"); + AddMimeMapping(".hdf", "application/x-hdf"); + AddMimeMapping(".help", "application/x-helpfile"); + AddMimeMapping(".hgl", "application/vnd.hp-hpgl"); + AddMimeMapping(".hh", "text/plain"); + AddMimeMapping(".hh", "text/x-h"); + AddMimeMapping(".hlb", "text/x-script"); + AddMimeMapping(".hlp", "application/hlp"); + AddMimeMapping(".hlp", "application/x-helpfile"); + AddMimeMapping(".hlp", "application/x-winhelp"); + AddMimeMapping(".hpg", "application/vnd.hp-hpgl"); + AddMimeMapping(".hpgl", "application/vnd.hp-hpgl"); + AddMimeMapping(".hqx", "application/binhex"); + AddMimeMapping(".hqx", "application/binhex4"); + AddMimeMapping(".hqx", "application/mac-binhex"); + AddMimeMapping(".hqx", "application/mac-binhex40"); + AddMimeMapping(".hqx", "application/x-binhex40"); + AddMimeMapping(".hqx", "application/x-mac-binhex40"); + AddMimeMapping(".hta", "application/hta"); + AddMimeMapping(".htc", "text/x-component"); + AddMimeMapping(".htm", "text/html"); + AddMimeMapping(".html", "text/html"); + AddMimeMapping(".htmls", "text/html"); + AddMimeMapping(".htt", "text/webviewhtml"); + AddMimeMapping(".htx", "text/html"); + AddMimeMapping(".ice", "x-conference/x-cooltalk"); + AddMimeMapping(".ico", "image/x-icon"); + AddMimeMapping(".idc", "text/plain"); + AddMimeMapping(".ief", "image/ief"); + AddMimeMapping(".iefs", "image/ief"); + AddMimeMapping(".iii", "application/x-iphone"); + AddMimeMapping(".iges", "application/iges"); + AddMimeMapping(".iges", "model/iges"); + AddMimeMapping(".igs", "application/iges"); + AddMimeMapping(".igs", "model/iges"); + AddMimeMapping(".ima", "application/x-ima"); + AddMimeMapping(".imap", "application/x-httpd-imap"); + AddMimeMapping(".inf", "application/inf"); + AddMimeMapping(".ins", "application/x-internett-signup"); + AddMimeMapping(".ip", "application/x-ip2"); + AddMimeMapping(".isp", "application/x-internet-signup"); + AddMimeMapping(".isu", "video/x-isvideo"); + AddMimeMapping(".it", "audio/it"); + AddMimeMapping(".iv", "application/x-inventor"); + AddMimeMapping(".ivf", "video/x-ivf"); + AddMimeMapping(".ivr", "i-world/i-vrml"); + AddMimeMapping(".ivy", "application/x-livescreen"); + AddMimeMapping(".jam", "audio/x-jam"); + AddMimeMapping(".jav", "text/plain"); + AddMimeMapping(".jav", "text/x-java-source"); + AddMimeMapping(".java", "text/plain"); + AddMimeMapping(".java", "text/x-java-source"); + AddMimeMapping(".jcm", "application/x-java-commerce"); + AddMimeMapping(".jfif", "image/jpeg"); + AddMimeMapping(".jfif", "image/pjpeg"); + AddMimeMapping(".jfif-tbnl", "image/jpeg"); + AddMimeMapping(".jpeg", "image/jpeg"); + AddMimeMapping(".jpe", "image/jpeg"); + AddMimeMapping(".jpe", "image/pjpeg"); + AddMimeMapping(".jpeg", "image/pjpeg"); + AddMimeMapping(".jpg", "image/jpeg"); + AddMimeMapping(".jpg", "image/pjpeg"); + AddMimeMapping(".jps", "image/x-jps"); + AddMimeMapping(".json", "application/json"); + AddMimeMapping(".js", "text/javascript"); + AddMimeMapping(".js", "application/javascript"); + AddMimeMapping(".js", "application/x-javascript"); + AddMimeMapping(".js", "application/ecmascript"); + AddMimeMapping(".js", "text/ecmascript"); + AddMimeMapping(".jut", "image/jutvision"); + AddMimeMapping(".kar", "audio/midi"); + AddMimeMapping(".kar", "music/x-karaoke"); + AddMimeMapping(".ksh", "application/x-ksh"); + AddMimeMapping(".ksh", "text/x-script.ksh"); + AddMimeMapping(".la", "audio/nspaudio"); + AddMimeMapping(".la", "audio/x-nspaudio"); + AddMimeMapping(".lam", "audio/x-liveaudio"); + AddMimeMapping(".latex", "application/x-latex"); + AddMimeMapping(".less", "text/css"); + AddMimeMapping(".lha", "application/lha"); + AddMimeMapping(".lha", "application/octet-stream"); + AddMimeMapping(".lha", "application/x-lha"); + AddMimeMapping(".lhx", "application/octet-stream"); + AddMimeMapping(".list", "text/plain"); + AddMimeMapping(".lma", "audio/nspaudio"); + AddMimeMapping(".lma", "audio/x-nspaudio"); + AddMimeMapping(".log", "text/plain"); + AddMimeMapping(".lsf", "video/x-la-asf"); + AddMimeMapping(".lsp", "application/x-lisp"); + AddMimeMapping(".lsp", "text/x-script.lisp"); + AddMimeMapping(".lst", "text/plain"); + AddMimeMapping(".lsx", "text/x-la-asf"); + AddMimeMapping(".ltx", "application/x-latex"); + AddMimeMapping(".lzh", "application/octet-stream"); + AddMimeMapping(".lzh", "application/x-lzh"); + AddMimeMapping(".lzx", "application/lzx"); + AddMimeMapping(".lzx", "application/octet-stream"); + AddMimeMapping(".lzx", "application/x-lzx"); + AddMimeMapping(".m", "text/plain"); + AddMimeMapping(".m", "text/x-m"); + AddMimeMapping(".m13", "application/x-msmediaview"); + AddMimeMapping(".m14", "application/x-msmediaview"); + AddMimeMapping(".m1v", "video/mpeg"); + AddMimeMapping(".m2a", "audio/mpeg"); + AddMimeMapping(".m2v", "video/mpeg"); + AddMimeMapping(".m3u", "audio/x-mpequrl"); + AddMimeMapping(".m4a", "audio/m4a"); + AddMimeMapping(".m4a", "audio/x-m4a"); + AddMimeMapping(".m4v", "video/mp4"); + AddMimeMapping(".m4v", "video/mpeg4"); + AddMimeMapping(".m4v", "video/x-m4v"); + AddMimeMapping(".man", "application/x-troff-man"); + AddMimeMapping(".manifest", "application/x-ms-manifest"); + AddMimeMapping(".map", "application/x-navimap"); + AddMimeMapping(".mar", "text/plain"); + AddMimeMapping(".mbd", "application/mbedlet"); + AddMimeMapping(".mdb", "application/x-msaccess"); + AddMimeMapping(".mc$", "application/x-magic-cap-package-1.0"); + AddMimeMapping(".mcd", "application/mcad"); + AddMimeMapping(".mcd", "application/x-mathcad"); + AddMimeMapping(".mcf", "image/vasa"); + AddMimeMapping(".mcf", "text/mcf"); + AddMimeMapping(".mcp", "application/netmc"); + AddMimeMapping(".me", "application/x-troff-me"); + AddMimeMapping(".mht", "message/rfc822"); + AddMimeMapping(".mhtml", "message/rfc822"); + AddMimeMapping(".mid", "application/x-midi"); + AddMimeMapping(".mid", "audio/midi"); + AddMimeMapping(".mid", "audio/x-mid"); + AddMimeMapping(".mid", "audio/x-midi"); + AddMimeMapping(".mid", "music/crescendo"); + AddMimeMapping(".mid", "x-music/x-midi"); + AddMimeMapping(".midi", "application/x-midi"); + AddMimeMapping(".midi", "audio/midi"); + AddMimeMapping(".midi", "audio/x-mid"); + AddMimeMapping(".midi", "audio/x-midi"); + AddMimeMapping(".midi", "music/crescendo"); + AddMimeMapping(".midi", "x-music/x-midi"); + AddMimeMapping(".mif", "application/x-frame"); + AddMimeMapping(".mif", "application/x-mif"); + AddMimeMapping(".mime", "message/rfc822"); + AddMimeMapping(".mime", "www/mime"); + AddMimeMapping(".mjf", "audio/x-vnd.audioexplosion.mjuicemediafile"); + AddMimeMapping(".mjpg", "video/x-motion-jpeg"); + AddMimeMapping(".mm", "application/base64"); + AddMimeMapping(".mm", "application/x-meme"); + AddMimeMapping(".mme", "application/base64"); + AddMimeMapping(".mny", "application/x-msmoney"); + AddMimeMapping(".mod", "audio/mod"); + AddMimeMapping(".mod", "audio/x-mod"); + AddMimeMapping(".moov", "video/quicktime"); + AddMimeMapping(".mov", "video/quicktime"); + AddMimeMapping(".movie", "video/x-sgi-movie"); + AddMimeMapping(".mp2", "audio/mpeg"); + AddMimeMapping(".mp2", "audio/x-mpeg"); + AddMimeMapping(".mp2", "video/mpeg"); + AddMimeMapping(".mp2", "video/x-mpeg"); + AddMimeMapping(".mp2", "video/x-mpeq2a"); + AddMimeMapping(".mp3", "audio/mpeg3"); + AddMimeMapping(".mp3", "audio/x-mpeg-3"); + AddMimeMapping(".mp3", "video/mpeg"); + AddMimeMapping(".mp3", "video/x-mpeg"); + AddMimeMapping(".mp4", "video/mp4"); + AddMimeMapping(".mpa", "audio/mpeg"); + AddMimeMapping(".mpa", "video/mpeg"); + AddMimeMapping(".mpc", "application/x-project"); + AddMimeMapping(".mpe", "video/mpeg"); + AddMimeMapping(".mpeg", "video/mpeg"); + AddMimeMapping(".mpg", "audio/mpeg"); + AddMimeMapping(".mpg", "video/mpeg"); + AddMimeMapping(".mpga", "audio/mpeg"); + AddMimeMapping(".mpp", "application/vnd.ms-project"); + AddMimeMapping(".mpt", "application/x-project"); + AddMimeMapping(".mpv", "application/x-project"); + AddMimeMapping(".mpv2", "video/mpeg"); + AddMimeMapping(".mpx", "application/x-project"); + AddMimeMapping(".mrc", "application/marc"); + AddMimeMapping(".ms", "application/x-troff-ms"); + AddMimeMapping(".mv", "video/x-sgi-movie"); + AddMimeMapping(".mvb", "application/x-msmediaview"); + AddMimeMapping(".my", "audio/make"); + AddMimeMapping(".mzz", "application/x-vnd.audioexplosion.mzz"); + AddMimeMapping(".nap", "image/naplps"); + AddMimeMapping(".naplps", "image/naplps"); + AddMimeMapping(".nc", "application/x-netcdf"); + AddMimeMapping(".ncm", "application/vnd.nokia.configuration-message"); + AddMimeMapping(".nif", "image/x-niff"); + AddMimeMapping(".niff", "image/x-niff"); + AddMimeMapping(".nix", "application/x-mix-transfer"); + AddMimeMapping(".nsc", "application/x-conference"); + AddMimeMapping(".nvd", "application/x-navidoc"); + AddMimeMapping(".nws", "message/rfc822"); + AddMimeMapping(".o", "application/octet-stream"); + AddMimeMapping(".oda", "application/oda"); + AddMimeMapping(".odp", "application/vnd.oasis.opendocument.presentation"); + AddMimeMapping(".ods", "application/vnd.oasis.opendocument.spreadsheet"); + AddMimeMapping(".odt", "application/vnd.oasis.opendocument.text"); + AddMimeMapping(".oform", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + AddMimeMapping(".oform", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.oform"); + AddMimeMapping(".oga", "audio/ogg"); + AddMimeMapping(".ogg", "video/ogg"); + AddMimeMapping(".ogg", "audio/ogg"); + AddMimeMapping(".ogv", "video/ogg"); + AddMimeMapping(".omc", "application/x-omc"); + AddMimeMapping(".omcd", "application/x-omcdatamaker"); + AddMimeMapping(".omcr", "application/x-omcregerator"); + AddMimeMapping(".otp", "application/vnd.oasis.opendocument.presentation-template"); + AddMimeMapping(".ots", "application/vnd.oasis.opendocument.spreadsheet-template"); + AddMimeMapping(".ott", "application/vnd.oasis.opendocument.text-template"); + AddMimeMapping(".p", "text/x-pascal"); + AddMimeMapping(".p10", "application/pkcs10"); + AddMimeMapping(".p10", "application/x-pkcs10"); + AddMimeMapping(".p12", "application/pkcs-12"); + AddMimeMapping(".p12", "application/x-pkcs12"); + AddMimeMapping(".p7a", "application/x-pkcs7-signature"); + AddMimeMapping(".p7b", "application/x-pkcs7-certificates"); + AddMimeMapping(".p7c", "application/pkcs7-mime"); + AddMimeMapping(".p7c", "application/x-pkcs7-mime"); + AddMimeMapping(".p7m", "application/pkcs7-mime"); + AddMimeMapping(".p7m", "application/x-pkcs7-mime"); + AddMimeMapping(".p7r", "application/x-pkcs7-certreqresp"); + AddMimeMapping(".p7s", "application/pkcs7-signature"); + AddMimeMapping(".part", "application/pro_eng"); + AddMimeMapping(".pas", "text/pascal"); + AddMimeMapping(".pbm", "image/x-portable-bitmap"); + AddMimeMapping(".pcl", "application/vnd.hp-pcl"); + AddMimeMapping(".pcl", "application/x-pcl"); + AddMimeMapping(".pct", "image/x-pict"); + AddMimeMapping(".pcx", "image/x-pcx"); + AddMimeMapping(".pdb", "chemical/x-pdb"); + AddMimeMapping(".pdf", "application/pdf"); + AddMimeMapping(".pfunk", "audio/make"); + AddMimeMapping(".pfunk", "audio/make.my.funk"); + AddMimeMapping(".pfx", "application/x-pkcs12"); + AddMimeMapping(".pgm", "image/x-portable-graymap"); + AddMimeMapping(".pgm", "image/x-portable-greymap"); + AddMimeMapping(".pic", "image/pict"); + AddMimeMapping(".pict", "image/pict"); + AddMimeMapping(".pkg", "application/x-newton-compatible-pkg"); + AddMimeMapping(".pko", "application/vnd.ms-pki.pko"); + AddMimeMapping(".pko", "application/vndms-pkipko"); + AddMimeMapping(".pl", "text/plain"); + AddMimeMapping(".pl", "text/x-script.perl"); + AddMimeMapping(".plx", "application/x-pixclscript"); + AddMimeMapping(".pm", "image/x-xpixmap"); + AddMimeMapping(".pm", "text/x-script.perl-module"); + AddMimeMapping(".pm4", "application/x-pagemaker"); + AddMimeMapping(".pm5", "application/x-pagemaker"); + AddMimeMapping(".pma", "application/x-perfmon"); + AddMimeMapping(".pmc", "application/x-perfmon"); + AddMimeMapping(".pml", "application/x-perfmon"); + AddMimeMapping(".pmr", "application/x-perfmon"); + AddMimeMapping(".pmw", "application/x-perfmon"); + AddMimeMapping(".png", "image/png"); + AddMimeMapping(".pnm", "application/x-portable-anymap"); + AddMimeMapping(".pnm", "image/x-portable-anymap"); + AddMimeMapping(".pot", "application/mspowerpoint"); + AddMimeMapping(".pot", "application/vnd.ms-powerpoint"); + AddMimeMapping(".potm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"); + AddMimeMapping(".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"); + AddMimeMapping(".pov", "model/x-pov"); + AddMimeMapping(".ppa", "application/vnd.ms-powerpoint"); + AddMimeMapping(".ppm", "image/x-portable-pixmap"); + AddMimeMapping(".pps", "application/mspowerpoint"); + AddMimeMapping(".pps", "application/vnd.ms-powerpoint"); + AddMimeMapping(".ppsm", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"); + AddMimeMapping(".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"); + AddMimeMapping(".ppt", "application/vnd.ms-powerpoint"); + AddMimeMapping(".ppt", "application/mspowerpoint"); + AddMimeMapping(".ppt", "application/powerpoint"); + AddMimeMapping(".ppt", "application/x-mspowerpoint"); + AddMimeMapping(".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"); + AddMimeMapping(".pptt", "application/pptt"); + AddMimeMapping(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); + AddMimeMapping(".ppz", "application/mspowerpoint"); + AddMimeMapping(".pre", "application/x-freelance"); + AddMimeMapping(".prf", "application/pics-rules"); + AddMimeMapping(".prt", "application/pro_eng"); + AddMimeMapping(".ps", "application/postscript"); + AddMimeMapping(".psd", "application/octet-stream"); + AddMimeMapping(".pub", "application/x-mspublisher"); + AddMimeMapping(".pvu", "paleovu/x-pv"); + AddMimeMapping(".pwz", "application/vnd.ms-powerpoint"); + AddMimeMapping(".py", "text/x-script.phyton"); + AddMimeMapping(".pyc", "applicaiton/x-bytecode.python"); + AddMimeMapping(".qcp", "audio/vnd.qcelp"); + AddMimeMapping(".qd3", "x-world/x-3dmf"); + AddMimeMapping(".qd3d", "x-world/x-3dmf"); + AddMimeMapping(".qif", "image/x-quicktime"); + AddMimeMapping(".qt", "video/quicktime"); + AddMimeMapping(".qtc", "video/x-qtc"); + AddMimeMapping(".qti", "image/x-quicktime"); + AddMimeMapping(".qtif", "image/x-quicktime"); + AddMimeMapping(".ra", "audio/x-pn-realaudio"); + AddMimeMapping(".ra", "audio/x-pn-realaudio-plugin"); + AddMimeMapping(".ra", "audio/x-realaudio"); + AddMimeMapping(".ram", "audio/x-pn-realaudio"); + AddMimeMapping(".ras", "application/x-cmu-raster"); + AddMimeMapping(".ras", "image/cmu-raster"); + AddMimeMapping(".ras", "image/x-cmu-raster"); + AddMimeMapping(".rast", "image/cmu-raster"); + AddMimeMapping(".rexx", "text/x-script.rexx"); + AddMimeMapping(".rf", "image/vnd.rn-realflash"); + AddMimeMapping(".rgb", "image/x-rgb"); + AddMimeMapping(".rm", "application/vnd.rn-realmedia"); + AddMimeMapping(".rm", "audio/x-pn-realaudio"); + AddMimeMapping(".rmi", "audio/mid"); + AddMimeMapping(".rmm", "audio/x-pn-realaudio"); + AddMimeMapping(".rmp", "audio/x-pn-realaudio"); + AddMimeMapping(".rmp", "audio/x-pn-realaudio-plugin"); + AddMimeMapping(".rng", "application/ringing-tones"); + AddMimeMapping(".rng", "application/vnd.nokia.ringing-tone"); + AddMimeMapping(".rnx", "application/vnd.rn-realplayer"); + AddMimeMapping(".roff", "application/x-troff"); + AddMimeMapping(".rp", "image/vnd.rn-realpix"); + AddMimeMapping(".rpm", "audio/x-pn-realaudio-plugin"); + AddMimeMapping(".rt", "text/richtext"); + AddMimeMapping(".rt", "text/vnd.rn-realtext"); + AddMimeMapping(".rtf", "application/rtf"); + AddMimeMapping(".rtf", "application/x-rtf"); + AddMimeMapping(".rtf", "text/richtext"); + AddMimeMapping(".rtx", "application/rtf"); + AddMimeMapping(".rtx", "text/richtext"); + AddMimeMapping(".rv", "video/vnd.rn-realvideo"); + AddMimeMapping(".s", "text/x-asm"); + AddMimeMapping(".s3m", "audio/s3m"); + AddMimeMapping(".saveme", "application/octet-stream"); + AddMimeMapping(".sbk", "application/x-tbook"); + AddMimeMapping(".scd", "application/x-msschedule"); + AddMimeMapping(".scm", "application/x-lotusscreencam"); + AddMimeMapping(".scm", "text/x-script.guile"); + AddMimeMapping(".scm", "text/x-script.scheme"); + AddMimeMapping(".scm", "video/x-scm"); + AddMimeMapping(".sct", "text/scriptlet"); + AddMimeMapping(".sdml", "text/plain"); + AddMimeMapping(".sdp", "application/sdp"); + AddMimeMapping(".sdp", "application/x-sdp"); + AddMimeMapping(".sdr", "application/sounder"); + AddMimeMapping(".sea", "application/sea"); + AddMimeMapping(".sea", "application/x-sea"); + AddMimeMapping(".set", "application/set"); + AddMimeMapping(".setpay", "application/set-payment-initiation"); + AddMimeMapping(".setreg", "application/set-registration-initiation"); + AddMimeMapping(".sgm", "text/sgml"); + AddMimeMapping(".sgm", "text/x-sgml"); + AddMimeMapping(".sgml", "text/sgml"); + AddMimeMapping(".sgml", "text/x-sgml"); + AddMimeMapping(".sh", "application/x-bsh"); + AddMimeMapping(".sh", "application/x-sh"); + AddMimeMapping(".sh", "application/x-shar"); + AddMimeMapping(".sh", "text/x-script.sh"); + AddMimeMapping(".shar", "application/x-bsh"); + AddMimeMapping(".shar", "application/x-shar"); + AddMimeMapping(".shtml", "text/html"); + AddMimeMapping(".shtml", "text/x-server-parsed-html"); + AddMimeMapping(".sid", "audio/x-psid"); + AddMimeMapping(".sit", "application/x-sit"); + AddMimeMapping(".sit", "application/x-stuffit"); + AddMimeMapping(".skd", "application/x-koan"); + AddMimeMapping(".skm", "application/x-koan"); + AddMimeMapping(".skp", "application/x-koan"); + AddMimeMapping(".skt", "application/x-koan"); + AddMimeMapping(".sl", "application/x-seelogo"); + AddMimeMapping(".smi", "application/smil"); + AddMimeMapping(".smil", "application/smil"); + AddMimeMapping(".snd", "audio/basic"); + AddMimeMapping(".snd", "audio/x-adpcm"); + AddMimeMapping(".sol", "application/solids"); + AddMimeMapping(".spc", "application/x-pkcs7-certificates"); + AddMimeMapping(".spc", "text/x-speech"); + AddMimeMapping(".spl", "application/futuresplash"); + AddMimeMapping(".spr", "application/x-sprite"); + AddMimeMapping(".sprite", "application/x-sprite"); + AddMimeMapping(".src", "application/x-wais-source"); + AddMimeMapping(".ssi", "text/x-server-parsed-html"); + AddMimeMapping(".ssm", "application/streamingmedia"); + AddMimeMapping(".sst", "application/vnd.ms-pki.certstore"); + AddMimeMapping(".sst", "application/vndms-pkicertstore"); + AddMimeMapping(".step", "application/step"); + AddMimeMapping(".stl", "application/sla"); + AddMimeMapping(".stl", "application/vnd.ms-pki.stl"); + AddMimeMapping(".stl", "application/x-navistyle"); + AddMimeMapping(".stl", "application/vndms-pkistl"); + AddMimeMapping(".stm", "text/html"); + AddMimeMapping(".stp", "application/step"); + AddMimeMapping(".sv4cpio", "application/x-sv4cpio"); + AddMimeMapping(".sv4crc", "application/x-sv4crc"); + AddMimeMapping(".svf", "image/vnd.dwg"); + AddMimeMapping(".svf", "image/x-dwg"); + AddMimeMapping(".svr", "application/x-world"); + AddMimeMapping(".svr", "x-world/x-svr"); + AddMimeMapping(".svg", "image/svg+xml"); + AddMimeMapping(".svgt", "image/svg+xml"); + AddMimeMapping(".swf", "application/x-shockwave-flash"); + AddMimeMapping(".t", "application/x-troff"); + AddMimeMapping(".talk", "text/x-speech"); + AddMimeMapping(".tar", "application/x-tar"); + AddMimeMapping(".tbk", "application/toolbook"); + AddMimeMapping(".tbk", "application/x-tbook"); + AddMimeMapping(".tcl", "application/x-tcl"); + AddMimeMapping(".tcl", "text/x-script.tcl"); + AddMimeMapping(".tcsh", "text/x-script.tcsh"); + AddMimeMapping(".tex", "application/x-tex"); + AddMimeMapping(".texi", "application/x-texinfo"); + AddMimeMapping(".texinfo", "application/x-texinfo"); + AddMimeMapping(".text", "application/plain"); + AddMimeMapping(".text", "text/plain"); + AddMimeMapping(".tgz", "application/x-compressed"); + AddMimeMapping(".tgz", "application/gnutar"); + AddMimeMapping(".tif", "image/tiff"); + AddMimeMapping(".tif", "image/x-tiff"); + AddMimeMapping(".tiff", "image/tiff"); + AddMimeMapping(".tiff", "image/x-tiff"); + AddMimeMapping(".tr", "application/x-troff"); + AddMimeMapping(".trm", "application/x-msterminal"); + AddMimeMapping(".tsi", "audio/tsp-audio"); + AddMimeMapping(".tsp", "application/dsptype"); + AddMimeMapping(".tsp", "audio/tsplayer"); + AddMimeMapping(".tsv", "text/tab-separated-values"); + AddMimeMapping(".turbot", "image/florian"); + AddMimeMapping(".txt", "text/plain"); + AddMimeMapping(".uil", "text/x-uil"); + AddMimeMapping(".uls", "text/iuls"); + AddMimeMapping(".uni", "text/uri-list"); + AddMimeMapping(".unis", "text/uri-list"); + AddMimeMapping(".unv", "application/i-deas"); + AddMimeMapping(".uri", "text/uri-list"); + AddMimeMapping(".uris", "text/uri-list"); + AddMimeMapping(".ustar", "application/x-ustar"); + AddMimeMapping(".ustar", "multipart/x-ustar"); + AddMimeMapping(".uu", "application/octet-stream"); + AddMimeMapping(".uu", "text/x-uuencode"); + AddMimeMapping(".uue", "text/x-uuencode"); + AddMimeMapping(".vcd", "application/x-cdlink"); + AddMimeMapping(".vcf", "text/x-vcard"); + AddMimeMapping(".vcs", "text/x-vcalendar"); + AddMimeMapping(".vda", "application/vda"); + AddMimeMapping(".vdo", "video/vdo"); + AddMimeMapping(".vew", "application/groupwise"); + AddMimeMapping(".viv", "video/vivo"); + AddMimeMapping(".viv", "video/vnd.vivo"); + AddMimeMapping(".vivo", "video/vivo"); + AddMimeMapping(".vivo", "video/vnd.vivo"); + AddMimeMapping(".vmd", "application/vocaltec-media-desc"); + AddMimeMapping(".vmf", "application/vocaltec-media-file"); + AddMimeMapping(".voc", "audio/voc"); + AddMimeMapping(".voc", "audio/x-voc"); + AddMimeMapping(".vos", "video/vosaic"); + AddMimeMapping(".vox", "audio/voxware"); + AddMimeMapping(".vqe", "audio/x-twinvq-plugin"); + AddMimeMapping(".vqf", "audio/x-twinvq"); + AddMimeMapping(".vql", "audio/x-twinvq-plugin"); + AddMimeMapping(".vrml", "application/x-vrml"); + AddMimeMapping(".vrml", "model/vrml"); + AddMimeMapping(".vrml", "x-world/x-vrml"); + AddMimeMapping(".vrt", "x-world/x-vrt"); + AddMimeMapping(".vsd", "application/x-visio"); + AddMimeMapping(".vst", "application/x-visio"); + AddMimeMapping(".vsw", "application/x-visio"); + AddMimeMapping(".w60", "application/wordperfect6.0"); + AddMimeMapping(".w61", "application/wordperfect6.1"); + AddMimeMapping(".w6w", "application/msword"); + AddMimeMapping(".wav", "audio/wav"); + AddMimeMapping(".wav", "audio/x-wav"); + AddMimeMapping(".wb1", "application/x-qpro"); + AddMimeMapping(".wbmp", "image/vnd.wap.wbmp"); + AddMimeMapping(".wcm", "application/vnd.ms-works"); + AddMimeMapping(".wdb", "application/vnd.ms-works"); + AddMimeMapping(".web", "application/vnd.xara"); + AddMimeMapping(".webm", "video/webm"); + AddMimeMapping(".webp", "image/webp"); + AddMimeMapping(".wiz", "application/msword"); + AddMimeMapping(".wk1", "application/x-123"); + AddMimeMapping(".wks", "application/vnd.ms-works"); + AddMimeMapping(".wmf", "windows/metafile"); + AddMimeMapping(".wmf", "application/x-msmetafile"); + AddMimeMapping(".wml", "text/vnd.wap.wml"); + AddMimeMapping(".wmlc", "application/vnd.wap.wmlc"); + AddMimeMapping(".wmls", "text/vnd.wap.wmlscript"); + AddMimeMapping(".wmlsc", "application/vnd.wap.wmlscriptc"); + AddMimeMapping(".woff2", "application/font-woff2"); + AddMimeMapping(".word", "application/msword"); + AddMimeMapping(".wp", "application/wordperfect"); + AddMimeMapping(".wp5", "application/wordperfect"); + AddMimeMapping(".wp5", "application/wordperfect6.0"); + AddMimeMapping(".wp6", "application/wordperfect"); + AddMimeMapping(".wpd", "application/wordperfect"); + AddMimeMapping(".wpd", "application/x-wpwin"); + AddMimeMapping(".wps", "application/vnd.ms-works"); + AddMimeMapping(".wq1", "application/x-lotus"); + AddMimeMapping(".wri", "application/mswrite"); + AddMimeMapping(".wri", "application/x-wri"); + AddMimeMapping(".wri", "application/x-mswrite"); + AddMimeMapping(".wrl", "application/x-world"); + AddMimeMapping(".wrl", "model/vrml"); + AddMimeMapping(".wrl", "x-world/x-vrml"); + AddMimeMapping(".wrz", "model/vrml"); + AddMimeMapping(".wrz", "x-world/x-vrml"); + AddMimeMapping(".wsc", "text/scriplet"); + AddMimeMapping(".wsdl", "text/xml"); + AddMimeMapping(".wsrc", "application/x-wais-source"); + AddMimeMapping(".wtk", "application/x-wintalk"); + AddMimeMapping(".x-png", "image/png"); + AddMimeMapping(".xaf", "x-world/x-vrml"); + AddMimeMapping(".xbm", "image/x-xbitmap"); + AddMimeMapping(".xbm", "image/x-xbm"); + AddMimeMapping(".xbm", "image/xbm"); + AddMimeMapping(".xdr", "video/x-amt-demorun"); + AddMimeMapping(".xgz", "xgl/drawing"); + AddMimeMapping(".xif", "image/vnd.xiff"); + AddMimeMapping(".xl", "application/excel"); + AddMimeMapping(".xla", "application/excel"); + AddMimeMapping(".xla", "application/x-excel"); + AddMimeMapping(".xla", "application/x-msexcel"); + AddMimeMapping(".xla", "application/vnd.ms-excel"); + AddMimeMapping(".xlb", "application/excel"); + AddMimeMapping(".xlb", "application/vnd.ms-excel"); + AddMimeMapping(".xlb", "application/x-excel"); + AddMimeMapping(".xlc", "application/excel"); + AddMimeMapping(".xlc", "application/vnd.ms-excel"); + AddMimeMapping(".xlc", "application/x-excel"); + AddMimeMapping(".xld", "application/excel"); + AddMimeMapping(".xld", "application/x-excel"); + AddMimeMapping(".xlk", "application/excel"); + AddMimeMapping(".xlk", "application/x-excel"); + AddMimeMapping(".xll", "application/excel"); + AddMimeMapping(".xll", "application/vnd.ms-excel"); + AddMimeMapping(".xll", "application/x-excel"); + AddMimeMapping(".xlm", "application/excel"); + AddMimeMapping(".xlm", "application/vnd.ms-excel"); + AddMimeMapping(".xlm", "application/x-excel"); + AddMimeMapping(".xls", "application/vnd.ms-excel"); + AddMimeMapping(".xls", "application/excel"); + AddMimeMapping(".xls", "application/x-excel"); + AddMimeMapping(".xls", "application/x-msexcel"); + AddMimeMapping(".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"); + AddMimeMapping(".xlsm", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + AddMimeMapping(".xlst", "application/xlst"); + AddMimeMapping(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + AddMimeMapping(".xlt", "application/excel"); + AddMimeMapping(".xlt", "application/x-excel"); + AddMimeMapping(".xlt", "application/vnd.ms-excel"); + AddMimeMapping(".xltm", "application/vnd.ms-excel.template.macroEnabled.12"); + AddMimeMapping(".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"); + AddMimeMapping(".xlv", "application/excel"); + AddMimeMapping(".xlv", "application/x-excel"); + AddMimeMapping(".xlw", "application/excel"); + AddMimeMapping(".xlw", "application/vnd.ms-excel"); + AddMimeMapping(".xlw", "application/x-excel"); + AddMimeMapping(".xlw", "application/x-msexcel"); + AddMimeMapping(".xm", "audio/xm"); + AddMimeMapping(".xml", "application/xml"); + AddMimeMapping(".xml", "text/xml"); + AddMimeMapping(".xmz", "xgl/movie"); + AddMimeMapping(".xof", "x-world/x-vrml"); + AddMimeMapping(".xpix", "application/x-vnd.ls-xpix"); + AddMimeMapping(".xpm", "image/x-xpixmap"); + AddMimeMapping(".xpm", "image/xpm"); + AddMimeMapping(".xps", "application/vnd.ms-xpsdocument"); + AddMimeMapping(".xsd", "text/xml"); + AddMimeMapping(".xsl", "text/xml"); + AddMimeMapping(".xsr", "video/x-amt-showrun"); + AddMimeMapping(".xwd", "image/x-xwd"); + AddMimeMapping(".xwd", "image/x-xwindowdump"); + AddMimeMapping(".xyz", "chemical/x-pdb"); + AddMimeMapping(".z", "application/x-compress"); + AddMimeMapping(".z", "application/x-compressed"); + AddMimeMapping(".zip", "application/zip"); + AddMimeMapping(".zip", "application/x-compressed"); + AddMimeMapping(".zip", "application/x-zip-compressed"); + AddMimeSynonym("application/x-zip-compressed", "application/zip"); + AddMimeMapping(".zip", "multipart/x-zip"); + AddMimeMapping(".zoo", "application/octet-stream"); + AddMimeMapping(".zsh", "text/x-script.zsh"); + AddMimeMapping(".*", "application/octet-stream"); + } + + public static string GetExtention(string mimeMapping) + { + if (string.IsNullOrEmpty(mimeMapping)) return null; + + foreach (DictionaryEntry entry in _extensionToMimeMappingTable) + { + var mime = (string)entry.Value; + if (mime == mimeMapping.ToLowerInvariant()) return (string)entry.Key; + if (!_mimeSynonyms.ContainsKey(mime)) continue; + if (_mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; } - public static string GetExtention(string mimeMapping) - { - if (string.IsNullOrEmpty(mimeMapping)) return null; - - foreach (DictionaryEntry entry in _extensionToMimeMappingTable) - { - var mime = (string)entry.Value; - if (mime == mimeMapping.ToLowerInvariant()) return (string)entry.Key; - if (!_mimeSynonyms.ContainsKey(mime)) continue; - if (_mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; - } - - return null; - } + return null; + } - public static string GetMimeMapping(string fileName) - { - string str = null; - var startIndex = fileName.LastIndexOf('.'); - - if (0 <= startIndex && fileName.LastIndexOf('\\') < startIndex) - str = (string)_extensionToMimeMappingTable[fileName.Substring(startIndex)]; - - if (str == null) str = (string)_extensionToMimeMappingTable[".*"]; - - return str; - } - - private static void AddMimeMapping(string extension, string MimeType) - { - if (_extensionToMimeMappingTable.ContainsKey(extension)) - AddMimeSynonym((string)_extensionToMimeMappingTable[extension], MimeType); - - else _extensionToMimeMappingTable.Add(extension, MimeType); - } - - private static void AddMimeSynonym(string mime, string synonym) - { - if (!_mimeSynonyms.ContainsKey(mime)) - _mimeSynonyms[mime] = new List<string>(); - - if (!_mimeSynonyms[mime].Contains(synonym)) - _mimeSynonyms[mime].Add(synonym); - } - } -} \ No newline at end of file + public static string GetMimeMapping(string fileName) + { + string str = null; + var startIndex = fileName.LastIndexOf('.'); + + if (0 <= startIndex && fileName.LastIndexOf('\\') < startIndex) + str = (string)_extensionToMimeMappingTable[fileName.Substring(startIndex)]; + + if (str == null) str = (string)_extensionToMimeMappingTable[".*"]; + + return str; + } + + private static void AddMimeMapping(string extension, string MimeType) + { + if (_extensionToMimeMappingTable.ContainsKey(extension)) + AddMimeSynonym((string)_extensionToMimeMappingTable[extension], MimeType); + + else _extensionToMimeMappingTable.Add(extension, MimeType); + } + + private static void AddMimeSynonym(string mime, string synonym) + { + if (!_mimeSynonyms.ContainsKey(mime)) + _mimeSynonyms[mime] = new List<string>(); + + if (!_mimeSynonyms[mime].Contains(synonym)) + _mimeSynonyms[mime].Add(synonym); + } +} diff --git a/common/ASC.Common/Web/RouteCallInfo.cs b/common/ASC.Common/Web/RouteCallInfo.cs index 547dbaf905..b2b0b1d026 100644 --- a/common/ASC.Common/Web/RouteCallInfo.cs +++ b/common/ASC.Common/Web/RouteCallInfo.cs @@ -23,22 +23,22 @@ * */ -namespace ASC.Common.Web -{ - public class RouteCallInfo - { - public int? Tid { get; set; } - public string Url { get; set; } - public string AttachmentUrl { get; set; } - public bool IsNewRequest { get; set; } - public string Method { get; set; } - public Dictionary<string, object> Params { get; set; } - public bool CleanupHtml { get; set; } - public RouteCallInfo() => CleanupHtml = true; //Default +namespace ASC.Common.Web; - public override string ToString() => - string.Format("{0} {1} T:{2},{3}", Method.ToUpper(), Url, Tid, - string.Join(",", - Params.Select(x => string.Format("{0}={1}", x.Key, x.Value)).ToArray())); - } -} \ No newline at end of file +public class RouteCallInfo +{ + public int? Tid { get; set; } + public string Url { get; set; } + public string AttachmentUrl { get; set; } + public bool IsNewRequest { get; set; } + public string Method { get; set; } + public Dictionary<string, object> Params { get; set; } + public bool CleanupHtml { get; set; } + + public RouteCallInfo() => CleanupHtml = true; //Default + + public override string ToString() => + string.Format("{0} {1} T:{2},{3}", Method.ToUpper(), Url, Tid, + string.Join(",", + Params.Select(x => string.Format("{0}={1}", x.Key, x.Value)).ToArray())); +} diff --git a/common/ASC.Common/Web/VirtualPathUtility.cs b/common/ASC.Common/Web/VirtualPathUtility.cs index 720ecee7ff..f055bf7553 100644 --- a/common/ASC.Common/Web/VirtualPathUtility.cs +++ b/common/ASC.Common/Web/VirtualPathUtility.cs @@ -1,16 +1,15 @@ -namespace ASC.Common.Web +namespace ASC.Common.Web; + +public class VirtualPathUtility { - public class VirtualPathUtility + public static string ToAbsolute(string virtualPath) { - public static string ToAbsolute(string virtualPath) - { - if (string.IsNullOrEmpty(virtualPath)) - return virtualPath; + if (string.IsNullOrEmpty(virtualPath)) + return virtualPath; - if (Uri.IsWellFormedUriString(virtualPath, UriKind.Absolute)) - return virtualPath; + if (Uri.IsWellFormedUriString(virtualPath, UriKind.Absolute)) + return virtualPath; - return "/" + virtualPath.TrimStart('~', '/'); - } + return "/" + virtualPath.TrimStart('~', '/'); } -} \ No newline at end of file +} From 7fddbbcd93a4c8143e95d2fc08e3f9dbdc992f47 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Fri, 4 Feb 2022 11:34:32 +0300 Subject: [PATCH 126/167] ApiCore: rename private static fileds by microsoft convention --- common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs | 8 ++++---- .../Middleware/WebhooksGlobalFilterAttribute.cs | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs index 0636af7bfd..eece12357a 100644 --- a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs +++ b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs @@ -3,7 +3,7 @@ [Scope] public class ProductSecurityFilter : IResourceFilter { - private static readonly IDictionary<string, Guid> _products; + private static readonly IDictionary<string, Guid> s_products; private readonly ILog _logger; private readonly WebItemSecurity _webItemSecurity; private readonly AuthContext _authContext; @@ -17,7 +17,7 @@ public class ProductSecurityFilter : IResourceFilter var wiki = new Guid("742cf945-cbbc-4a57-82d6-1600a12cf8ca"); var photo = new Guid("9d51954f-db9b-4aed-94e3-ed70b914e101"); - _products = new Dictionary<string, Guid> + s_products = new Dictionary<string, Guid> { { "blog", blog }, { "bookmark", bookmark }, @@ -80,11 +80,11 @@ public class ProductSecurityFilter : IResourceFilter if (!string.IsNullOrEmpty(url)) { var module = url.Split('/')[0]; - if (_products.ContainsKey(module)) return _products[module]; + if (s_products.ContainsKey(module)) return s_products[module]; } } - if (_products.ContainsKey(name)) return _products[name]; + if (s_products.ContainsKey(name)) return s_products[name]; return default; } diff --git a/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs b/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs index 1252a1c864..8086ff97ea 100644 --- a/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs +++ b/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs @@ -7,7 +7,7 @@ public class WebhooksGlobalFilterAttribute : ResultFilterAttribute { private readonly IWebhookPublisher _webhookPublisher; private readonly JsonSerializerOptions _jsonSerializerOptions; - private static List<string> _methodList = new List<string> { "POST", "UPDATE", "DELETE" }; + private static List<string> s_methodList = new List<string> { "POST", "UPDATE", "DELETE" }; public WebhooksGlobalFilterAttribute(IWebhookPublisher webhookPublisher, Action<JsonOptions> projectJsonOptions) { @@ -22,7 +22,7 @@ public class WebhooksGlobalFilterAttribute : ResultFilterAttribute { var method = context.HttpContext.Request.Method; - if (!_methodList.Contains(method) || context.Canceled) + if (!s_methodList.Contains(method) || context.Canceled) { base.OnResultExecuted(context); From 1858db913254ab6915051bc474beb668ae0394f4 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Fri, 4 Feb 2022 12:15:54 +0300 Subject: [PATCH 127/167] rename db model --- .../EF/Context/AuditTrailContext.cs | 2 +- .../EF/Context/MessagesContext.cs | 2 +- .../Audit/{AuditEvent.cs => DbAuditEvent.cs} | 290 +++++++++--------- .../Audit/{LoginEvent.cs => DbLoginEvent.cs} | 7 +- 4 files changed, 151 insertions(+), 150 deletions(-) rename common/ASC.Core.Common/EF/Model/Audit/{AuditEvent.cs => DbAuditEvent.cs} (94%) rename common/ASC.Core.Common/EF/Model/Audit/{LoginEvent.cs => DbLoginEvent.cs} (96%) diff --git a/common/ASC.Core.Common/EF/Context/AuditTrailContext.cs b/common/ASC.Core.Common/EF/Context/AuditTrailContext.cs index 72f83381ff..5fb1776c26 100644 --- a/common/ASC.Core.Common/EF/Context/AuditTrailContext.cs +++ b/common/ASC.Core.Common/EF/Context/AuditTrailContext.cs @@ -4,7 +4,7 @@ public class PostgreSqlAuditTrailContext : AuditTrailContext { } public class AuditTrailContext : BaseDbContext { - public DbSet<AuditEvent> AuditEvents { get; set; } + public DbSet<DbAuditEvent> AuditEvents { get; set; } public DbSet<User> Users { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) diff --git a/common/ASC.Core.Common/EF/Context/MessagesContext.cs b/common/ASC.Core.Common/EF/Context/MessagesContext.cs index 04d8885243..478f37d73e 100644 --- a/common/ASC.Core.Common/EF/Context/MessagesContext.cs +++ b/common/ASC.Core.Common/EF/Context/MessagesContext.cs @@ -4,7 +4,7 @@ public class PostgreSqlMessagesContext : MessagesContext { } public class MessagesContext : BaseDbContext { - public DbSet<LoginEvent> LoginEvents { get; set; } + public DbSet<DbLoginEvent> LoginEvents { get; set; } public DbSet<User> Users { get; set; } protected override Dictionary<Provider, Func<BaseDbContext>> ProviderContext diff --git a/common/ASC.Core.Common/EF/Model/Audit/AuditEvent.cs b/common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs similarity index 94% rename from common/ASC.Core.Common/EF/Model/Audit/AuditEvent.cs rename to common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs index 91c7eb7b1c..0026533a32 100644 --- a/common/ASC.Core.Common/EF/Model/Audit/AuditEvent.cs +++ b/common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs @@ -1,145 +1,145 @@ -namespace ASC.Core.Common.EF.Model -{ - public class AuditEvent : MessageEvent - { - public string Initiator { get; set; } - public string Target { get; set; } - } - public static class AuditEventExtension - { - public static ModelBuilderWrapper AddAuditEvent(this ModelBuilderWrapper modelBuilder) - { - modelBuilder - .Add(MySqlAddAuditEvent, Provider.MySql) - .Add(PgSqlAddAuditEvent, Provider.PostgreSql); - return modelBuilder; - } - public static void MySqlAddAuditEvent(this ModelBuilder modelBuilder) - { - modelBuilder.Entity<AuditEvent>(entity => - { - entity.ToTable("audit_events"); - - entity.HasIndex(e => new { e.TenantId, e.Date }) - .HasDatabaseName("date"); - - entity - .Property(e => e.Id) - .HasColumnName("id") - .ValueGeneratedOnAdd(); - - entity.Property(e => e.Action).HasColumnName("action"); - - entity.Property(e => e.Browser) - .HasColumnName("browser") - .HasColumnType("varchar(200)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Date) - .HasColumnName("date") - .HasColumnType("datetime"); - - entity.Property(e => e.Description) - .HasColumnName("description") - .HasColumnType("varchar(20000)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Initiator) - .HasColumnName("initiator") - .HasColumnType("varchar(200)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Ip) - .HasColumnName("ip") - .HasColumnType("varchar(50)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Page) - .HasColumnName("page") - .HasColumnType("varchar(300)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Platform) - .HasColumnName("platform") - .HasColumnType("varchar(200)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.Target) - .HasColumnName("target") - .HasColumnType("text") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - - entity.Property(e => e.TenantId).HasColumnName("tenant_id"); - - entity.Property(e => e.UserId) - .HasColumnName("user_id") - .HasColumnType("char(38)") - .HasCharSet("utf8") - .UseCollation("utf8_general_ci"); - }); - } - public static void PgSqlAddAuditEvent(this ModelBuilder modelBuilder) - { - modelBuilder.Entity<AuditEvent>(entity => - { - entity.ToTable("audit_events", "onlyoffice"); - - entity.HasIndex(e => new { e.TenantId, e.Date }) - .HasDatabaseName("date"); - - entity.Property(e => e.Id).HasColumnName("id"); - - entity.Property(e => e.Action).HasColumnName("action"); - - entity.Property(e => e.Browser) - .HasColumnName("browser") - .HasMaxLength(200) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.Date).HasColumnName("date"); - - entity.Property(e => e.Description) - .HasColumnName("description") - .HasMaxLength(20000) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.Initiator) - .HasColumnName("initiator") - .HasMaxLength(200) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.Ip) - .HasColumnName("ip") - .HasMaxLength(50) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.Page) - .HasColumnName("page") - .HasMaxLength(300) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.Platform) - .HasColumnName("platform") - .HasMaxLength(200) - .HasDefaultValueSql("NULL"); - - entity.Property(e => e.Target).HasColumnName("target"); - - entity.Property(e => e.TenantId).HasColumnName("tenant_id"); - - entity.Property(e => e.UserId) - .HasColumnName("user_id") - .HasMaxLength(38) - .IsFixedLength() - .HasDefaultValueSql("NULL"); - }); - } - } -} +namespace ASC.Core.Common.EF.Model +{ + public class DbAuditEvent : MessageEvent + { + public string Initiator { get; set; } + public string Target { get; set; } + } + public static class AuditEventExtension + { + public static ModelBuilderWrapper AddAuditEvent(this ModelBuilderWrapper modelBuilder) + { + modelBuilder + .Add(MySqlAddAuditEvent, Provider.MySql) + .Add(PgSqlAddAuditEvent, Provider.PostgreSql); + return modelBuilder; + } + public static void MySqlAddAuditEvent(this ModelBuilder modelBuilder) + { + modelBuilder.Entity<DbAuditEvent>(entity => + { + entity.ToTable("audit_events"); + + entity.HasIndex(e => new { e.TenantId, e.Date }) + .HasDatabaseName("date"); + + entity + .Property(e => e.Id) + .HasColumnName("id") + .ValueGeneratedOnAdd(); + + entity.Property(e => e.Action).HasColumnName("action"); + + entity.Property(e => e.Browser) + .HasColumnName("browser") + .HasColumnType("varchar(200)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Date) + .HasColumnName("date") + .HasColumnType("datetime"); + + entity.Property(e => e.Description) + .HasColumnName("description") + .HasColumnType("varchar(20000)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Initiator) + .HasColumnName("initiator") + .HasColumnType("varchar(200)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Ip) + .HasColumnName("ip") + .HasColumnType("varchar(50)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Page) + .HasColumnName("page") + .HasColumnType("varchar(300)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Platform) + .HasColumnName("platform") + .HasColumnType("varchar(200)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.Target) + .HasColumnName("target") + .HasColumnType("text") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + + entity.Property(e => e.TenantId).HasColumnName("tenant_id"); + + entity.Property(e => e.UserId) + .HasColumnName("user_id") + .HasColumnType("char(38)") + .HasCharSet("utf8") + .UseCollation("utf8_general_ci"); + }); + } + public static void PgSqlAddAuditEvent(this ModelBuilder modelBuilder) + { + modelBuilder.Entity<DbAuditEvent>(entity => + { + entity.ToTable("audit_events", "onlyoffice"); + + entity.HasIndex(e => new { e.TenantId, e.Date }) + .HasDatabaseName("date"); + + entity.Property(e => e.Id).HasColumnName("id"); + + entity.Property(e => e.Action).HasColumnName("action"); + + entity.Property(e => e.Browser) + .HasColumnName("browser") + .HasMaxLength(200) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.Date).HasColumnName("date"); + + entity.Property(e => e.Description) + .HasColumnName("description") + .HasMaxLength(20000) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.Initiator) + .HasColumnName("initiator") + .HasMaxLength(200) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.Ip) + .HasColumnName("ip") + .HasMaxLength(50) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.Page) + .HasColumnName("page") + .HasMaxLength(300) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.Platform) + .HasColumnName("platform") + .HasMaxLength(200) + .HasDefaultValueSql("NULL"); + + entity.Property(e => e.Target).HasColumnName("target"); + + entity.Property(e => e.TenantId).HasColumnName("tenant_id"); + + entity.Property(e => e.UserId) + .HasColumnName("user_id") + .HasMaxLength(38) + .IsFixedLength() + .HasDefaultValueSql("NULL"); + }); + } + } +} diff --git a/common/ASC.Core.Common/EF/Model/Audit/LoginEvent.cs b/common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs similarity index 96% rename from common/ASC.Core.Common/EF/Model/Audit/LoginEvent.cs rename to common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs index e08f186815..2257cf3afe 100644 --- a/common/ASC.Core.Common/EF/Model/Audit/LoginEvent.cs +++ b/common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs @@ -1,9 +1,10 @@ namespace ASC.Core.Common.EF.Model { - public class LoginEvent : MessageEvent + public class DbLoginEvent : MessageEvent { public string Login { get; set; } } + public static class LoginEventsExtension { public static ModelBuilderWrapper AddLoginEvents(this ModelBuilderWrapper modelBuilder) @@ -15,7 +16,7 @@ } public static void MySqlAddLoginEvents(this ModelBuilder modelBuilder) { - modelBuilder.Entity<LoginEvent>(entity => + modelBuilder.Entity<DbLoginEvent>(entity => { entity.ToTable("login_events"); @@ -81,7 +82,7 @@ } public static void PgSqlAddLoginEvents(this ModelBuilder modelBuilder) { - modelBuilder.Entity<LoginEvent>(entity => + modelBuilder.Entity<DbLoginEvent>(entity => { entity.ToTable("login_events", "onlyoffice"); From 07bb12ac431a01aae47d1971738d55ec95877a05 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Fri, 4 Feb 2022 12:16:04 +0300 Subject: [PATCH 128/167] rename db model --- common/ASC.MessagingSystem/DbSender/MessagesRepository.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs index 4abbac5d0d..da94f18940 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -149,7 +149,7 @@ namespace ASC.MessagingSystem.DbSender private static void AddLoginEvent(EventMessage message, MessagesContext dbContext) { - var le = new LoginEvent + var le = new DbLoginEvent { Ip = message.IP, Login = message.Initiator, @@ -177,7 +177,7 @@ namespace ASC.MessagingSystem.DbSender private static void AddAuditEvent(EventMessage message, Messages dbContext) { - var ae = new AuditEvent + var ae = new DbAuditEvent { Ip = message.IP, Initiator = message.Initiator, @@ -253,7 +253,7 @@ namespace ASC.MessagingSystem.DbSender public class Messages : MessagesContext { - public DbSet<AuditEvent> AuditEvents { get; set; } + public DbSet<DbAuditEvent> AuditEvents { get; set; } public DbSet<DbTenant> Tenants { get; set; } public DbSet<DbWebstudioSettings> WebstudioSettings { get; set; } } From 8c203b07c21d2d7a916c1ee4757b4b783d7f5df4 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Fri, 4 Feb 2022 12:18:22 +0300 Subject: [PATCH 129/167] rename intermediate model --- .../ASC.AuditTrail/Mappers/AuditActionMapper.cs | 10 +++++----- .../Models/{AuditEventDto.cs => AuditEvent.cs} | 8 ++++---- .../services/ASC.AuditTrail/Models/AuditEventQuery.cs | 2 +- .../Models/{LoginEventDto.cs => LoginEvent.cs} | 8 ++++---- .../services/ASC.AuditTrail/Models/LoginEventQuery.cs | 2 +- .../Models/Mapping/AuditEventMappingAction.cs | 10 +++++----- .../Models/Mapping/LoginEventMappingAction.cs | 4 ++-- .../Repositories/AuditEventsRepository.cs | 10 +++++----- .../Repositories/LoginEventsRepository.cs | 8 ++++---- .../ASC.ClearEvents/ClearEventsServiceLauncher.cs | 2 +- 10 files changed, 32 insertions(+), 32 deletions(-) rename common/services/ASC.AuditTrail/Models/{AuditEventDto.cs => AuditEvent.cs} (90%) rename common/services/ASC.AuditTrail/Models/{LoginEventDto.cs => LoginEvent.cs} (89%) diff --git a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs index 0a268a8f3e..8982c39298 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -47,7 +47,7 @@ public class AuditActionMapper .ToDictionary(x => x.Key, x => x.Value); } - public string GetActionText(AuditEventDto evt) + public string GetActionText(AuditEvent evt) { var action = (MessageAction)evt.Action; if (!_actions.ContainsKey(action)) @@ -77,7 +77,7 @@ public class AuditActionMapper } } - public string GetActionText(LoginEventDTO evt) + public string GetActionText(LoginEvent evt) { var action = (MessageAction)evt.Action; if (!_actions.ContainsKey(action)) @@ -105,7 +105,7 @@ public class AuditActionMapper } } - public string GetActionTypeText(AuditEventDto evt) + public string GetActionTypeText(AuditEvent evt) { var action = (MessageAction)evt.Action; @@ -114,7 +114,7 @@ public class AuditActionMapper : _actions[(MessageAction)evt.Action].GetActionTypeText(); } - public string GetProductText(AuditEventDto evt) + public string GetProductText(AuditEvent evt) { var action = (MessageAction)evt.Action; @@ -123,7 +123,7 @@ public class AuditActionMapper : _actions[(MessageAction)evt.Action].GetProduct(); } - public string GetModuleText(AuditEventDto evt) + public string GetModuleText(AuditEvent evt) { var action = (MessageAction)evt.Action; diff --git a/common/services/ASC.AuditTrail/Models/AuditEventDto.cs b/common/services/ASC.AuditTrail/Models/AuditEvent.cs similarity index 90% rename from common/services/ASC.AuditTrail/Models/AuditEventDto.cs rename to common/services/ASC.AuditTrail/Models/AuditEvent.cs index 14d3cb2356..86420c1cf5 100644 --- a/common/services/ASC.AuditTrail/Models/AuditEventDto.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEvent.cs @@ -25,7 +25,7 @@ namespace ASC.AuditTrail.Models; -public class AuditEventDto : BaseEvent, IMapFrom<AuditEventQuery> +public class AuditEvent : BaseEvent, IMapFrom<AuditEventQuery> { public string Initiator { get; set; } @@ -46,13 +46,13 @@ public class AuditEventDto : BaseEvent, IMapFrom<AuditEventQuery> public void Mapping(Profile profile) { - profile.CreateMap<AuditEvent, AuditEventDto>() + profile.CreateMap<DbAuditEvent, AuditEvent>() .ForMember(src => src.Description, opt => opt.Ignore()); - profile.CreateMap<User, AuditEventDto>() + profile.CreateMap<User, AuditEvent>() .ForMember(src => src.Id, opt => opt.Ignore()); - profile.CreateMap<AuditEventQuery, AuditEventDto>() + profile.CreateMap<AuditEventQuery, AuditEvent>() .IncludeMembers(src => src.AuditEvent, src => src.User) .AfterMap<AuditEventMappingAction>(); } diff --git a/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs b/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs index 7ada06aa20..19bfbe51a9 100644 --- a/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs @@ -2,6 +2,6 @@ public class AuditEventQuery { - public AuditEvent AuditEvent { get; set; } + public DbAuditEvent AuditEvent { get; set; } public User User { get; set; } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/LoginEventDto.cs b/common/services/ASC.AuditTrail/Models/LoginEvent.cs similarity index 89% rename from common/services/ASC.AuditTrail/Models/LoginEventDto.cs rename to common/services/ASC.AuditTrail/Models/LoginEvent.cs index 02861a406f..d8ae4ebea5 100644 --- a/common/services/ASC.AuditTrail/Models/LoginEventDto.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEvent.cs @@ -25,20 +25,20 @@ namespace ASC.AuditTrail.Models; -public class LoginEventDTO : BaseEvent, IMapFrom<LoginEventQuery> +public class LoginEvent : BaseEvent, IMapFrom<LoginEventQuery> { public string Login { get; set; } public int Action { get; set; } public void Mapping(Profile profile) { - profile.CreateMap<LoginEvent, LoginEventDTO>() + profile.CreateMap<DbLoginEvent, LoginEvent>() .ForMember(src => src.Description, opt => opt.Ignore()); - profile.CreateMap<User, LoginEventDTO>() + profile.CreateMap<User, LoginEvent>() .ForMember(src => src.Id, opt => opt.Ignore()); - profile.CreateMap<LoginEventQuery, LoginEventDTO>() + profile.CreateMap<LoginEventQuery, LoginEvent>() .IncludeMembers(src => src.LoginEvents, src => src.User) .AfterMap<LoginEventMappingAction>(); } diff --git a/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs b/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs index 55c2b5b269..796bf3ccd1 100644 --- a/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs @@ -2,6 +2,6 @@ public class LoginEventQuery { - public LoginEvent LoginEvents { get; set; } + public DbLoginEvent LoginEvents { get; set; } public User User { get; set; } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs b/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs index de48d05214..250d9f8c10 100644 --- a/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs +++ b/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs @@ -1,10 +1,10 @@ namespace ASC.AuditTrail.Models.Mapping.Actions; -public class AuditEventMappingAction : IMappingAction<AuditEventQuery, AuditEventDto> +public class AuditEventMappingAction : IMappingAction<AuditEventQuery, AuditEvent> { - private MessageTarget _messageTarget; - private UserFormatter _userFormatter; - private AuditActionMapper _auditActionMapper; + private readonly MessageTarget _messageTarget; + private readonly UserFormatter _userFormatter; + private readonly AuditActionMapper _auditActionMapper; public AuditEventMappingAction( MessageTarget messageTarget, @@ -16,7 +16,7 @@ public class AuditEventMappingAction : IMappingAction<AuditEventQuery, AuditEven _auditActionMapper = auditActionMapper; } - public void Process(AuditEventQuery source, AuditEventDto destination, ResolutionContext context) + public void Process(AuditEventQuery source, AuditEvent destination, ResolutionContext context) { if (source.AuditEvent.Description != null) destination.Description = JsonConvert.DeserializeObject<IList<string>>( diff --git a/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs b/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs index 72ba05c6ba..19770b866b 100644 --- a/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs +++ b/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs @@ -1,6 +1,6 @@ namespace ASC.AuditTrail.Models.Mapping.Actions; -public class LoginEventMappingAction : IMappingAction<LoginEventQuery, LoginEventDTO> +public class LoginEventMappingAction : IMappingAction<LoginEventQuery, LoginEvent> { private readonly UserFormatter _userFormatter; private readonly AuditActionMapper _auditActionMapper; @@ -11,7 +11,7 @@ public class LoginEventMappingAction : IMappingAction<LoginEventQuery, LoginEven _auditActionMapper = auditActionMapper; } - public void Process(LoginEventQuery source, LoginEventDTO destination, ResolutionContext context) + public void Process(LoginEventQuery source, LoginEvent destination, ResolutionContext context) { if (source.LoginEvents.Description != null) destination.Description = JsonConvert.DeserializeObject<IList<string>>( diff --git a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs index 528670e557..faa7713f5a 100644 --- a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs @@ -41,13 +41,13 @@ public class AuditEventsRepository _mapper = mapper; } - public IEnumerable<AuditEventDto> GetLast(int tenant, int chunk) => Get(tenant, null, null, chunk); + public IEnumerable<AuditEvent> GetLast(int tenant, int chunk) => Get(tenant, null, null, chunk); - public IEnumerable<AuditEventDto> Get(int tenant, DateTime from, DateTime to) => Get(tenant, from, to, null); + public IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) => Get(tenant, from, to, null); public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) { - IQueryable<Core.Common.EF.Model.AuditEvent> query = AuditTrailContext.AuditEvents + IQueryable<DbAuditEvent> query = AuditTrailContext.AuditEvents .Where(a => a.TenantId == tenant) .OrderByDescending(a => a.Date); @@ -57,7 +57,7 @@ public class AuditEventsRepository return query.Count(); } - private IEnumerable<AuditEventDto> Get(int tenant, DateTime? fromDate, DateTime? to, int? limit) + private IEnumerable<AuditEvent> Get(int tenant, DateTime? fromDate, DateTime? to, int? limit) { var query = from q in AuditTrailContext.AuditEvents @@ -71,6 +71,6 @@ public class AuditEventsRepository if (limit.HasValue) query = query.Take((int)limit); - return query.AsEnumerable().Select(_mapper.Map<AuditEventDto>).ToList(); + return query.AsEnumerable().Select(_mapper.Map<AuditEvent>).ToList(); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs index f62fcf86be..49374657bf 100644 --- a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs @@ -41,7 +41,7 @@ public class LoginEventsRepository _mapper = mapper; } - public IEnumerable<LoginEventDTO> GetLast(int tenant, int chunk) + public IEnumerable<LoginEvent> GetLast(int tenant, int chunk) { var query = (from b in MessagesContext.LoginEvents @@ -51,10 +51,10 @@ public class LoginEventsRepository select new LoginEventQuery { LoginEvents = b, User = p }) .Take(chunk); - return query.AsEnumerable().Select(_mapper.Map<LoginEventDTO>).ToList(); + return query.AsEnumerable().Select(_mapper.Map<LoginEvent>).ToList(); } - public IEnumerable<LoginEventDTO> Get(int tenant, DateTime fromDate, DateTime to) + public IEnumerable<LoginEvent> Get(int tenant, DateTime fromDate, DateTime to) { var query = from q in MessagesContext.LoginEvents @@ -65,7 +65,7 @@ public class LoginEventsRepository orderby q.Date descending select new LoginEventQuery { LoginEvents = q, User = p }; - return query.AsEnumerable().Select(_mapper.Map<LoginEventDTO>).ToList(); + return query.AsEnumerable().Select(_mapper.Map<LoginEvent>).ToList(); } public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) diff --git a/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs b/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs index 281e4958cd..b297cb929d 100644 --- a/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs +++ b/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs @@ -105,7 +105,7 @@ namespace ASC.Thumbnails.Svc public class Messages : MessagesContext { - public DbSet<AuditEvent> AuditEvents { get; } + public DbSet<DbAuditEvent> AuditEvents { get; } public DbSet<DbTenant> Tenants { get; } public DbSet<DbWebstudioSettings> WebstudioSettings { get; } } From 9f561702dfe6a7cce0d85a27c0d317ef99be376d Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Fri, 4 Feb 2022 12:46:24 +0300 Subject: [PATCH 130/167] Coomon: static private fields renamed as per microsoft convention --- .../Logging/SelfCleaningAppender.cs | 19 ++++++------- .../ASC.Common/Logging/SelfCleaningTarget.cs | 19 ++++++------- .../Security/Authorizing/AzObjectIdHelper.cs | 4 +-- common/ASC.Common/Utils/HtmlUtil.cs | 17 ++++++----- common/ASC.Common/Web/MimeMapping.cs | 28 +++++++++---------- 5 files changed, 42 insertions(+), 45 deletions(-) diff --git a/common/ASC.Common/Logging/SelfCleaningAppender.cs b/common/ASC.Common/Logging/SelfCleaningAppender.cs index 90c346d64c..2de68f3d48 100644 --- a/common/ASC.Common/Logging/SelfCleaningAppender.cs +++ b/common/ASC.Common/Logging/SelfCleaningAppender.cs @@ -27,15 +27,14 @@ namespace ASC.Common.Logging; public class SelfCleaningAppender : RollingFileAppender { - private static DateTime _lastCleanDate; - - private static int? _cleanPeriod; + private static DateTime s_lastCleanDate; + private static int? s_cleanPeriod; protected override void Append(LoggingEvent loggingEvent) { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) + if (DateTime.UtcNow.Date > s_lastCleanDate.Date) { - _lastCleanDate = DateTime.UtcNow.Date; + s_lastCleanDate = DateTime.UtcNow.Date; Clean(); } @@ -44,9 +43,9 @@ public class SelfCleaningAppender : RollingFileAppender protected override void Append(LoggingEvent[] loggingEvents) { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) + if (DateTime.UtcNow.Date > s_lastCleanDate.Date) { - _lastCleanDate = DateTime.UtcNow.Date; + s_lastCleanDate = DateTime.UtcNow.Date; Clean(); } @@ -55,8 +54,8 @@ public class SelfCleaningAppender : RollingFileAppender private static int GetCleanPeriod() { - if (_cleanPeriod != null) - return _cleanPeriod.Value; + if (s_cleanPeriod != null) + return s_cleanPeriod.Value; const string key = "CleanPeriod"; @@ -67,7 +66,7 @@ public class SelfCleaningAppender : RollingFileAppender if (repo != null && repo.Properties.GetKeys().Contains(key)) int.TryParse(repo.Properties[key].ToString(), out value); - _cleanPeriod = value; + s_cleanPeriod = value; return value; } diff --git a/common/ASC.Common/Logging/SelfCleaningTarget.cs b/common/ASC.Common/Logging/SelfCleaningTarget.cs index 1a3fe0a3b0..96cd4b1f10 100644 --- a/common/ASC.Common/Logging/SelfCleaningTarget.cs +++ b/common/ASC.Common/Logging/SelfCleaningTarget.cs @@ -30,15 +30,14 @@ namespace ASC.Common.Logging; [Target("SelfCleaning")] public class SelfCleaningTarget : FileTarget { - private static DateTime _lastCleanDate; - - private static int? _cleanPeriod; + private static DateTime s_lastCleanDate; + private static int? s_cleanPeriod; protected override void Write(IList<AsyncLogEventInfo> logEvents) { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) + if (DateTime.UtcNow.Date > s_lastCleanDate.Date) { - _lastCleanDate = DateTime.UtcNow.Date; + s_lastCleanDate = DateTime.UtcNow.Date; Clean(); } @@ -57,9 +56,9 @@ public class SelfCleaningTarget : FileTarget protected override void Write(LogEventInfo logEvent) { - if (DateTime.UtcNow.Date > _lastCleanDate.Date) + if (DateTime.UtcNow.Date > s_lastCleanDate.Date) { - _lastCleanDate = DateTime.UtcNow.Date; + s_lastCleanDate = DateTime.UtcNow.Date; Clean(); } @@ -68,8 +67,8 @@ public class SelfCleaningTarget : FileTarget private static int GetCleanPeriod() { - if (_cleanPeriod != null) - return _cleanPeriod.Value; + if (s_cleanPeriod != null) + return s_cleanPeriod.Value; var value = 30; @@ -83,7 +82,7 @@ public class SelfCleaningTarget : FileTarget int.TryParse(variable.Text, out value); } - _cleanPeriod = value; + s_cleanPeriod = value; return value; } diff --git a/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs b/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs index 87eade24d5..3cdd70de85 100644 --- a/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs +++ b/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs @@ -28,12 +28,12 @@ namespace ASC.Common.Security.Authorizing; public static class AzObjectIdHelper { - private static readonly string separator = "|"; + private static readonly string s_separator = "|"; public static string GetFullObjectId(ISecurityObjectId objectId) { if (objectId == null) return null; - return $"{objectId.ObjectType.FullName}{separator}{objectId.SecurityId}"; + return $"{objectId.ObjectType.FullName}{s_separator}{objectId.SecurityId}"; } } diff --git a/common/ASC.Common/Utils/HtmlUtil.cs b/common/ASC.Common/Utils/HtmlUtil.cs index 2d4bb297e0..b991d199c7 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -27,36 +27,35 @@ namespace ASC.Common.Utils; public static class HtmlUtil { - private static readonly Regex _tagReplacer + private static readonly Regex s_tagReplacer = new Regex("<[^>]*>", RegexOptions.Multiline | RegexOptions.Compiled); - private static readonly Regex _commentsReplacer + private static readonly Regex s_commentsReplacer = new Regex("<!--(?s).*?-->", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex _xssReplacer + private static readonly Regex s_xssReplacer = new Regex(@"<\s*(style|script)[^>]*>(.*?)<\s*/\s*(style|script)>", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Singleline); - private static readonly Regex _worder = + private static readonly Regex s_worder = new Regex(@"\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - public static string GetText(string html, int maxLength = 0, string endBlockTemplate = "...") { var unformatedText = string.Empty; if (!string.IsNullOrEmpty(html)) { - html = _xssReplacer.Replace(html, string.Empty); //Clean malicious tags. <script> <style> + html = s_xssReplacer.Replace(html, string.Empty); //Clean malicious tags. <script> <style> if (string.IsNullOrEmpty(html)) return html; - unformatedText = _tagReplacer.Replace(html, string.Empty); + unformatedText = s_tagReplacer.Replace(html, string.Empty); if (!string.IsNullOrEmpty(unformatedText)) { // kill comments - unformatedText = _commentsReplacer.Replace(unformatedText, string.Empty); + unformatedText = s_commentsReplacer.Replace(unformatedText, string.Empty); unformatedText = unformatedText.Trim(); if (!string.IsNullOrEmpty(unformatedText)) @@ -97,7 +96,7 @@ public static class HtmlUtil { if (string.IsNullOrEmpty(searchText) || string.IsNullOrEmpty(htmlText)) return htmlText; - var regexpstr = _worder.Matches(searchText).Cast<Match>().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); + var regexpstr = s_worder.Matches(searchText).Cast<Match>().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); var wordsFinder = new Regex(Regex.Escape(regexpstr), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline); return wordsFinder.Replace(htmlText, m => string.Format("<span class='searchTextHighlight{1}'>{0}</span>", m.Value, withoutLink ? " bold" : string.Empty)); diff --git a/common/ASC.Common/Web/MimeMapping.cs b/common/ASC.Common/Web/MimeMapping.cs index 7ebd83b1f7..a6af276230 100644 --- a/common/ASC.Common/Web/MimeMapping.cs +++ b/common/ASC.Common/Web/MimeMapping.cs @@ -27,8 +27,8 @@ namespace ASC.Common.Web; public static class MimeMapping { - private static readonly Hashtable _extensionToMimeMappingTable = new Hashtable(200, StringComparer.CurrentCultureIgnoreCase); - private static readonly IDictionary<string, IList<string>> _mimeSynonyms = new Dictionary<string, IList<string>>(); + private static readonly Hashtable s_extensionToMimeMappingTable = new Hashtable(200, StringComparer.CurrentCultureIgnoreCase); + private static readonly IDictionary<string, IList<string>> s_mimeSynonyms = new Dictionary<string, IList<string>>(); static MimeMapping() { @@ -810,12 +810,12 @@ public static class MimeMapping { if (string.IsNullOrEmpty(mimeMapping)) return null; - foreach (DictionaryEntry entry in _extensionToMimeMappingTable) + foreach (DictionaryEntry entry in s_extensionToMimeMappingTable) { var mime = (string)entry.Value; if (mime == mimeMapping.ToLowerInvariant()) return (string)entry.Key; - if (!_mimeSynonyms.ContainsKey(mime)) continue; - if (_mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; + if (!s_mimeSynonyms.ContainsKey(mime)) continue; + if (s_mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; } return null; @@ -827,27 +827,27 @@ public static class MimeMapping var startIndex = fileName.LastIndexOf('.'); if (0 <= startIndex && fileName.LastIndexOf('\\') < startIndex) - str = (string)_extensionToMimeMappingTable[fileName.Substring(startIndex)]; + str = (string)s_extensionToMimeMappingTable[fileName.Substring(startIndex)]; - if (str == null) str = (string)_extensionToMimeMappingTable[".*"]; + if (str == null) str = (string)s_extensionToMimeMappingTable[".*"]; return str; } private static void AddMimeMapping(string extension, string MimeType) { - if (_extensionToMimeMappingTable.ContainsKey(extension)) - AddMimeSynonym((string)_extensionToMimeMappingTable[extension], MimeType); + if (s_extensionToMimeMappingTable.ContainsKey(extension)) + AddMimeSynonym((string)s_extensionToMimeMappingTable[extension], MimeType); - else _extensionToMimeMappingTable.Add(extension, MimeType); + else s_extensionToMimeMappingTable.Add(extension, MimeType); } private static void AddMimeSynonym(string mime, string synonym) { - if (!_mimeSynonyms.ContainsKey(mime)) - _mimeSynonyms[mime] = new List<string>(); + if (!s_mimeSynonyms.ContainsKey(mime)) + s_mimeSynonyms[mime] = new List<string>(); - if (!_mimeSynonyms[mime].Contains(synonym)) - _mimeSynonyms[mime].Add(synonym); + if (!s_mimeSynonyms[mime].Contains(synonym)) + s_mimeSynonyms[mime].Add(synonym); } } From 6d841257f107a9a69718540075294e6d505a1270 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Fri, 4 Feb 2022 12:56:15 +0300 Subject: [PATCH 131/167] Common: add IServiceScopeFactory --- .../Threading/DistributedTaskQueue.cs | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/common/ASC.Common/Threading/DistributedTaskQueue.cs b/common/ASC.Common/Threading/DistributedTaskQueue.cs index ce95eb3638..726c20c0d4 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -87,11 +87,16 @@ public class ConfigureDistributedTaskQueue : IConfigureNamedOptions<DistributedT { private DistributedTaskCacheNotify DistributedTaskCacheNotify { get; } public IServiceProvider ServiceProvider { get; } + public IServiceScopeFactory ServiceScopeFactory { get; } - public ConfigureDistributedTaskQueue(DistributedTaskCacheNotify distributedTaskCacheNotify, IServiceProvider serviceProvider) + public ConfigureDistributedTaskQueue( + DistributedTaskCacheNotify distributedTaskCacheNotify, + IServiceProvider serviceProvider, + IServiceScopeFactory serviceScopeFactory) { DistributedTaskCacheNotify = distributedTaskCacheNotify; ServiceProvider = serviceProvider; + ServiceScopeFactory = serviceScopeFactory; } public void Configure(DistributedTaskQueue queue) @@ -110,6 +115,7 @@ public class ConfigureDistributedTaskQueue : IConfigureNamedOptions<DistributedT public class DistributedTaskQueue { public IServiceProvider ServiceProvider { get; set; } + public IServiceScopeFactory ServiceScopeFactory { get; set; } public DistributedTaskCacheNotify DistributedTaskCacheNotify { get; set; } public string Name { @@ -123,18 +129,17 @@ public class DistributedTaskQueue : new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, value).ConcurrentScheduler; } - public static readonly int InstanceId; - - private TaskScheduler Scheduler { get; set; } = TaskScheduler.Default; private ICache Cache => DistributedTaskCacheNotify.Cache; + private TaskScheduler Scheduler { get; set; } = TaskScheduler.Default; + + public static readonly int InstanceId; + private string _name; + private ConcurrentDictionary<string, CancellationTokenSource> Cancelations => DistributedTaskCacheNotify.Cancelations; - private string _name; - static DistributedTaskQueue() => InstanceId = Process.GetCurrentProcess().Id; - public void QueueTask(DistributedTaskProgress taskProgress) => QueueTask((a, b) => taskProgress.RunJob(), taskProgress); @@ -199,7 +204,7 @@ public class DistributedTaskQueue var cache = Cache.HashGet<DistributedTaskCache>(_name, id); if (cache != null) { - using var scope = ServiceProvider.CreateScope(); + using var scope = ServiceScopeFactory.CreateScope(); var task = scope.ServiceProvider.GetService<T>(); task.DistributedTaskCache = cache; From eed733b83cee28ba34b66299bc9869088c211cd0 Mon Sep 17 00:00:00 2001 From: Alexey Bannov <alexey.bannov@onlyoffice.com> Date: Fri, 4 Feb 2022 20:59:58 +0300 Subject: [PATCH 132/167] fixed user photo thumbnail generator --- common/ASC.Core.Common/Data/DbSettingsManager.cs | 7 ++++++- web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs | 10 +++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/common/ASC.Core.Common/Data/DbSettingsManager.cs b/common/ASC.Core.Common/Data/DbSettingsManager.cs index d83a3c85d7..f17b2f1027 100644 --- a/common/ASC.Core.Common/Data/DbSettingsManager.cs +++ b/common/ASC.Core.Common/Data/DbSettingsManager.cs @@ -326,7 +326,12 @@ namespace ASC.Core.Data private T Deserialize<T>(string data) { - return JsonSerializer.Deserialize<T>(data); + var options = new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }; + + return JsonSerializer.Deserialize<T>(data, options); } private string Serialize<T>(T settings) diff --git a/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs b/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs index d58dbc6f7d..fe1279878c 100644 --- a/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs @@ -78,16 +78,20 @@ namespace ASC.Web.Core.Users var x = thumbnailSettings.Point.X > 0 ? thumbnailSettings.Point.X : 0; var y = thumbnailSettings.Point.Y > 0 ? thumbnailSettings.Point.Y : 0; + var width = x + thumbnailSettings.Size.Width > mainImg.Width ? mainImg.Width : thumbnailSettings.Size.Width; + var height = y + thumbnailSettings.Size.Height > mainImg.Height ? mainImg.Height : thumbnailSettings.Size.Height; + var rect = new Rectangle(x, y, - thumbnailSettings.Size.Width, - thumbnailSettings.Size.Height); + width, + height); Image destRound = mainImg.Clone(x => x.Crop(rect).Resize(new ResizeOptions { Size = size, Mode = ResizeMode.Stretch - })); + })); + return destRound; } } From 42bcb87eeb42c5080c4b1ff54165e6dbb1031572 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Mon, 7 Feb 2022 17:05:12 +0300 Subject: [PATCH 133/167] fixed the inability to create a folder named data in projects --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index ba34bff1df..b43bdf73eb 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,7 @@ /build/deploy *.log /products/ASC.People/Data/ -Data/ +/Data Logs/ **/.DS_Store .eslintcache From e00657439d03d21a420972c3876629398d1ad416 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Mon, 7 Feb 2022 17:06:00 +0300 Subject: [PATCH 134/167] ClearEvents: add events context --- common/services/ASC.ClearEvents/Data/EventsContext.cs | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 common/services/ASC.ClearEvents/Data/EventsContext.cs diff --git a/common/services/ASC.ClearEvents/Data/EventsContext.cs b/common/services/ASC.ClearEvents/Data/EventsContext.cs new file mode 100644 index 0000000000..ead0a53770 --- /dev/null +++ b/common/services/ASC.ClearEvents/Data/EventsContext.cs @@ -0,0 +1,7 @@ +namespace ASC.ClearEvents.Data; + +public class EventsContext : MessagesContext +{ + public DbSet<DbTenant> Tenants { get; set; } + public DbSet<DbWebstudioSettings> WebstudioSettings { get; set; } +} \ No newline at end of file From 9e583e60cb04c1ef54d3024d83714906d281096c Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Mon, 7 Feb 2022 17:06:25 +0300 Subject: [PATCH 135/167] add AuditEvents dbset and model configuration --- common/ASC.Core.Common/EF/Context/MessagesContext.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/common/ASC.Core.Common/EF/Context/MessagesContext.cs b/common/ASC.Core.Common/EF/Context/MessagesContext.cs index 341db18625..8e0d63ac27 100644 --- a/common/ASC.Core.Common/EF/Context/MessagesContext.cs +++ b/common/ASC.Core.Common/EF/Context/MessagesContext.cs @@ -4,6 +4,7 @@ public class PostgreSqlMessagesContext : MessagesContext { } public class MessagesContext : BaseDbContext { + public DbSet<AuditEvent> AuditEvents { get; set; } public DbSet<LoginEvents> LoginEvents { get; set; } public DbSet<User> Users { get; set; } @@ -23,6 +24,7 @@ { ModelBuilderWrapper .From(modelBuilder, Provider) + .AddAuditEvent() .AddLoginEvents() .AddUser() .AddDbFunction(); From da1914638151ea6b911bbb76098f694f3cf61d8c Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Mon, 7 Feb 2022 17:07:22 +0300 Subject: [PATCH 136/167] ClearEvents: rename TimedClearEventsService to ClearEventsService --- ...EventsService.cs => ClearEventsService.cs} | 24 +++++-------------- 1 file changed, 6 insertions(+), 18 deletions(-) rename common/services/ASC.ClearEvents/Services/{TimedClearEventsService.cs => ClearEventsService.cs} (83%) diff --git a/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs b/common/services/ASC.ClearEvents/Services/ClearEventsService.cs similarity index 83% rename from common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs rename to common/services/ASC.ClearEvents/Services/ClearEventsService.cs index cf4a7d3e30..7fd2764bf1 100644 --- a/common/services/ASC.ClearEvents/Services/TimedClearEventsService.cs +++ b/common/services/ASC.ClearEvents/Services/ClearEventsService.cs @@ -25,14 +25,14 @@ namespace ASC.ClearEvents.Services; -[Scope(Additional = typeof(MessagesRepositoryExtension))] -public class TimedClearEventsService : IHostedService, IDisposable +[Scope] +public class ClearEventsService : IHostedService, IDisposable { private readonly ILog _logger; private readonly IServiceScopeFactory _serviceScopeFactory; private Timer _timer = null!; - public TimedClearEventsService(IOptionsMonitor<ILog> options, IServiceScopeFactory serviceScopeFactory) + public ClearEventsService(IOptionsMonitor<ILog> options, IServiceScopeFactory serviceScopeFactory) { _logger = options.CurrentValue; _serviceScopeFactory = serviceScopeFactory; @@ -43,7 +43,7 @@ public class TimedClearEventsService : IHostedService, IDisposable _logger.Info("Timer Clear Events Service running."); _timer = new Timer(DeleteOldEvents, null, TimeSpan.Zero, - TimeSpan.FromDays(1)); + TimeSpan.FromSeconds(15)); return Task.CompletedTask; } @@ -80,14 +80,14 @@ public class TimedClearEventsService : IHostedService, IDisposable } } - private void GetOldEvents<T>(Expression<Func<Messages, DbSet<T>>> func, string settings) where T : MessageEvent + private void GetOldEvents<T>(Expression<Func<EventsContext, DbSet<T>>> func, string settings) where T : MessageEvent { List<T> ids; var compile = func.Compile(); do { using var scope = _serviceScopeFactory.CreateScope(); - using var ef = scope.ServiceProvider.GetService<DbContextManager<Messages>>().Get("messages"); + using var ef = scope.ServiceProvider.GetService<DbContextManager<EventsContext>>().Get("messages"); var table = compile.Invoke(ef); var ae = table @@ -115,16 +115,4 @@ public class TimedClearEventsService : IHostedService, IDisposable } while (ids.Any()); } -} - -public class Messages : MessagesContext -{ - public DbSet<AuditEvent> AuditEvents { get; } - public DbSet<DbTenant> Tenants { get; } - public DbSet<DbWebstudioSettings> WebstudioSettings { get; } -} - -public class MessagesRepositoryExtension -{ - public static void Register(DIHelper services) => services.TryAdd<DbContextManager<Messages>>(); } \ No newline at end of file From 69c20291cc1ae7f4f61ef41d6d5dec67df415867 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Mon, 7 Feb 2022 17:07:36 +0300 Subject: [PATCH 137/167] ClearEvents: add service --- common/services/ASC.ClearEvents/Program.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/common/services/ASC.ClearEvents/Program.cs b/common/services/ASC.ClearEvents/Program.cs index 2dce2843e1..8992c072e4 100644 --- a/common/services/ASC.ClearEvents/Program.cs +++ b/common/services/ASC.ClearEvents/Program.cs @@ -68,8 +68,9 @@ builder.Host.ConfigureServices((hostContext, services) => else diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); - services.AddHostedService<TimedClearEventsService>(); - diHelper.TryAdd<TimedClearEventsService>(); + services.AddHostedService<ClearEventsService>(); + diHelper.TryAdd<ClearEventsService>(); + diHelper.TryAdd<DbContextManager<EventsContext>>(); }); builder.Host.ConfigureContainer<ContainerBuilder>((context, builder) => From bcb7005ce63cd96d9745c3e77f3302a7c0dec7a4 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Mon, 7 Feb 2022 17:07:48 +0300 Subject: [PATCH 138/167] ClearEvents: add using --- common/services/ASC.ClearEvents/GlobalUsings.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/common/services/ASC.ClearEvents/GlobalUsings.cs b/common/services/ASC.ClearEvents/GlobalUsings.cs index b8522744e2..b2f4380e8d 100644 --- a/common/services/ASC.ClearEvents/GlobalUsings.cs +++ b/common/services/ASC.ClearEvents/GlobalUsings.cs @@ -8,6 +8,7 @@ global using System.Threading.Tasks; global using ASC.Api.Core; global using ASC.ClearEvents.Services; +global using ASC.ClearEvents.Data; global using ASC.Common; global using ASC.Common.Utils; global using ASC.Common.Caching; From 812241a69abaffddc9cb9af5c43793ce4079f5a2 Mon Sep 17 00:00:00 2001 From: pavelbannov <pavel.bannov@onlyoffice.com> Date: Mon, 7 Feb 2022 17:53:58 +0300 Subject: [PATCH 139/167] Analyzers: fix --- common/ASC.Common/Utils/HtmlUtil.cs | 2 +- .../ASC.Core.Common/Data/DbTenantService.cs | 5 ++-- .../Tasks/BackupPortalTask.cs | 10 +++---- .../Tasks/RestorePortalTask.cs | 16 +++++++++-- .../ReassignProgressItem.cs | 1 + .../ASC.Data.Reassigns/RemoveProgressItem.cs | 3 ++- common/ASC.FederatedLogin/AccountLinker.cs | 5 ++-- .../Data/FeedAggregateDataProvider.cs | 2 +- .../States/HeaderFormatterState.cs | 4 +-- common/ASC.VoipService/Dao/VoipDao.cs | 9 ++++--- .../ASC.Webhooks.Core.csproj | 11 ++++---- .../Properties/launchSettings.json | 27 ------------------- .../Mappers/AuditActionMapper.cs | 4 +-- .../ASC.ElasticSearch/Engine/BaseIndexer.cs | 17 ++++++++---- .../Service/FeedAggregatorService.cs | 4 +-- .../Core/Core/Dao/TeamlabDao/FileDao.cs | 7 +++-- .../Core/Core/Dao/TeamlabDao/TagDao.cs | 2 +- .../Core/Core/Entries/EditHistory.cs | 4 +-- .../ASC.Files/Core/Core/Entries/FileHelper.cs | 10 ++----- .../Core/HttpHandlers/FileHandler.ashx.cs | 13 ++++++--- .../DocbuilderReportsUtility.cs | 2 +- .../DocumentService/DocumentServiceHelper.cs | 4 +-- .../FileOperations/FileDownloadOperation.cs | 11 ++++---- .../ASC.Files/Core/Utils/FileConverter.cs | 3 ++- .../ASC.Files/Core/Utils/MailMergeTask.cs | 25 +++++++++++++++-- .../Server/Controllers/PeopleController.cs | 17 ++++++++++-- web/ASC.Web.Core/Sms/SmsManager.cs | 2 +- web/ASC.Web.Core/Sms/SmsProvider.cs | 4 +-- web/ASC.Web.Core/Utility/TenantExtra.cs | 8 +++--- web/ASC.Web.Core/WebItemManager.cs | 7 +++-- 30 files changed, 137 insertions(+), 102 deletions(-) delete mode 100644 common/ASC.Webhooks.Core/Properties/launchSettings.json diff --git a/common/ASC.Common/Utils/HtmlUtil.cs b/common/ASC.Common/Utils/HtmlUtil.cs index ff90d5e5bb..3837d983d4 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -104,7 +104,7 @@ namespace ASC.Common.Utils var regexpstr = Worder.Matches(searchText).Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); var wordsFinder = new Regex(Regex.Escape(regexpstr), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline); - return wordsFinder.Replace(htmlText, m => "<span class='searchTextHighlight" + (withoutLink ? " bold" : string.Empty) + "'>{0}</span>"); + return wordsFinder.Replace(htmlText, m => "<span class='searchTextHighlight" + (withoutLink ? " bold" : string.Empty) + "'>" + m.Value + "</span>"); } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Data/DbTenantService.cs b/common/ASC.Core.Common/Data/DbTenantService.cs index a4ded10215..f87e802feb 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -228,7 +228,8 @@ namespace ASC.Core.Data .Where(r => r.Email == login) .Where(r => r.Status == EmployeeStatus.Active) .Where(r => !r.Removed) - .Select(r => r.Id); + .Select(r => r.Id) + .ToList(); var passwordHashs = usersQuery.Select(r => GetPasswordHash(r, passwordHash)).ToList(); @@ -253,7 +254,7 @@ namespace ASC.Core.Data public Tenant GetTenant(string domain) { if (string.IsNullOrEmpty(domain)) throw new ArgumentNullException(nameof(domain)); - + domain = domain.ToLowerInvariant(); return TenantsQuery() diff --git a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs index 5a0f1b8b58..046e82f3fa 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -320,7 +320,7 @@ namespace ASC.Data.Backup.Tasks { using var connection = DbFactory.OpenConnection(); var command = connection.CreateCommand(); - command.CommandText = $"select max({primaryIndex}), min({primaryIndex}) from {t}"; + command.CommandText = $"select max({primaryIndex}), min({primaryIndex}) from {t}"; var minMax = ExecuteList(command).ConvertAll(r => new Tuple<int, int>(Convert.ToInt32(r[0]), Convert.ToInt32(r[1]))).FirstOrDefault(); primaryIndexStart = minMax.Item2; primaryIndexStep = (minMax.Item1 - minMax.Item2) / count; @@ -391,9 +391,9 @@ namespace ASC.Data.Backup.Tasks private void SaveToFile(string path, string t, IReadOnlyCollection<string> columns, List<object[]> data) { - Logger.DebugFormat("save to file {0}", t); - List<object[]> portion = data.Take(BatchLimit).ToList(); - while (portion.Count > 0) + Logger.DebugFormat("save to file {0}", t); + List<object[]> portion; + while ((portion = data.Take(BatchLimit).ToList()).Count > 0) { using (var sw = new StreamWriter(path, true)) using (var writer = new JsonTextWriter(sw)) @@ -410,7 +410,7 @@ namespace ASC.Data.Backup.Tasks for (var i = 0; i < obj.Length; i++) { - var value = obj[i]; + var value = obj[i]; if (value is byte[] byteArray) { sw.Write("0x"); diff --git a/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs b/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs index 5dc5985a30..ffcafd2855 100644 --- a/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs @@ -368,9 +368,21 @@ namespace ASC.Data.Backup.Tasks private void SetTenantActive(int tenantId) { - using var connection = DbFactory.OpenConnection(); + using var connection = DbFactory.OpenConnection(); + var commandText = string.Format( + "update tenants_tenants " + + "set " + + " status={0}, " + + " last_modified='{1}', " + + " statuschanged='{1}' " + + "where id = '{2}'", + (int)TenantStatus.Active, + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"), + tenantId); - connection.CreateCommand().WithTimeout(120).ExecuteNonQuery(); + var command = connection.CreateCommand().WithTimeout(120); + command.CommandText = commandText; + command.ExecuteNonQuery(); } } } diff --git a/common/ASC.Data.Reassigns/ReassignProgressItem.cs b/common/ASC.Data.Reassigns/ReassignProgressItem.cs index 4606febd22..ccd69d8665 100644 --- a/common/ASC.Data.Reassigns/ReassignProgressItem.cs +++ b/common/ASC.Data.Reassigns/ReassignProgressItem.cs @@ -102,6 +102,7 @@ namespace ASC.Data.Reassigns var scopeClass = scope.ServiceProvider.GetService<ReassignProgressItemScope>(); var (tenantManager, coreBaseSettings, messageService, studioNotifyService, securityContext, userManager, userPhotoManager, displayUserSettingsHelper, messageTarget, options) = scopeClass; var logger = options.Get("ASC.Web"); + tenantManager.SetCurrentTenant(_tenantId); try { diff --git a/common/ASC.Data.Reassigns/RemoveProgressItem.cs b/common/ASC.Data.Reassigns/RemoveProgressItem.cs index f035389f52..f71393935e 100644 --- a/common/ASC.Data.Reassigns/RemoveProgressItem.cs +++ b/common/ASC.Data.Reassigns/RemoveProgressItem.cs @@ -97,7 +97,8 @@ namespace ASC.Data.Reassigns using var scope = ServiceProvider.CreateScope(); var scopeClass = scope.ServiceProvider.GetService<RemoveProgressItemScope>(); var (tenantManager, coreBaseSettings, messageService, studioNotifyService, securityContext, userManager, messageTarget, webItemManagerSecurity, storageFactory, userFormatter, options) = scopeClass; - var logger = options.Get("ASC.Web"); + var logger = options.Get("ASC.Web"); + tenantManager.SetCurrentTenant(_tenantId); var userName = userFormatter.GetUserName(User, DisplayUserNameFormat.Default); try diff --git a/common/ASC.FederatedLogin/AccountLinker.cs b/common/ASC.FederatedLogin/AccountLinker.cs index 45794e2c74..4cee029002 100644 --- a/common/ASC.FederatedLogin/AccountLinker.cs +++ b/common/ASC.FederatedLogin/AccountLinker.cs @@ -169,8 +169,9 @@ namespace ASC.FederatedLogin //Retrieve by uinque id return AccountLinks .Where(r => r.Id == obj) - .Select(x => LoginProfile.CreateFromSerializedString(Signature, InstanceCrypto, x.Profile)) - .ToList(); + .Select(r => r.Profile) + .ToList() + .ConvertAll(x => LoginProfile.CreateFromSerializedString(Signature, InstanceCrypto, x)); } public void AddLink(string obj, LoginProfile profile) diff --git a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs index 9a9d1c4129..134c1cc2cd 100644 --- a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs +++ b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs @@ -244,7 +244,7 @@ namespace ASC.Feed.Data q = q.Where(r => keys.Any(k => r.aggregates.Keywords.StartsWith(k))); } - var news = q.Select(r => r.aggregates); + var news = q.Select(r => r.aggregates).ToList(); return news.Select(r => new FeedResultItem( r.Json, diff --git a/common/ASC.Textile/States/HeaderFormatterState.cs b/common/ASC.Textile/States/HeaderFormatterState.cs index bd28563a05..0f091116b1 100644 --- a/common/ASC.Textile/States/HeaderFormatterState.cs +++ b/common/ASC.Textile/States/HeaderFormatterState.cs @@ -32,7 +32,7 @@ namespace Textile.States { for (var i = 0; i < HeaderLevel; i++) { - Formatter.Output.Write("<br {0}/>"); + Formatter.Output.Write($"<br {FormattedStylesAndAlignment("br")}/>"); } } @@ -77,7 +77,7 @@ namespace Textile.States public override void Enter() { - Formatter.Output.Write("<h"+ HeaderLevel + FormattedStylesAndAlignment("h" + HeaderLevel) + ">"); + Formatter.Output.Write("<h" + HeaderLevel + FormattedStylesAndAlignment("h" + HeaderLevel) + ">"); } public override void Exit() diff --git a/common/ASC.VoipService/Dao/VoipDao.cs b/common/ASC.VoipService/Dao/VoipDao.cs index 650430d80a..bb025abcaa 100644 --- a/common/ASC.VoipService/Dao/VoipDao.cs +++ b/common/ASC.VoipService/Dao/VoipDao.cs @@ -93,7 +93,8 @@ namespace ASC.VoipService.Dao { return VoipDbContext.VoipNumbers .Where(r => r.TenantId == TenantID) - .Select(ToPhone); + .ToList() + .ConvertAll(ToPhone); } public virtual IEnumerable<VoipPhone> GetNumbers(params string[] ids) @@ -105,7 +106,7 @@ namespace ASC.VoipService.Dao numbers = numbers.Where(r => ids.Any(a => a == r.Number || a == r.Id)); } - return numbers.Select(ToPhone); + return numbers.ToList().ConvertAll(ToPhone); } public VoipPhone GetNumber(string id) @@ -203,7 +204,7 @@ namespace ASC.VoipService.Dao query = query.Skip((int)filter.Offset); query = query.Take((int)filter.Max * 3); - var calls = query.Select(ToCall); + var calls = query.ToList().ConvertAll(ToCall); calls = calls.GroupJoin(calls, call => call.Id, h => h.ParentID, (call, h) => { @@ -248,7 +249,7 @@ namespace ASC.VoipService.Dao .Max(tmp => tmp.DialDate) }).Where(r => r.dbVoipCall.DbVoipCall.DialDate >= r.tmpDate || r.tmpDate == default); - return a.Select(r => ToCall(r.dbVoipCall)).ToList(); + return a.ToList().ConvertAll(r => ToCall(r.dbVoipCall)); } private IQueryable<CallContact> GetCallsQuery(VoipCallFilter filter) diff --git a/common/ASC.Webhooks.Core/ASC.Webhooks.Core.csproj b/common/ASC.Webhooks.Core/ASC.Webhooks.Core.csproj index fae7e9e936..5aa604c97e 100644 --- a/common/ASC.Webhooks.Core/ASC.Webhooks.Core.csproj +++ b/common/ASC.Webhooks.Core/ASC.Webhooks.Core.csproj @@ -1,12 +1,7 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> +<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> - <IsPackable>false</IsPackable> - <DefaultItemExcludes>$(DefaultItemExcludes);</DefaultItemExcludes> - <RazorCompileOnBuild>false</RazorCompileOnBuild> - <GenerateMvcApplicationPartsAssemblyAttributes>false</GenerateMvcApplicationPartsAssemblyAttributes> - <OutputType>Library</OutputType> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> @@ -33,4 +28,8 @@ <Protobuf Include="proto\webhook_request.proto" /> </ItemGroup> + <ItemGroup> + <Folder Include="Properties\" /> + </ItemGroup> + </Project> diff --git a/common/ASC.Webhooks.Core/Properties/launchSettings.json b/common/ASC.Webhooks.Core/Properties/launchSettings.json deleted file mode 100644 index f05963afcc..0000000000 --- a/common/ASC.Webhooks.Core/Properties/launchSettings.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:49337/", - "sslPort": 44374 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "ASC.Webhooks.Core": { - "commandName": "Project", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "https://localhost:5001;http://localhost:5000" - } - } -} \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs index f0afbbb24b..039a3c54e4 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -71,7 +71,7 @@ namespace ASC.AuditTrail.Mappers { var actionText = Actions[(MessageAction)evt.Action].GetActionText(); - if (evt.Description == null || evt.Description.Count > 0) return actionText; + if (evt.Description == null || evt.Description.Count == 0) return actionText; var description = evt.Description .Select(t => t.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) @@ -100,7 +100,7 @@ namespace ASC.AuditTrail.Mappers { var actionText = Actions[(MessageAction)evt.Action].GetActionText(); - if (evt.Description == null || evt.Description.Count > 0) return actionText; + if (evt.Description == null || evt.Description.Count == 0) return actionText; var description = evt.Description .Select(t => t.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index 78fcaeaabd..b07b2e50e2 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -444,6 +444,14 @@ namespace ASC.ElasticSearch return b; } + Client.Instance.Indices.Create(data.IndexName, + c => + c.Map<T>(m => m.AutoMap()) + .Settings(r => r.Analysis(a => + a.Analyzers(analyzers) + .CharFilters(d => d.HtmlStrip(CharFilter.html.ToString()) + .Mapping(CharFilter.io.ToString(), m => m.Mappings("ё => е", "Р=> Е")))))); + IsExist = true; } } @@ -520,8 +528,7 @@ namespace ASC.ElasticSearch var sourceExprText = ""; - name = TryGetName(expression, out var member); - while (!string.IsNullOrEmpty(name)) + while (!string.IsNullOrEmpty(name = TryGetName(expression, out var member))) { sourceExprText = "." + name + sourceExprText; } @@ -574,10 +581,10 @@ namespace ASC.ElasticSearch var sourceExprText = ""; - name = TryGetName(expression, out var member); - while (!string.IsNullOrEmpty(name)) + while (!string.IsNullOrEmpty(name = TryGetName(expression, out var member))) { - sourceExprText = "." + name + sourceExprText; + sourceExprText = "." + name + sourceExprText; + expression = member.Expression; } var parameters = new Dictionary<string, object>(); diff --git a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs index d9dfda1545..325417599e 100644 --- a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs +++ b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs @@ -200,9 +200,9 @@ namespace ASC.Feed.Aggregator { dictionary = new Dictionary<Guid, int>(); } - if (dictionary.TryGetValue(userGuid, out var value)) + if (dictionary.ContainsKey(userGuid)) { - ++value; + ++dictionary[userGuid]; } else { diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index d292ed8702..1eb8f76e88 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -666,6 +666,9 @@ namespace ASC.Files.Core.Data .Distinct() .ToList(); + var toDeleteLinks = Query(FilesDbContext.TagLink).Where(r => r.EntryId == fileId.ToString() && r.EntryType == FileEntryType.File); + FilesDbContext.RemoveRange(toDeleteLinks); + var toDeleteFiles = Query(FilesDbContext.Files).Where(r => r.Id == fileId); FilesDbContext.RemoveRange(toDeleteFiles); @@ -690,7 +693,7 @@ namespace ASC.Files.Core.Data tx.Commit(); - foreach(var folderId in fromFolders) + foreach (var folderId in fromFolders) { RecalculateFilesCount(folderId); } @@ -770,7 +773,7 @@ namespace ASC.Files.Core.Data FilesDbContext.SaveChanges(); tx.Commit(); - foreach(var folderId in fromFolders) + foreach (var folderId in fromFolders) { RecalculateFilesCount(folderId); } diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs index d5cb793cf7..c3f0b963b6 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/TagDao.cs @@ -730,7 +730,7 @@ namespace ASC.Files.Core.Data var monitorFolderIdsInt = monitorFolderIds.OfType<int>().ToList(); var subFoldersSqlQuery = getFolderQuery(FilesDbContext, monitorFolderIdsInt, deepSearch); - monitorFolderIds = monitorFolderIds.Concat(subFoldersSqlQuery.Select(r => (object)r)); + monitorFolderIds = monitorFolderIds.Concat(subFoldersSqlQuery.ToList().ConvertAll(r => (object)r)); var monitorFolderIdsStrings = monitorFolderIds.Select(r => r.ToString()).ToList(); diff --git a/products/ASC.Files/Core/Core/Entries/EditHistory.cs b/products/ASC.Files/Core/Core/Entries/EditHistory.cs index ac39999117..1798d62fd5 100644 --- a/products/ASC.Files/Core/Core/Entries/EditHistory.cs +++ b/products/ASC.Files/Core/Core/Entries/EditHistory.cs @@ -168,11 +168,11 @@ namespace ASC.Files.Core { get { - UserInfo user = UserManager.GetUsers(Id); + UserInfo user; return Id.Equals(Guid.Empty) || Id.Equals(ASC.Core.Configuration.Constants.Guest.ID) - || (user).Equals(Constants.LostUser) + || (user = UserManager.GetUsers(Id)).Equals(Constants.LostUser) ? string.IsNullOrEmpty(_name) ? FilesCommonResource.Guest : _name diff --git a/products/ASC.Files/Core/Core/Entries/FileHelper.cs b/products/ASC.Files/Core/Core/Entries/FileHelper.cs index db899371b3..7564bfb884 100644 --- a/products/ASC.Files/Core/Core/Entries/FileHelper.cs +++ b/products/ASC.Files/Core/Core/Entries/FileHelper.cs @@ -23,11 +23,8 @@ * */ -using System; - using ASC.Common; using ASC.Web.Core.Files; -using ASC.Web.Files.Classes; using ASC.Web.Files.Utils; namespace ASC.Files.Core @@ -43,16 +40,13 @@ namespace ASC.Files.Core private FileConverter FileConverter { get; set; } - private Global Global { get; set; } - - public FileHelper(FileTrackerHelper fileTracker, FilesLinkUtility filesLinkUtility, FileUtility fileUtility, FileConverter fileConverter, Global global) + public FileHelper(FileTrackerHelper fileTracker, FilesLinkUtility filesLinkUtility, FileUtility fileUtility, FileConverter fileConverter) { FileTracker = fileTracker; FilesLinkUtility = filesLinkUtility; FileUtility = fileUtility; FileConverter = fileConverter; - Global = global; - } + } internal string GetTitle<T>(File<T> file) { diff --git a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs index 9dbe4c48c7..618161336a 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -271,14 +271,19 @@ namespace ASC.Web.Files private async Task InternalBulkDownloadFile(HttpContext context, IDataStore store, string path, string ext) { try - { + { + var flushed = false; using (var readStream = store.GetReadStream(FileConstant.StorageDomainTmp, path)) { - long offset = 0; + long offset = 0; + var length = readStream.Length; if (readStream.CanSeek) - { + { + length = ProcessRangeHeader(context, readStream.Length, ref offset); readStream.Seek(offset, SeekOrigin.Begin); - } + } + + await SendStreamByChunksAsync(context, length, FileConstant.DownloadTitle + ext, readStream, flushed); } await context.Response.Body.FlushAsync(); diff --git a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs index e4b8a3d817..f7c2bc687d 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs @@ -189,7 +189,7 @@ namespace ASC.Web.Files.Services.DocumentService if (builderKey == null) throw new NullReferenceException(); - if (urls != null && urls.Count > 0) throw new Exception("Empty response"); + if (urls != null && urls.Count == 0) throw new Exception("Empty response"); if (urls != null && urls.ContainsKey(TmpFileName)) break; diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs index a7664ccc0f..9d3baf7539 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs @@ -251,10 +251,10 @@ namespace ASC.Web.Files.Services.DocumentService { rightChangeHistory = false; - bool coauth = FileUtility.CanCoAuhtoring(file.Title); + bool coauth; if ((editPossible || reviewPossible || fillFormsPossible || commentPossible) && tryCoauth - && (!coauth || FileTracker.IsEditingAlone(file.ID))) + && (!(coauth = FileUtility.CanCoAuhtoring(file.Title)) || FileTracker.IsEditingAlone(file.ID))) { if (tryEdit) { diff --git a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs index c9a6edf1e6..e4f74fe9a5 100644 --- a/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs +++ b/products/ASC.Files/Core/Services/WCFService/FileOperations/FileDownloadOperation.cs @@ -36,7 +36,6 @@ using ASC.Common.Threading; using ASC.Common.Web; using ASC.Core.Tenants; using ASC.Files.Core; -using ASC.Files.Core.EF; using ASC.Files.Core.Resources; using ASC.MessagingSystem; using ASC.Web.Core.Files; @@ -96,7 +95,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations { string archiveExtension; - using(var zip = scope.ServiceProvider.GetService<CompressToArchive>()) + using (var zip = scope.ServiceProvider.GetService<CompressToArchive>()) { archiveExtension = zip.ArchiveExtension; } @@ -233,7 +232,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations { var folders = FilesSecurity.FilterRead(FolderDao.GetFolders(Files)); - foreach(var folder in folders) + foreach (var folder in folders) { fileMarker.RemoveMarkAsNew(folder); } @@ -276,8 +275,8 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations entriesPathId.Add(filesInFolder); } return entriesPathId; - } - + } + internal void CompressToZip(Stream stream, IServiceScope scope) { if (_entriesPathId == null) return; @@ -330,7 +329,7 @@ namespace ASC.Web.Files.Services.WCFService.FileOperations if (!Equals(entryId, default(T))) { - newtitle = newtitle.IndexOf('.') > -1 ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix) : newtitle + suffix; + newtitle = newtitle.IndexOf('.') > 0 ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix) : newtitle + suffix; } else { diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index 5692ceba25..8728933fa6 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -172,7 +172,8 @@ namespace ASC.Web.Files.Utils var queues = conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) && (x.Value.Progress == 100 && DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(1) || - DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(10))); + DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(10))) + .ToList(); foreach (var q in queues) { diff --git a/products/ASC.Files/Core/Utils/MailMergeTask.cs b/products/ASC.Files/Core/Utils/MailMergeTask.cs index 1f0d7bc9c4..88e78d3dae 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -99,7 +99,16 @@ namespace ASC.Web.Files.Utils } private void CreateDraftMail(MailMergeTask mailMergeTask) - { + { + //var apiUrlCreate = $"{SetupInfo.WebApiBaseUrl}mail/drafts/save.json"; + //var bodyCreate = + // string.Format( + // MailMergeTask.MessageBodyFormat, + // mailMergeTask.MessageId, + // HttpUtility.UrlEncode(mailMergeTask.From), + // HttpUtility.UrlEncode(mailMergeTask.Subject), + // HttpUtility.UrlEncode(mailMergeTask.To), + // HttpUtility.UrlEncode(mailMergeTask.Message)); const string responseCreateString = null; //TODO: Encoding.UTF8.GetString(Convert.FromBase64String(Api.GetApiResponse(apiUrlCreate, "PUT", bodyCreate))); var responseCreate = JObject.Parse(responseCreateString); @@ -161,7 +170,19 @@ namespace ASC.Web.Files.Utils } private string SendMail(MailMergeTask mailMergeTask, string bodySendAttach) - { + { + //var apiUrlSend = $"{SetupInfo.WebApiBaseUrl}mail/messages/send.json"; + + //var bodySend = + // string.Format( + // MailMergeTask.MessageBodyFormat, + // mailMergeTask.MessageId, + // HttpUtility.UrlEncode(mailMergeTask.From), + // HttpUtility.UrlEncode(mailMergeTask.Subject), + // HttpUtility.UrlEncode(mailMergeTask.To), + // HttpUtility.UrlEncode(mailMergeTask.Message)); + + //bodySend += bodySendAttach; const string responseSendString = null;//TODO: Encoding.UTF8.GetString(Convert.FromBase64String(Api.GetApiResponse(apiUrlSend, "PUT", bodySend))); var responseSend = JObject.Parse(responseSendString); diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index 618e5c2305..e5513ebbff 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -895,14 +895,26 @@ namespace ASC.Employee.Core.Controllers [Update("{userid}/contacts")] public EmployeeWraperFull UpdateMemberContactsFromBody(string userid, [FromBody] UpdateMemberModel memberModel) { - return SetMemberContacts(userid, memberModel); + return UpdateMemberContacts(userid, memberModel); } [Update("{userid}/contacts")] [Consumes("application/x-www-form-urlencoded")] public EmployeeWraperFull UpdateMemberContactsFromForm(string userid, [FromForm] UpdateMemberModel memberModel) { - return SetMemberContacts(userid, memberModel); + return UpdateMemberContacts(userid, memberModel); + } + + private EmployeeWraperFull UpdateMemberContacts(string userid, UpdateMemberModel memberModel) + { + var user = GetUserInfo(userid); + + if (UserManager.IsSystemUser(user.ID)) + throw new SecurityException(); + + UpdateContacts(memberModel.Contacts, user); + UserManager.SaveUserInfo(user); + return EmployeeWraperFullHelper.GetFull(user); } [Create("{userid}/contacts")] @@ -925,6 +937,7 @@ namespace ASC.Employee.Core.Controllers if (UserManager.IsSystemUser(user.ID)) throw new SecurityException(); + user.ContactsList.Clear(); UpdateContacts(memberModel.Contacts, user); UserManager.SaveUserInfo(user); return EmployeeWraperFullHelper.GetFull(user); diff --git a/web/ASC.Web.Core/Sms/SmsManager.cs b/web/ASC.Web.Core/Sms/SmsManager.cs index 6465c80bdc..b1f5874c25 100644 --- a/web/ASC.Web.Core/Sms/SmsManager.cs +++ b/web/ASC.Web.Core/Sms/SmsManager.cs @@ -140,7 +140,7 @@ namespace ASC.Web.Studio.Core.SMS if (!SecurityContext.IsAuthenticated) { - //var cookiesKey = SecurityContext.AuthenticateMe(user.ID); + SecurityContext.AuthenticateMe(user.ID); //CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey); } diff --git a/web/ASC.Web.Core/Sms/SmsProvider.cs b/web/ASC.Web.Core/Sms/SmsProvider.cs index 2b1e6fe867..993931efcc 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -84,9 +84,9 @@ namespace ASC.Web.Core.Sms provider = ClickatellProvider; } - string smsUsa = ClickatellProvider["clickatellUSA"]; + string smsUsa; if (ClickatellUSAProvider.Enable() - && !string.IsNullOrEmpty(smsUsa) && Regex.IsMatch(number, smsUsa)) + && !string.IsNullOrEmpty(smsUsa = ClickatellProvider["clickatellUSA"]) && Regex.IsMatch(number, smsUsa)) { provider = ClickatellUSAProvider; } diff --git a/web/ASC.Web.Core/Utility/TenantExtra.cs b/web/ASC.Web.Core/Utility/TenantExtra.cs index 50b287e1f1..b102438855 100644 --- a/web/ASC.Web.Core/Utility/TenantExtra.cs +++ b/web/ASC.Web.Core/Utility/TenantExtra.cs @@ -207,9 +207,9 @@ namespace ASC.Web.Studio.Utility { get { - DateTime licenseDay = GetCurrentTariff().LicenseDate.Date; + DateTime licenseDay; return CoreBaseSettings.Standalone - && licenseDay < DateTime.Today + && (licenseDay = GetCurrentTariff().LicenseDate.Date) < DateTime.Today && licenseDay < LicenseReader.VersionReleaseDate; } } @@ -224,9 +224,9 @@ namespace ASC.Web.Studio.Utility public bool IsNotPaid() { - Tariff tariff = GetCurrentTariff(); + Tariff tariff; return EnableTariffSettings - && (tariff.State >= TariffState.NotPaid + && ((tariff = GetCurrentTariff()).State >= TariffState.NotPaid || Enterprise && !EnterprisePaid && tariff.LicenseDate == DateTime.MaxValue); } diff --git a/web/ASC.Web.Core/WebItemManager.cs b/web/ASC.Web.Core/WebItemManager.cs index fd15c79ec0..9cb9ca2f43 100644 --- a/web/ASC.Web.Core/WebItemManager.cs +++ b/web/ASC.Web.Core/WebItemManager.cs @@ -261,8 +261,11 @@ namespace ASC.Web.Core public List<IWebItem> GetSubItems(Guid parentItemID, ItemAvailableState avaliableState) { - return GetItems(WebZoneType.All, avaliableState).Where(p => ((IModule)p).ProjectId == parentItemID) - .ToList(); + return GetItems(WebZoneType.All, avaliableState) + .OfType<IModule>() + .Where(p => p.ProjectId == parentItemID) + .Cast<IWebItem>() + .ToList(); } } } \ No newline at end of file From 37c88dad50273389564c6df3710fa2fb47e3fdfb Mon Sep 17 00:00:00 2001 From: pavelbannov <pavel.bannov@onlyoffice.com> Date: Mon, 7 Feb 2022 18:10:27 +0300 Subject: [PATCH 140/167] Analyzers: fix --- products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs index 1eb8f76e88..96730f23db 100644 --- a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs +++ b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FileDao.cs @@ -455,7 +455,7 @@ namespace ASC.Files.Core.Data parentFoldersIds = parentFolders.Select(r => r.ParentId).ToList(); - if (parentFoldersIds.Count == 0) + if (parentFoldersIds.Count > 0) { var folderToUpdate = FilesDbContext.Folders .Where(r => parentFoldersIds.Contains(r.Id)); From 179c8ddb84c55a124cd2f86d232d73601f679f5e Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Mon, 7 Feb 2022 19:03:16 +0300 Subject: [PATCH 141/167] ApiCore: single line expressions replaced by expressions with braces --- .../ASC.Api.Core/Auth/ConfirmAuthHandler.cs | 24 ++- common/ASC.Api.Core/Auth/CookieAuthHandler.cs | 4 +- .../ControllerNameAttributeConvention.cs | 7 +- common/ASC.Api.Core/Core/ApiContext.cs | 47 ++++- common/ASC.Api.Core/Core/ApiDateTime.cs | 162 ++++++++++++++---- common/ASC.Api.Core/Core/BaseStartup.cs | 18 +- .../Core/CustomEndpointDataSource.cs | 13 +- common/ASC.Api.Core/Core/CustomHealthCheck.cs | 9 +- common/ASC.Api.Core/Core/ItemKeyValuePair.cs | 1 - common/ASC.Api.Core/Core/Validate.cs | 36 ++-- .../ASC.Api.Core/Core/XmlOutputFormatter.cs | 6 +- common/ASC.Api.Core/GlobalUsings.cs | 3 +- .../Middleware/CommonApiResponse.cs | 49 ++++-- .../Middleware/CultureMiddleware.cs | 21 ++- .../Middleware/DisposeMiddleware.cs | 11 +- .../Middleware/ProductSecurityFilter.cs | 22 ++- .../Middleware/ResponseWrapper.cs | 5 +- common/ASC.Api.Core/Model/Contact.cs | 5 +- common/ASC.Api.Core/Model/EmployeeWraper.cs | 21 ++- .../ASC.Api.Core/Model/EmployeeWraperFull.cs | 47 ++++- .../ASC.Api.Core/Model/GroupWrapperSummary.cs | 11 +- common/ASC.Api.Core/Routing/DefaultRoute.cs | 5 +- 22 files changed, 407 insertions(+), 120 deletions(-) diff --git a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs index 945aadfbd2..c7ed847f32 100644 --- a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs @@ -57,9 +57,9 @@ public class ConfirmAuthHandler : AuthenticationHandler<AuthenticationSchemeOpti } var claims = new List<Claim>() - { + { new Claim(ClaimTypes.Role, emailValidationKeyModel.Type.ToString()) - }; + }; if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Ok) { @@ -67,19 +67,27 @@ public class ConfirmAuthHandler : AuthenticationHandler<AuthenticationSchemeOpti if (!_securityContext.IsAuthenticated) { if (emailValidationKeyModel.UiD.HasValue && !emailValidationKeyModel.UiD.Equals(Guid.Empty)) + { userId = emailValidationKeyModel.UiD.Value; + } else { - if (emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmailActivation - || emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.EmpInvite - || emailValidationKeyModel.Type == Web.Studio.Utility.ConfirmType.LinkInvite) + if (emailValidationKeyModel.Type == ConfirmType.EmailActivation + || emailValidationKeyModel.Type == ConfirmType.EmpInvite + || emailValidationKeyModel.Type == ConfirmType.LinkInvite) + { userId = ASC.Core.Configuration.Constants.CoreSystem.ID; + } else + { userId = _userManager.GetUserByEmail(emailValidationKeyModel.Email).ID; + } } } else + { userId = _securityContext.CurrentAccount.ID; + } _securityContext.AuthenticateMeWithoutCookie(userId, claims); } @@ -96,6 +104,8 @@ public class ConfirmAuthHandler : AuthenticationHandler<AuthenticationSchemeOpti public class ConfirmAuthHandlerExtension { - public static void Register(DIHelper services) => - services.TryAdd<EmailValidationKeyModelHelper>(); + public static void Register(DIHelper services) + { + return services.TryAdd<EmailValidationKeyModelHelper>(); + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Auth/CookieAuthHandler.cs b/common/ASC.Api.Core/Auth/CookieAuthHandler.cs index 19c1b45ed2..079e73c130 100644 --- a/common/ASC.Api.Core/Auth/CookieAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/CookieAuthHandler.cs @@ -31,7 +31,6 @@ public class CookieAuthHandler : AuthenticationHandler<AuthenticationSchemeOptio protected override Task<AuthenticateResult> HandleAuthenticateAsync() { var result = _authorizationHelper.ProcessBasicAuthorization(out _); - if (!result) { _securityContext.Logout(); @@ -42,7 +41,6 @@ public class CookieAuthHandler : AuthenticationHandler<AuthenticationSchemeOptio return Task.FromResult( result ? AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)) : - AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString())) - ); + AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString()))); } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs b/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs index 24028c2ff3..dfc5d14a9d 100644 --- a/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs +++ b/common/ASC.Api.Core/Convention/ControllerNameAttributeConvention.cs @@ -5,7 +5,10 @@ public class ControllerNameAttribute : Attribute { public string Name { get; } - public ControllerNameAttribute(string name) => Name = name; + public ControllerNameAttribute(string name) + { + Name = name; + } } public class ControllerNameAttributeConvention : IControllerModelConvention @@ -14,6 +17,8 @@ public class ControllerNameAttributeConvention : IControllerModelConvention { var controllerNameAttribute = controller.Attributes.OfType<ControllerNameAttribute>().SingleOrDefault(); if (controllerNameAttribute != null) + { controller.ControllerName = controllerNameAttribute.Name; + } } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/ApiContext.cs b/common/ASC.Api.Core/Core/ApiContext.cs index 6e043854fa..767b6b78cf 100644 --- a/common/ASC.Api.Core/Core/ApiContext.cs +++ b/common/ASC.Api.Core/Core/ApiContext.cs @@ -40,9 +40,13 @@ public class ApiContext : ICloneable set { if (HttpContextAccessor.HttpContext.Items.ContainsKey(nameof(TotalCount))) + { HttpContextAccessor.HttpContext.Items[nameof(TotalCount)] = value; + } else + { HttpContextAccessor.HttpContext.Items.Add(nameof(TotalCount), value); + } } } @@ -115,14 +119,20 @@ public class ApiContext : ICloneable _securityContext = securityContext; _tenantManager = tenantManager; HttpContextAccessor = httpContextAccessor; - if (httpContextAccessor.HttpContext == null) return; + if (httpContextAccessor.HttpContext == null) + { + return; + } Count = s_maxCount; var query = HttpContextAccessor.HttpContext.Request.Query; //Try parse values var count = query.GetRequestValue("count"); if (!string.IsNullOrEmpty(count) && ulong.TryParse(count, out var countParsed)) - Count = Math.Min((long)countParsed, s_maxCount); //Count specified and valid + { + //Count specified and valid + Count = Math.Min((long)countParsed, s_maxCount); + } var startIndex = query.GetRequestValue("startIndex"); if (startIndex != null && long.TryParse(startIndex, out var startIndexParsed)) @@ -132,7 +142,10 @@ public class ApiContext : ICloneable } var sortOrder = query.GetRequestValue("sortOrder"); - if ("descending".Equals(sortOrder)) SortDescending = true; + if ("descending".Equals(sortOrder)) + { + SortDescending = true; + } FilterToType = query.GetRequestValue("type"); SortBy = query.GetRequestValue("sortBy"); @@ -143,7 +156,10 @@ public class ApiContext : ICloneable Fields = query.GetRequestArray("fields"); var updatedSince = query.GetRequestValue("updatedSince"); - if (updatedSince != null) UpdatedSince = Convert.ToDateTime(updatedSince); + if (updatedSince != null) + { + UpdatedSince = Convert.ToDateTime(updatedSince); + } } /// <summary> @@ -187,15 +203,24 @@ public class ApiContext : ICloneable return this; } - public object Clone() => MemberwiseClone(); + public object Clone() + { + return MemberwiseClone(); + } - public override string ToString() => string.Format("C:{0},S:{1},So:{2},Sd:{3},Fb;{4},Fo:{5},Fv:{6},Us:{7},Ftt:{8}", Count, StartIndex, + public override string ToString() + { + return string.Format("C:{0},S:{1},So:{2},Sd:{3},Fb;{4},Fo:{5},Fv:{6},Us:{7},Ftt:{8}", Count, StartIndex, SortBy, SortDescending, FilterBy, FilterOp, FilterValue, UpdatedSince.Ticks, FilterToType); + } public void AuthByClaim() { var id = HttpContextAccessor.HttpContext.User.Claims.FirstOrDefault(r => r.Type == ClaimTypes.Sid); - if (Guid.TryParse(id?.Value, out var userId)) _securityContext.AuthenticateMeWithoutCookie(userId); + if (Guid.TryParse(id?.Value, out var userId)) + { + _securityContext.AuthenticateMeWithoutCookie(userId); + } } } @@ -235,6 +260,10 @@ public static class QueryExtension public static class ApiContextExtension { - public static bool Check(this ApiContext context, string field) => - context?.Fields == null || (context.Fields != null && context.Fields.Contains(field, StringComparer.InvariantCultureIgnoreCase)); + public static bool Check(this ApiContext context, string field) + { + return context?.Fields == null + || (context.Fields != null + && context.Fields.Contains(field, StringComparer.InvariantCultureIgnoreCase)); + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/ApiDateTime.cs b/common/ASC.Api.Core/Core/ApiDateTime.cs index b890d695fa..7bf88312de 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -78,33 +78,45 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable TimeZoneOffset = offset; } - public static ApiDateTime Parse(string data, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) => - Parse(data, null, tenantManager, timeZoneConverter); + public static ApiDateTime Parse(string data, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) + { + return Parse(data, null, tenantManager, timeZoneConverter); + } public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) { - if (string.IsNullOrEmpty(data)) throw new ArgumentNullException(nameof(data)); - - if (data.Length < 7) throw new ArgumentException("invalid date time format"); + if (string.IsNullOrEmpty(data)) + { + throw new ArgumentNullException(nameof(data)); + } + if (data.Length < 7) + { + throw new ArgumentException("invalid date time format"); + } var offsetPart = data.Substring(data.Length - 6, 6); if (DateTime.TryParseExact(data, Formats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var dateTime)) { //Parse time var tzOffset = TimeSpan.Zero; - if (offsetPart.Contains(':') && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset)) + if (offsetPart.Contains(':') + && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset)) + { return new ApiDateTime(dateTime, tzOffset); - + } + if (!data.EndsWith("Z", true, CultureInfo.InvariantCulture)) { - if (tz == null) tz = GetTimeZoneInfo(tenantManager, timeZoneConverter); + if (tz == null) + { + tz = GetTimeZoneInfo(tenantManager, timeZoneConverter); + } tzOffset = tz.GetUtcOffset(dateTime); dateTime = dateTime.Subtract(tzOffset); } return new ApiDateTime(dateTime, tzOffset); - } throw new ArgumentException("invalid date time format: " + data); @@ -117,17 +129,25 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable UtcTime = DateTime.MinValue; if (timeZone == null) + { timeZone = GetTimeZoneInfo(_tenantManager, _timeZoneConverter); + } //Hack if (timeZone.IsInvalidTime(new DateTime(value.Ticks, DateTimeKind.Unspecified))) + { value = value.AddHours(1); + } if (value.Kind == DateTimeKind.Local) + { value = TimeZoneInfo.ConvertTimeToUtc(new DateTime(value.Ticks, DateTimeKind.Unspecified), timeZone); + } if (value.Kind == DateTimeKind.Unspecified) + { value = new DateTime(value.Ticks, DateTimeKind.Utc); //Assume it's utc + } if (value.Kind == DateTimeKind.Utc) { @@ -154,7 +174,9 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable private string ToRoundTripString(DateTime date, TimeSpan offset) { var dateString = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff", CultureInfo.InvariantCulture); - var offsetString = offset.Ticks == 0 ? "Z" : ((offset < TimeSpan.Zero) ? "-" : "+") + offset.ToString("hh\\:mm", CultureInfo.InvariantCulture); + var offsetString = offset.Ticks == 0 + ? "Z" : ((offset < TimeSpan.Zero) + ? "-" : "+") + offset.ToString("hh\\:mm", CultureInfo.InvariantCulture); return dateString + offsetString; } @@ -180,64 +202,115 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable public static bool operator >(ApiDateTime left, ApiDateTime right) { - if (ReferenceEquals(left, right)) return false; - if (left == null) return false; + if (ReferenceEquals(left, right)) + { + return false; + } + if (left == null) + { + return false; + } return left.CompareTo(right) > 0; } public static bool operator >=(ApiDateTime left, ApiDateTime right) { - if (ReferenceEquals(left, right)) return false; - if (left == null) return false; + if (ReferenceEquals(left, right)) + { + return false; + } + if (left == null) + { + return false; + } return left.CompareTo(right) >= 0; } - public static bool operator <=(ApiDateTime left, ApiDateTime right) => !(left >= right); + public static bool operator <=(ApiDateTime left, ApiDateTime right) + { + return !(left >= right); + } - public static bool operator <(ApiDateTime left, ApiDateTime right) => !(left > right); + public static bool operator <(ApiDateTime left, ApiDateTime right) + { + return !(left > right); + } - public static bool operator ==(ApiDateTime left, ApiDateTime right) => Equals(left, right); + public static bool operator ==(ApiDateTime left, ApiDateTime right) + { + return Equals(left, right); + } - public static bool operator !=(ApiDateTime left, ApiDateTime right) => !(left == right); + public static bool operator !=(ApiDateTime left, ApiDateTime right) + { + return !(left == right); + } public static implicit operator DateTime(ApiDateTime d) { - if (d == null) return DateTime.MinValue; + if (d == null) + { + return DateTime.MinValue; + } return d.UtcTime; } public static implicit operator DateTime?(ApiDateTime d) { - if (d == null) return null; + if (d == null) + { + return null; + } return d.UtcTime; } - public int CompareTo(DateTime other) => CompareTo(new ApiDateTime(_tenantManager, _timeZoneConverter, other)); + public int CompareTo(DateTime other) + { + return CompareTo(new ApiDateTime(_tenantManager, _timeZoneConverter, other)); + } public int CompareTo(ApiDateTime other) { - if (other == null) return 1; + if (other == null) + { + return 1; + } return UtcTime.CompareTo(other.UtcTime); } public override bool Equals(object obj) { - if (obj is null) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != typeof(ApiDateTime)) return false; + if (obj is null) + { + return false; + } + if (ReferenceEquals(this, obj)) + { + return true; + } + if (obj.GetType() != typeof(ApiDateTime)) + { + return false; + } return Equals((ApiDateTime)obj); } public bool Equals(ApiDateTime other) { - if (other is null) return false; - if (ReferenceEquals(this, other)) return true; + if (other is null) + { + return false; + } + if (ReferenceEquals(this, other)) + { + return true; + } return UtcTime.Equals(other.UtcTime) && TimeZoneOffset.Equals(other.TimeZoneOffset); } @@ -253,7 +326,9 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable public int CompareTo(object obj) { if (obj is DateTime dateTime) + { return CompareTo(dateTime); + } return obj is ApiDateTime apiDateTime ? CompareTo(apiDateTime) : 0; } @@ -261,14 +336,18 @@ public class ApiDateTime : IComparable<ApiDateTime>, IComparable public override string ToString() { var localUtcTime = UtcTime; - if (!UtcTime.Equals(DateTime.MinValue)) + { localUtcTime = UtcTime.Add(TimeZoneOffset); + } return ToRoundTripString(localUtcTime, TimeZoneOffset); } - public static ApiDateTime GetSample() => new ApiDateTime(DateTime.UtcNow, TimeSpan.Zero); + public static ApiDateTime GetSample() + { + return new ApiDateTime(DateTime.UtcNow, TimeSpan.Zero); + } } public class ApiDateTimeTypeConverter : DateTimeConverter @@ -276,7 +355,9 @@ public class ApiDateTimeTypeConverter : DateTimeConverter public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) + { return value.ToString(); + } return base.ConvertTo(context, culture, value, destinationType); } @@ -284,10 +365,13 @@ public class ApiDateTimeTypeConverter : DateTimeConverter public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string @string) + { return ApiDateTime.Parse(@string, null, null); - + } if (value is DateTime time) + { return new ApiDateTime(null, null, time); + } return base.ConvertFrom(context, culture, value); } @@ -298,18 +382,27 @@ public class ApiDateTimeConverter : System.Text.Json.Serialization.JsonConverter public override ApiDateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TryGetDateTime(out var result)) + { return new ApiDateTime(result, TimeSpan.Zero); + } else { - if (DateTime.TryParseExact(reader.GetString(), ApiDateTime.Formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var dateTime)) + if (DateTime.TryParseExact(reader.GetString(), ApiDateTime.Formats, + CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var dateTime)) + { return new ApiDateTime(dateTime, TimeSpan.Zero); + } else + { return new ApiDateTime(); + } } } - public override void Write(Utf8JsonWriter writer, ApiDateTime value, JsonSerializerOptions options) => + public override void Write(Utf8JsonWriter writer, ApiDateTime value, JsonSerializerOptions options) + { writer.WriteStringValue(value.ToString()); + } } [Scope] @@ -324,5 +417,8 @@ public class ApiDateTimeHelper _timeZoneConverter = timeZoneConverter; } - public ApiDateTime Get(DateTime? from) => ApiDateTime.FromDate(_tenantManager, _timeZoneConverter, from); + public ApiDateTime Get(DateTime? from) + { + return ApiDateTime.FromDate(_tenantManager, _timeZoneConverter, from); + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index 8d5d6c4688..c223e884d3 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -21,7 +21,9 @@ public abstract class BaseStartup DIHelper = new DIHelper(); if (bool.TryParse(Configuration["core:products"], out var loadProducts)) + { LoadProducts = loadProducts; + } } public virtual void ConfigureServices(IServiceCollection services) @@ -31,7 +33,9 @@ public abstract class BaseStartup services.AddMemoryCache(); if (AddAndUseSession) + { services.AddSession(); + } DIHelper.Configure(services); @@ -70,8 +74,9 @@ public abstract class BaseStartup var kafkaConfiguration = Configuration.GetSection("kafka").Get<KafkaSettings>(); if (kafkaConfiguration != null) + { DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); - + } else if (redisConfiguration != null) { DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); @@ -79,12 +84,16 @@ public abstract class BaseStartup services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else + { DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + } DIHelper.TryAdd(typeof(IWebhookPublisher), typeof(WebhookPublisher)); if (LoadProducts) + { DIHelper.RegisterProducts(Configuration, HostEnvironment.ContentRootPath); + } var builder = services.AddMvcCore(config => { @@ -111,7 +120,9 @@ public abstract class BaseStartup .AddScheme<AuthenticationSchemeOptions, CookieAuthHandler>("cookie", a => { }); if (ConfirmAddScheme) + { authBuilder.AddScheme<AuthenticationSchemeOptions, ConfirmAuthHandler>("confirm", a => { }); + } services.AddAutoMapper(Assembly.GetAssembly(typeof(MappingProfile))); } @@ -126,7 +137,9 @@ public abstract class BaseStartup app.UseRouting(); if (AddAndUseSession) + { app.UseSession(); + } app.UseAuthentication(); @@ -165,7 +178,8 @@ public static class LogNLogConfigureExtenstion { return hostBuilder.ConfigureLogging((hostBuildexContext, r) => { - _ = new ConfigureLogNLog(hostBuildexContext.Configuration, new ConfigurationExtension(hostBuildexContext.Configuration), hostBuildexContext.HostingEnvironment); + _ = new ConfigureLogNLog(hostBuildexContext.Configuration, + new ConfigurationExtension(hostBuildexContext.Configuration), hostBuildexContext.HostingEnvironment); r.AddNLog(LogManager.Configuration); }); } diff --git a/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs b/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs index 0d1d4f6155..ed0e358bc2 100644 --- a/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs +++ b/common/ASC.Api.Core/Core/CustomEndpointDataSource.cs @@ -18,18 +18,25 @@ public class CustomEndpointDataSource : EndpointDataSource var enableFormat = attr == null || !attr.DisableFormat; if (enableFormat) - endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".{format}"), r.Order, r.Metadata, r.DisplayName)); + { + endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + + ".{format}"), r.Order, r.Metadata, r.DisplayName)); + } else { endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".json"), r.Order - 1, r.Metadata, r.DisplayName)); endpoints.Add(new RouteEndpoint(r.RequestDelegate, RoutePatternFactory.Parse(r.RoutePattern.RawText + ".xml"), r.Order - 1, r.Metadata, r.DisplayName)); } - + return endpoints; + }).ToList(); } - public override IChangeToken GetChangeToken() => Source.GetChangeToken(); + public override IChangeToken GetChangeToken() + { + return Source.GetChangeToken(); + } } public static class EndpointExtension diff --git a/common/ASC.Api.Core/Core/CustomHealthCheck.cs b/common/ASC.Api.Core/Core/CustomHealthCheck.cs index 9a3a152051..046c5d494b 100644 --- a/common/ASC.Api.Core/Core/CustomHealthCheck.cs +++ b/common/ASC.Api.Core/Core/CustomHealthCheck.cs @@ -23,7 +23,6 @@ public static class CustomHealthCheck tags: new string[] { "postgredb" }); var kafkaSettings = configurationExtension.GetSetting<KafkaSettings>("kafka"); - if (kafkaSettings != null && !string.IsNullOrEmpty(kafkaSettings.BootstrapServers)) { var clientConfig = new ClientConfig { BootstrapServers = kafkaSettings.BootstrapServers }; @@ -34,9 +33,7 @@ public static class CustomHealthCheck } - var elasticSettings = configuration.GetSection("elastic"); - if (elasticSettings != null && elasticSettings.GetChildren().Any()) { var host = elasticSettings.GetSection("Host").Value ?? "localhost"; @@ -45,9 +42,11 @@ public static class CustomHealthCheck var elasticSearchUri = $"{scheme}://{host}:{port}"; if (Uri.IsWellFormedUriString(elasticSearchUri, UriKind.Absolute)) + { hcBuilder.AddElasticsearch(elasticSearchUri, - name: "elasticsearch", - tags: new string[] { "elasticsearch" }); + name: "elasticsearch", + tags: new string[] { "elasticsearch" }); + } } return services; diff --git a/common/ASC.Api.Core/Core/ItemKeyValuePair.cs b/common/ASC.Api.Core/Core/ItemKeyValuePair.cs index f9d5e562c4..b79f45edd2 100644 --- a/common/ASC.Api.Core/Core/ItemKeyValuePair.cs +++ b/common/ASC.Api.Core/Core/ItemKeyValuePair.cs @@ -29,5 +29,4 @@ public class ItemKeyValuePair<TKey, TValue> { public TKey Key { get; set; } public TValue Value { get; set; } - } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/Validate.cs b/common/ASC.Api.Core/Core/Validate.cs index a63d949ff3..d4efdada6c 100644 --- a/common/ASC.Api.Core/Core/Validate.cs +++ b/common/ASC.Api.Core/Core/Validate.cs @@ -27,21 +27,33 @@ namespace ASC.Api.Utils; public static class Validate { - public static T If<T>(this T item, Func<T, bool> @if, Func<T> then) where T : class => - @if(item) ? then() : item; + public static T If<T>(this T item, Func<T, bool> @if, Func<T> then) where T : class + { + return @if(item) ? then() : item; + } - public static T IfNull<T>(this T item, Func<T> func) where T : class => item.If((x) => - x == default(T), func); + public static T IfNull<T>(this T item, Func<T> func) where T : class + { + return item.If((x) => x == default(T), func); + } - public static T ThrowIfNull<T>(this T item, Exception e) where T : class => - item.IfNull(() => { throw e; }); + public static T ThrowIfNull<T>(this T item, Exception e) where T : class + { + return item.IfNull(() => { throw e; }); + } - public static T NotFoundIfNull<T>(this T item) where T : class => - NotFoundIfNull(item, "Item not found"); + public static T NotFoundIfNull<T>(this T item) where T : class + { + return NotFoundIfNull(item, "Item not found"); + } - public static T NotFoundIfNull<T>(this T item, string message) where T : class => - item.IfNull(() => { throw new ItemNotFoundException(message); }); + public static T NotFoundIfNull<T>(this T item, string message) where T : class + { + return item.IfNull(() => { throw new ItemNotFoundException(message); }); + } - public static T? NullIfDefault<T>(this T item) where T : struct => - EqualityComparer<T>.Default.Equals(item, default(T)) ? default(T?) : item; + public static T? NullIfDefault<T>(this T item) where T : struct + { + return EqualityComparer<T>.Default.Equals(item, default(T)) ? default(T?) : item; + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Core/XmlOutputFormatter.cs b/common/ASC.Api.Core/Core/XmlOutputFormatter.cs index 8fb1039788..6de91fd4b9 100644 --- a/common/ASC.Api.Core/Core/XmlOutputFormatter.cs +++ b/common/ASC.Api.Core/Core/XmlOutputFormatter.cs @@ -2,8 +2,10 @@ public class XmlOutputFormatter : IOutputFormatter { - public bool CanWriteResult(OutputFormatterCanWriteContext context) => - context.ContentType == MimeMapping.GetMimeMapping(".xml"); + public bool CanWriteResult(OutputFormatterCanWriteContext context) + { + return context.ContentType == MimeMapping.GetMimeMapping(".xml"); + } public Task WriteAsync(OutputFormatterWriteContext context) { diff --git a/common/ASC.Api.Core/GlobalUsings.cs b/common/ASC.Api.Core/GlobalUsings.cs index bbf9966001..16ed75be94 100644 --- a/common/ASC.Api.Core/GlobalUsings.cs +++ b/common/ASC.Api.Core/GlobalUsings.cs @@ -80,5 +80,4 @@ global using Newtonsoft.Json.Serialization; global using NLog; global using NLog.Extensions.Logging; -global using StackExchange.Redis.Extensions.Core.Configuration; -global using StackExchange.Redis.Extensions.Newtonsoft; \ No newline at end of file +global using StackExchange.Redis.Extensions.Core.Configuration; \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/CommonApiResponse.cs b/common/ASC.Api.Core/Middleware/CommonApiResponse.cs index 2d21843487..d92c8804bf 100644 --- a/common/ASC.Api.Core/Middleware/CommonApiResponse.cs +++ b/common/ASC.Api.Core/Middleware/CommonApiResponse.cs @@ -5,13 +5,21 @@ public abstract class CommonApiResponse public int Status { get; set; } public HttpStatusCode StatusCode { get; set; } - protected CommonApiResponse(HttpStatusCode statusCode) => StatusCode = statusCode; + protected CommonApiResponse(HttpStatusCode statusCode) + { + StatusCode = statusCode; - public static SuccessApiResponse Create(HttpStatusCode statusCode, object response) => - new SuccessApiResponse(statusCode, response); + } - public static ErrorApiResponse CreateError(HttpStatusCode statusCode, Exception error) => - new ErrorApiResponse(statusCode, error); + public static SuccessApiResponse Create(HttpStatusCode statusCode, object response) + { + return new SuccessApiResponse(statusCode, response); + } + + public static ErrorApiResponse CreateError(HttpStatusCode statusCode, Exception error) + { + return new ErrorApiResponse(statusCode, error); + } } public class ErrorApiResponse : CommonApiResponse @@ -37,13 +45,28 @@ public class SuccessApiResponse : CommonApiResponse Response = response; Total = total; - if (count.HasValue) Count = count; + if (count.HasValue) + { + Count = count; + } else { - if (response is List<object> list) Count = list.Count; - else if (response is IEnumerable<object> collection) Count = collection.Count(); - else if (response == null) Count = 0; - else Count = 1; + if (response is List<object> list) + { + Count = list.Count; + } + else if (response is IEnumerable<object> collection) + { + Count = collection.Count(); + } + else if (response == null) + { + Count = 0; + } + else + { + Count = 1; + } } } } @@ -55,12 +78,14 @@ public class CommonApiError public string Stack { get; set; } public int Hresult { get; set; } - public static CommonApiError FromException(Exception exception, string message = null) => - new CommonApiError() + public static CommonApiError FromException(Exception exception, string message = null) + { + return new CommonApiError() { Message = message ?? exception.Message, Type = exception.GetType().ToString(), Stack = exception.StackTrace, Hresult = exception.HResult }; + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/CultureMiddleware.cs b/common/ASC.Api.Core/Middleware/CultureMiddleware.cs index b5f1397099..ce05d55665 100644 --- a/common/ASC.Api.Core/Middleware/CultureMiddleware.cs +++ b/common/ASC.Api.Core/Middleware/CultureMiddleware.cs @@ -4,7 +4,10 @@ public class CultureMiddleware { private readonly RequestDelegate _next; - public CultureMiddleware(RequestDelegate next) => _next = next; + public CultureMiddleware(RequestDelegate next) + { + _next = next; + } public async Task Invoke(HttpContext context, UserManager userManager, TenantManager tenantManager, AuthContext authContext) { @@ -14,10 +17,16 @@ public class CultureMiddleware { var user = userManager.GetUsers(authContext.CurrentAccount.ID); - if (!string.IsNullOrEmpty(user.CultureName)) culture = user.GetCulture(); + if (!string.IsNullOrEmpty(user.CultureName)) + { + culture = user.GetCulture(); + } } - if (culture == null) culture = tenantManager.GetCurrentTenant().GetCulture(); + if (culture == null) + { + culture = tenantManager.GetCurrentTenant().GetCulture(); + } Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; @@ -28,6 +37,8 @@ public class CultureMiddleware public static class CultureMiddlewareExtensions { - public static IApplicationBuilder UseCultureMiddleware(this IApplicationBuilder builder) => - builder.UseMiddleware<CultureMiddleware>(); + public static IApplicationBuilder UseCultureMiddleware(this IApplicationBuilder builder) + { + return builder.UseMiddleware<CultureMiddleware>(); + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs b/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs index 9f38589fa0..a418416cf1 100644 --- a/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs +++ b/common/ASC.Api.Core/Middleware/DisposeMiddleware.cs @@ -4,7 +4,10 @@ public class DisposeMiddleware { private readonly RequestDelegate _next; - public DisposeMiddleware(RequestDelegate next) => _next = next; + public DisposeMiddleware(RequestDelegate next) + { + _next = next; + } public async Task Invoke(HttpContext context) { @@ -16,6 +19,8 @@ public class DisposeMiddleware public static class DisposeMiddlewareExtensions { - public static IApplicationBuilder UseDisposeMiddleware(this IApplicationBuilder builder) => - builder.UseMiddleware<DisposeMiddleware>(); + public static IApplicationBuilder UseDisposeMiddleware(this IApplicationBuilder builder) + { + return builder.UseMiddleware<DisposeMiddleware>(); + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs index eece12357a..1cc042c288 100644 --- a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs +++ b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs @@ -50,7 +50,10 @@ public class ProductSecurityFilter : IResourceFilter public void OnResourceExecuting(ResourceExecutingContext context) { - if (!_authContext.IsAuthenticated) return; + if (!_authContext.IsAuthenticated) + { + return; + } if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor) { @@ -58,7 +61,9 @@ public class ProductSecurityFilter : IResourceFilter if (pid != Guid.Empty) { if (CallContext.GetData("asc.web.product_id") == null) + { CallContext.SetData("asc.web.product_id", pid); + } if (!_webItemSecurity.IsAvailableForMe(pid)) { @@ -71,7 +76,10 @@ public class ProductSecurityFilter : IResourceFilter private static Guid FindProduct(ControllerActionDescriptor method) { - if (method == null || string.IsNullOrEmpty(method.ControllerName)) return default; + if (method == null || string.IsNullOrEmpty(method.ControllerName)) + { + return default; + } var name = method.ControllerName.ToLower(); if (name == "community") @@ -80,11 +88,17 @@ public class ProductSecurityFilter : IResourceFilter if (!string.IsNullOrEmpty(url)) { var module = url.Split('/')[0]; - if (s_products.ContainsKey(module)) return s_products[module]; + if (s_products.ContainsKey(module)) + { + return s_products[module]; + } } } - if (s_products.ContainsKey(name)) return s_products[name]; + if (s_products.ContainsKey(name)) + { + return s_products[name]; + } return default; } diff --git a/common/ASC.Api.Core/Middleware/ResponseWrapper.cs b/common/ASC.Api.Core/Middleware/ResponseWrapper.cs index 454f7cef50..99f18790c5 100644 --- a/common/ASC.Api.Core/Middleware/ResponseWrapper.cs +++ b/common/ASC.Api.Core/Middleware/ResponseWrapper.cs @@ -7,7 +7,10 @@ public class CustomExceptionFilterAttribute : ExceptionFilterAttribute var status = (HttpStatusCode)context.HttpContext.Response.StatusCode; string message = null; - if (status == HttpStatusCode.OK) status = HttpStatusCode.InternalServerError; + if (status == HttpStatusCode.OK) + { + status = HttpStatusCode.InternalServerError; + } switch (context.Exception) { diff --git a/common/ASC.Api.Core/Model/Contact.cs b/common/ASC.Api.Core/Model/Contact.cs index 959a41b534..3ce3436894 100644 --- a/common/ASC.Api.Core/Model/Contact.cs +++ b/common/ASC.Api.Core/Model/Contact.cs @@ -39,5 +39,8 @@ public class Contact Value = value; } - public static Contact GetSample() => new Contact("GTalk", "my@gmail.com"); + public static Contact GetSample() + { + return new Contact("GTalk", "my@gmail.com"); + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Model/EmployeeWraper.cs b/common/ASC.Api.Core/Model/EmployeeWraper.cs index f3d095e45f..be55d466de 100644 --- a/common/ASC.Api.Core/Model/EmployeeWraper.cs +++ b/common/ASC.Api.Core/Model/EmployeeWraper.cs @@ -33,14 +33,16 @@ public class EmployeeWraper public string AvatarSmall { get; set; } public string ProfileUrl { get; set; } - public static EmployeeWraper GetSample() => - new EmployeeWraper + public static EmployeeWraper GetSample() + { + return new EmployeeWraper { Id = Guid.Empty, DisplayName = "Mike Zanyatski", Title = "Manager", AvatarSmall = "url to small avatar", }; + } } [Scope] @@ -68,7 +70,10 @@ public class EmployeeWraperHelper } - public EmployeeWraper Get(UserInfo userInfo) => Init(new EmployeeWraper(), userInfo); + public EmployeeWraper Get(UserInfo userInfo) + { + return Init(new EmployeeWraper(), userInfo); + } public EmployeeWraper Get(Guid userId) { @@ -87,12 +92,18 @@ public class EmployeeWraperHelper result.Id = userInfo.ID; result.DisplayName = _displayUserSettingsHelper.GetFullUserName(userInfo); - if (!string.IsNullOrEmpty(userInfo.Title)) result.Title = userInfo.Title; + if (!string.IsNullOrEmpty(userInfo.Title)) + { + result.Title = userInfo.Title; + } var userInfoLM = userInfo.LastModified.GetHashCode(); if (_httpContext.Check("avatarSmall")) - result.AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + { + result.AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.ID, out var isdef) + + (isdef ? "" : $"?_={userInfoLM}"); + } if (result.Id != Guid.Empty) { diff --git a/common/ASC.Api.Core/Model/EmployeeWraperFull.cs b/common/ASC.Api.Core/Model/EmployeeWraperFull.cs index 0054a6be17..417e8023ec 100644 --- a/common/ASC.Api.Core/Model/EmployeeWraperFull.cs +++ b/common/ASC.Api.Core/Model/EmployeeWraperFull.cs @@ -112,7 +112,11 @@ public class EmployeeWraperFullHelper : EmployeeWraperHelper public static Expression<Func<User, UserInfo>> GetExpression(ApiContext apiContext) { - if (apiContext?.Fields == null) return null; + if (apiContext?.Fields == null) + { + return null; + } + var newExpr = Expression.New(typeof(UserInfo)); //i => new UserInfo { ID = i.id } @@ -120,7 +124,10 @@ public class EmployeeWraperFullHelper : EmployeeWraperHelper var bindExprs = new List<MemberAssignment>(); if (apiContext.Check("Id")) - bindExprs.Add(Expression.Bind(typeof(UserInfo).GetProperty("ID"), Expression.Property(parameter, typeof(User).GetProperty("Id")))); + { + bindExprs.Add(Expression.Bind(typeof(UserInfo).GetProperty("ID"), + Expression.Property(parameter, typeof(User).GetProperty("Id")))); + } var body = Expression.MemberInit(newExpr, bindExprs); var lambda = Expression.Lambda<Func<User, UserInfo>>(body, parameter); @@ -151,21 +158,31 @@ public class EmployeeWraperFullHelper : EmployeeWraperHelper Init(result, userInfo); if (userInfo.Sex.HasValue) + { result.Sex = userInfo.Sex.Value ? "male" : "female"; + } if (!string.IsNullOrEmpty(userInfo.Location)) + { result.Location = userInfo.Location; + } if (!string.IsNullOrEmpty(userInfo.Notes)) + { result.Notes = userInfo.Notes; + } if (!string.IsNullOrEmpty(userInfo.MobilePhone)) + { result.MobilePhone = userInfo.MobilePhone; + } result.MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus; if (!string.IsNullOrEmpty(userInfo.CultureName)) + { result.CultureName = userInfo.CultureName; + } FillConacts(result, userInfo); @@ -180,25 +197,36 @@ public class EmployeeWraperFullHelper : EmployeeWraperHelper result.Groups = groups; result.Department = string.Join(", ", result.Groups.Select(d => d.Name.HtmlEncode())); } - else result.Department = ""; + else + { + result.Department = ""; + } } var userInfoLM = userInfo.LastModified.GetHashCode(); if (_context.Check("avatarMax")) + { result.AvatarMax = UserPhotoManager.GetMaxPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + } if (_context.Check("avatarMedium")) + { result.AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + } if (_context.Check("avatar")) + { result.Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.ID, out var isdef) + (isdef ? "" : $"?_={userInfoLM}"); + } if (_context.Check("listAdminModules")) { var listAdminModules = userInfo.GetListAdminModules(_webItemSecurity); - - if (listAdminModules.Any()) result.ListAdminModules = listAdminModules; + if (listAdminModules.Any()) + { + result.ListAdminModules = listAdminModules; + } } return result; @@ -206,17 +234,24 @@ public class EmployeeWraperFullHelper : EmployeeWraperHelper private void FillConacts(EmployeeWraperFull employeeWraperFull, UserInfo userInfo) { - if (userInfo.ContactsList == null) return; + if (userInfo.ContactsList == null) + { + return; + } var contacts = new List<Contact>(); for (var i = 0; i < userInfo.ContactsList.Count; i += 2) { if (i + 1 < userInfo.ContactsList.Count) + { contacts.Add(new Contact(userInfo.ContactsList[i], userInfo.ContactsList[i + 1])); + } } if (contacts.Any()) + { employeeWraperFull.Contacts = contacts; + } } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Model/GroupWrapperSummary.cs b/common/ASC.Api.Core/Model/GroupWrapperSummary.cs index 0730231a5d..e3d57de3b9 100644 --- a/common/ASC.Api.Core/Model/GroupWrapperSummary.cs +++ b/common/ASC.Api.Core/Model/GroupWrapperSummary.cs @@ -42,6 +42,13 @@ public class GroupWrapperSummary Manager = userManager.GetUsers(userManager.GetDepartmentManager(group.ID)).UserName; } - public static GroupWrapperSummary GetSample() => - new GroupWrapperSummary { Id = Guid.Empty, Manager = "Jake.Zazhitski", Name = "Group Name" }; + public static GroupWrapperSummary GetSample() + { + return new GroupWrapperSummary + { + Id = Guid.Empty, + Manager = "Jake.Zazhitski", + Name = "Group Name" + }; + } } \ No newline at end of file diff --git a/common/ASC.Api.Core/Routing/DefaultRoute.cs b/common/ASC.Api.Core/Routing/DefaultRoute.cs index 578a7da0f9..be5bc6864d 100644 --- a/common/ASC.Api.Core/Routing/DefaultRoute.cs +++ b/common/ASC.Api.Core/Routing/DefaultRoute.cs @@ -4,7 +4,10 @@ public class DefaultRouteAttribute : RouteAttribute { public static string BaseUrl { get; set; } - static DefaultRouteAttribute() => BaseUrl = "api/2.0"; + static DefaultRouteAttribute() + { + BaseUrl = "api/2.0"; + } public DefaultRouteAttribute() : base(BaseUrl) { } } \ No newline at end of file From b2079ccacebed863d697bb88a0e7c633719f3089 Mon Sep 17 00:00:00 2001 From: pavelbannov <pavel.bannov@onlyoffice.com> Date: Mon, 7 Feb 2022 20:19:58 +0300 Subject: [PATCH 142/167] fixed warnings --- common/ASC.Api.Core/Core/BaseStartup.cs | 1 - common/ASC.Common/Caching/AscCache.cs | 2 - common/ASC.Common/Utils/RandomString.cs | 1 - .../ASC.Core.Common/Billing/CouponManager.cs | 1 - .../Billing/License/LicenseReader.cs | 1 - common/ASC.Core.Common/Core/UserGroupRef.cs | 1 - .../Notify/Jabber/JabberServiceClientWcf.cs | 1 - .../Notify/Telegram/Dao/CachedTelegramDao.cs | 1 - common/ASC.Data.Backup.Core/Core/DbHelper.cs | 1 - .../Storage/BackupRepository.cs | 1 - .../Tasks/Data/TableInfo.cs | 1 - .../services/ASC.Data.Backup/GlobalUsings.cs | 3 - .../services/ASC.TelegramService/Startup.cs | 3 - .../ASC.Files/Core/Core/FileStorageService.cs | 1 - .../Core/Helpers/ThirdpartyConfiguration.cs | 1 - .../Services/DocumentService/Configuration.cs | 16 +- .../DocumentService/DocumentServiceTracker.cs | 1 - products/ASC.Files/Core/Utils/EntryManager.cs | 161 +++++++++--------- .../Server/Helpers/FilesControllerHelper.cs | 1 - products/ASC.Files/Server/Startup.cs | 3 - .../ASC.Files/Service/Thumbnail/Builder.cs | 2 - .../Service/Thumbnail/FileDataProvider.cs | 1 - products/ASC.People/Server/Startup.cs | 5 +- web/ASC.Web.Core/Files/DocumentService.cs | 1 - web/ASC.Web.Core/QuotaSync.cs | 1 - web/ASC.Web.HealthChecks.UI/Program.cs | 2 - web/ASC.Web.Studio/Startup.cs | 3 - 27 files changed, 86 insertions(+), 131 deletions(-) diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index 05ceda2c3d..e2f50f1c1f 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -23,7 +23,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Authorization; diff --git a/common/ASC.Common/Caching/AscCache.cs b/common/ASC.Common/Caching/AscCache.cs index e78b469ee0..92a461f2e7 100644 --- a/common/ASC.Common/Caching/AscCache.cs +++ b/common/ASC.Common/Caching/AscCache.cs @@ -30,8 +30,6 @@ using System.Linq; using System.Runtime.Caching; using System.Text.RegularExpressions; -using Google.Protobuf; - using Microsoft.Extensions.Caching.Memory; namespace ASC.Common.Caching diff --git a/common/ASC.Common/Utils/RandomString.cs b/common/ASC.Common/Utils/RandomString.cs index a7adf92428..2b268f8bd1 100644 --- a/common/ASC.Common/Utils/RandomString.cs +++ b/common/ASC.Common/Utils/RandomString.cs @@ -24,7 +24,6 @@ */ -using System; using System.Security.Cryptography; using System.Text; diff --git a/common/ASC.Core.Common/Billing/CouponManager.cs b/common/ASC.Core.Common/Billing/CouponManager.cs index 27cd20b1a7..f83815f3b3 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -28,7 +28,6 @@ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; -using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Text; diff --git a/common/ASC.Core.Common/Billing/License/LicenseReader.cs b/common/ASC.Core.Common/Billing/License/LicenseReader.cs index 859128a981..8f8df79c71 100644 --- a/common/ASC.Core.Common/Billing/License/LicenseReader.cs +++ b/common/ASC.Core.Common/Billing/License/LicenseReader.cs @@ -26,7 +26,6 @@ using System; using System.IO; -using System.Linq; using ASC.Common; using ASC.Common.Logging; diff --git a/common/ASC.Core.Common/Core/UserGroupRef.cs b/common/ASC.Core.Common/Core/UserGroupRef.cs index 7b7fc291da..cba8c9fe17 100644 --- a/common/ASC.Core.Common/Core/UserGroupRef.cs +++ b/common/ASC.Core.Common/Core/UserGroupRef.cs @@ -27,7 +27,6 @@ using System; using System.Diagnostics; -using ASC.Common.Caching; using ASC.Core.Caching; namespace ASC.Core diff --git a/common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs b/common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs index 8961e34aa5..5767129aad 100644 --- a/common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs +++ b/common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs @@ -24,7 +24,6 @@ */ -using System; using System.Collections.Generic; using ASC.Common.Module; diff --git a/common/ASC.Core.Common/Notify/Telegram/Dao/CachedTelegramDao.cs b/common/ASC.Core.Common/Notify/Telegram/Dao/CachedTelegramDao.cs index da2395908b..d9315cac80 100644 --- a/common/ASC.Core.Common/Notify/Telegram/Dao/CachedTelegramDao.cs +++ b/common/ASC.Core.Common/Notify/Telegram/Dao/CachedTelegramDao.cs @@ -26,7 +26,6 @@ using System; using System.Collections.Generic; -using System.Linq; using ASC.Common; using ASC.Common.Caching; diff --git a/common/ASC.Data.Backup.Core/Core/DbHelper.cs b/common/ASC.Data.Backup.Core/Core/DbHelper.cs index 64abdee234..af0f64580e 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -14,7 +14,6 @@ using ASC.Common.Logging; using ASC.Common.Utils; using ASC.Core.Common.EF; using ASC.Core.Common.EF.Context; -using ASC.Data.Backup.EF.Context; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; diff --git a/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs b/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs index 83647816c8..dd735303c9 100644 --- a/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs +++ b/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs @@ -30,7 +30,6 @@ using System.Linq; using ASC.Common; using ASC.Core.Common.EF; -using ASC.Core.Common.EF.Context; using ASC.Core.Tenants; using ASC.Data.Backup.EF.Context; using ASC.Data.Backup.EF.Model; diff --git a/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs b/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs index c52d383545..9f3b0b9d0c 100644 --- a/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs +++ b/common/ASC.Data.Backup.Core/Tasks/Data/TableInfo.cs @@ -26,7 +26,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Linq; namespace ASC.Data.Backup.Tasks.Data { diff --git a/common/services/ASC.Data.Backup/GlobalUsings.cs b/common/services/ASC.Data.Backup/GlobalUsings.cs index bc8c334827..45e32aa25b 100644 --- a/common/services/ASC.Data.Backup/GlobalUsings.cs +++ b/common/services/ASC.Data.Backup/GlobalUsings.cs @@ -37,7 +37,4 @@ global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.Hosting; global using Microsoft.Extensions.Options; -global using StackExchange.Redis.Extensions.Core.Configuration; -global using StackExchange.Redis.Extensions.Newtonsoft; - global using static ASC.Data.Backup.BackupAjaxHandler; diff --git a/common/services/ASC.TelegramService/Startup.cs b/common/services/ASC.TelegramService/Startup.cs index fbe9944c0b..38ed2fc431 100644 --- a/common/services/ASC.TelegramService/Startup.cs +++ b/common/services/ASC.TelegramService/Startup.cs @@ -30,9 +30,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using StackExchange.Redis.Extensions.Core.Configuration; -using StackExchange.Redis.Extensions.Newtonsoft; - namespace ASC.TelegramService { public class Startup : BaseStartup diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index be3045ec18..79d57f77b5 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -45,7 +45,6 @@ using ASC.Core.Common.Configuration; using ASC.Core.Common.Settings; using ASC.Core.Users; using ASC.Data.Storage; -using ASC.ElasticSearch; using ASC.FederatedLogin.LoginProviders; using ASC.Files.Core; using ASC.Files.Core.Resources; diff --git a/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs b/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs index cccc309a71..32f1fbaa4a 100644 --- a/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs +++ b/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs @@ -26,7 +26,6 @@ using System; using System.Collections.Generic; -using System.Linq; using ASC.Common; using ASC.Core.Common.Configuration; diff --git a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs index 02d8606e3b..2cb3ce3379 100644 --- a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs +++ b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs @@ -681,7 +681,7 @@ namespace ASC.Web.Files.Services.DocumentService Logo.SetConfiguration(_configuration); } - private string _gobackUrl; + //private string _gobackUrl; public bool IsRetina { get; set; } = false; @@ -726,13 +726,13 @@ namespace ASC.Web.Files.Services.DocumentService { if (_configuration.EditorType == EditorType.Embedded || _configuration.EditorType == EditorType.External) return null; if (!AuthContext.IsAuthenticated) return null; - if (_gobackUrl != null) - { - return new GobackConfig - { - Url = _gobackUrl, - }; - } + //if (_gobackUrl != null) + //{ + // return new GobackConfig + // { + // Url = _gobackUrl, + // }; + //} var folderDao = DaoFactory.GetFolderDao<T>(); try diff --git a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs index 2dc17ce56b..4c4ff24621 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -30,7 +30,6 @@ using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; -using System.Net; using System.Net.Http; using System.Text; using System.Text.Json; diff --git a/products/ASC.Files/Core/Utils/EntryManager.cs b/products/ASC.Files/Core/Utils/EntryManager.cs index 05b05f562f..7b3b69b09f 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -28,10 +28,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Net; using System.Net.Http; using System.Security; -using System.Text; using System.Threading; using ASC.Common; @@ -55,8 +53,6 @@ using ASC.Web.Studio.Core; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Newtonsoft.Json.Linq; - using FileShare = ASC.Files.Core.Security.FileShare; namespace ASC.Web.Files.Utils @@ -253,7 +249,6 @@ namespace ASC.Web.Files.Utils private FilesIntegration FilesIntegration { get; } private FileMarker FileMarker { get; } private FileUtility FileUtility { get; } - private Global Global { get; } private GlobalStore GlobalStore { get; } private CoreBaseSettings CoreBaseSettings { get; } private FilesSettingsHelper FilesSettingsHelper { get; } @@ -279,7 +274,6 @@ namespace ASC.Web.Files.Utils FilesIntegration filesIntegration, FileMarker fileMarker, FileUtility fileUtility, - Global global, GlobalStore globalStore, CoreBaseSettings coreBaseSettings, FilesSettingsHelper filesSettingsHelper, @@ -307,7 +301,6 @@ namespace ASC.Web.Files.Utils FilesIntegration = filesIntegration; FileMarker = fileMarker; FileUtility = fileUtility; - Global = global; GlobalStore = globalStore; CoreBaseSettings = coreBaseSettings; FilesSettingsHelper = filesSettingsHelper; @@ -347,99 +340,99 @@ namespace ASC.Web.Files.Utils //var apiServer = new ASC.Api.ApiServer(); //var apiUrl = string.Format("{0}project/maxlastmodified.json", SetupInfo.WebApiBaseUrl); - const string responseBody = null;// apiServer.GetApiResponse(apiUrl, "GET"); - if (responseBody != null) - { - JObject responseApi; + //const string responseBody = null;// apiServer.GetApiResponse(apiUrl, "GET"); + //if (responseBody != null) + //{ + // JObject responseApi; - Dictionary<int, KeyValuePair<int, string>> folderIDProjectTitle = null; + // Dictionary<int, KeyValuePair<int, string>> folderIDProjectTitle = null; - if (folderIDProjectTitle == null) - { - //apiUrl = string.Format("{0}project/filter.json?sortBy=title&sortOrder=ascending&status=open&fields=id,title,security,projectFolder", SetupInfo.WebApiBaseUrl); + // if (folderIDProjectTitle == null) + // { + // //apiUrl = string.Format("{0}project/filter.json?sortBy=title&sortOrder=ascending&status=open&fields=id,title,security,projectFolder", SetupInfo.WebApiBaseUrl); - responseApi = JObject.Parse(""); //Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET")))); + // responseApi = JObject.Parse(""); //Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET")))); - var responseData = responseApi["response"]; + // var responseData = responseApi["response"]; - if (!(responseData is JArray)) return entries.ToList(); + // if (!(responseData is JArray)) return entries.ToList(); - folderIDProjectTitle = new Dictionary<int, KeyValuePair<int, string>>(); - foreach (JObject projectInfo in responseData.Children().OfType<JObject>()) - { - var projectID = projectInfo["id"].Value<int>(); - var projectTitle = Global.ReplaceInvalidCharsAndTruncate(projectInfo["title"].Value<string>()); + // folderIDProjectTitle = new Dictionary<int, KeyValuePair<int, string>>(); + // foreach (JObject projectInfo in responseData.Children().OfType<JObject>()) + // { + // var projectID = projectInfo["id"].Value<int>(); + // var projectTitle = Global.ReplaceInvalidCharsAndTruncate(projectInfo["title"].Value<string>()); - if (projectInfo.TryGetValue("security", out var projectSecurityJToken)) - { - var projectSecurity = projectInfo["security"].Value<JObject>(); - if (projectSecurity.TryGetValue("canReadFiles", out var projectCanFileReadJToken)) - { - if (!projectSecurity["canReadFiles"].Value<bool>()) - { - continue; - } - } - } + // if (projectInfo.TryGetValue("security", out var projectSecurityJToken)) + // { + // var projectSecurity = projectInfo["security"].Value<JObject>(); + // if (projectSecurity.TryGetValue("canReadFiles", out var projectCanFileReadJToken)) + // { + // if (!projectSecurity["canReadFiles"].Value<bool>()) + // { + // continue; + // } + // } + // } - int projectFolderID; - if (projectInfo.TryGetValue("projectFolder", out var projectFolderIDjToken)) - projectFolderID = projectFolderIDjToken.Value<int>(); - else - projectFolderID = FilesIntegration.RegisterBunch<int>("projects", "project", projectID.ToString()); + // int projectFolderID; + // if (projectInfo.TryGetValue("projectFolder", out var projectFolderIDjToken)) + // projectFolderID = projectFolderIDjToken.Value<int>(); + // else + // projectFolderID = FilesIntegration.RegisterBunch<int>("projects", "project", projectID.ToString()); - if (!folderIDProjectTitle.ContainsKey(projectFolderID)) - folderIDProjectTitle.Add(projectFolderID, new KeyValuePair<int, string>(projectID, projectTitle)); + // if (!folderIDProjectTitle.ContainsKey(projectFolderID)) + // folderIDProjectTitle.Add(projectFolderID, new KeyValuePair<int, string>(projectID, projectTitle)); - Cache.Remove("documents/folders/" + projectFolderID); - Cache.Insert("documents/folders/" + projectFolderID, projectTitle, TimeSpan.FromMinutes(30)); - } - } + // Cache.Remove("documents/folders/" + projectFolderID); + // Cache.Insert("documents/folders/" + projectFolderID, projectTitle, TimeSpan.FromMinutes(30)); + // } + // } - var rootKeys = folderIDProjectTitle.Keys.ToArray(); - if (filter == FilterType.None || filter == FilterType.FoldersOnly) - { - var folders = DaoFactory.GetFolderDao<int>().GetFolders(rootKeys, filter, subjectGroup, subjectId, searchText, withSubfolders, false); + // var rootKeys = folderIDProjectTitle.Keys.ToArray(); + // if (filter == FilterType.None || filter == FilterType.FoldersOnly) + // { + // var folders = DaoFactory.GetFolderDao<int>().GetFolders(rootKeys, filter, subjectGroup, subjectId, searchText, withSubfolders, false); - var emptyFilter = string.IsNullOrEmpty(searchText) && filter == FilterType.None && subjectId == Guid.Empty; - if (!emptyFilter) - { - var projectFolderIds = - folderIDProjectTitle - .Where(projectFolder => string.IsNullOrEmpty(searchText) - || (projectFolder.Value.Value ?? "").ToLower().Trim().Contains(searchText.ToLower().Trim())) - .Select(projectFolder => projectFolder.Key); + // var emptyFilter = string.IsNullOrEmpty(searchText) && filter == FilterType.None && subjectId == Guid.Empty; + // if (!emptyFilter) + // { + // var projectFolderIds = + // folderIDProjectTitle + // .Where(projectFolder => string.IsNullOrEmpty(searchText) + // || (projectFolder.Value.Value ?? "").ToLower().Trim().Contains(searchText.ToLower().Trim())) + // .Select(projectFolder => projectFolder.Key); - folders.RemoveAll(folder => rootKeys.Contains(folder.ID)); + // folders.RemoveAll(folder => rootKeys.Contains(folder.ID)); - var projectFolders = DaoFactory.GetFolderDao<int>().GetFolders(projectFolderIds.ToList(), filter, subjectGroup, subjectId, null, false, false); - folders.AddRange(projectFolders); - } + // var projectFolders = DaoFactory.GetFolderDao<int>().GetFolders(projectFolderIds.ToList(), filter, subjectGroup, subjectId, null, false, false); + // folders.AddRange(projectFolders); + // } - folders.ForEach(x => - { - x.Title = folderIDProjectTitle.ContainsKey(x.ID) ? folderIDProjectTitle[x.ID].Value : x.Title; - x.FolderUrl = folderIDProjectTitle.ContainsKey(x.ID) ? PathProvider.GetFolderUrl(x, folderIDProjectTitle[x.ID].Key) : string.Empty; - }); + // folders.ForEach(x => + // { + // x.Title = folderIDProjectTitle.ContainsKey(x.ID) ? folderIDProjectTitle[x.ID].Value : x.Title; + // x.FolderUrl = folderIDProjectTitle.ContainsKey(x.ID) ? PathProvider.GetFolderUrl(x, folderIDProjectTitle[x.ID].Key) : string.Empty; + // }); - if (withSubfolders) - { - entries = entries.Concat(fileSecurity.FilterRead(folders)); - } - else - { - entries = entries.Concat(folders); - } - } + // if (withSubfolders) + // { + // entries = entries.Concat(fileSecurity.FilterRead(folders)); + // } + // else + // { + // entries = entries.Concat(folders); + // } + // } - if (filter != FilterType.FoldersOnly && withSubfolders) - { - var files = DaoFactory.GetFileDao<int>().GetFiles(rootKeys, filter, subjectGroup, subjectId, searchText, searchInContent); - entries = entries.Concat(fileSecurity.FilterRead(files)); - } - } + // if (filter != FilterType.FoldersOnly && withSubfolders) + // { + // var files = DaoFactory.GetFileDao<int>().GetFiles(rootKeys, filter, subjectGroup, subjectId, searchText, searchInContent); + // entries = entries.Concat(fileSecurity.FilterRead(files)); + // } + //} - CalculateTotal(); + //CalculateTotal(); } else if (parent.FolderType == FolderType.SHARE) { @@ -595,11 +588,11 @@ namespace ASC.Web.Files.Utils if (folderList.Count > 0) { var securityDao = DaoFactory.GetSecurityDao<string>(); - var ids = securityDao.GetPureShareRecords(folderList) + var ids = securityDao.GetPureShareRecords(folderList) //.Where(x => x.Owner == SecurityContext.CurrentAccount.ID) .Select(x => x.EntryId).Distinct(); - foreach(var id in ids) + foreach (var id in ids) { folderList.First(y => y.ID.Equals(id)).Shared = true; } diff --git a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs index 5efc0905eb..52bd9db9ad 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Net; using System.Net.Http; using System.Text; using System.Text.Json; diff --git a/products/ASC.Files/Server/Startup.cs b/products/ASC.Files/Server/Startup.cs index 57bd7c9b16..e6b321652a 100644 --- a/products/ASC.Files/Server/Startup.cs +++ b/products/ASC.Files/Server/Startup.cs @@ -13,9 +13,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using StackExchange.Redis.Extensions.Core.Configuration; -using StackExchange.Redis.Extensions.Newtonsoft; - namespace ASC.Files { public class Startup : BaseStartup diff --git a/products/ASC.Files/Service/Thumbnail/Builder.cs b/products/ASC.Files/Service/Thumbnail/Builder.cs index 48ef826a49..4d901c9782 100644 --- a/products/ASC.Files/Service/Thumbnail/Builder.cs +++ b/products/ASC.Files/Service/Thumbnail/Builder.cs @@ -19,7 +19,6 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -48,7 +47,6 @@ namespace ASC.Files.ThumbnailBuilder { private readonly ThumbnailSettings config; private readonly ILog logger; - private readonly IHttpClientFactory clientFactory; private IServiceProvider ServiceProvider { get; } public BuilderQueue(IServiceProvider serviceProvider, IOptionsMonitor<ILog> log, ThumbnailSettings settings) diff --git a/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs b/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs index f8330ef99f..46a6f62cc7 100644 --- a/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs +++ b/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs @@ -23,7 +23,6 @@ using System.Linq.Expressions; using ASC.Common; using ASC.Common.Caching; using ASC.Core.Common.EF; -using ASC.Core.Common.EF.Context; using ASC.Core.Tenants; using ASC.Files.Core; using ASC.Files.Core.EF; diff --git a/products/ASC.People/Server/Startup.cs b/products/ASC.People/Server/Startup.cs index 31d8e6196b..77b01317d7 100644 --- a/products/ASC.People/Server/Startup.cs +++ b/products/ASC.People/Server/Startup.cs @@ -7,12 +7,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using StackExchange.Redis.Extensions.Core.Configuration; -using StackExchange.Redis.Extensions.Newtonsoft; - namespace ASC.People { -public class Startup : BaseStartup + public class Startup : BaseStartup { public override bool ConfirmAddScheme { get => true; } diff --git a/web/ASC.Web.Core/Files/DocumentService.cs b/web/ASC.Web.Core/Files/DocumentService.cs index 506ad7912b..aa24156847 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -41,7 +41,6 @@ using System.Text.Json.Serialization; using System.Text.RegularExpressions; using ASC.Common.Web; -using ASC.Core; using ASC.Core.Billing; using Newtonsoft.Json; diff --git a/web/ASC.Web.Core/QuotaSync.cs b/web/ASC.Web.Core/QuotaSync.cs index de0cce7a79..4f62fb6ce2 100644 --- a/web/ASC.Web.Core/QuotaSync.cs +++ b/web/ASC.Web.Core/QuotaSync.cs @@ -25,7 +25,6 @@ using System; -using System.Linq; using ASC.Common.Threading; using ASC.Core; diff --git a/web/ASC.Web.HealthChecks.UI/Program.cs b/web/ASC.Web.HealthChecks.UI/Program.cs index e0f94d0fe8..4f643d32f4 100644 --- a/web/ASC.Web.HealthChecks.UI/Program.cs +++ b/web/ASC.Web.HealthChecks.UI/Program.cs @@ -1,7 +1,5 @@ using System.Threading.Tasks; -using ASC.Api.Core; - using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; diff --git a/web/ASC.Web.Studio/Startup.cs b/web/ASC.Web.Studio/Startup.cs index a2c2023cee..887a039237 100644 --- a/web/ASC.Web.Studio/Startup.cs +++ b/web/ASC.Web.Studio/Startup.cs @@ -12,9 +12,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using StackExchange.Redis.Extensions.Core.Configuration; -using StackExchange.Redis.Extensions.Newtonsoft; - namespace ASC.Web.Studio { public class Startup : BaseStartup From b1be9953ad7370d377ea5c850441000422ba8acf Mon Sep 17 00:00:00 2001 From: pavelbannov <pavel.bannov@onlyoffice.com> Date: Mon, 7 Feb 2022 22:15:32 +0300 Subject: [PATCH 143/167] fixed solution build --- .../Server/Core/Search/FactoryIndexerCase.cs | 2 +- .../Core/Search/FactoryIndexerContact.cs | 2 +- .../Core/Search/FactoryIndexerContactInfo.cs | 2 +- .../Server/Core/Search/FactoryIndexerDeal.cs | 2 +- .../Core/Search/FactoryIndexerEvents.cs | 2 +- .../Core/Search/FactoryIndexerFieldValue.cs | 2 +- .../Core/Search/FactoryIndexerInvoice.cs | 2 +- .../Server/Core/Search/FactoryIndexerTask.cs | 2 +- .../ASC.CRM/Server/Utils/CurrencyProvider.cs | 10 ++-- products/ASC.CRM/Server/Utils/MailSender.cs | 12 ++--- .../Server/iCalParser/iCalendarEmitter.cs | 53 ++++++++++--------- 11 files changed, 44 insertions(+), 47 deletions(-) diff --git a/products/ASC.CRM/Server/Core/Search/FactoryIndexerCase.cs b/products/ASC.CRM/Server/Core/Search/FactoryIndexerCase.cs index 8e6a83fbae..039847b799 100644 --- a/products/ASC.CRM/Server/Core/Search/FactoryIndexerCase.cs +++ b/products/ASC.CRM/Server/Core/Search/FactoryIndexerCase.cs @@ -68,7 +68,7 @@ namespace ASC.Web.CRM.Core.Search IQueryable<DbCase> GetBaseQuery(DateTime lastIndexed) => entityDao.CrmDbContext.Cases .Where(r => r.LastModifedOn >= lastIndexed) - .Join(entityDao.TenantDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) + .Join(entityDao.CrmDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) .Where(r => r.DbTenant.Status == ASC.Core.Tenants.TenantStatus.Active) .Select(r => r.DbEntity); diff --git a/products/ASC.CRM/Server/Core/Search/FactoryIndexerContact.cs b/products/ASC.CRM/Server/Core/Search/FactoryIndexerContact.cs index 4beed3b7c4..d906c5726f 100644 --- a/products/ASC.CRM/Server/Core/Search/FactoryIndexerContact.cs +++ b/products/ASC.CRM/Server/Core/Search/FactoryIndexerContact.cs @@ -68,7 +68,7 @@ namespace ASC.Web.CRM.Core.Search IQueryable<DbContact> GetBaseQuery(DateTime lastIndexed) => entityDao.CrmDbContext.Contacts .Where(r => r.LastModifedOn >= lastIndexed) - .Join(entityDao.TenantDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) + .Join(entityDao.CrmDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) .Where(r => r.DbTenant.Status == ASC.Core.Tenants.TenantStatus.Active) .Select(r => r.DbEntity); diff --git a/products/ASC.CRM/Server/Core/Search/FactoryIndexerContactInfo.cs b/products/ASC.CRM/Server/Core/Search/FactoryIndexerContactInfo.cs index cac8d01298..569494840e 100644 --- a/products/ASC.CRM/Server/Core/Search/FactoryIndexerContactInfo.cs +++ b/products/ASC.CRM/Server/Core/Search/FactoryIndexerContactInfo.cs @@ -68,7 +68,7 @@ namespace ASC.Web.CRM.Core.Search IQueryable<DbContactInfo> GetBaseQuery(DateTime lastIndexed) => entityDao.CrmDbContext.ContactsInfo .Where(r => r.LastModifedOn >= lastIndexed) - .Join(entityDao.TenantDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) + .Join(entityDao.CrmDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) .Where(r => r.DbTenant.Status == ASC.Core.Tenants.TenantStatus.Active) .Select(r => r.DbEntity); diff --git a/products/ASC.CRM/Server/Core/Search/FactoryIndexerDeal.cs b/products/ASC.CRM/Server/Core/Search/FactoryIndexerDeal.cs index bfc8d194bf..a891a61665 100644 --- a/products/ASC.CRM/Server/Core/Search/FactoryIndexerDeal.cs +++ b/products/ASC.CRM/Server/Core/Search/FactoryIndexerDeal.cs @@ -42,7 +42,7 @@ namespace ASC.Web.CRM.Core.Search IQueryable<DbDeal> GetBaseQuery(DateTime lastIndexed) => entityDao.CrmDbContext.Deals .Where(r => r.LastModifedOn >= lastIndexed) - .Join(entityDao.TenantDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) + .Join(entityDao.CrmDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) .Where(r => r.DbTenant.Status == ASC.Core.Tenants.TenantStatus.Active) .Select(r => r.DbEntity); diff --git a/products/ASC.CRM/Server/Core/Search/FactoryIndexerEvents.cs b/products/ASC.CRM/Server/Core/Search/FactoryIndexerEvents.cs index 64c79f11c5..3a3352a4ff 100644 --- a/products/ASC.CRM/Server/Core/Search/FactoryIndexerEvents.cs +++ b/products/ASC.CRM/Server/Core/Search/FactoryIndexerEvents.cs @@ -67,7 +67,7 @@ namespace ASC.Web.CRM.Core.Search IQueryable<DbRelationshipEvent> GetBaseQuery(DateTime lastIndexed) => entityDao.CrmDbContext.RelationshipEvent .Where(r => r.LastModifedOn >= lastIndexed) - .Join(entityDao.TenantDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) + .Join(entityDao.CrmDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) .Where(r => r.DbTenant.Status == ASC.Core.Tenants.TenantStatus.Active) .Select(r => r.DbEntity); diff --git a/products/ASC.CRM/Server/Core/Search/FactoryIndexerFieldValue.cs b/products/ASC.CRM/Server/Core/Search/FactoryIndexerFieldValue.cs index 294e1c0632..abab074969 100644 --- a/products/ASC.CRM/Server/Core/Search/FactoryIndexerFieldValue.cs +++ b/products/ASC.CRM/Server/Core/Search/FactoryIndexerFieldValue.cs @@ -68,7 +68,7 @@ namespace ASC.Web.CRM.Core.Search IQueryable<DbFieldValue> GetBaseQuery(DateTime lastIndexed) => entityDao.CrmDbContext.FieldValue .Where(r => r.LastModifedOn >= lastIndexed) - .Join(entityDao.TenantDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) + .Join(entityDao.CrmDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) .Where(r => r.DbTenant.Status == ASC.Core.Tenants.TenantStatus.Active) .Select(r => r.DbEntity); diff --git a/products/ASC.CRM/Server/Core/Search/FactoryIndexerInvoice.cs b/products/ASC.CRM/Server/Core/Search/FactoryIndexerInvoice.cs index 24d40cc93a..0170f1848f 100644 --- a/products/ASC.CRM/Server/Core/Search/FactoryIndexerInvoice.cs +++ b/products/ASC.CRM/Server/Core/Search/FactoryIndexerInvoice.cs @@ -68,7 +68,7 @@ namespace ASC.Web.CRM.Core.Search IQueryable<DbInvoice> GetBaseQuery(DateTime lastIndexed) => entityDao.CrmDbContext.Invoices .Where(r => r.LastModifedOn >= lastIndexed) - .Join(entityDao.TenantDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) + .Join(entityDao.CrmDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) .Where(r => r.DbTenant.Status == ASC.Core.Tenants.TenantStatus.Active) .Select(r => r.DbEntity); diff --git a/products/ASC.CRM/Server/Core/Search/FactoryIndexerTask.cs b/products/ASC.CRM/Server/Core/Search/FactoryIndexerTask.cs index 75802f80f1..f9ccb64981 100644 --- a/products/ASC.CRM/Server/Core/Search/FactoryIndexerTask.cs +++ b/products/ASC.CRM/Server/Core/Search/FactoryIndexerTask.cs @@ -68,7 +68,7 @@ namespace ASC.Web.CRM.Core.Search IQueryable<DbTask> GetBaseQuery(DateTime lastIndexed) => entityDao.CrmDbContext.Tasks .Where(r => r.LastModifedOn >= lastIndexed) - .Join(entityDao.TenantDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) + .Join(entityDao.CrmDbContext.Tenants, r => r.TenantId, r => r.Id, (f, t) => new { DbEntity = f, DbTenant = t }) .Where(r => r.DbTenant.Status == ASC.Core.Tenants.TenantStatus.Active) .Select(r => r.DbEntity); diff --git a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs index b4be4f5f31..273d14ce5e 100644 --- a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs +++ b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs @@ -254,7 +254,7 @@ namespace ASC.Web.CRM.Classes } catch (Exception error) { - _logger.Error(error); + _log.Error(error); _publisherDate = DateTime.UtcNow; } } @@ -308,7 +308,7 @@ namespace ASC.Web.CRM.Classes } catch (Exception err) { - _logger.Error(err); + _log.Error(err); } } } @@ -322,7 +322,7 @@ namespace ASC.Web.CRM.Classes } catch (Exception err) { - _logger.Error(err); + _log.Error(err); } } @@ -338,7 +338,7 @@ namespace ASC.Web.CRM.Classes Directory.CreateDirectory(dir); } - var destinationURI = new Uri("https://themoneyconverter.com/"+ currency + "/" + currency + ".aspx"); + var destinationURI = new Uri("https://themoneyconverter.com/" + currency + "/" + currency + ".aspx"); var request = new HttpRequestMessage(); request.RequestUri = destinationURI; @@ -362,7 +362,7 @@ namespace ASC.Web.CRM.Classes } catch (Exception error) { - _logger.Error(error); + _log.Error(error); } } diff --git a/products/ASC.CRM/Server/Utils/MailSender.cs b/products/ASC.CRM/Server/Utils/MailSender.cs index 70ca2befc7..b2408b241b 100644 --- a/products/ASC.CRM/Server/Utils/MailSender.cs +++ b/products/ASC.CRM/Server/Utils/MailSender.cs @@ -51,9 +51,8 @@ using ASC.CRM.Core.Dao; using ASC.CRM.Core.Entities; using ASC.CRM.Core.Enums; using ASC.CRM.Resources; -using ASC.Web.Files.Api; - -using MailKit; +using ASC.Web.Files.Api; + using MailKit.Net.Smtp; using MailKit.Security; @@ -275,7 +274,7 @@ namespace ASC.Web.CRM.Classes continue; } - var to = new MailboxAddress(recipientEmail); + var to = MailboxAddress.Parse(recipientEmail); var mimeMessage = new MimeMessage { @@ -431,8 +430,6 @@ namespace ASC.Web.CRM.Classes { var client = new SmtpClient { - ServerCertificateValidationCallback = (sender, certificate, chain, errors) => - WorkContext.IsMono || MailKit.MailService.DefaultServerCertificateValidationCallback(sender, certificate, chain, errors), Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds }; @@ -563,7 +560,6 @@ namespace ASC.Web.CRM.Classes { var client = new SmtpClient { - ServerCertificateValidationCallback = (sender, certificate, chain, errors) => MailService.DefaultServerCertificateValidationCallback(sender, certificate, chain, errors), Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds }; @@ -594,7 +590,7 @@ namespace ASC.Web.CRM.Classes { try { - var toAddress = new MailboxAddress(recipientEmail); + var toAddress = MailboxAddress.Parse(recipientEmail); var fromAddress = new MailboxAddress(smtpSetting.SenderDisplayName, smtpSetting.SenderEmailAddress); var mimeMessage = new MimeMessage diff --git a/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs b/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs index a22ab26dec..bb5fe3bcb7 100644 --- a/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs +++ b/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs @@ -27,10 +27,11 @@ using System; using System.Collections.Generic; using System.Linq; -using ASC.Common.Utils; -using ASC.Web.Core.Calendars; -using ASC.Core; using System.Net.Http; + +using ASC.Common.Utils; +using ASC.Core; +using ASC.Web.Core.Calendars; namespace ASC.Calendar.iCalParser { @@ -39,7 +40,7 @@ namespace ASC.Calendar.iCalParser private iCalendar _curCalendar; private iCalEvent _curEvent; - private Stack<Token> _component= new Stack<Token>(); + private Stack<Token> _component = new Stack<Token>(); private Token _curPropToken = null; public Parser VParser { get; set; } @@ -65,12 +66,12 @@ namespace ASC.Calendar.iCalParser } - public void doIntro(){} + public void doIntro() { } public void doOutro() { } - public void doComponent() { } - + public void doComponent() { } + public void doResource(Token t) { } public void emit(string val) { } @@ -85,44 +86,44 @@ namespace ASC.Calendar.iCalParser } public void doBegin(Token t) - { + { } - public void doEndComponent() + public void doEndComponent() { _component.Pop(); } public void doComponentBegin(Token t) - { + { _component.Push(t); switch (t.TokenVal) { - case TokenValue.Tvcalendar: + case TokenValue.Tvcalendar: _curCalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager, ClientFactory); break; case TokenValue.Tvevent: - case TokenValue.Tvjournal: + case TokenValue.Tvjournal: _curEvent = new iCalEvent(); _curCalendar.Events.Add(_curEvent); _curEvent.CalendarId = _curCalendar.Id; break; } - } - + } + public void doID(Token t) { - _curPropToken = t; + _curPropToken = t; } public void doSymbolic(Token t) - { + { } public void doURIResource(Token t) - { + { } public void doMailto(Token t) @@ -135,7 +136,7 @@ namespace ASC.Calendar.iCalParser bool isAllDay = true; bool isUTC = true; - if (_curPropToken.TokenVal == TokenValue.Tdtstart + if (_curPropToken.TokenVal == TokenValue.Tdtstart || _curPropToken.TokenVal == TokenValue.Tdtend || _curPropToken.TokenVal == TokenValue.Texdate) { @@ -186,7 +187,7 @@ namespace ASC.Calendar.iCalParser } public void doIprop(Token t, Token iprop) - { + { } public void doRest(Token t, Token id) @@ -208,8 +209,8 @@ namespace ASC.Calendar.iCalParser case "x:wrtimezone": _curCalendar.xTimeZone = t.TokenText; - break; - + break; + case "x:wrcalname": _curCalendar.Name = t.TokenText; break; @@ -266,7 +267,7 @@ namespace ASC.Calendar.iCalParser //event rrule if (_curPropToken.TokenVal == TokenValue.Trrule && _component.Peek().TokenVal == TokenValue.Tvevent) { - switch(key.TokenText.ToLowerInvariant()) + switch (key.TokenText.ToLowerInvariant()) { case "freq": _curEvent.RecurrenceRule.Freq = RecurrenceRule.ParseFrequency(val.TokenText); @@ -290,7 +291,7 @@ namespace ASC.Calendar.iCalParser break; case "byminute": - _curEvent.RecurrenceRule.ByMinute= val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray(); + _curEvent.RecurrenceRule.ByMinute = val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray(); break; case "byhour": @@ -298,7 +299,7 @@ namespace ASC.Calendar.iCalParser break; case "byday": - _curEvent.RecurrenceRule.ByDay = val.TokenText.Split(',').Select(v => RecurrenceRule.WeekDay.Parse(v)).ToArray(); + _curEvent.RecurrenceRule.ByDay = val.TokenText.Split(',').Select(v => RecurrenceRule.WeekDay.ParseWeekDay(v)).ToArray(); break; case "bymonthday": @@ -318,11 +319,11 @@ namespace ASC.Calendar.iCalParser break; case "bysetpos": - _curEvent.RecurrenceRule.BySetPos= val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray(); + _curEvent.RecurrenceRule.BySetPos = val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray(); break; case "wkst": - _curEvent.RecurrenceRule.WKST = RecurrenceRule.WeekDay.Parse(val.TokenText); + _curEvent.RecurrenceRule.WKST = RecurrenceRule.WeekDay.ParseWeekDay(val.TokenText); break; } } From 09e46f52d5292f703847d69be93143efb7b1fab5 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 03:04:33 +0300 Subject: [PATCH 144/167] resolve property name for mapping --- common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs | 4 ++-- common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs | 4 ++-- common/ASC.Core.Common/EF/Model/Audit/MessageEvent.cs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs b/common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs index 0026533a32..3075f4a3c9 100644 --- a/common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs +++ b/common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs @@ -40,7 +40,7 @@ .HasColumnName("date") .HasColumnType("datetime"); - entity.Property(e => e.Description) + entity.Property(e => e.DescriptionRaw) .HasColumnName("description") .HasColumnType("varchar(20000)") .HasCharSet("utf8") @@ -105,7 +105,7 @@ entity.Property(e => e.Date).HasColumnName("date"); - entity.Property(e => e.Description) + entity.Property(e => e.DescriptionRaw) .HasColumnName("description") .HasMaxLength(20000) .HasDefaultValueSql("NULL"); diff --git a/common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs b/common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs index 2257cf3afe..33de6b9ec8 100644 --- a/common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs +++ b/common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs @@ -40,7 +40,7 @@ .HasColumnName("date") .HasColumnType("datetime"); - entity.Property(e => e.Description) + entity.Property(e => e.DescriptionRaw) .HasColumnName("description") .HasColumnType("varchar(500)") .HasCharSet("utf8") @@ -103,7 +103,7 @@ entity.Property(e => e.Date).HasColumnName("date"); - entity.Property(e => e.Description) + entity.Property(e => e.DescriptionRaw) .HasColumnName("description") .HasMaxLength(500) .HasDefaultValueSql("NULL"); diff --git a/common/ASC.Core.Common/EF/Model/Audit/MessageEvent.cs b/common/ASC.Core.Common/EF/Model/Audit/MessageEvent.cs index 4594d2de49..782cd331ed 100644 --- a/common/ASC.Core.Common/EF/Model/Audit/MessageEvent.cs +++ b/common/ASC.Core.Common/EF/Model/Audit/MessageEvent.cs @@ -11,6 +11,6 @@ public Guid UserId { get; set; } public string Page { get; set; } public int Action { get; set; } - public string Description { get; set; } + public string DescriptionRaw { get; set; } } } From 3c4cf0f62e8e260f1b5b6e5e8fb8ff79b3f68d68 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 03:04:49 +0300 Subject: [PATCH 145/167] resolve property name for mapping --- common/ASC.MessagingSystem/DbSender/MessagesRepository.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs index da94f18940..47d2507fba 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -164,7 +164,7 @@ namespace ASC.MessagingSystem.DbSender if (message.Description != null && message.Description.Any()) { - le.Description = + le.DescriptionRaw = JsonConvert.SerializeObject(message.Description, new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc @@ -193,7 +193,7 @@ namespace ASC.MessagingSystem.DbSender if (message.Description != null && message.Description.Any()) { - ae.Description = + ae.DescriptionRaw = JsonConvert.SerializeObject(GetSafeDescription(message.Description), new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc From f7eda83bb0387a37ffedf7af95204751f8519299 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 03:05:25 +0300 Subject: [PATCH 146/167] AuditTrail: delete unnecessary --- .../Models/Mapping/AuditEventMappingAction.cs | 38 ------------------- .../Models/Mapping/LoginEventMappingAction.cs | 34 ----------------- 2 files changed, 72 deletions(-) delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs diff --git a/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs b/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs deleted file mode 100644 index 250d9f8c10..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/AuditEventMappingAction.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace ASC.AuditTrail.Models.Mapping.Actions; - -public class AuditEventMappingAction : IMappingAction<AuditEventQuery, AuditEvent> -{ - private readonly MessageTarget _messageTarget; - private readonly UserFormatter _userFormatter; - private readonly AuditActionMapper _auditActionMapper; - - public AuditEventMappingAction( - MessageTarget messageTarget, - UserFormatter userFormatter, - AuditActionMapper auditActionMapper) - { - _messageTarget = messageTarget; - _userFormatter = userFormatter; - _auditActionMapper = auditActionMapper; - } - - public void Process(AuditEventQuery source, AuditEvent destination, ResolutionContext context) - { - if (source.AuditEvent.Description != null) - destination.Description = JsonConvert.DeserializeObject<IList<string>>( - Convert.ToString(source.AuditEvent.Description), - new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); - - destination.Target = _messageTarget.Parse(source.AuditEvent.Target); - - destination.UserName = (source.User.FirstName != null && source.User.LastName != null) ? _userFormatter.GetUserName(source.User.FirstName, source.User.LastName) : - source.AuditEvent.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : - source.AuditEvent.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : - source.AuditEvent.Initiator ?? AuditReportResource.UnknownAccount; - - destination.ActionText = _auditActionMapper.GetActionText(destination); - destination.ActionTypeText = _auditActionMapper.GetActionTypeText(destination); - destination.Product = _auditActionMapper.GetProductText(destination); - destination.Module = _auditActionMapper.GetModuleText(destination); - } -} \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs b/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs deleted file mode 100644 index 19770b866b..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/LoginEventMappingAction.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace ASC.AuditTrail.Models.Mapping.Actions; - -public class LoginEventMappingAction : IMappingAction<LoginEventQuery, LoginEvent> -{ - private readonly UserFormatter _userFormatter; - private readonly AuditActionMapper _auditActionMapper; - - public LoginEventMappingAction(UserFormatter userFormatter, AuditActionMapper auditActionMapper) - { - _userFormatter = userFormatter; - _auditActionMapper = auditActionMapper; - } - - public void Process(LoginEventQuery source, LoginEvent destination, ResolutionContext context) - { - if (source.LoginEvents.Description != null) - destination.Description = JsonConvert.DeserializeObject<IList<string>>( - source.LoginEvents.Description, - new JsonSerializerSettings - { - DateTimeZoneHandling = DateTimeZoneHandling.Utc - }); - - destination.UserName = (!string.IsNullOrEmpty(source.User?.FirstName) && !string.IsNullOrEmpty(source.User?.LastName)) - ? _userFormatter.GetUserName(source.User.FirstName, source.User.LastName) - : !string.IsNullOrWhiteSpace(source.LoginEvents.Login) - ? source.LoginEvents.Login - : source.LoginEvents.UserId == Core.Configuration.Constants.Guest.ID - ? AuditReportResource.GuestAccount - : AuditReportResource.UnknownAccount; - - destination.ActionText = _auditActionMapper.GetActionText(destination); - } -} \ No newline at end of file From 4e497e47640847d96c1096cf3a0c176815c4078c Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 03:05:45 +0300 Subject: [PATCH 147/167] AuditTrail: add events type converter --- .../Models/Mapping/EventsConverter.cs | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 common/services/ASC.AuditTrail/Models/Mapping/EventsConverter.cs diff --git a/common/services/ASC.AuditTrail/Models/Mapping/EventsConverter.cs b/common/services/ASC.AuditTrail/Models/Mapping/EventsConverter.cs new file mode 100644 index 0000000000..63591c48b2 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mapping/EventsConverter.cs @@ -0,0 +1,74 @@ +namespace ASC.AuditTrail.Models.Mapping +{ + public class EventsConverter : ITypeConverter<LoginEventQuery, LoginEvent>, ITypeConverter<AuditEventQuery, AuditEvent> + { + private readonly UserFormatter _userFormatter; + private readonly AuditActionMapper _auditActionMapper; + private readonly MessageTarget _messageTarget; + + public EventsConverter( + UserFormatter userFormatter, + AuditActionMapper actionMapper, + MessageTarget messageTarget) + { + _userFormatter = userFormatter; + _auditActionMapper = actionMapper; + _messageTarget = messageTarget; + } + + public LoginEvent Convert(LoginEventQuery source, LoginEvent destination, ResolutionContext context) + { + var result = context.Mapper.Map<LoginEvent>(source.Event); + + if (source.Event.DescriptionRaw != null) + { + result.Description = JsonConvert.DeserializeObject<IList<string>>(source.Event.DescriptionRaw, + new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.Utc + }); + } + + result.UserName = (!string.IsNullOrEmpty(source.FirstName) && !string.IsNullOrEmpty(source.LastName)) + ? _userFormatter.GetUserName(source.FirstName, source.LastName) + : !string.IsNullOrWhiteSpace(source.Event.Login) + ? source.Event.Login + : source.Event.UserId == Core.Configuration.Constants.Guest.ID + ? AuditReportResource.GuestAccount + : AuditReportResource.UnknownAccount; + + result.ActionText = _auditActionMapper.GetActionText(result); + + return result; + } + + public AuditEvent Convert(AuditEventQuery source, AuditEvent destination, ResolutionContext context) + { + var result = context.Mapper.Map<AuditEvent>(source.Event); + + if (source.Event.DescriptionRaw != null) + { + result.Description = JsonConvert.DeserializeObject<IList<string>>( + JsonConvert.ToString(source.Event.DescriptionRaw), + new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.Utc + }); + } + + result.Target = _messageTarget.Parse(source.Event.Target); + + result.UserName = (source.FirstName != null && source.LastName != null) ? _userFormatter.GetUserName(source.FirstName, source.LastName) : + source.Event.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : + source.Event.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : + source.Event.Initiator ?? AuditReportResource.UnknownAccount; + + result.ActionText = _auditActionMapper.GetActionText(result); + result.ActionTypeText = _auditActionMapper.GetActionTypeText(result); + result.Product = _auditActionMapper.GetProductText(result); + result.Module = _auditActionMapper.GetModuleText(result); + + return result; + } + } +} \ No newline at end of file From 9fcf703c76472ed83aaa6b8e2f48124131bd0790 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 03:07:34 +0300 Subject: [PATCH 148/167] AuditTrail: change mapping --- common/services/ASC.AuditTrail/Models/AuditEvent.cs | 9 ++------- common/services/ASC.AuditTrail/Models/LoginEvent.cs | 11 ++++------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/common/services/ASC.AuditTrail/Models/AuditEvent.cs b/common/services/ASC.AuditTrail/Models/AuditEvent.cs index 86420c1cf5..857fba2c27 100644 --- a/common/services/ASC.AuditTrail/Models/AuditEvent.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEvent.cs @@ -46,14 +46,9 @@ public class AuditEvent : BaseEvent, IMapFrom<AuditEventQuery> public void Mapping(Profile profile) { - profile.CreateMap<DbAuditEvent, AuditEvent>() - .ForMember(src => src.Description, opt => opt.Ignore()); - - profile.CreateMap<User, AuditEvent>() - .ForMember(src => src.Id, opt => opt.Ignore()); + profile.CreateMap<DbAuditEvent, AuditEvent>(); profile.CreateMap<AuditEventQuery, AuditEvent>() - .IncludeMembers(src => src.AuditEvent, src => src.User) - .AfterMap<AuditEventMappingAction>(); + .ConvertUsing<EventsConverter>(); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/LoginEvent.cs b/common/services/ASC.AuditTrail/Models/LoginEvent.cs index d8ae4ebea5..dc78853399 100644 --- a/common/services/ASC.AuditTrail/Models/LoginEvent.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEvent.cs @@ -23,6 +23,8 @@ * */ +using ASC.AuditTrail.Models.Mapping; + namespace ASC.AuditTrail.Models; public class LoginEvent : BaseEvent, IMapFrom<LoginEventQuery> @@ -32,14 +34,9 @@ public class LoginEvent : BaseEvent, IMapFrom<LoginEventQuery> public void Mapping(Profile profile) { - profile.CreateMap<DbLoginEvent, LoginEvent>() - .ForMember(src => src.Description, opt => opt.Ignore()); - - profile.CreateMap<User, LoginEvent>() - .ForMember(src => src.Id, opt => opt.Ignore()); + profile.CreateMap<DbLoginEvent, LoginEvent>(); profile.CreateMap<LoginEventQuery, LoginEvent>() - .IncludeMembers(src => src.LoginEvents, src => src.User) - .AfterMap<LoginEventMappingAction>(); + .ConvertUsing<EventsConverter>(); } } \ No newline at end of file From 797208c5e761e505a6c85b789712c2532ea6a97c Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 03:07:55 +0300 Subject: [PATCH 149/167] AuditTrail: model simplification --- common/services/ASC.AuditTrail/Models/AuditEventQuery.cs | 6 ++++-- common/services/ASC.AuditTrail/Models/LoginEventQuery.cs | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs b/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs index 19bfbe51a9..9ca296a7d1 100644 --- a/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs @@ -2,6 +2,8 @@ public class AuditEventQuery { - public DbAuditEvent AuditEvent { get; set; } - public User User { get; set; } + public DbAuditEvent Event { get; set; } + public string UserName { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs b/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs index 796bf3ccd1..e68d511581 100644 --- a/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs @@ -2,6 +2,8 @@ public class LoginEventQuery { - public DbLoginEvent LoginEvents { get; set; } - public User User { get; set; } + public DbLoginEvent Event { get; set; } + public string UserName { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } } \ No newline at end of file From f094094abf6e2f650954955706abef1dd8c681e0 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 03:08:35 +0300 Subject: [PATCH 150/167] AuditTrail: change mapping, change select --- .../Repositories/AuditEventsRepository.cs | 12 +++++++--- .../Repositories/LoginEventsRepository.cs | 22 ++++++++++++++----- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs index faa7713f5a..4d46922385 100644 --- a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs @@ -64,13 +64,19 @@ public class AuditEventsRepository from p in AuditTrailContext.Users.Where(p => q.UserId == p.Id).DefaultIfEmpty() where q.TenantId == tenant orderby q.Date descending - select new AuditEventQuery { AuditEvent = q, User = p }; + select new AuditEventQuery + { + Event = q, + FirstName = p.FirstName, + LastName = p.LastName, + UserName = p.UserName + }; if (fromDate.HasValue && to.HasValue) - query = query.Where(q => q.AuditEvent.Date >= fromDate & q.AuditEvent.Date <= to); + query = query.Where(q => q.Event.Date >= fromDate & q.Event.Date <= to); if (limit.HasValue) query = query.Take((int)limit); - return query.AsEnumerable().Select(_mapper.Map<AuditEvent>).ToList(); + return _mapper.Map<List<AuditEventQuery>, List<AuditEvent>>(query.ToList()); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs index 49374657bf..7d174dd52c 100644 --- a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs @@ -48,10 +48,16 @@ public class LoginEventsRepository from p in MessagesContext.Users.Where(p => b.UserId == p.Id).DefaultIfEmpty() where b.TenantId == tenant orderby b.Date descending - select new LoginEventQuery { LoginEvents = b, User = p }) - .Take(chunk); + select new LoginEventQuery + { + Event = b, + UserName = p.UserName, + FirstName = p.FirstName, + LastName = p.LastName + }) + .Take(chunk); - return query.AsEnumerable().Select(_mapper.Map<LoginEvent>).ToList(); + return _mapper.Map<List<LoginEventQuery>, List<LoginEvent>>(query.ToList()); } public IEnumerable<LoginEvent> Get(int tenant, DateTime fromDate, DateTime to) @@ -63,9 +69,15 @@ public class LoginEventsRepository where q.Date >= fromDate where q.Date <= to orderby q.Date descending - select new LoginEventQuery { LoginEvents = q, User = p }; + select new LoginEventQuery + { + Event = q, + UserName = p.UserName, + FirstName = p.FirstName, + LastName = p.LastName + }; - return query.AsEnumerable().Select(_mapper.Map<LoginEvent>).ToList(); + return _mapper.Map<List<LoginEventQuery>, List<LoginEvent>>(query.ToList()); } public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) From d591a6e1294a73edb80be31b7c01f79e7dfebeab Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 03:08:46 +0300 Subject: [PATCH 151/167] AuditTrail: add using --- common/services/ASC.AuditTrail/GlobalUsings.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/services/ASC.AuditTrail/GlobalUsings.cs b/common/services/ASC.AuditTrail/GlobalUsings.cs index da99639c7a..c9b5502621 100644 --- a/common/services/ASC.AuditTrail/GlobalUsings.cs +++ b/common/services/ASC.AuditTrail/GlobalUsings.cs @@ -20,7 +20,7 @@ global using ASC.Web.Core.Files; global using ASC.Web.Files.Classes; global using ASC.Web.Files.Utils; global using ASC.AuditTrail.Models; -global using ASC.AuditTrail.Models.Mapping.Actions; +global using ASC.AuditTrail.Models.Mapping; global using ASC.Common.Mapping; global using Autofac; From 45b6e59350adb50ddc070374ab67c1fc1318d169 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 03:11:22 +0300 Subject: [PATCH 152/167] AuditTrail: add braces --- .../Repositories/AuditEventsRepository.cs | 19 ++++++++++++++++--- .../Repositories/LoginEventsRepository.cs | 5 ++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs index 4d46922385..c8a85ad337 100644 --- a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs @@ -41,9 +41,15 @@ public class AuditEventsRepository _mapper = mapper; } - public IEnumerable<AuditEvent> GetLast(int tenant, int chunk) => Get(tenant, null, null, chunk); + public IEnumerable<AuditEvent> GetLast(int tenant, int chunk) + { + return Get(tenant, null, null, chunk); + } - public IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) => Get(tenant, from, to, null); + public IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) + { + return Get(tenant, from, to, null); + } public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) { @@ -52,7 +58,9 @@ public class AuditEventsRepository .OrderByDescending(a => a.Date); if (from.HasValue && to.HasValue) + { query = query.Where(a => a.Date >= from & a.Date <= to); + } return query.Count(); } @@ -73,9 +81,14 @@ public class AuditEventsRepository }; if (fromDate.HasValue && to.HasValue) + { query = query.Where(q => q.Event.Date >= fromDate & q.Event.Date <= to); + } - if (limit.HasValue) query = query.Take((int)limit); + if (limit.HasValue) + { + query = query.Take((int)limit); + } return _mapper.Map<List<AuditEventQuery>, List<AuditEvent>>(query.ToList()); } diff --git a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs index 7d174dd52c..7e2fd4b323 100644 --- a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs @@ -85,7 +85,10 @@ public class LoginEventsRepository var query = MessagesContext.LoginEvents .Where(l => l.TenantId == tenant); - if (from.HasValue && to.HasValue) query = query.Where(l => l.Date >= from & l.Date <= to); + if (from.HasValue && to.HasValue) + { + query = query.Where(l => l.Date >= from & l.Date <= to); + } return query.Count(); } From 60a4f7c9abff346f97f0d532f9b521529065f0f9 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 12:07:07 +0300 Subject: [PATCH 153/167] ClearEvents: fix --- common/services/ASC.ClearEvents/Services/ClearEventsService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/services/ASC.ClearEvents/Services/ClearEventsService.cs b/common/services/ASC.ClearEvents/Services/ClearEventsService.cs index 7fd2764bf1..68d771e6e6 100644 --- a/common/services/ASC.ClearEvents/Services/ClearEventsService.cs +++ b/common/services/ASC.ClearEvents/Services/ClearEventsService.cs @@ -43,7 +43,7 @@ public class ClearEventsService : IHostedService, IDisposable _logger.Info("Timer Clear Events Service running."); _timer = new Timer(DeleteOldEvents, null, TimeSpan.Zero, - TimeSpan.FromSeconds(15)); + TimeSpan.FromDays(1)); return Task.CompletedTask; } From e3e43669eea7d87c55844225d42ba0b01a4e4ad4 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 12:59:22 +0300 Subject: [PATCH 154/167] ClearEvents: add braces --- common/services/ASC.ClearEvents/Program.cs | 17 ++++++++++++----- .../Services/ClearEventsService.cs | 7 ++++++- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/common/services/ASC.ClearEvents/Program.cs b/common/services/ASC.ClearEvents/Program.cs index 8992c072e4..bf6724c907 100644 --- a/common/services/ASC.ClearEvents/Program.cs +++ b/common/services/ASC.ClearEvents/Program.cs @@ -62,11 +62,18 @@ builder.Host.ConfigureServices((hostContext, services) => var redisConfiguration = hostContext.Configuration.GetSection("Redis").Get<RedisConfiguration>(); var kafkaConfiguration = hostContext.Configuration.GetSection("kafka").Get<KafkaSettings>(); - if (kafkaConfiguration != null) diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); - - else if (redisConfiguration != null) diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); - - else diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + if (kafkaConfiguration != null) + { + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCache<>)); + } + else if (redisConfiguration != null) + { + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCache<>)); + } + else + { + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); + } services.AddHostedService<ClearEventsService>(); diHelper.TryAdd<ClearEventsService>(); diff --git a/common/services/ASC.ClearEvents/Services/ClearEventsService.cs b/common/services/ASC.ClearEvents/Services/ClearEventsService.cs index 68d771e6e6..467f750579 100644 --- a/common/services/ASC.ClearEvents/Services/ClearEventsService.cs +++ b/common/services/ASC.ClearEvents/Services/ClearEventsService.cs @@ -62,7 +62,9 @@ public class ClearEventsService : IHostedService, IDisposable var handle = new AutoResetEvent(false); if ((bool)!(_timer?.Dispose(handle))) + { throw new Exception("Timer already disposed"); + } handle.WaitOne(); } @@ -108,7 +110,10 @@ public class ClearEventsService : IHostedService, IDisposable ids = ae.Select(r => r.ef).ToList(); - if (!ids.Any()) return; + if (!ids.Any()) + { + return; + } table.RemoveRange(ids); ef.SaveChanges(); From 2e3837fc7d16b3220591f3d95b128c2317c050c5 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 14:07:28 +0300 Subject: [PATCH 155/167] Common: add braces --- common/ASC.Common/Caching/AscCache.cs | 27 +- common/ASC.Common/Caching/EventBusKafka.cs | 20 +- .../ASC.Common/Caching/EventBusMemoryCache.cs | 19 +- common/ASC.Common/Caching/EventBusRedis.cs | 10 +- common/ASC.Common/Caching/ICache.cs | 1 - common/ASC.Common/Caching/Protobuf.cs | 14 +- .../Collections/CachedDictionaryBase.cs | 68 ++- .../Collections/HttpRequestDictionary.cs | 20 +- common/ASC.Common/DIHelper.cs | 123 +++-- common/ASC.Common/Data/TempPath.cs | 20 +- common/ASC.Common/Data/TempStream.cs | 17 +- .../DependencyInjection/AutofacExtension.cs | 48 +- common/ASC.Common/Logging/EFLoggerFactory.cs | 25 +- common/ASC.Common/Logging/Log.cs | 430 ++++++++++++++---- .../Logging/SelfCleaningAppender.cs | 14 +- .../ASC.Common/Logging/SelfCleaningTarget.cs | 25 +- .../Logging/SpecialFolderPathConverter.cs | 19 +- common/ASC.Common/Mapping/IMapFrom.cs | 5 +- common/ASC.Common/Mapping/MappingProfile.cs | 5 +- common/ASC.Common/Security/AscRandom.cs | 42 +- .../Security/Authentication/Account.cs | 20 +- .../Authorizing/AuthorizingException.cs | 36 +- .../Security/Authorizing/AzObjectIdHelper.cs | 5 +- .../AzObjectSecurityProviderHelper.cs | 21 +- .../Security/Authorizing/Domain/Action.cs | 22 +- .../Security/Authorizing/Domain/Role.cs | 25 +- .../Security/Cryptography/Hasher.cs | 93 +++- .../Security/Cryptography/InstanceCrypto.cs | 10 +- .../Cryptography/MachinePseudoKeys.cs | 15 +- .../Security/Cryptography/PasswordHasher.cs | 19 +- .../ASC.Common/Security/SecurityObjectId.cs | 15 +- .../ASC.Common/Threading/DistributedTask.cs | 22 +- .../Threading/DistributedTaskProgress.cs | 7 +- .../Threading/DistributedTaskQueue.cs | 120 +++-- .../ASC.Common/Utils/ConfigurationManager.cs | 30 +- common/ASC.Common/Utils/CrossPlatformUtils.cs | 4 +- common/ASC.Common/Utils/DnsLookup.cs | 34 +- common/ASC.Common/Utils/HtmlUtil.cs | 21 +- .../ASC.Common/Utils/HttpRequestExtensions.cs | 56 ++- common/ASC.Common/Utils/MailAddressUtils.cs | 15 +- common/ASC.Common/Utils/MimeHeaderUtils.cs | 15 +- common/ASC.Common/Utils/Signature.cs | 19 +- .../TimeZoneConverter/TimeZoneConverter.cs | 173 ++++--- common/ASC.Common/Utils/VelocityFormatter.cs | 18 +- common/ASC.Common/Utils/Wildcard.cs | 27 +- .../Web/AbstractHttpAsyncHandler.cs | 5 +- .../ASC.Common/Web/DisposableHttpContext.cs | 16 +- common/ASC.Common/Web/HttpException.cs | 39 +- common/ASC.Common/Web/RouteCallInfo.cs | 13 +- common/ASC.Common/Web/VirtualPathUtility.cs | 4 + 50 files changed, 1424 insertions(+), 447 deletions(-) diff --git a/common/ASC.Common/Caching/AscCache.cs b/common/ASC.Common/Caching/AscCache.cs index 87ada38b7e..6bb0a037da 100644 --- a/common/ASC.Common/Caching/AscCache.cs +++ b/common/ASC.Common/Caching/AscCache.cs @@ -62,7 +62,10 @@ public class AscCache : ICache _memoryCacheKeys = new ConcurrentDictionary<string, object>(); } - public T Get<T>(string key) where T : class => _memoryCache.Get<T>(key); + public T Get<T>(string key) where T : class + { + return _memoryCache.Get<T>(key); + } public void Insert(string key, object value, TimeSpan sligingExpiration) { @@ -84,7 +87,10 @@ public class AscCache : ICache _memoryCacheKeys.TryAdd(key, null); } - public void Remove(string key) => _memoryCache.Remove(key); + public void Remove(string key) + { + _memoryCache.Remove(key); + } public void Remove(Regex pattern) { @@ -104,7 +110,9 @@ public class AscCache : ICache { if (_memoryCache.TryGetValue<ConcurrentDictionary<string, T>>(key, out var dic) && dic.TryGetValue(field, out var value)) + { return value; + } return default; } @@ -121,12 +129,19 @@ public class AscCache : ICache { dic.TryRemove(field, out _); - if (dic.IsEmpty) _memoryCache.Remove(key); - - else _memoryCache.Set(key, dic, DateTime.MaxValue); + if (dic.IsEmpty) + { + _memoryCache.Remove(key); + } + else + { + _memoryCache.Set(key, dic, DateTime.MaxValue); + } } } - private void EvictionCallback(object key, object value, EvictionReason reason, object state) => + private void EvictionCallback(object key, object value, EvictionReason reason, object state) + { _memoryCacheKeys.TryRemove(key.ToString(), out _); + } } \ No newline at end of file diff --git a/common/ASC.Common/Caching/EventBusKafka.cs b/common/ASC.Common/Caching/EventBusKafka.cs index 9d83fc4102..c6724b1987 100644 --- a/common/ASC.Common/Caching/EventBusKafka.cs +++ b/common/ASC.Common/Caching/EventBusKafka.cs @@ -45,7 +45,10 @@ public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, var channelName = GetChannelName(eventType); - if (_actions.TryGetValue(channelName, out var onchange)) onchange(obj); + if (_actions.TryGetValue(channelName, out var onchange)) + { + onchange(obj); + } var message = new Message<AscCacheItem, T> { @@ -151,7 +154,10 @@ public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, { _cancelationToken.TryGetValue(GetChannelName(eventType), out var source); - if (source != null) source.Cancel(); + if (source != null) + { + source.Cancel(); + } } public void Dispose() @@ -164,7 +170,10 @@ public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, { if (!_disposedValue) { - if (disposing && _producer != null) _producer.Dispose(); + if (disposing && _producer != null) + { + _producer.Dispose(); + } _disposedValue = true; } @@ -175,7 +184,10 @@ public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, Dispose(false); } - private string GetChannelName(EventType eventType) => $"ascchannel{eventType}{typeof(T).FullName}".ToLower(); + private string GetChannelName(EventType eventType) + { + return $"ascchannel{eventType}{typeof(T).FullName}".ToLower(); + } } public class KafkaSettings diff --git a/common/ASC.Common/Caching/EventBusMemoryCache.cs b/common/ASC.Common/Caching/EventBusMemoryCache.cs index c777f0c2a2..ae664b0a39 100644 --- a/common/ASC.Common/Caching/EventBusMemoryCache.cs +++ b/common/ASC.Common/Caching/EventBusMemoryCache.cs @@ -5,22 +5,35 @@ public class EventBusMemoryCache<T> : IEventBus<T> where T : IMessage<T>, new() { private readonly ConcurrentDictionary<string, List<Action<T>>> _actions; - public EventBusMemoryCache() => _actions = new ConcurrentDictionary<string, List<Action<T>>>(); + public EventBusMemoryCache() + { + _actions = new ConcurrentDictionary<string, List<Action<T>>>(); + } public void Publish(T obj, EventType action) { if (_actions.TryGetValue(GetKey(action), out var onchange) && onchange != null) + { Parallel.ForEach(onchange, a => a(obj)); + } } public void Subscribe(Action<T> onchange, EventType notifyAction) { if (onchange != null) + { _actions.GetOrAdd(GetKey(notifyAction), new List<Action<T>>()) .Add(onchange); + } } - public void Unsubscribe(EventType action) => _actions.TryRemove(GetKey(action), out _); + public void Unsubscribe(EventType action) + { + _actions.TryRemove(GetKey(action), out _); + } - private string GetKey(EventType cacheNotifyAction) => $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); + private string GetKey(EventType cacheNotifyAction) + { + return $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); + } } \ No newline at end of file diff --git a/common/ASC.Common/Caching/EventBusRedis.cs b/common/ASC.Common/Caching/EventBusRedis.cs index dc4380908c..6cda191cb5 100644 --- a/common/ASC.Common/Caching/EventBusRedis.cs +++ b/common/ASC.Common/Caching/EventBusRedis.cs @@ -21,7 +21,10 @@ public class EventBusRedis<T> : IEventBus<T> where T : IMessage<T>, new() { private readonly IRedisDatabase _redis; - public EventBusRedis(IRedisCacheClient redisCacheClient) => _redis = redisCacheClient.GetDbFromConfiguration(); + public EventBusRedis(IRedisCacheClient redisCacheClient) + { + _redis = redisCacheClient.GetDbFromConfiguration(); + } public void Publish(T obj, EventType action) { @@ -50,7 +53,10 @@ public class EventBusRedis<T> : IEventBus<T> where T : IMessage<T>, new() .GetResult(); } - private string GetChannelName(EventType cacheNotifyAction) => $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); + private string GetChannelName(EventType cacheNotifyAction) + { + return $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); + } class RedisCachePubSubItem<T0> { diff --git a/common/ASC.Common/Caching/ICache.cs b/common/ASC.Common/Caching/ICache.cs index 80d1b6c869..e9d79345b0 100644 --- a/common/ASC.Common/Caching/ICache.cs +++ b/common/ASC.Common/Caching/ICache.cs @@ -38,7 +38,6 @@ public interface ICache void Remove(Regex pattern); - ConcurrentDictionary<string, T> HashGetAll<T>(string key); T HashGet<T>(string key, string field); diff --git a/common/ASC.Common/Caching/Protobuf.cs b/common/ASC.Common/Caching/Protobuf.cs index 69c1cf7398..40c6329d22 100644 --- a/common/ASC.Common/Caching/Protobuf.cs +++ b/common/ASC.Common/Caching/Protobuf.cs @@ -2,17 +2,25 @@ public class ProtobufSerializer<T> : ISerializer<T> where T : IMessage<T>, new() { - public byte[] Serialize(T data, SerializationContext context) => data.ToByteArray(); + public byte[] Serialize(T data, SerializationContext context) + { + return data.ToByteArray(); + } } public class ProtobufDeserializer<T> : IDeserializer<T> where T : IMessage<T>, new() { private readonly MessageParser<T> _parser; - public ProtobufDeserializer() => _parser = new MessageParser<T>(() => new T()); + public ProtobufDeserializer() + { + _parser = new MessageParser<T>(() => new T()); + } public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context) - => _parser.ParseFrom(data.ToArray()); + { + return _parser.ParseFrom(data.ToArray()); + } } public static class GuidExtension diff --git a/common/ASC.Common/Collections/CachedDictionaryBase.cs b/common/ASC.Common/Collections/CachedDictionaryBase.cs index 3c265b4294..5637915aad 100644 --- a/common/ASC.Common/Collections/CachedDictionaryBase.cs +++ b/common/ASC.Common/Collections/CachedDictionaryBase.cs @@ -36,23 +36,40 @@ public abstract class CachedDictionaryBase<T> protected abstract void InsertRootKey(string rootKey); - public void Clear() => InsertRootKey(BaseKey); + public void Clear() + { + InsertRootKey(BaseKey); + } - public void Clear(string rootKey) => InsertRootKey(BuildKey(string.Empty, rootKey)); + public void Clear(string rootKey) + { + InsertRootKey(BuildKey(string.Empty, rootKey)); + } - public void Reset(string key) => Reset(string.Empty, key); + public void Reset(string key) + { + Reset(string.Empty, key); + } - public abstract void Reset(string rootKey, string key); + public T Get(string key) + { + return Get(string.Empty, key, null); + } - public T Get(string key) => Get(string.Empty, key, null); + public T Get(string key, Func<T> defaults) + { + return Get(string.Empty, key, defaults); + } - public T Get(string key, Func<T> defaults) => Get(string.Empty, key, defaults); + public void Add(string key, T newValue) + { + Add(string.Empty, key, newValue); + } - public void Add(string key, T newValue) => Add(string.Empty, key, newValue); - - public abstract void Add(string rootkey, string key, T newValue); - - public bool HasItem(string key) => !Equals(Get(key), default(T)); + public bool HasItem(string key) + { + return !Equals(Get(key), default(T)); + } public T Get(Func<T> @default) { @@ -90,17 +107,36 @@ public abstract class CachedDictionaryBase<T> return default; } - protected virtual bool FitsCondition(object cached) => cached != null && cached is T; + public abstract void Add(string rootkey, string key, T newValue); - protected virtual T ReturnCached(object objectCache) => (T)objectCache; + public abstract void Reset(string rootKey, string key); - protected string BuildKey(string key, string rootkey) => $"{BaseKey}-{rootkey}-{key}"; + protected virtual bool FitsCondition(object cached) + { + return cached != null && cached is T; + } + + protected virtual T ReturnCached(object objectCache) + { + return (T)objectCache; + } + + protected string BuildKey(string key, string rootkey) + { + return $"{BaseKey}-{rootkey}-{key}"; + } protected abstract object GetObjectFromCache(string fullKey); [Conditional("DEBUG")] - protected virtual void OnHit(string fullKey) => Debug.Print("cache hit:{0}", fullKey); + protected virtual void OnHit(string fullKey) + { + Debug.Print("cache hit:{0}", fullKey); + } [Conditional("DEBUG")] - protected virtual void OnMiss(string fullKey) => Debug.Print("cache miss:{0}", fullKey); + protected virtual void OnMiss(string fullKey) + { + Debug.Print("cache miss:{0}", fullKey); + } } \ No newline at end of file diff --git a/common/ASC.Common/Collections/HttpRequestDictionary.cs b/common/ASC.Common/Collections/HttpRequestDictionary.cs index 3c0ddcf883..2d633a0bbd 100644 --- a/common/ASC.Common/Collections/HttpRequestDictionary.cs +++ b/common/ASC.Common/Collections/HttpRequestDictionary.cs @@ -54,11 +54,20 @@ public sealed class HttpRequestDictionary<T> : CachedDictionaryBase<T> } } - protected override object GetObjectFromCache(string fullKey) => _httpContext?.Items[fullKey]; + protected override object GetObjectFromCache(string fullKey) + { + return _httpContext?.Items[fullKey]; + } - protected override bool FitsCondition(object cached) => cached is CachedItem; + protected override bool FitsCondition(object cached) + { + return cached is CachedItem; + } - protected override T ReturnCached(object objectCache) => ((CachedItem)objectCache).Value; + protected override T ReturnCached(object objectCache) + { + return ((CachedItem)objectCache).Value; + } protected override void OnHit(string fullKey) { } @@ -73,6 +82,9 @@ public sealed class HttpRequestDictionary<T> : CachedDictionaryBase<T> { internal T Value { get; set; } - internal CachedItem(T value) => Value = value; + internal CachedItem(T value) + { + Value = value; + } } } \ No newline at end of file diff --git a/common/ASC.Common/DIHelper.cs b/common/ASC.Common/DIHelper.cs index b03d2df7b1..1342b2959a 100644 --- a/common/ASC.Common/DIHelper.cs +++ b/common/ASC.Common/DIHelper.cs @@ -19,9 +19,14 @@ public class TransientAttribute : DIAttribute public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) { - if (implementation != null) services.AddTransient(service, implementation); - - else services.AddTransient(service); + if (implementation != null) + { + services.AddTransient(service, implementation); + } + else + { + services.AddTransient(service); + } } } @@ -37,9 +42,14 @@ public class ScopeAttribute : DIAttribute public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) { - if (implementation != null) services.AddScoped(service, implementation); - - else services.AddScoped(service); + if (implementation != null) + { + services.AddScoped(service, implementation); + } + else + { + services.AddScoped(service); + } } } @@ -55,9 +65,14 @@ public class SingletoneAttribute : DIAttribute public override void TryAdd(IServiceCollection services, Type service, Type implementation = null) { - if (implementation != null) services.AddSingleton(service, implementation); - - else services.AddSingleton(service); + if (implementation != null) + { + services.AddSingleton(service, implementation); + } + else + { + services.AddSingleton(service); + } } } @@ -70,7 +85,10 @@ public abstract class DIAttribute : Attribute public DIAttribute() { } - public DIAttribute(Type service) => Service = service; + public DIAttribute(Type service) + { + Service = service; + } public DIAttribute(Type service, Type implementation) { @@ -101,21 +119,35 @@ public class DIHelper Configured = new List<string>(); } - public DIHelper(IServiceCollection serviceCollection) : this() => ServiceCollection = serviceCollection; + public DIHelper(IServiceCollection serviceCollection) : this() + { + ServiceCollection = serviceCollection; + } - public void Configure(IServiceCollection serviceCollection) => ServiceCollection = serviceCollection; + public void Configure(IServiceCollection serviceCollection) + { + ServiceCollection = serviceCollection; + } public void RegisterProducts(IConfiguration configuration, string path) { var types = AutofacExtension.FindAndLoad(configuration, path); foreach (var t in types.Select(Type.GetType).Where(r => r != null)) + { TryAdd(t); + } } - public bool TryAdd<TService>() where TService : class => TryAdd(typeof(TService)); + public bool TryAdd<TService>() where TService : class + { + return TryAdd(typeof(TService)); + } - public bool TryAdd<TService, TImplementation>() where TService : class => TryAdd(typeof(TService), typeof(TImplementation)); + public bool TryAdd<TService, TImplementation>() where TService : class + { + return TryAdd(typeof(TService), typeof(TImplementation)); + } public bool TryAdd(Type service, Type implementation = null) { @@ -127,12 +159,18 @@ public class DIHelper { service = service.GetGenericArguments().FirstOrDefault(); - if (service == null) return false; + if (service == null) + { + return false; + } } var serviceName = $"{service}{implementation}"; - if (Added.Contains(serviceName)) return false; + if (Added.Contains(serviceName)) + { + return false; + } Added.Add(serviceName); @@ -155,7 +193,10 @@ public class DIHelper if (!service.IsInterface || implementation != null) { isnew = implementation != null ? Register(service, implementation) : Register(service); - if (!isnew) return false; + if (!isnew) + { + return false; + } } if (service.IsInterface && implementation == null || !service.IsInterface) @@ -180,7 +221,10 @@ public class DIHelper { TryAdd(g); - if (service.IsInterface && di.Implementation == null) TryAdd(service, g); + if (service.IsInterface && di.Implementation == null) + { + TryAdd(service, g); + } } } @@ -215,7 +259,10 @@ public class DIHelper isnew = Register(service, di.Service); TryAdd(di.Service); } - else Register(di.Service); + else + { + Register(di.Service); + } } } @@ -237,7 +284,10 @@ public class DIHelper if (g != service) { //TryAdd(g); - if (service.IsInterface && implementation == null) TryAdd(service, g); + if (service.IsInterface && implementation == null) + { + TryAdd(service, g); + } } } @@ -256,14 +306,20 @@ public class DIHelper TryAdd(b1); c = a1.MakeGenericType(b1); } - else c = a1.MakeGenericType(service.GetGenericArguments()); + else + { + c = a1.MakeGenericType(service.GetGenericArguments()); + } TryAdd(c, di.Implementation.MakeGenericType(service.GetGenericArguments())); //a, di.Service } } - else isnew = TryAdd(service, di.Implementation); + else + { + isnew = TryAdd(service, di.Implementation); + } } } } @@ -272,18 +328,27 @@ public class DIHelper { ConstructorInfo[] props = null; - if (!service.IsInterface) props = service.GetConstructors(); - - else if (implementation != null) props = implementation.GetConstructors(); - - else if (di.Service != null) props = di.Service.GetConstructors(); + if (!service.IsInterface) + { + props = service.GetConstructors(); + } + else if (implementation != null) + { + props = implementation.GetConstructors(); + } + else if (di.Service != null) + { + props = di.Service.GetConstructors(); + } if (props != null) { var par = props.SelectMany(r => r.GetParameters()).Distinct(); foreach (var p1 in par) + { TryAdd(p1.ParameterType); + } } } @@ -346,7 +411,9 @@ public class DIHelper { if (service.IsSubclassOf(typeof(ControllerBase)) || service.GetInterfaces().Contains(typeof(IResourceFilter)) || service.GetInterfaces().Contains(typeof(IDictionary<string, string>))) + { return true; + } var c = service.IsGenericType && ( service.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) || @@ -366,4 +433,4 @@ public class DIHelper return false; } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Data/TempPath.cs b/common/ASC.Common/Data/TempPath.cs index f7d53c36e5..376a7074b6 100644 --- a/common/ASC.Common/Data/TempPath.cs +++ b/common/ASC.Common/Data/TempPath.cs @@ -24,19 +24,27 @@ public class TempPath public TempPath(IConfiguration configuration) { string rootFolder = AppContext.BaseDirectory; - if (string.IsNullOrEmpty(rootFolder)) + { rootFolder = Assembly.GetEntryAssembly().Location; + } _tempFolder = configuration["temp"] ?? Path.Combine("..", "Data", "temp"); - if (!Path.IsPathRooted(_tempFolder)) + { _tempFolder = Path.GetFullPath(Path.Combine(rootFolder, _tempFolder)); + } - if (!Directory.Exists(_tempFolder)) Directory.CreateDirectory(_tempFolder); + if (!Directory.Exists(_tempFolder)) + { + Directory.CreateDirectory(_tempFolder); + } } - public string GetTempPath() => _tempFolder; + public string GetTempPath() + { + return _tempFolder; + } public string GetTempFileName() { @@ -58,12 +66,16 @@ public class TempPath catch (IOException ex) { if (ex.HResult != -2147024816 || count++ > 65536) + { throw; + } } catch (UnauthorizedAccessException ex) { if (count++ > 65536) + { throw new IOException(ex.Message, ex); + } } } while (f == null); diff --git a/common/ASC.Common/Data/TempStream.cs b/common/ASC.Common/Data/TempStream.cs index b80f2f89bc..d917fb9044 100644 --- a/common/ASC.Common/Data/TempStream.cs +++ b/common/ASC.Common/Data/TempStream.cs @@ -21,11 +21,17 @@ public class TempStream { private readonly TempPath _tempPath; - public TempStream(TempPath tempPath) => _tempPath = tempPath; + public TempStream(TempPath tempPath) + { + _tempPath = tempPath; + } public Stream GetBuffered(Stream srcStream) { - if (srcStream == null) throw new ArgumentNullException(nameof(srcStream)); + if (srcStream == null) + { + throw new ArgumentNullException(nameof(srcStream)); + } if (!srcStream.CanSeek || srcStream.CanTimeout) { @@ -40,6 +46,9 @@ public class TempStream return srcStream; } - public Stream Create() => new FileStream(_tempPath.GetTempFileName(), FileMode.OpenOrCreate, - FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose); + public Stream Create() + { + return new FileStream(_tempPath.GetTempFileName(), FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose); + } } \ No newline at end of file diff --git a/common/ASC.Common/DependencyInjection/AutofacExtension.cs b/common/ASC.Common/DependencyInjection/AutofacExtension.cs index 2f4cb4c895..b76c0b5e7a 100644 --- a/common/ASC.Common/DependencyInjection/AutofacExtension.cs +++ b/common/ASC.Common/DependencyInjection/AutofacExtension.cs @@ -22,19 +22,28 @@ public static class AutofacExtension }; if (loadproducts) + { modules.Add((true, "autofac.products.json")); + } if (loadconsumers) + { modules.Add((true, "autofac.consumers.json")); + } if (intern != null) + { modules.AddRange(intern.Select(r => (false, r))); + } foreach (var p in modules) { var config = new ConfigurationBuilder(); - if (p.Item1) config.SetBasePath(configuration["pathToConf"]); + if (p.Item1) + { + config.SetBasePath(configuration["pathToConf"]); + } config.AddJsonFile(p.Item2); @@ -54,8 +63,10 @@ public static class AutofacExtension var root = config.Build(); var sectionSettings = root.GetSection("components"); - - if (sectionSettings == null) return new List<string>(); + if (sectionSettings == null) + { + return new List<string>(); + } var folder = configuration["core:products:folder"]; var subfolder = configuration["core:products:subfolder"]; @@ -64,12 +75,18 @@ public static class AutofacExtension if (!Path.IsPathRooted(folder)) { if (currentDir.EndsWith(CrossPlatform.PathCombine(Path.GetFileName(folder), Assembly.GetEntryAssembly().GetName().Name, subfolder))) + { productsDir = Path.GetFullPath(CrossPlatform.PathCombine("..", "..")); - - else productsDir = Path.GetFullPath(CrossPlatform.PathCombine(currentDir, folder)); + } + else + { + productsDir = Path.GetFullPath(CrossPlatform.PathCombine(currentDir, folder)); + } + } + else + { + productsDir = folder; } - - else productsDir = folder; var cs = new List<AutofacComponent>(); sectionSettings.Bind(cs); @@ -97,7 +114,9 @@ public static class AutofacExtension var path = GetFullPath(dll); if (!string.IsNullOrEmpty(path)) + { AssemblyLoadContext.Default.Resolving += new Resolver(path).Resolving; + } } string GetFullPath(string n) @@ -110,7 +129,10 @@ public static class AutofacExtension static string GetPath(string dirPath, string dll, SearchOption searchOption) { - if (!Directory.Exists(dirPath)) return null; + if (!Directory.Exists(dirPath)) + { + return null; + } return Directory.GetFiles(dirPath, $"{dll}.dll", searchOption).FirstOrDefault(); } @@ -121,13 +143,19 @@ class Resolver { private readonly string _resolvePath; - public Resolver(string assemblyPath) => _resolvePath = assemblyPath; + public Resolver(string assemblyPath) + { + _resolvePath = assemblyPath; + } public Assembly Resolving(AssemblyLoadContext context, AssemblyName assemblyName) { var path = CrossPlatform.PathCombine(Path.GetDirectoryName(_resolvePath), $"{assemblyName.Name}.dll"); - if (!File.Exists(path)) return null; + if (!File.Exists(path)) + { + return null; + } return context.LoadFromAssemblyPath(path); } diff --git a/common/ASC.Common/Logging/EFLoggerFactory.cs b/common/ASC.Common/Logging/EFLoggerFactory.cs index b3db84d929..d225a16759 100644 --- a/common/ASC.Common/Logging/EFLoggerFactory.cs +++ b/common/ASC.Common/Logging/EFLoggerFactory.cs @@ -20,7 +20,10 @@ public class EFLoggerFactory : ILoggerFactory //LoggerProvider = provider; } - public ILogger CreateLogger(string categoryName) => _logger.Value; + public ILogger CreateLogger(string categoryName) + { + return _logger.Value; + } public void Dispose() { } } @@ -30,9 +33,15 @@ public class EFLoggerProvider : ILoggerProvider { private readonly IOptionsMonitor<ILog> _option; - public EFLoggerProvider(IOptionsMonitor<ILog> option) => _option = option; + public EFLoggerProvider(IOptionsMonitor<ILog> option) + { + _option = option; + } - public ILogger CreateLogger(string categoryName) => new EFLogger(_option.Get("ASC.SQL")); + public ILogger CreateLogger(string categoryName) + { + return new EFLogger(_option.Get("ASC.SQL")); + } public void Dispose() { } } @@ -41,9 +50,15 @@ public class EFLogger : ILogger { public ILog CustomLogger { get; } - public EFLogger(ILog customLogger) => CustomLogger = customLogger; + public EFLogger(ILog customLogger) + { + CustomLogger = customLogger; + } - public IDisposable BeginScope<TState>(TState state) { return null; } + public IDisposable BeginScope<TState>(TState state) + { + return null; + } public bool IsEnabled(LogLevel logLevel) { diff --git a/common/ASC.Common/Logging/Log.cs b/common/ASC.Common/Logging/Log.cs index c7b580ff86..3185e9a14c 100644 --- a/common/ASC.Common/Logging/Log.cs +++ b/common/ASC.Common/Logging/Log.cs @@ -101,9 +101,15 @@ public class Log : ILog private log4net.ILog _logger; - public Log(string name) => Configure(name); + public Log(string name) + { + Configure(name); + } - static Log() => XmlConfigurator.Configure(log4net.LogManager.GetRepository(Assembly.GetCallingAssembly())); + static Log() + { + XmlConfigurator.Configure(log4net.LogManager.GetRepository(Assembly.GetCallingAssembly())); + } public void Configure(string name) { @@ -119,52 +125,82 @@ public class Log : ILog public void Trace(object message) { - if (IsTraceEnabled) _logger.Logger.Log(GetType(), Level.Trace, message, null); + if (IsTraceEnabled) + { + _logger.Logger.Log(GetType(), Level.Trace, message, null); + } } public void TraceFormat(string message, object arg0) { - if (IsTraceEnabled) _logger.Logger.Log(GetType(), Level.Trace, string.Format(message, arg0), null); + if (IsTraceEnabled) + { + _logger.Logger.Log(GetType(), Level.Trace, string.Format(message, arg0), null); + } } public void Debug(object message) { - if (IsDebugEnabled) _logger.Debug(message); + if (IsDebugEnabled) + { + _logger.Debug(message); + } } public void Debug(object message, Exception exception) { - if (IsDebugEnabled) _logger.Debug(message, exception); + if (IsDebugEnabled) + { + _logger.Debug(message, exception); + } } public void DebugFormat(string format, params object[] args) { - if (IsDebugEnabled) _logger.DebugFormat(format, args); + if (IsDebugEnabled) + { + _logger.DebugFormat(format, args); + } } public void DebugFormat(string format, object arg0) { - if (IsDebugEnabled) _logger.DebugFormat(format, arg0); + if (IsDebugEnabled) + { + _logger.DebugFormat(format, arg0); + } } public void DebugFormat(string format, object arg0, object arg1) { - if (IsDebugEnabled) _logger.DebugFormat(format, arg0, arg1); + if (IsDebugEnabled) + { + _logger.DebugFormat(format, arg0, arg1); + } } public void DebugFormat(string format, object arg0, object arg1, object arg2) { - if (IsDebugEnabled) _logger.DebugFormat(format, arg0, arg1, arg2); + if (IsDebugEnabled) + { + _logger.DebugFormat(format, arg0, arg1, arg2); + } } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { - if (IsDebugEnabled) _logger.DebugFormat(provider, format, args); + if (IsDebugEnabled) + { + _logger.DebugFormat(provider, format, args); + } } public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) { - if (!IsDebugEnabled) return; + if (!IsDebugEnabled) + { + return; + } foreach (var p in props) { @@ -177,150 +213,237 @@ public class Log : ILog public void Info(object message) { - if (IsInfoEnabled) _logger.Info(message); + if (IsInfoEnabled) + { + _logger.Info(message); + } } public void Info(string message, Exception exception) { - if (IsInfoEnabled) _logger.Info(message, exception); + if (IsInfoEnabled) + { + _logger.Info(message, exception); + } } public void InfoFormat(string format, params object[] args) { - if (IsInfoEnabled) _logger.InfoFormat(format, args); + if (IsInfoEnabled) + { + _logger.InfoFormat(format, args); + } } public void InfoFormat(string format, object arg0) { - if (IsInfoEnabled) _logger.InfoFormat(format, arg0); + if (IsInfoEnabled) + { + _logger.InfoFormat(format, arg0); + } } public void InfoFormat(string format, object arg0, object arg1) { - if (IsInfoEnabled) _logger.InfoFormat(format, arg0, arg1); + if (IsInfoEnabled) + { + _logger.InfoFormat(format, arg0, arg1); + } } public void InfoFormat(string format, object arg0, object arg1, object arg2) { - if (IsInfoEnabled) _logger.InfoFormat(format, arg0, arg1, arg2); + if (IsInfoEnabled) + { + _logger.InfoFormat(format, arg0, arg1, arg2); + } } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { - if (IsInfoEnabled) _logger.InfoFormat(provider, format, args); + if (IsInfoEnabled) + { + _logger.InfoFormat(provider, format, args); + } } public void Warn(object message) { - if (IsWarnEnabled) _logger.Warn(message); + if (IsWarnEnabled) + { + _logger.Warn(message); + } } public void Warn(object message, Exception exception) { - if (IsWarnEnabled) _logger.Warn(message, exception); + if (IsWarnEnabled) + { + _logger.Warn(message, exception); + } } public void WarnFormat(string format, params object[] args) { - if (IsWarnEnabled) _logger.WarnFormat(format, args); + if (IsWarnEnabled) + { + _logger.WarnFormat(format, args); + } } public void WarnFormat(string format, object arg0) { - if (IsWarnEnabled) _logger.WarnFormat(format, arg0); + if (IsWarnEnabled) + { + _logger.WarnFormat(format, arg0); + } } public void WarnFormat(string format, object arg0, object arg1) { - if (IsWarnEnabled) _logger.WarnFormat(format, arg0, arg1); + if (IsWarnEnabled) + { + _logger.WarnFormat(format, arg0, arg1); + } } public void WarnFormat(string format, object arg0, object arg1, object arg2) { - if (IsWarnEnabled) _logger.WarnFormat(format, arg0, arg1, arg2); + if (IsWarnEnabled) + { + _logger.WarnFormat(format, arg0, arg1, arg2); + } } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { - if (IsWarnEnabled) _logger.WarnFormat(provider, format, args); + if (IsWarnEnabled) + { + _logger.WarnFormat(provider, format, args); + } } public void Error(object message) { - if (IsErrorEnabled) _logger.Error(message); + if (IsErrorEnabled) + { + _logger.Error(message); + } } public void Error(object message, Exception exception) { - if (IsErrorEnabled) _logger.Error(message, exception); + if (IsErrorEnabled) + { + _logger.Error(message, exception); + } } public void ErrorFormat(string format, params object[] args) { - if (IsErrorEnabled) _logger.ErrorFormat(format, args); + if (IsErrorEnabled) + { + _logger.ErrorFormat(format, args); + } } public void ErrorFormat(string format, object arg0) { - if (IsErrorEnabled) _logger.ErrorFormat(format, arg0); + if (IsErrorEnabled) + { + _logger.ErrorFormat(format, arg0); + } } public void ErrorFormat(string format, object arg0, object arg1) { - if (IsErrorEnabled) _logger.ErrorFormat(format, arg0, arg1); + if (IsErrorEnabled) + { + _logger.ErrorFormat(format, arg0, arg1); + } } public void ErrorFormat(string format, object arg0, object arg1, object arg2) { - if (IsErrorEnabled) _logger.ErrorFormat(format, arg0, arg1, arg2); + if (IsErrorEnabled) + { + _logger.ErrorFormat(format, arg0, arg1, arg2); + } } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { - if (IsErrorEnabled) _logger.ErrorFormat(provider, format, args); + if (IsErrorEnabled) + { + _logger.ErrorFormat(provider, format, args); + } } public void Fatal(object message) { - if (IsFatalEnabled) _logger.Fatal(message); + if (IsFatalEnabled) + { + _logger.Fatal(message); + } } public void Fatal(string message, Exception exception) { - if (IsFatalEnabled) _logger.Fatal(message, exception); + if (IsFatalEnabled) + { + _logger.Fatal(message, exception); + } } public void FatalFormat(string format, params object[] args) { - if (IsFatalEnabled) _logger.FatalFormat(format, args); + if (IsFatalEnabled) + { + _logger.FatalFormat(format, args); + } } public void FatalFormat(string format, object arg0) { - if (IsFatalEnabled) _logger.FatalFormat(format, arg0); + if (IsFatalEnabled) + { + _logger.FatalFormat(format, arg0); + } } public void FatalFormat(string format, object arg0, object arg1) { - if (IsFatalEnabled) _logger.FatalFormat(format, arg0, arg1); + if (IsFatalEnabled) + { + _logger.FatalFormat(format, arg0, arg1); + } } public void FatalFormat(string format, object arg0, object arg1, object arg2) { - if (IsFatalEnabled) _logger.FatalFormat(format, arg0, arg1, arg2); + if (IsFatalEnabled) + { + _logger.FatalFormat(format, arg0, arg1, arg2); + } } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { - if (IsFatalEnabled) _logger.FatalFormat(provider, format, args); + if (IsFatalEnabled) + { + _logger.FatalFormat(provider, format, args); + } } public void DebugWithProps(string message, KeyValuePair<string, object> prop1, KeyValuePair<string, object> prop2, KeyValuePair<string, object> prop3) { - if (!IsDebugEnabled) return; + if (!IsDebugEnabled) + { + return; + } AddProp(prop1); AddProp(prop2); @@ -359,22 +482,31 @@ public class ConfigureLogNLog : IConfigureNamedOptions<LogNLog> var settings = _configurationExtension.GetSetting<NLogSettings>("log"); if (!string.IsNullOrEmpty(settings.Name)) + { LogManager.Configuration.Variables["name"] = settings.Name; + } if (!string.IsNullOrEmpty(settings.Dir)) + { LogManager.Configuration.Variables["dir"] = CrossPlatform.PathCombine(hostingEnvironment.ContentRootPath, settings.Dir) .TrimEnd('/').TrimEnd('\\') + Path.DirectorySeparatorChar; + } - NLog.Targets.Target.Register<SelfCleaningTarget>("SelfCleaning"); + Target.Register<SelfCleaningTarget>("SelfCleaning"); } public void Configure(LogNLog options) => options.Configure("ASC"); public void Configure(string name, LogNLog options) { - if (string.IsNullOrEmpty(name)) Configure(options); - - else options.Configure(name); + if (string.IsNullOrEmpty(name)) + { + Configure(options); + } + else + { + options.Configure(name); + } } } @@ -417,56 +549,89 @@ public class LogNLog : ILog private NLog.ILogger _logger; private string _name; - public void Configure(string name) => Name = name; + public void Configure(string name) + { + Name = name; + } public void Trace(object message) { - if (IsTraceEnabled) Logger.Log(LogLevel.Trace, message); + if (IsTraceEnabled) + { + Logger.Log(LogLevel.Trace, message); + } } public void TraceFormat(string message, object arg0) { - if (IsTraceEnabled) Logger.Log(LogLevel.Trace, string.Format(message, arg0)); + if (IsTraceEnabled) + { + Logger.Log(LogLevel.Trace, string.Format(message, arg0)); + } } public void Debug(object message) { - if (IsDebugEnabled) Logger.Debug(message); + if (IsDebugEnabled) + { + Logger.Debug(message); + } } public void Debug(object message, Exception exception) { - if (IsDebugEnabled) Logger.Debug(exception, "{0}", message); + if (IsDebugEnabled) + { + Logger.Debug(exception, "{0}", message); + } } public void DebugFormat(string format, params object[] args) { - if (IsDebugEnabled) Logger.Debug(format, args); + if (IsDebugEnabled) + { + Logger.Debug(format, args); + } } public void DebugFormat(string format, object arg0) { - if (IsDebugEnabled) Logger.Debug(format, arg0); + if (IsDebugEnabled) + { + Logger.Debug(format, arg0); + } } public void DebugFormat(string format, object arg0, object arg1) { - if (IsDebugEnabled) Logger.Debug(format, arg0, arg1); + if (IsDebugEnabled) + { + Logger.Debug(format, arg0, arg1); + } } public void DebugFormat(string format, object arg0, object arg1, object arg2) { - if (IsDebugEnabled) Logger.Debug(format, arg0, arg1, arg2); + if (IsDebugEnabled) + { + Logger.Debug(format, arg0, arg1, arg2); + } } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { - if (IsDebugEnabled) Logger.Debug(provider, format, args); + if (IsDebugEnabled) + { + Logger.Debug(provider, format, args); + } } public void DebugWithProps(string message, IEnumerable<KeyValuePair<string, object>> props) { - if (!IsDebugEnabled) return; + if (!IsDebugEnabled) + { + return; + } var theEvent = new LogEventInfo { Message = message, LoggerName = Name, Level = LogLevel.Debug }; @@ -480,145 +645,229 @@ public class LogNLog : ILog public void Info(object message) { - if (IsInfoEnabled) Logger.Info(message); + if (IsInfoEnabled) + { + Logger.Info(message); + } } public void Info(string message, Exception exception) { - if (IsInfoEnabled) Logger.Info(exception, message); + if (IsInfoEnabled) + { + Logger.Info(exception, message); + } } public void InfoFormat(string format, params object[] args) { - if (IsInfoEnabled) Logger.Info(format, args); + if (IsInfoEnabled) + { + Logger.Info(format, args); + } } public void InfoFormat(string format, object arg0) { - if (IsInfoEnabled) Logger.Info(format, arg0); + if (IsInfoEnabled) + { + Logger.Info(format, arg0); + } } public void InfoFormat(string format, object arg0, object arg1) { - if (IsInfoEnabled) Logger.Info(format, arg0, arg1); + if (IsInfoEnabled) + { + Logger.Info(format, arg0, arg1); + } } public void InfoFormat(string format, object arg0, object arg1, object arg2) { - if (IsInfoEnabled) Logger.Info(format, arg0, arg1, arg2); + if (IsInfoEnabled) + { + Logger.Info(format, arg0, arg1, arg2); + } } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { - if (IsInfoEnabled) Logger.Info(provider, format, args); + if (IsInfoEnabled) + { + Logger.Info(provider, format, args); + } } public void Warn(object message) { - if (IsWarnEnabled) Logger.Warn(message); + if (IsWarnEnabled) + { + Logger.Warn(message); + } } public void Warn(object message, Exception exception) { - if (IsWarnEnabled) Logger.Warn(exception, "{0}", message); + if (IsWarnEnabled) + { + Logger.Warn(exception, "{0}", message); + } } public void WarnFormat(string format, params object[] args) { - if (IsWarnEnabled) Logger.Warn(format, args); + if (IsWarnEnabled) + { + Logger.Warn(format, args); + } } public void WarnFormat(string format, object arg0) { - if (IsWarnEnabled) Logger.Warn(format, arg0); + if (IsWarnEnabled) + { + Logger.Warn(format, arg0); + } } public void WarnFormat(string format, object arg0, object arg1) { - if (IsWarnEnabled) Logger.Warn(format, arg0, arg1); + if (IsWarnEnabled) + { + Logger.Warn(format, arg0, arg1); + } } public void WarnFormat(string format, object arg0, object arg1, object arg2) { - if (IsWarnEnabled) Logger.Warn(format, arg0, arg1, arg2); + if (IsWarnEnabled) + { + Logger.Warn(format, arg0, arg1, arg2); + } } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { - if (IsWarnEnabled) Logger.Warn(provider, format, args); + if (IsWarnEnabled) + { + Logger.Warn(provider, format, args); + } } public void Error(object message) { - if (IsErrorEnabled) Logger.Error(message); + if (IsErrorEnabled) + { + Logger.Error(message); + } } public void Error(object message, Exception exception) { - if (IsErrorEnabled) Logger.Error(exception, "{0}", message); + if (IsErrorEnabled) + { + Logger.Error(exception, "{0}", message); + } } public void ErrorFormat(string format, params object[] args) { - if (IsErrorEnabled) Logger.Error(format, args); + if (IsErrorEnabled) + { + Logger.Error(format, args); + } } public void ErrorFormat(string format, object arg0) { - if (IsErrorEnabled) Logger.Error(format, arg0); + if (IsErrorEnabled) + { + Logger.Error(format, arg0); + } } public void ErrorFormat(string format, object arg0, object arg1) { - if (IsErrorEnabled) Logger.Error(format, arg0, arg1); + if (IsErrorEnabled) + { + Logger.Error(format, arg0, arg1); + } } public void ErrorFormat(string format, object arg0, object arg1, object arg2) { - if (IsErrorEnabled) Logger.Error(format, arg0, arg1, arg2); + if (IsErrorEnabled) + { + Logger.Error(format, arg0, arg1, arg2); + } } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { - if (IsErrorEnabled) Logger.Error(provider, format, args); + if (IsErrorEnabled) + { + Logger.Error(provider, format, args); + } } public void Fatal(object message) { - if (IsFatalEnabled) Logger.Fatal(message); + if (IsFatalEnabled) + { + Logger.Fatal(message); + } } public void Fatal(string message, Exception exception) { - if (IsFatalEnabled) Logger.Fatal(exception, message); + if (IsFatalEnabled) + { + Logger.Fatal(exception, message); + } } public void FatalFormat(string format, params object[] args) { - if (IsFatalEnabled) Logger.Fatal(format, args); + if (IsFatalEnabled) + { + Logger.Fatal(format, args); + } } public void FatalFormat(string format, object arg0) { - if (IsFatalEnabled) Logger.Fatal(format, arg0); + if (IsFatalEnabled) + { + Logger.Fatal(format, arg0); + } } public void FatalFormat(string format, object arg0, object arg1) { - if (IsFatalEnabled) Logger.Fatal(format, arg0, arg1); + if (IsFatalEnabled) + { + Logger.Fatal(format, arg0, arg1); + } } public void FatalFormat(string format, object arg0, object arg1, object arg2) { - if (IsFatalEnabled) Logger.Fatal(format, arg0, arg1, arg2); + if (IsFatalEnabled) + { + Logger.Fatal(format, arg0, arg1, arg2); + } } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { - if (IsFatalEnabled) Logger.Fatal(provider, format, args); + if (IsFatalEnabled) + { + Logger.Fatal(provider, format, args); + } } } @@ -724,7 +973,10 @@ public class LogManager<T> : OptionsMonitor<T> where T : class, ILog, new() { var log = base.Get(name); - if (string.IsNullOrEmpty(log?.Name)) log = CurrentValue; + if (string.IsNullOrEmpty(log?.Name)) + { + log = CurrentValue; + } return log; } @@ -732,12 +984,16 @@ public class LogManager<T> : OptionsMonitor<T> where T : class, ILog, new() public class LoggerExtension<T> where T : class, ILog, new() { - public static void RegisterLog(DIHelper services) => + public static void RegisterLog(DIHelper services) + { services.TryAdd(typeof(IOptionsMonitor<ILog>), typeof(LogManager<T>)); + } } public class LogNLogExtension : LoggerExtension<LogNLog> { - public static void Register(DIHelper services) => + public static void Register(DIHelper services) + { RegisterLog(services); + } } diff --git a/common/ASC.Common/Logging/SelfCleaningAppender.cs b/common/ASC.Common/Logging/SelfCleaningAppender.cs index 2de68f3d48..5eca630b79 100644 --- a/common/ASC.Common/Logging/SelfCleaningAppender.cs +++ b/common/ASC.Common/Logging/SelfCleaningAppender.cs @@ -55,16 +55,19 @@ public class SelfCleaningAppender : RollingFileAppender private static int GetCleanPeriod() { if (s_cleanPeriod != null) + { return s_cleanPeriod.Value; + } const string key = "CleanPeriod"; var value = 30; var repo = log4net.LogManager.GetRepository(Assembly.GetCallingAssembly()); - if (repo != null && repo.Properties.GetKeys().Contains(key)) + { int.TryParse(repo.Properties[key].ToString(), out value); + } s_cleanPeriod = value; @@ -76,20 +79,23 @@ public class SelfCleaningAppender : RollingFileAppender try { if (string.IsNullOrEmpty(File)) + { return; + } var fileInfo = new FileInfo(File); - if (!fileInfo.Exists) + { return; + } var directory = fileInfo.Directory; - if (directory == null || !directory.Exists) + { return; + } var files = directory.GetFiles(); - var cleanPeriod = GetCleanPeriod(); foreach (var file in files.Where(file => (DateTime.UtcNow.Date - file.CreationTimeUtc.Date).Days > cleanPeriod)) diff --git a/common/ASC.Common/Logging/SelfCleaningTarget.cs b/common/ASC.Common/Logging/SelfCleaningTarget.cs index 96cd4b1f10..6be0839189 100644 --- a/common/ASC.Common/Logging/SelfCleaningTarget.cs +++ b/common/ASC.Common/Logging/SelfCleaningTarget.cs @@ -46,7 +46,11 @@ public class SelfCleaningTarget : FileTarget foreach (var logEvent in logEvents) { buffer.Add(logEvent); - if (buffer.Count < 10) continue; + if (buffer.Count < 10) + { + continue; + } + base.Write(buffer); buffer.Clear(); } @@ -68,7 +72,9 @@ public class SelfCleaningTarget : FileTarget private static int GetCleanPeriod() { if (s_cleanPeriod != null) + { return s_cleanPeriod.Value; + } var value = 30; @@ -79,7 +85,9 @@ public class SelfCleaningTarget : FileTarget var variable = LogManager.Configuration.Variables[key]; if (variable != null && !string.IsNullOrEmpty(variable.Text)) + { int.TryParse(variable.Text, out value); + } } s_cleanPeriod = value; @@ -95,28 +103,33 @@ public class SelfCleaningTarget : FileTarget try { if (FileName == null) + { return; + } filePath = ((NLog.Layouts.SimpleLayout)FileName).Text; - if (string.IsNullOrEmpty(filePath)) + { return; + } dirPath = Path.GetDirectoryName(filePath); - if (string.IsNullOrEmpty(dirPath)) + { return; - + } if (!Path.IsPathRooted(dirPath)) + { dirPath = CrossPlatform.PathCombine(AppDomain.CurrentDomain.BaseDirectory, dirPath); + } var directory = new DirectoryInfo(dirPath); - if (!directory.Exists) + { return; + } var files = directory.GetFiles(); - var cleanPeriod = GetCleanPeriod(); foreach (var file in files.Where(file => (DateTime.UtcNow.Date - file.CreationTimeUtc.Date).Days > cleanPeriod)) diff --git a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs index e51115490b..da1d6768ba 100644 --- a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs +++ b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs @@ -29,7 +29,10 @@ public class SpecialFolderPathConverter : PatternConverter { protected override void Convert(TextWriter writer, object state) { - if (string.IsNullOrEmpty(Option)) return; + if (string.IsNullOrEmpty(Option)) + { + return; + } try { @@ -42,7 +45,9 @@ public class SpecialFolderPathConverter : PatternConverter for (var i = 0; i < args.Length - 1; i++) { if (args[i].Equals(Option.Substring(CMD_LINE.Length), StringComparison.InvariantCultureIgnoreCase)) + { result = args[i + 1]; + } } } else @@ -54,10 +59,14 @@ public class SpecialFolderPathConverter : PatternConverter foreach (var key in repo.Properties.GetKeys()) { if (Path.DirectorySeparatorChar == '/' && key == "UNIX:" + Option) + { realKey = "UNIX:" + Option; + } if (Path.DirectorySeparatorChar == '\\' && key == "WINDOWS:" + Option) + { realKey = "WINDOWS:" + Option; + } } var val = repo.Properties[realKey]; @@ -66,8 +75,10 @@ public class SpecialFolderPathConverter : PatternConverter patternString.ActivateOptions(); patternString.Format(writer); } - - else if (val != null) result = val.ToString(); + else if (val != null) + { + result = val.ToString(); + } } } @@ -82,4 +93,4 @@ public class SpecialFolderPathConverter : PatternConverter LogLog.Error(GetType(), "Can not convert " + Option, err); } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Mapping/IMapFrom.cs b/common/ASC.Common/Mapping/IMapFrom.cs index bd96a3f229..8efcc8dd4b 100644 --- a/common/ASC.Common/Mapping/IMapFrom.cs +++ b/common/ASC.Common/Mapping/IMapFrom.cs @@ -27,5 +27,8 @@ namespace ASC.Common.Mapping; public interface IMapFrom<T> { - void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType()); + void Mapping(Profile profile) + { + profile.CreateMap(typeof(T), GetType()); + } } diff --git a/common/ASC.Common/Mapping/MappingProfile.cs b/common/ASC.Common/Mapping/MappingProfile.cs index d90d4991bd..0012b4f6d4 100644 --- a/common/ASC.Common/Mapping/MappingProfile.cs +++ b/common/ASC.Common/Mapping/MappingProfile.cs @@ -31,7 +31,10 @@ public class MappingProfile : Profile private void ApplyMappingsFromAssembly(Assembly assembly) { - if (!assembly.GetName().Name.StartsWith("ASC.")) return; + if (!assembly.GetName().Name.StartsWith("ASC.")) + { + return; + } var types = assembly.GetExportedTypes() .Where(t => t.GetInterfaces().Any(i => diff --git a/common/ASC.Common/Security/AscRandom.cs b/common/ASC.Common/Security/AscRandom.cs index 0458ba4054..e1202bf91f 100644 --- a/common/ASC.Common/Security/AscRandom.cs +++ b/common/ASC.Common/Security/AscRandom.cs @@ -51,7 +51,10 @@ public class AscRandom : Random _seeds[index] = num3; num3 = num2 - num3; - if (num3 < 0) num3 += int.MaxValue; + if (num3 < 0) + { + num3 += int.MaxValue; + } num2 = _seeds[index]; } @@ -62,7 +65,10 @@ public class AscRandom : Random { _seeds[k] -= _seeds[1 + ((k + 30) % (_seeds.Length - 1))]; - if (_seeds[k] < 0) _seeds[k] += int.MaxValue; + if (_seeds[k] < 0) + { + _seeds[k] += int.MaxValue; + } } } @@ -72,14 +78,20 @@ public class AscRandom : Random public override int Next(int maxValue) { - if (maxValue < 0) throw new ArgumentOutOfRangeException(nameof(maxValue)); + if (maxValue < 0) + { + throw new ArgumentOutOfRangeException(nameof(maxValue)); + } return (int)(InternalSample() * 4.6566128752457969E-10 * maxValue); } public override void NextBytes(byte[] buffer) { - if (buffer == null) throw new ArgumentNullException(nameof(buffer)); + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer)); + } for (var i = 0; i < buffer.Length; i++) { @@ -92,15 +104,27 @@ public class AscRandom : Random var inext = _inext; var inextp = _inextp; - if (++inext >= _seeds.Length - 1) inext = 1; + if (++inext >= _seeds.Length - 1) + { + inext = 1; + } - if (++inextp >= _seeds.Length - 1) inextp = 1; + if (++inextp >= _seeds.Length - 1) + { + inextp = 1; + } var num = _seeds[inext] - _seeds[inextp]; - if (num == int.MaxValue) num--; + if (num == int.MaxValue) + { + num--; + } - if (num < 0) num += int.MaxValue; + if (num < 0) + { + num += int.MaxValue; + } _seeds[inext] = num; _inext = inext; @@ -108,4 +132,4 @@ public class AscRandom : Random return num; } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Security/Authentication/Account.cs b/common/ASC.Common/Security/Authentication/Account.cs index 71ba28d655..fc8c335172 100644 --- a/common/ASC.Common/Security/Authentication/Account.cs +++ b/common/ASC.Common/Security/Authentication/Account.cs @@ -40,11 +40,23 @@ public class Account : IAccount IsAuthenticated = authenticated; } - public object Clone() => MemberwiseClone(); + public object Clone() + { + return MemberwiseClone(); + } - public override bool Equals(object obj) => obj is IAccount a && ID.Equals(a.ID); + public override bool Equals(object obj) + { + return obj is IAccount a && ID.Equals(a.ID); + } - public override int GetHashCode() => ID.GetHashCode(); + public override int GetHashCode() + { + return ID.GetHashCode(); + } - public override string ToString() => Name; + public override string ToString() + { + return Name; + } } diff --git a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs index b815fe550b..0ae5dee759 100644 --- a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs +++ b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs @@ -40,7 +40,10 @@ public class AuthorizingException : Exception public AuthorizingException(ISubject subject, IAction[] actions) { - if (actions == null || actions.Length == 0) throw new ArgumentNullException(nameof(actions)); + if (actions == null || actions.Length == 0) + { + throw new ArgumentNullException(nameof(actions)); + } Subject = subject ?? throw new ArgumentNullException(nameof(subject)); Actions = actions; @@ -77,12 +80,26 @@ public class AuthorizingException : Exception internal static string FormatErrorMessage(ISubject subject, IAction[] actions, ISubject[] denySubjects, IAction[] denyActions) { - if (subject == null) throw new ArgumentNullException(nameof(subject)); - if (actions == null || actions.Length == 0) throw new ArgumentNullException(nameof(actions)); - if (denySubjects == null || denySubjects.Length == 0) throw new ArgumentNullException(nameof(denySubjects)); - if (denyActions == null || denyActions.Length == 0) throw new ArgumentNullException(nameof(denyActions)); + if (subject == null) + { + throw new ArgumentNullException(nameof(subject)); + } + if (actions == null || actions.Length == 0) + { + throw new ArgumentNullException(nameof(actions)); + } + if (denySubjects == null || denySubjects.Length == 0) + { + throw new ArgumentNullException(nameof(denySubjects)); + } + if (denyActions == null || denyActions.Length == 0) + { + throw new ArgumentNullException(nameof(denyActions)); + } if (actions.Length != denySubjects.Length || actions.Length != denyActions.Length) + { throw new ArgumentException(); + } var reasons = ""; for (var i = 0; i < actions.Length; i++) @@ -90,15 +107,22 @@ public class AuthorizingException : Exception var reason = ""; if (denySubjects[i] != null && denyActions[i] != null) + { reason = string.Format("{0}:{1} access denied {2}.", actions[i].Name, (denySubjects[i] is IRole ? "role:" : "") + denySubjects[i].Name, denyActions[i].Name ); - else reason = string.Format("{0}: access denied.", actions[i].Name); + } + else + { + reason = string.Format("{0}: access denied.", actions[i].Name); + } if (i != actions.Length - 1) + { reason += ", "; + } reasons += reason; } diff --git a/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs b/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs index 3cdd70de85..69dd7dc877 100644 --- a/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs +++ b/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs @@ -32,7 +32,10 @@ public static class AzObjectIdHelper public static string GetFullObjectId(ISecurityObjectId objectId) { - if (objectId == null) return null; + if (objectId == null) + { + return null; + } return $"{objectId.ObjectType.FullName}{s_separator}{objectId.SecurityId}"; } diff --git a/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs b/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs index 505f09863f..673f5a6e8e 100644 --- a/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs +++ b/common/ASC.Common/Security/Authorizing/AzObjectSecurityProviderHelper.cs @@ -55,7 +55,10 @@ public class AzObjectSecurityProviderHelper foreach (var role in roles) { - if (!_callContext.RolesList.Contains(role)) _callContext.RolesList.Add(role); + if (!_callContext.RolesList.Contains(role)) + { + _callContext.RolesList.Add(role); + } } return roles; @@ -63,13 +66,21 @@ public class AzObjectSecurityProviderHelper public bool NextInherit() { - if (_currSecObjProvider == null || !_currSecObjProvider.InheritSupported) return false; + if (_currSecObjProvider == null || !_currSecObjProvider.InheritSupported) + { + return false; + } CurrentObjectId = _currSecObjProvider.InheritFrom(CurrentObjectId); + if (CurrentObjectId == null) + { + return false; + } - if (CurrentObjectId == null) return false; - - if (_currObjIdAsProvider) _currSecObjProvider = CurrentObjectId as ISecurityObjectProvider; + if (_currObjIdAsProvider) + { + _currSecObjProvider = CurrentObjectId as ISecurityObjectProvider; + } _callContext.ObjectsStack.Insert(0, CurrentObjectId); diff --git a/common/ASC.Common/Security/Authorizing/Domain/Action.cs b/common/ASC.Common/Security/Authorizing/Domain/Action.cs index 067286393b..5dde202a27 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Action.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Action.cs @@ -38,7 +38,10 @@ public class Action : IAction public Action(Guid id, string name, bool administratorAlwaysAllow, bool conjunction) { - if (id == Guid.Empty) throw new ArgumentNullException(nameof(id)); + if (id == Guid.Empty) + { + throw new ArgumentNullException(nameof(id)); + } ID = id; Name = name; @@ -46,9 +49,18 @@ public class Action : IAction Conjunction = conjunction; } - public override int GetHashCode() => ID.GetHashCode(); + public override int GetHashCode() + { + return ID.GetHashCode(); + } - public override bool Equals(object obj) => obj is Action a && a.ID == ID; + public override bool Equals(object obj) + { + return obj is Action a && a.ID == ID; + } - public override string ToString() => Name; -} + public override string ToString() + { + return Name; + } +} \ No newline at end of file diff --git a/common/ASC.Common/Security/Authorizing/Domain/Role.cs b/common/ASC.Common/Security/Authorizing/Domain/Role.cs index 50fbb28835..b5721611eb 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Role.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Role.cs @@ -42,16 +42,31 @@ public sealed class Role : IRole public Role(Guid id, string name) { - if (id == Guid.Empty) throw new ArgumentException(nameof(id)); - if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); + if (id == Guid.Empty) + { + throw new ArgumentException(nameof(id)); + } + if (string.IsNullOrEmpty(name)) + { + throw new ArgumentNullException(nameof(name)); + } ID = id; Name = name; } - public override int GetHashCode() => ID.GetHashCode(); + public override int GetHashCode() + { + return ID.GetHashCode(); + } - public override bool Equals(object obj) => obj is Role r && r.ID == ID; + public override bool Equals(object obj) + { + return obj is Role r && r.ID == ID; + } - public override string ToString() => $"Role: {Name}"; + public override string ToString() + { + return $"Role: {Name}"; + } } diff --git a/common/ASC.Common/Security/Cryptography/Hasher.cs b/common/ASC.Common/Security/Cryptography/Hasher.cs index ed2961f49c..32135e014d 100644 --- a/common/ASC.Common/Security/Cryptography/Hasher.cs +++ b/common/ASC.Common/Security/Cryptography/Hasher.cs @@ -29,26 +29,60 @@ public sealed class Hasher { private const HashAlg DefaultAlg = HashAlg.SHA256; - public static byte[] Hash(string data, HashAlg hashAlg) => ComputeHash(data, hashAlg); + public static byte[] Hash(string data, HashAlg hashAlg) + { + return ComputeHash(data, hashAlg); + } - public static byte[] Hash(string data) => Hash(data, DefaultAlg); + public static byte[] Hash(string data) + { + return Hash(data, DefaultAlg); + } - public static byte[] Hash(byte[] data, HashAlg hashAlg) => ComputeHash(data, hashAlg); + public static byte[] Hash(byte[] data, HashAlg hashAlg) + { + return ComputeHash(data, hashAlg); + } - public static byte[] Hash(byte[] data) => Hash(data, DefaultAlg); + public static byte[] Hash(byte[] data) + { + return Hash(data, DefaultAlg); + } - public static string Base64Hash(string data, HashAlg hashAlg) => ComputeHash64(data, hashAlg); + public static string Base64Hash(string data, HashAlg hashAlg) + { + return ComputeHash64(data, hashAlg); + } - public static string Base64Hash(string data) => Base64Hash(data, DefaultAlg); + public static string Base64Hash(string data) + { + return Base64Hash(data, DefaultAlg); + } - public static string Base64Hash(byte[] data, HashAlg hashAlg) => ComputeHash64(data, hashAlg); + public static string Base64Hash(byte[] data, HashAlg hashAlg) + { + return ComputeHash64(data, hashAlg); + } - public static string Base64Hash(byte[] data) => Base64Hash(data, DefaultAlg); - public static bool EqualHash(byte[] dataToCompare, byte[] hash) => EqualHash(dataToCompare, hash, DefaultAlg); + public static string Base64Hash(byte[] data) + { + return Base64Hash(data, DefaultAlg); + } - public static bool EqualHash(string dataToCompare, string hash, HashAlg hashAlg) => EqualHash(S2B(dataToCompare), S642B(hash), hashAlg); + public static bool EqualHash(byte[] dataToCompare, byte[] hash) + { + return EqualHash(dataToCompare, hash, DefaultAlg); + } - public static bool EqualHash(string dataToCompare, string hash) => EqualHash(dataToCompare, hash, DefaultAlg); + public static bool EqualHash(string dataToCompare, string hash, HashAlg hashAlg) + { + return EqualHash(S2B(dataToCompare), S642B(hash), hashAlg); + } + + public static bool EqualHash(string dataToCompare, string hash) + { + return EqualHash(dataToCompare, hash, DefaultAlg); + } public static bool EqualHash(byte[] dataToCompare, byte[] hash, HashAlg hashAlg) { @@ -72,28 +106,40 @@ public sealed class Hasher private static byte[] S2B(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if (str == null) + { + throw new ArgumentNullException(nameof(str)); + } return Encoding.UTF8.GetBytes(str); } private static string B2S(byte[] data) { - if (data == null) throw new ArgumentNullException(nameof(data)); + if (data == null) + { + throw new ArgumentNullException(nameof(data)); + } return Encoding.UTF8.GetString(data); } private static byte[] S642B(string str) { - if (str == null) throw new ArgumentNullException(nameof(str)); + if (str == null) + { + throw new ArgumentNullException(nameof(str)); + } return Convert.FromBase64String(str); } private static string B2S64(byte[] data) { - if (data == null) throw new ArgumentNullException(nameof(data)); + if (data == null) + { + throw new ArgumentNullException(nameof(data)); + } return Convert.ToBase64String(data); } @@ -105,9 +151,18 @@ public sealed class Hasher return alg.ComputeHash(data); } - private static byte[] ComputeHash(string data, HashAlg hashAlg) => ComputeHash(S2B(data), hashAlg); + private static byte[] ComputeHash(string data, HashAlg hashAlg) + { + return ComputeHash(S2B(data), hashAlg); + } - private static string ComputeHash64(byte[] data, HashAlg hashAlg) => B2S64(ComputeHash(data, hashAlg)); + private static string ComputeHash64(byte[] data, HashAlg hashAlg) + { + return B2S64(ComputeHash(data, hashAlg)); + } - private static string ComputeHash64(string data, HashAlg hashAlg) => ComputeHash64(S2B(data), hashAlg); -} + private static string ComputeHash64(string data, HashAlg hashAlg) + { + return ComputeHash64(S2B(data), hashAlg); + } +} \ No newline at end of file diff --git a/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs b/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs index 4f8f93f717..34f091f5e3 100644 --- a/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs +++ b/common/ASC.Common/Security/Cryptography/InstanceCrypto.cs @@ -30,11 +30,15 @@ public class InstanceCrypto { private readonly byte[] _eKey; - public InstanceCrypto(MachinePseudoKeys machinePseudoKeys) => + public InstanceCrypto(MachinePseudoKeys machinePseudoKeys) + { _eKey = machinePseudoKeys.GetMachineConstant(32); + } - public string Encrypt(string data) => - Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(data))); + public string Encrypt(string data) + { + return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(data))); + } public byte[] Encrypt(byte[] data) { diff --git a/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs b/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs index 7b386c0eca..a287ce6006 100644 --- a/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs +++ b/common/ASC.Common/Security/Cryptography/MachinePseudoKeys.cs @@ -34,15 +34,24 @@ public class MachinePseudoKeys { var key = configuration["core:machinekey"]; - if (string.IsNullOrEmpty(key)) key = configuration["asc:common.machinekey"]; + if (string.IsNullOrEmpty(key)) + { + key = configuration["asc:common.machinekey"]; + } - if (!string.IsNullOrEmpty(key)) _confKey = Encoding.UTF8.GetBytes(key); + if (!string.IsNullOrEmpty(key)) + { + _confKey = Encoding.UTF8.GetBytes(key); + } } public byte[] GetMachineConstant() { - if (_confKey != null) return _confKey; + if (_confKey != null) + { + return _confKey; + } var path = typeof(MachinePseudoKeys).Assembly.Location; var fi = new FileInfo(path); diff --git a/common/ASC.Common/Security/Cryptography/PasswordHasher.cs b/common/ASC.Common/Security/Cryptography/PasswordHasher.cs index 5ec25eeabe..6975659dbd 100644 --- a/common/ASC.Common/Security/Cryptography/PasswordHasher.cs +++ b/common/ASC.Common/Security/Cryptography/PasswordHasher.cs @@ -34,10 +34,18 @@ public class PasswordHasher public PasswordHasher(IConfiguration configuration, MachinePseudoKeys machinePseudoKeys) { - if (!int.TryParse(configuration["core:password:size"], out var size)) size = 256; + if (!int.TryParse(configuration["core:password:size"], out var size)) + { + size = 256; + } + Size = size; - if (!int.TryParse(configuration["core.password.iterations"], out var iterations)) iterations = 100000; + if (!int.TryParse(configuration["core.password.iterations"], out var iterations)) + { + iterations = 100000; + } + Iterations = iterations; Salt = (configuration["core:password:salt"] ?? "").Trim(); @@ -57,7 +65,10 @@ public class PasswordHasher public string GetClientPassword(string password) { - if (string.IsNullOrWhiteSpace(password)) password = Guid.NewGuid().ToString(); + if (string.IsNullOrWhiteSpace(password)) + { + password = Guid.NewGuid().ToString(); + } var salt = new UTF8Encoding(false).GetBytes(Salt); @@ -72,4 +83,4 @@ public class PasswordHasher return hash; } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Security/SecurityObjectId.cs b/common/ASC.Common/Security/SecurityObjectId.cs index d6e8209a80..498869db02 100644 --- a/common/ASC.Common/Security/SecurityObjectId.cs +++ b/common/ASC.Common/Security/SecurityObjectId.cs @@ -37,9 +37,14 @@ public class SecurityObjectId : ISecurityObjectId ObjectType = objType ?? throw new ArgumentNullException(nameof(objType)); } - public override int GetHashCode() => AzObjectIdHelper.GetFullObjectId(this).GetHashCode(); + public override int GetHashCode() + { + return AzObjectIdHelper.GetFullObjectId(this).GetHashCode(); + } - public override bool Equals(object obj) => - obj is SecurityObjectId other && - Equals(AzObjectIdHelper.GetFullObjectId(other), AzObjectIdHelper.GetFullObjectId(this)); -} + public override bool Equals(object obj) + { + return obj is SecurityObjectId other && + Equals(AzObjectIdHelper.GetFullObjectId(other), AzObjectIdHelper.GetFullObjectId(this)); + } +} \ No newline at end of file diff --git a/common/ASC.Common/Threading/DistributedTask.cs b/common/ASC.Common/Threading/DistributedTask.cs index d5e3c8d000..134060ad9b 100644 --- a/common/ASC.Common/Threading/DistributedTask.cs +++ b/common/ASC.Common/Threading/DistributedTask.cs @@ -66,8 +66,10 @@ public class DistributedTask public T GetProperty<T>(string name) { var prop = DistributedTaskCache.Props.FirstOrDefault(r => r.Key == name); - - if (prop == null) return default; + if (prop == null) + { + return default; + } return JsonSerializer.Deserialize<T>(prop.Value); } @@ -81,15 +83,23 @@ public class DistributedTask }; var current = DistributedTaskCache.Props.SingleOrDefault(r => r.Key == name); + if (current != null) + { + DistributedTaskCache.Props.Remove(current); + } - if (current != null) DistributedTaskCache.Props.Remove(current); - - if (value != null) DistributedTaskCache.Props.Add(prop); + if (value != null) + { + DistributedTaskCache.Props.Add(prop); + } } public void PublishChanges() { - if (Publication == null) throw new InvalidOperationException("Publication not found."); + if (Publication == null) + { + throw new InvalidOperationException("Publication not found."); + } Publication(this); } diff --git a/common/ASC.Common/Threading/DistributedTaskProgress.cs b/common/ASC.Common/Threading/DistributedTaskProgress.cs index 4e1c1012bf..d661ff1ce2 100644 --- a/common/ASC.Common/Threading/DistributedTaskProgress.cs +++ b/common/ASC.Common/Threading/DistributedTaskProgress.cs @@ -31,8 +31,11 @@ public class DistributedTaskProgress : DistributedTask protected void StepDone() { - if (StepCount > 0) Percentage += 100.0 / StepCount; + if (StepCount > 0) + { + Percentage += 100.0 / StepCount; + } PublishChanges(); } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Threading/DistributedTaskQueue.cs b/common/ASC.Common/Threading/DistributedTaskQueue.cs index 726c20c0d4..f44040f106 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -47,8 +47,10 @@ public class DistributedTaskCacheNotify eventBusNotify.Subscribe((c) => { - if (Cancelations.TryGetValue(c.Id, out var s)) s.Cancel(); - + if (Cancelations.TryGetValue(c.Id, out var s)) + { + s.Cancel(); + } }, EventType.Remove); _eventBusCache = eventBusCache; @@ -64,14 +66,20 @@ public class DistributedTaskCacheNotify }, EventType.InsertOrUpdate); } - public void CancelTask(string id) => + public void CancelTask(string id) + { _eventBusNotify.Publish(new DistributedTaskCancelation() { Id = id }, EventType.Remove); + } - public void SetTask(DistributedTask task) => + public void SetTask(DistributedTask task) + { _eventBusCache.Publish(task.DistributedTaskCache, EventType.InsertOrUpdate); + } - public void RemoveTask(string id, string key) => + public void RemoveTask(string id, string key) + { _eventBusCache.Publish(new DistributedTaskCache() { Id = id, Key = key }, EventType.Remove); + } } [Singletone(typeof(ConfigureDistributedTaskQueue))] @@ -79,30 +87,33 @@ public class DistributedTaskQueueOptionsManager : OptionsManager<DistributedTask { public DistributedTaskQueueOptionsManager(IOptionsFactory<DistributedTaskQueue> factory) : base(factory) { } - public DistributedTaskQueue Get<T>() where T : DistributedTask => Get(typeof(T).FullName); + public DistributedTaskQueue Get<T>() where T : DistributedTask + { + return Get(typeof(T).FullName); + } } [Scope] public class ConfigureDistributedTaskQueue : IConfigureNamedOptions<DistributedTaskQueue> { - private DistributedTaskCacheNotify DistributedTaskCacheNotify { get; } - public IServiceProvider ServiceProvider { get; } - public IServiceScopeFactory ServiceScopeFactory { get; } + private readonly DistributedTaskCacheNotify _distributedTaskCacheNotify; + public readonly IServiceProvider _serviceProvider; + public readonly IServiceScopeFactory _serviceScopeFactory; public ConfigureDistributedTaskQueue( DistributedTaskCacheNotify distributedTaskCacheNotify, IServiceProvider serviceProvider, IServiceScopeFactory serviceScopeFactory) { - DistributedTaskCacheNotify = distributedTaskCacheNotify; - ServiceProvider = serviceProvider; - ServiceScopeFactory = serviceScopeFactory; + _distributedTaskCacheNotify = distributedTaskCacheNotify; + _serviceProvider = serviceProvider; + _serviceScopeFactory = serviceScopeFactory; } public void Configure(DistributedTaskQueue queue) { - queue.DistributedTaskCacheNotify = DistributedTaskCacheNotify; - queue.ServiceProvider = ServiceProvider; + queue.DistributedTaskCacheNotify = _distributedTaskCacheNotify; + queue.ServiceProvider = _serviceProvider; } public void Configure(string name, DistributedTaskQueue options) @@ -135,17 +146,30 @@ public class DistributedTaskQueue public static readonly int InstanceId; private string _name; - private ConcurrentDictionary<string, CancellationTokenSource> Cancelations => - DistributedTaskCacheNotify.Cancelations; + private ConcurrentDictionary<string, CancellationTokenSource> Cancelations + { + get + { + return DistributedTaskCacheNotify.Cancelations; + } + } - static DistributedTaskQueue() => InstanceId = Process.GetCurrentProcess().Id; + static DistributedTaskQueue() + { + InstanceId = Process.GetCurrentProcess().Id; + } - public void QueueTask(DistributedTaskProgress taskProgress) => - QueueTask((a, b) => taskProgress.RunJob(), taskProgress); + public void QueueTask(DistributedTaskProgress taskProgress) + { + QueueTask((a, b) => taskProgress.RunJob(), taskProgress); + } public void QueueTask(Action<DistributedTask, CancellationToken> action, DistributedTask distributedTask = null) { - if (distributedTask == null) distributedTask = new DistributedTask(); + if (distributedTask == null) + { + distributedTask = new DistributedTask(); + } distributedTask.InstanceId = InstanceId; @@ -162,7 +186,9 @@ public class DistributedTaskQueue distributedTask.Status = DistributedTaskStatus.Running; if (distributedTask.Publication == null) + { distributedTask.Publication = GetPublication(); + } distributedTask.PublishChanges(); @@ -175,7 +201,10 @@ public class DistributedTaskQueue tasks.ForEach(t => { - if (t.Publication == null) t.Publication = GetPublication(); + if (t.Publication == null) + { + t.Publication = GetPublication(); + } }); return tasks; @@ -193,7 +222,10 @@ public class DistributedTaskQueue tasks.ForEach(t => { - if (t.Publication == null) t.Publication = GetPublication(); + if (t.Publication == null) + { + t.Publication = GetPublication(); + } }); return tasks; @@ -209,7 +241,9 @@ public class DistributedTaskQueue task.DistributedTaskCache = cache; if (task != null && task.Publication == null) + { task.Publication = GetPublication(); + } return task; } @@ -225,7 +259,10 @@ public class DistributedTaskQueue var task = new DistributedTask(); task.DistributedTaskCache = cache; - if (task != null && task.Publication == null) task.Publication = GetPublication(); + if (task != null && task.Publication == null) + { + task.Publication = GetPublication(); + } return task; } @@ -233,11 +270,20 @@ public class DistributedTaskQueue return null; } - public void SetTask(DistributedTask task) => DistributedTaskCacheNotify.SetTask(task); + public void SetTask(DistributedTask task) + { + DistributedTaskCacheNotify.SetTask(task); + } - public void RemoveTask(string id) => DistributedTaskCacheNotify.RemoveTask(id, _name); + public void RemoveTask(string id) + { + DistributedTaskCacheNotify.RemoveTask(id, _name); + } - public void CancelTask(string id) => DistributedTaskCacheNotify.CancelTask(id); + public void CancelTask(string id) + { + DistributedTaskCacheNotify.CancelTask(id); + } private void OnCompleted(Task task, string id) { @@ -247,9 +293,15 @@ public class DistributedTaskQueue distributedTask.Status = DistributedTaskStatus.Completed; distributedTask.Exception = task.Exception; - if (task.IsFaulted) distributedTask.Status = DistributedTaskStatus.Failted; + if (task.IsFaulted) + { + distributedTask.Status = DistributedTaskStatus.Failted; + } - if (task.IsCanceled) distributedTask.Status = DistributedTaskStatus.Canceled; + if (task.IsCanceled) + { + distributedTask.Status = DistributedTaskStatus.Canceled; + } Cancelations.TryRemove(id, out _); @@ -261,7 +313,10 @@ public class DistributedTaskQueue { return (t) => { - if (t.DistributedTaskCache != null) t.DistributedTaskCache.Key = _name; + if (t.DistributedTaskCache != null) + { + t.DistributedTaskCache.Key = _name; + } DistributedTaskCacheNotify.SetTask(t); }; @@ -278,7 +333,10 @@ public static class DistributedTaskQueueExtention var type = typeof(T); - if (!type.IsAbstract) services.TryAdd<T>(); + if (!type.IsAbstract) + { + services.TryAdd<T>(); + } services.TryAddSingleton<IConfigureOptions<DistributedTaskQueue>, ConfigureDistributedTaskQueue>(); @@ -290,4 +348,4 @@ public static class DistributedTaskQueueExtention return services; } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/ConfigurationManager.cs b/common/ASC.Common/Utils/ConfigurationManager.cs index 1fdcf4e920..8288f7d044 100644 --- a/common/ASC.Common/Utils/ConfigurationManager.cs +++ b/common/ASC.Common/Utils/ConfigurationManager.cs @@ -6,11 +6,20 @@ public class ConnectionStringCollection : IEnumerable<ConnectionStringSettings> public ConnectionStringSettings this[string name] => _data.FirstOrDefault(r => r.Name == name); - public ConnectionStringCollection(IEnumerable<ConnectionStringSettings> data) => _data = data.ToList(); + public ConnectionStringCollection(IEnumerable<ConnectionStringSettings> data) + { + _data = data.ToList(); + } - public IEnumerator<ConnectionStringSettings> GetEnumerator() => _data.GetEnumerator(); + public IEnumerator<ConnectionStringSettings> GetEnumerator() + { + return _data.GetEnumerator(); + } - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } } [Singletone] @@ -47,7 +56,10 @@ public class ConfigurationExtension return result; } - public T GetSetting<T>(string section) where T : new() => GetSetting(section, new T()); + public T GetSetting<T>(string section) where T : new() + { + return GetSetting(section, new T()); + } public T GetSetting<T>(string section, T instance) { @@ -58,7 +70,13 @@ public class ConfigurationExtension return instance; } - public ConnectionStringCollection GetConnectionStrings() => _connectionStringSettings.Value; + public ConnectionStringCollection GetConnectionStrings() + { + return _connectionStringSettings.Value; + } - public ConnectionStringSettings GetConnectionStrings(string key) => GetConnectionStrings()[key]; + public ConnectionStringSettings GetConnectionStrings(string key) + { + return GetConnectionStrings()[key]; + } } diff --git a/common/ASC.Common/Utils/CrossPlatformUtils.cs b/common/ASC.Common/Utils/CrossPlatformUtils.cs index b26ac4ddfc..b4bfe15b68 100644 --- a/common/ASC.Common/Utils/CrossPlatformUtils.cs +++ b/common/ASC.Common/Utils/CrossPlatformUtils.cs @@ -27,11 +27,11 @@ namespace ASC.Common.Utils; public static class CrossPlatform { - private static char[] _pathSplitCharacters = new char[] { '/', '\\' }; + private static char[] s_pathSplitCharacters = new char[] { '/', '\\' }; public static string PathCombine(string basePath, params string[] additional) { - var splits = additional.Select(s => s.Split(_pathSplitCharacters)).ToArray(); + var splits = additional.Select(s => s.Split(s_pathSplitCharacters)).ToArray(); var totalLength = splits.Sum(arr => arr.Length); var segments = new string[totalLength + 1]; segments[0] = basePath; diff --git a/common/ASC.Common/Utils/DnsLookup.cs b/common/ASC.Common/Utils/DnsLookup.cs index d73f29c101..a18a0a770b 100644 --- a/common/ASC.Common/Utils/DnsLookup.cs +++ b/common/ASC.Common/Utils/DnsLookup.cs @@ -46,7 +46,9 @@ public class DnsLookup public List<MxRecord> GetDomainMxRecords(string domainName) { if (string.IsNullOrEmpty(domainName)) + { throw new ArgumentNullException(nameof(domainName)); + } var mxRecords = DnsResolve<MxRecord>(domainName, RecordType.Mx); @@ -64,10 +66,14 @@ public class DnsLookup public bool IsDomainMxRecordExists(string domainName, string mxRecord) { if (string.IsNullOrEmpty(domainName)) + { throw new ArgumentNullException(nameof(domainName)); + } if (string.IsNullOrEmpty(mxRecord)) + { throw new ArgumentNullException(nameof(mxRecord)); + } var mxDomain = DomainName.Parse(mxRecord); @@ -88,7 +94,9 @@ public class DnsLookup public bool IsDomainExists(string domainName) { if (string.IsNullOrEmpty(domainName)) + { throw new ArgumentNullException(nameof(domainName)); + } var dnsMessage = GetDnsMessage(domainName); @@ -105,7 +113,9 @@ public class DnsLookup public List<ARecord> GetDomainARecords(string domainName) { if (string.IsNullOrEmpty(domainName)) + { throw new ArgumentNullException(nameof(domainName)); + } var aRecords = DnsResolve<ARecord>(domainName, RecordType.A); @@ -122,7 +132,9 @@ public class DnsLookup public List<IPAddress> GetDomainIPs(string domainName) { if (string.IsNullOrEmpty(domainName)) + { throw new ArgumentNullException(nameof(domainName)); + } var addresses = _sDnsResolver.ResolveHost(domainName); @@ -139,7 +151,9 @@ public class DnsLookup public List<TxtRecord> GetDomainTxtRecords(string domainName) { if (string.IsNullOrEmpty(domainName)) + { throw new ArgumentNullException(nameof(domainName)); + } var txtRecords = DnsResolve<TxtRecord>(domainName, RecordType.Txt); @@ -193,10 +207,13 @@ public class DnsLookup public bool IsDomainPtrRecordExists(IPAddress ipAddress, string domainName) { if (string.IsNullOrEmpty(domainName)) + { throw new ArgumentNullException(nameof(domainName)); - + } if (ipAddress == null) + { throw new ArgumentNullException(nameof(ipAddress)); + } var domain = DomainName.Parse(domainName); @@ -214,21 +231,26 @@ public class DnsLookup /// <exception cref="ArgumentException">if domainName is invalid</exception> /// <exception cref="FormatException">if ipAddress is invalid</exception> /// <returns>true if exists and vice versa</returns> - public bool IsDomainPtrRecordExists(string ipAddress, string domainName) => - IsDomainPtrRecordExists(IPAddress.Parse(ipAddress), domainName); + public bool IsDomainPtrRecordExists(string ipAddress, string domainName) + { + return IsDomainPtrRecordExists(IPAddress.Parse(ipAddress), domainName); + } private DnsMessage GetDnsMessage(string domainName, RecordType? type = null) { if (string.IsNullOrEmpty(domainName)) + { throw new ArgumentNullException(nameof(domainName)); + } var domain = DomainName.Parse(domainName); var dnsMessage = type.HasValue ? _dnsClient.Resolve(domain, type.Value) : _dnsClient.Resolve(domain); - if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain))) + { throw new SystemException(); // DNS request failed + } return dnsMessage; } @@ -236,10 +258,12 @@ public class DnsLookup private List<T> DnsResolve<T>(string domainName, RecordType type) { if (string.IsNullOrEmpty(domainName)) + { throw new ArgumentNullException(nameof(domainName)); + } var dnsMessage = GetDnsMessage(domainName, type); return dnsMessage.AnswerRecords.Where(r => r.RecordType == type).Cast<T>().ToList(); } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/HtmlUtil.cs b/common/ASC.Common/Utils/HtmlUtil.cs index b991d199c7..80763c5a5c 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -48,7 +48,10 @@ public static class HtmlUtil { html = s_xssReplacer.Replace(html, string.Empty); //Clean malicious tags. <script> <style> - if (string.IsNullOrEmpty(html)) return html; + if (string.IsNullOrEmpty(html)) + { + return html; + } unformatedText = s_tagReplacer.Replace(html, string.Empty); @@ -61,7 +64,9 @@ public static class HtmlUtil if (!string.IsNullOrEmpty(unformatedText)) { if (maxLength == 0 || unformatedText.Length < maxLength) + { return HttpUtility.HtmlDecode(unformatedText); + } //Set maximum length with end block maxLength = Math.Max(0, maxLength - endBlockTemplate.Length); @@ -75,7 +80,9 @@ public static class HtmlUtil : unformatedText.Substring(0, maxLength); if (!string.IsNullOrEmpty(endBlockTemplate)) + { unformatedText += endBlockTemplate; + } } } } @@ -83,7 +90,10 @@ public static class HtmlUtil return HttpUtility.HtmlDecode(unformatedText);//TODO:!!! } - public static string ToPlainText(string html) => GetText(html); + public static string ToPlainText(string html) + { + return GetText(html); + } /// <summary> /// The function highlight all words in htmlText by searchText. @@ -94,11 +104,14 @@ public static class HtmlUtil /// <returns>highlighted html</returns> public static string SearchTextHighlight(string searchText, string htmlText, bool withoutLink = false) { - if (string.IsNullOrEmpty(searchText) || string.IsNullOrEmpty(htmlText)) return htmlText; + if (string.IsNullOrEmpty(searchText) || string.IsNullOrEmpty(htmlText)) + { + return htmlText; + } var regexpstr = s_worder.Matches(searchText).Cast<Match>().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); var wordsFinder = new Regex(Regex.Escape(regexpstr), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline); return wordsFinder.Replace(htmlText, m => string.Format("<span class='searchTextHighlight{1}'>{0}</span>", m.Value, withoutLink ? " bold" : string.Empty)); } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/HttpRequestExtensions.cs b/common/ASC.Common/Utils/HttpRequestExtensions.cs index b343be9753..e369e344b6 100644 --- a/common/ASC.Common/Utils/HttpRequestExtensions.cs +++ b/common/ASC.Common/Utils/HttpRequestExtensions.cs @@ -32,11 +32,15 @@ public static class HttpRequestExtensions { public static readonly string UrlRewriterHeader = "X-REWRITER-URL"; - public static Uri GetUrlRewriter(this HttpRequest request) => - request != null ? GetUrlRewriter(request.Headers, request) : null; + public static Uri GetUrlRewriter(this HttpRequest request) + { + return request != null ? GetUrlRewriter(request.Headers, request) : null; + } - public static Uri Url(this HttpRequest request) => - request != null ? new Uri(request.GetDisplayUrl()) : null; + public static Uri Url(this HttpRequest request) + { + return request != null ? new Uri(request.GetDisplayUrl()) : null; + } /*public static Uri GetUrlRewriter(this HttpRequestBase request) { @@ -88,8 +92,10 @@ public static class HttpRequestExtensions return request.Url(); } - public static Uri PushRewritenUri(this HttpContext context) => - context != null ? PushRewritenUri(context, GetUrlRewriter(context.Request)) : null; + public static Uri PushRewritenUri(this HttpContext context) + { + return context != null ? PushRewritenUri(context, GetUrlRewriter(context.Request)) : null; + } public static Uri PushRewritenUri(this HttpContext context, Uri rewrittenUri) { @@ -113,11 +119,15 @@ public static class HttpRequestExtensions rewrittenUri.Port.ToString(CultureInfo.InvariantCulture)); if (rewrittenUri.IsDefaultPort) + { request.Headers.SetCommaSeparatedValues("HTTP_HOST", rewrittenUri.Host); - - else request.Headers.SetCommaSeparatedValues("HTTP_HOST", + } + else + { + request.Headers.SetCommaSeparatedValues("HTTP_HOST", rewrittenUri.Host + ":" + requestUri.Port); + } //Hack: typeof(HttpRequest).InvokeMember("_url", BindingFlags.NonPublic | BindingFlags.SetField | @@ -141,7 +151,10 @@ public static class HttpRequestExtensions { var rewriteTo = context.Items["oldUri"] as Uri; - if (rewriteTo != null) return PushRewritenUri(context, rewriteTo); + if (rewriteTo != null) + { + return PushRewritenUri(context, rewriteTo); + } } return null; @@ -161,29 +174,40 @@ public static class HttpRequestExtensions || !string.IsNullOrEmpty(request.Headers[HeaderNames.UserAgent]) && request.Headers[HeaderNames.UserAgent].ToString().Contains("SailfishOS")); } - public static string GetUserHostAddress(this HttpRequest request) => - request.HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString(); + public static string GetUserHostAddress(this HttpRequest request) + { + return request.HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString(); + } private static Uri ParseRewriterUrl(string s) { - if (string.IsNullOrEmpty(s)) return null; + if (string.IsNullOrEmpty(s)) + { + return null; + } const StringComparison cmp = StringComparison.OrdinalIgnoreCase; if (0 < s.Length && (s.StartsWith("0", cmp))) + { s = Uri.UriSchemeHttp + s.Substring(1); - + } else if (3 < s.Length && s.StartsWith("OFF", cmp)) + { s = Uri.UriSchemeHttp + s.Substring(3); - + } else if (0 < s.Length && (s.StartsWith("1", cmp))) + { s = Uri.UriSchemeHttps + s.Substring(1); - + } else if (2 < s.Length && s.StartsWith("ON", cmp)) + { s = Uri.UriSchemeHttps + s.Substring(2); - + } else if (s.StartsWith(Uri.UriSchemeHttp + "%3A%2F%2F", cmp) || s.StartsWith(Uri.UriSchemeHttps + "%3A%2F%2F", cmp)) + { s = HttpUtility.UrlDecode(s); + } Uri.TryCreate(s, UriKind.Absolute, out var result); diff --git a/common/ASC.Common/Utils/MailAddressUtils.cs b/common/ASC.Common/Utils/MailAddressUtils.cs index cedd9926dc..9651363416 100644 --- a/common/ASC.Common/Utils/MailAddressUtils.cs +++ b/common/ASC.Common/Utils/MailAddressUtils.cs @@ -35,7 +35,9 @@ public static class MailAddressUtils var lastPos = address.LastIndexOf('"'); if (firstPos != -1 && firstPos < lastPos && address.IndexOf('"', firstPos + 1, lastPos - firstPos - 1) != -1) + { address = new StringBuilder(address).Replace("\"", string.Empty, firstPos + 1, lastPos - firstPos - 1).ToString(); + } } return new MailAddress(address); @@ -48,14 +50,21 @@ public static class MailAddressUtils displayName = displayName.Replace("\"", string.Empty); if (125 < displayName.Length) + { displayName = displayName.Substring(0, 125); + } } return Create(ToSmtpAddress(address, displayName)); } - public static string ToEncodedString(this MailAddress m) => - ToSmtpAddress(m.Address, MimeHeaderUtils.EncodeMime(m.DisplayName)); + public static string ToEncodedString(this MailAddress m) + { + return ToSmtpAddress(m.Address, MimeHeaderUtils.EncodeMime(m.DisplayName)); + } - private static string ToSmtpAddress(string address, string displayName) => $"\"{displayName}\" <{address}>"; + private static string ToSmtpAddress(string address, string displayName) + { + return $"\"{displayName}\" <{address}>"; + } } diff --git a/common/ASC.Common/Utils/MimeHeaderUtils.cs b/common/ASC.Common/Utils/MimeHeaderUtils.cs index ae9417d13e..5faad0aec0 100644 --- a/common/ASC.Common/Utils/MimeHeaderUtils.cs +++ b/common/ASC.Common/Utils/MimeHeaderUtils.cs @@ -27,8 +27,10 @@ namespace ASC.Common.Utils; public static class MimeHeaderUtils { - public static string EncodeMime(string mimeHeaderValue) => - EncodeMime(mimeHeaderValue, Encoding.UTF8, false); + public static string EncodeMime(string mimeHeaderValue) + { + return EncodeMime(mimeHeaderValue, Encoding.UTF8, false); + } public static string EncodeMime(string mimeHeaderValue, Encoding charset, bool split) { @@ -59,9 +61,12 @@ public static class MimeHeaderUtils return result.ToString(); } + return mimeHeaderValue; } - public static bool MustEncode(string text) => - !string.IsNullOrEmpty(text) && text.Any(c => c > 127); -} + public static bool MustEncode(string text) + { + return !string.IsNullOrEmpty(text) && text.Any(c => c > 127); + } +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/Signature.cs b/common/ASC.Common/Utils/Signature.cs index 7ed82a4cbf..66c8d2ce00 100644 --- a/common/ASC.Common/Utils/Signature.cs +++ b/common/ASC.Common/Utils/Signature.cs @@ -30,10 +30,15 @@ public class Signature { private readonly MachinePseudoKeys _machinePseudoKeys; - public Signature(MachinePseudoKeys machinePseudoKeys) => _machinePseudoKeys = machinePseudoKeys; + public Signature(MachinePseudoKeys machinePseudoKeys) + { + _machinePseudoKeys = machinePseudoKeys; + } - public string Create<T>(T obj) => - Create(obj, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant())); + public string Create<T>(T obj) + { + return Create(obj, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant())); + } public static string Create<T>(T obj, string secret) { @@ -43,8 +48,10 @@ public class Signature return WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(payload)); } - public T Read<T>(string signature) => - Read<T>(signature, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant())); + public T Read<T>(string signature) + { + return Read<T>(signature, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant())); + } public static T Read<T>(string signature, string secret) { @@ -54,7 +61,9 @@ public class Signature var payloadParts = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(rightSignature)).Split('?'); if (GetHashBase64(payloadParts[1] + secret) == payloadParts[0]) + { return JsonConvert.DeserializeObject<T>(payloadParts[1]); //Sig correct + } } catch (Exception) { } diff --git a/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs b/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs index ea0b1c3dbe..9dffa2f00c 100644 --- a/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs +++ b/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs @@ -55,7 +55,10 @@ public class TimeZoneConverter var name = tz.BaseUtcOffset.ToString(@"hh\:mm"); displayName = $"(UTC{offSet}{name}) {displayName}"; } - else displayName = "(UTC) " + displayName; + else + { + displayName = "(UTC) " + displayName; + } } return displayName; @@ -66,12 +69,16 @@ public class TimeZoneConverter var mapZone = GetMapZoneByWindowsTzId(olsonTimeZoneId); if (mapZone != null) + { return olsonTimeZoneId; //already Windows + } mapZone = GetMapZoneByOlsonTzId(olsonTimeZoneId); if (mapZone != null) + { return mapZone.WindowsTimeZoneId; + } _logger.Error($"OlsonTimeZone {olsonTimeZoneId} not found"); @@ -83,12 +90,16 @@ public class TimeZoneConverter var mapZone = GetMapZoneByOlsonTzId(windowsTimeZoneId); if (mapZone != null) + { return windowsTimeZoneId; //already Olson + } mapZone = GetMapZoneByWindowsTzId(windowsTimeZoneId); if (mapZone != null) + { return mapZone.OlsonTimeZoneId; + } _logger.Error($"WindowsTimeZone {windowsTimeZoneId} not found"); @@ -100,7 +111,9 @@ public class TimeZoneConverter var defaultTimezone = GetTimeZoneDefault(); if (string.IsNullOrEmpty(timeZoneId)) + { return defaultIfNoMatch ? defaultTimezone : null; + } try { @@ -111,14 +124,16 @@ public class TimeZoneConverter try { var mapZone = GetMapZoneByOlsonTzId(timeZoneId); - if (mapZone != null) + { return TimeZoneInfo.FindSystemTimeZoneById(mapZone.WindowsTimeZoneId); + } mapZone = GetMapZoneByWindowsTzId(timeZoneId); - if (mapZone != null) + { return TimeZoneInfo.FindSystemTimeZoneById(mapZone.OlsonTimeZoneId); + } _logger.InfoFormat("TimeZone {0} not found", timeZoneId); @@ -162,17 +177,23 @@ public class TimeZoneConverter tz.StandardName == timeZoneId || tz.DaylightName == timeZoneId); - if (timeZone != null) return timeZone; + if (timeZone != null) + { + return timeZone; + } var regex = new Regex(@"[+-][0-9]{2}:[0-9]{2}\b"); var offsetStr = regex.Match(timeZoneId).Value.TrimStart('+'); - - if (string.IsNullOrEmpty(offsetStr)) return null; - + if (string.IsNullOrEmpty(offsetStr)) + { + return null; + } if (!TimeSpan.TryParse(offsetStr, out var offset)) + { return null; + } return systemTimeZones.FirstOrDefault(tz => tz.BaseUtcOffset == offset); } @@ -206,6 +227,78 @@ public class TimeZoneConverter } } + public string GetTimeZoneName(TimeZoneInfo timeZone) + { + if (!_customMode) + { + return _isMono ? timeZone.Id : timeZone.DisplayName; + } + + return _translations.ContainsKey(timeZone.Id) ? _translations[timeZone.Id] : timeZone.DisplayName; + } + + private TimeZoneInfo GetTimeZoneDefault() + { + if (_defaultTimeZone == null) + { + try + { + var tz = TimeZoneInfo.Local; + if (Path.DirectorySeparatorChar == '/') + { + if (tz.StandardName == "UTC" || tz.StandardName == "UCT") + { + tz = TimeZoneInfo.Utc; + } + else + { + var id = string.Empty; + + if (File.Exists("/etc/timezone")) + { + _isMono = true; + id = File.ReadAllText("/etc/timezone").Trim(); + } + + if (string.IsNullOrEmpty(id)) + { + var psi = new ProcessStartInfo + { + FileName = "/bin/bash", + Arguments = "date +%Z", + RedirectStandardOutput = true, + UseShellExecute = false, + }; + + using var p = Process.Start(psi); + + if (p.WaitForExit(1000)) + { + id = p.StandardOutput.ReadToEnd(); + } + + p.Close(); + } + + if (!string.IsNullOrEmpty(id)) + { + tz = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(z => z.Id == id) ?? tz; + } + } + } + + _defaultTimeZone = tz; + } + catch (Exception) + { + // ignore + _defaultTimeZone = TimeZoneInfo.Utc; + } + } + + return _defaultTimeZone; + } + private void InitTranslations() { try @@ -234,74 +327,10 @@ public class TimeZoneConverter } } - public string GetTimeZoneName(TimeZoneInfo timeZone) - { - if (!_customMode) - return _isMono ? timeZone.Id : timeZone.DisplayName; - - return _translations.ContainsKey(timeZone.Id) ? _translations[timeZone.Id] : timeZone.DisplayName; - } - - private TimeZoneInfo GetTimeZoneDefault() - { - if (_defaultTimeZone == null) - { - try - { - var tz = TimeZoneInfo.Local; - if (Path.DirectorySeparatorChar == '/') - { - if (tz.StandardName == "UTC" || tz.StandardName == "UCT") - tz = TimeZoneInfo.Utc; - else - { - var id = string.Empty; - - if (File.Exists("/etc/timezone")) - { - _isMono = true; - id = File.ReadAllText("/etc/timezone").Trim(); - } - - if (string.IsNullOrEmpty(id)) - { - var psi = new ProcessStartInfo - { - FileName = "/bin/bash", - Arguments = "date +%Z", - RedirectStandardOutput = true, - UseShellExecute = false, - }; - - using var p = Process.Start(psi); - - if (p.WaitForExit(1000)) - id = p.StandardOutput.ReadToEnd(); - - p.Close(); - } - - if (!string.IsNullOrEmpty(id)) - tz = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(z => z.Id == id) ?? tz; - } - } - - _defaultTimeZone = tz; - } - catch (Exception) - { - // ignore - _defaultTimeZone = TimeZoneInfo.Utc; - } - } - - return _defaultTimeZone; - } - private class MapZone { public string OlsonTimeZoneId { get; set; } public string WindowsTimeZoneId { get; set; } public string Territory { get; set; } } -} +} \ No newline at end of file diff --git a/common/ASC.Common/Utils/VelocityFormatter.cs b/common/ASC.Common/Utils/VelocityFormatter.cs index 19b96032b1..1c618d29ed 100644 --- a/common/ASC.Common/Utils/VelocityFormatter.cs +++ b/common/ASC.Common/Utils/VelocityFormatter.cs @@ -32,12 +32,20 @@ public class TextLoader : ResourceLoader //nothing to configure } - public override Stream GetResourceStream(string source) => - new MemoryStream(Encoding.UTF8.GetBytes(source)); + public override Stream GetResourceStream(string source) + { + return new MemoryStream(Encoding.UTF8.GetBytes(source)); + } - public override long GetLastModified(NVelocity.Runtime.Resource.Resource resource) => 1; + public override long GetLastModified(NVelocity.Runtime.Resource.Resource resource) + { + return 1; + } - public override bool IsSourceModified(NVelocity.Runtime.Resource.Resource resource) => false; + public override bool IsSourceModified(NVelocity.Runtime.Resource.Resource resource) + { + return false; + } } public class VelocityFormatter @@ -50,7 +58,9 @@ public class VelocityFormatter var nvelocityContext = new VelocityContext(); foreach (var tagValue in values) + { nvelocityContext.Put(tagValue.Key, tagValue.Value); + } return FormatText(templateText, nvelocityContext); } diff --git a/common/ASC.Common/Utils/Wildcard.cs b/common/ASC.Common/Utils/Wildcard.cs index 3c516e68d5..8eaa67d9f2 100644 --- a/common/ASC.Common/Utils/Wildcard.cs +++ b/common/ASC.Common/Utils/Wildcard.cs @@ -28,18 +28,25 @@ namespace ASC.Common.Utils; public static class Wildcard { - public static bool WildcardMatch(this string input, string pattern) => - WildcardMatch(input, pattern, true); + public static bool WildcardMatch(this string input, string pattern) + { + return WildcardMatch(input, pattern, true); + } public static bool WildcardMatch(this string input, string pattern, bool ignoreCase) { - if (!string.IsNullOrEmpty(input)) return IsMatch(pattern, input, ignoreCase); + if (!string.IsNullOrEmpty(input)) + { + return IsMatch(pattern, input, ignoreCase); + } return false; } - public static bool IsMatch(string pattern, string input) => - IsMatch(pattern, input, true); + public static bool IsMatch(string pattern, string input) + { + return IsMatch(pattern, input, true); + } public static bool IsMatch(string pattern, string input, bool ignoreCase) { @@ -65,12 +72,16 @@ public static class Wildcard } if (i >= pattern.Length) + { return true; + } continue; default: if (offsetInput >= input.Length) + { return false; + } if ((ignoreCase ? char.ToLower(input[offsetInput]) @@ -81,7 +92,9 @@ public static class Wildcard : pattern[i])) { if (!isAsterix) + { return false; + } offsetInput++; @@ -94,10 +107,14 @@ public static class Wildcard } if (i > input.Length) + { return false; + } while (i < pattern.Length && pattern[i] == '*') + { ++i; + } return (offsetInput == input.Length); } diff --git a/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs b/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs index bf7ec58f2d..df818ae36d 100644 --- a/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs +++ b/common/ASC.Common/Web/AbstractHttpAsyncHandler.cs @@ -51,7 +51,10 @@ public abstract class AbstractHttpAsyncHandler // : IHttpAsyncHandler, IReadOnly return _processRequest.BeginInvoke(context, cb, extraData); } - public void EndProcessRequest(IAsyncResult result) => _processRequest.EndInvoke(result); + public void EndProcessRequest(IAsyncResult result) + { + _processRequest.EndInvoke(result); + } public abstract void OnProcessRequest(HttpContext context); } diff --git a/common/ASC.Common/Web/DisposableHttpContext.cs b/common/ASC.Common/Web/DisposableHttpContext.cs index c42c086f48..139f7714d7 100644 --- a/common/ASC.Common/Web/DisposableHttpContext.cs +++ b/common/ASC.Common/Web/DisposableHttpContext.cs @@ -34,8 +34,16 @@ public class DisposableHttpContext : IDisposable get => Items.ContainsKey(key) ? Items[key] : null; set { - if (value == null) throw new ArgumentNullException(); - if (!(value is IDisposable)) throw new ArgumentException("Only IDisposable may be added!"); + if (value == null) + { + throw new ArgumentNullException(); + } + + if (!(value is IDisposable)) + { + throw new ArgumentException("Only IDisposable may be added!"); + } + Items[key] = (IDisposable)value; } } @@ -59,8 +67,10 @@ public class DisposableHttpContext : IDisposable private readonly HttpContext _context; private bool _isDisposed; - public DisposableHttpContext(HttpContext ctx) => + public DisposableHttpContext(HttpContext ctx) + { _context = ctx ?? throw new ArgumentNullException(nameof(ctx)); + } public void Dispose() { diff --git a/common/ASC.Common/Web/HttpException.cs b/common/ASC.Common/Web/HttpException.cs index 8de8e38b4c..c5a114b488 100644 --- a/common/ASC.Common/Web/HttpException.cs +++ b/common/ASC.Common/Web/HttpException.cs @@ -4,16 +4,33 @@ public class HttpException : Exception { public int StatusCode { get; } - public HttpException(int httpStatusCode) => StatusCode = httpStatusCode; + public HttpException(int httpStatusCode) + { + StatusCode = httpStatusCode; + } - public HttpException(HttpStatusCode httpStatusCode) => StatusCode = (int)httpStatusCode; - - public HttpException(int httpStatusCode, string message) : base(message) => StatusCode = httpStatusCode; - - public HttpException(HttpStatusCode httpStatusCode, string message) : base(message) => StatusCode = (int)httpStatusCode; - - public HttpException(int httpStatusCode, string message, Exception inner) : base(message, inner) => StatusCode = httpStatusCode; - - public HttpException(HttpStatusCode httpStatusCode, string message, Exception inner) : base(message, inner) => + public HttpException(HttpStatusCode httpStatusCode) + { StatusCode = (int)httpStatusCode; -} + } + + public HttpException(int httpStatusCode, string message) : base(message) + { + StatusCode = httpStatusCode; + } + + public HttpException(HttpStatusCode httpStatusCode, string message) : base(message) + { + StatusCode = (int)httpStatusCode; + } + + public HttpException(int httpStatusCode, string message, Exception inner) : base(message, inner) + { + StatusCode = httpStatusCode; + } + + public HttpException(HttpStatusCode httpStatusCode, string message, Exception inner) : base(message, inner) + { + StatusCode = (int)httpStatusCode; + } +} \ No newline at end of file diff --git a/common/ASC.Common/Web/RouteCallInfo.cs b/common/ASC.Common/Web/RouteCallInfo.cs index b2b0b1d026..d43cf21369 100644 --- a/common/ASC.Common/Web/RouteCallInfo.cs +++ b/common/ASC.Common/Web/RouteCallInfo.cs @@ -35,10 +35,15 @@ public class RouteCallInfo public Dictionary<string, object> Params { get; set; } public bool CleanupHtml { get; set; } - public RouteCallInfo() => CleanupHtml = true; //Default + public RouteCallInfo() + { + CleanupHtml = true; //Default + } - public override string ToString() => - string.Format("{0} {1} T:{2},{3}", Method.ToUpper(), Url, Tid, + public override string ToString() + { + return string.Format("{0} {1} T:{2},{3}", Method.ToUpper(), Url, Tid, string.Join(",", - Params.Select(x => string.Format("{0}={1}", x.Key, x.Value)).ToArray())); + Params.Select(x => string.Format("{0}={1}", x.Key, x.Value)).ToArray())); + } } diff --git a/common/ASC.Common/Web/VirtualPathUtility.cs b/common/ASC.Common/Web/VirtualPathUtility.cs index f055bf7553..d4c80ec3cc 100644 --- a/common/ASC.Common/Web/VirtualPathUtility.cs +++ b/common/ASC.Common/Web/VirtualPathUtility.cs @@ -5,10 +5,14 @@ public class VirtualPathUtility public static string ToAbsolute(string virtualPath) { if (string.IsNullOrEmpty(virtualPath)) + { return virtualPath; + } if (Uri.IsWellFormedUriString(virtualPath, UriKind.Absolute)) + { return virtualPath; + } return "/" + virtualPath.TrimStart('~', '/'); } From 3bf8c338f604d76d1758aa830de262a8c7566991 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 14:20:37 +0300 Subject: [PATCH 156/167] Common: delete unnecessary scopefactory --- common/ASC.Common/Threading/DistributedTaskQueue.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/common/ASC.Common/Threading/DistributedTaskQueue.cs b/common/ASC.Common/Threading/DistributedTaskQueue.cs index f44040f106..841abd679a 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -98,16 +98,13 @@ public class ConfigureDistributedTaskQueue : IConfigureNamedOptions<DistributedT { private readonly DistributedTaskCacheNotify _distributedTaskCacheNotify; public readonly IServiceProvider _serviceProvider; - public readonly IServiceScopeFactory _serviceScopeFactory; public ConfigureDistributedTaskQueue( DistributedTaskCacheNotify distributedTaskCacheNotify, - IServiceProvider serviceProvider, - IServiceScopeFactory serviceScopeFactory) + IServiceProvider serviceProvider) { _distributedTaskCacheNotify = distributedTaskCacheNotify; _serviceProvider = serviceProvider; - _serviceScopeFactory = serviceScopeFactory; } public void Configure(DistributedTaskQueue queue) @@ -126,7 +123,6 @@ public class ConfigureDistributedTaskQueue : IConfigureNamedOptions<DistributedT public class DistributedTaskQueue { public IServiceProvider ServiceProvider { get; set; } - public IServiceScopeFactory ServiceScopeFactory { get; set; } public DistributedTaskCacheNotify DistributedTaskCacheNotify { get; set; } public string Name { @@ -236,7 +232,7 @@ public class DistributedTaskQueue var cache = Cache.HashGet<DistributedTaskCache>(_name, id); if (cache != null) { - using var scope = ServiceScopeFactory.CreateScope(); + using var scope = ServiceProvider.CreateScope(); var task = scope.ServiceProvider.GetService<T>(); task.DistributedTaskCache = cache; From 6314251a59b84513d8e248e872c4e03d48e721c2 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Tue, 8 Feb 2022 14:20:50 +0300 Subject: [PATCH 157/167] Common: add braces --- common/ASC.Common/Threading/DistributedTask.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/common/ASC.Common/Threading/DistributedTask.cs b/common/ASC.Common/Threading/DistributedTask.cs index 134060ad9b..f80d20793d 100644 --- a/common/ASC.Common/Threading/DistributedTask.cs +++ b/common/ASC.Common/Threading/DistributedTask.cs @@ -60,8 +60,10 @@ public class DistributedTask }; } - public DistributedTask(DistributedTaskCache distributedTaskCache) => - DistributedTaskCache = distributedTaskCache; + public DistributedTask(DistributedTaskCache distributedTaskCache) + { + DistributedTaskCache = distributedTaskCache; + } public T GetProperty<T>(string name) { @@ -103,4 +105,4 @@ public class DistributedTask Publication(this); } -} +} \ No newline at end of file From 93506010b83653e0dd701fa77b6535ffa87ed1d8 Mon Sep 17 00:00:00 2001 From: Alexey Bannov <alexey.bannov@onlyoffice.com> Date: Tue, 8 Feb 2022 15:00:07 +0300 Subject: [PATCH 158/167] ASC.AuditTrail: refactoring --- .../services/ASC.AuditTrail/GlobalUsings.cs | 2 +- .../ASC.AuditTrail/Models/AuditEvent.cs | 2 +- .../ASC.AuditTrail/Models/LoginEvent.cs | 4 +- .../Models/Mapping/EventsConverter.cs | 74 ------------------- .../Models/Mappings/EventTypeConverter.cs | 74 +++++++++++++++++++ .../Repositories/AuditEventsRepository.cs | 2 +- .../Repositories/LoginEventsRepository.cs | 4 +- 7 files changed, 80 insertions(+), 82 deletions(-) delete mode 100644 common/services/ASC.AuditTrail/Models/Mapping/EventsConverter.cs create mode 100644 common/services/ASC.AuditTrail/Models/Mappings/EventTypeConverter.cs diff --git a/common/services/ASC.AuditTrail/GlobalUsings.cs b/common/services/ASC.AuditTrail/GlobalUsings.cs index c9b5502621..55a3cbe545 100644 --- a/common/services/ASC.AuditTrail/GlobalUsings.cs +++ b/common/services/ASC.AuditTrail/GlobalUsings.cs @@ -20,7 +20,7 @@ global using ASC.Web.Core.Files; global using ASC.Web.Files.Classes; global using ASC.Web.Files.Utils; global using ASC.AuditTrail.Models; -global using ASC.AuditTrail.Models.Mapping; +global using ASC.AuditTrail.Models.Mappings; global using ASC.Common.Mapping; global using Autofac; diff --git a/common/services/ASC.AuditTrail/Models/AuditEvent.cs b/common/services/ASC.AuditTrail/Models/AuditEvent.cs index 857fba2c27..ef0c460261 100644 --- a/common/services/ASC.AuditTrail/Models/AuditEvent.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEvent.cs @@ -49,6 +49,6 @@ public class AuditEvent : BaseEvent, IMapFrom<AuditEventQuery> profile.CreateMap<DbAuditEvent, AuditEvent>(); profile.CreateMap<AuditEventQuery, AuditEvent>() - .ConvertUsing<EventsConverter>(); + .ConvertUsing<EventTypeConverter>(); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/LoginEvent.cs b/common/services/ASC.AuditTrail/Models/LoginEvent.cs index dc78853399..bf2de24e20 100644 --- a/common/services/ASC.AuditTrail/Models/LoginEvent.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEvent.cs @@ -23,8 +23,6 @@ * */ -using ASC.AuditTrail.Models.Mapping; - namespace ASC.AuditTrail.Models; public class LoginEvent : BaseEvent, IMapFrom<LoginEventQuery> @@ -37,6 +35,6 @@ public class LoginEvent : BaseEvent, IMapFrom<LoginEventQuery> profile.CreateMap<DbLoginEvent, LoginEvent>(); profile.CreateMap<LoginEventQuery, LoginEvent>() - .ConvertUsing<EventsConverter>(); + .ConvertUsing<EventTypeConverter>(); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/Mapping/EventsConverter.cs b/common/services/ASC.AuditTrail/Models/Mapping/EventsConverter.cs deleted file mode 100644 index 63591c48b2..0000000000 --- a/common/services/ASC.AuditTrail/Models/Mapping/EventsConverter.cs +++ /dev/null @@ -1,74 +0,0 @@ -namespace ASC.AuditTrail.Models.Mapping -{ - public class EventsConverter : ITypeConverter<LoginEventQuery, LoginEvent>, ITypeConverter<AuditEventQuery, AuditEvent> - { - private readonly UserFormatter _userFormatter; - private readonly AuditActionMapper _auditActionMapper; - private readonly MessageTarget _messageTarget; - - public EventsConverter( - UserFormatter userFormatter, - AuditActionMapper actionMapper, - MessageTarget messageTarget) - { - _userFormatter = userFormatter; - _auditActionMapper = actionMapper; - _messageTarget = messageTarget; - } - - public LoginEvent Convert(LoginEventQuery source, LoginEvent destination, ResolutionContext context) - { - var result = context.Mapper.Map<LoginEvent>(source.Event); - - if (source.Event.DescriptionRaw != null) - { - result.Description = JsonConvert.DeserializeObject<IList<string>>(source.Event.DescriptionRaw, - new JsonSerializerSettings - { - DateTimeZoneHandling = DateTimeZoneHandling.Utc - }); - } - - result.UserName = (!string.IsNullOrEmpty(source.FirstName) && !string.IsNullOrEmpty(source.LastName)) - ? _userFormatter.GetUserName(source.FirstName, source.LastName) - : !string.IsNullOrWhiteSpace(source.Event.Login) - ? source.Event.Login - : source.Event.UserId == Core.Configuration.Constants.Guest.ID - ? AuditReportResource.GuestAccount - : AuditReportResource.UnknownAccount; - - result.ActionText = _auditActionMapper.GetActionText(result); - - return result; - } - - public AuditEvent Convert(AuditEventQuery source, AuditEvent destination, ResolutionContext context) - { - var result = context.Mapper.Map<AuditEvent>(source.Event); - - if (source.Event.DescriptionRaw != null) - { - result.Description = JsonConvert.DeserializeObject<IList<string>>( - JsonConvert.ToString(source.Event.DescriptionRaw), - new JsonSerializerSettings - { - DateTimeZoneHandling = DateTimeZoneHandling.Utc - }); - } - - result.Target = _messageTarget.Parse(source.Event.Target); - - result.UserName = (source.FirstName != null && source.LastName != null) ? _userFormatter.GetUserName(source.FirstName, source.LastName) : - source.Event.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : - source.Event.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : - source.Event.Initiator ?? AuditReportResource.UnknownAccount; - - result.ActionText = _auditActionMapper.GetActionText(result); - result.ActionTypeText = _auditActionMapper.GetActionTypeText(result); - result.Product = _auditActionMapper.GetProductText(result); - result.Module = _auditActionMapper.GetModuleText(result); - - return result; - } - } -} \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/Mappings/EventTypeConverter.cs b/common/services/ASC.AuditTrail/Models/Mappings/EventTypeConverter.cs new file mode 100644 index 0000000000..58af3287a7 --- /dev/null +++ b/common/services/ASC.AuditTrail/Models/Mappings/EventTypeConverter.cs @@ -0,0 +1,74 @@ +namespace ASC.AuditTrail.Models.Mappings; + +public class EventTypeConverter : ITypeConverter<LoginEventQuery, LoginEvent>, + ITypeConverter<AuditEventQuery, AuditEvent> +{ + private readonly UserFormatter _userFormatter; + private readonly AuditActionMapper _auditActionMapper; + private readonly MessageTarget _messageTarget; + + public EventTypeConverter( + UserFormatter userFormatter, + AuditActionMapper actionMapper, + MessageTarget messageTarget) + { + _userFormatter = userFormatter; + _auditActionMapper = actionMapper; + _messageTarget = messageTarget; + } + + public LoginEvent Convert(LoginEventQuery source, LoginEvent destination, ResolutionContext context) + { + var result = context.Mapper.Map<LoginEvent>(source.Event); + + if (source.Event.DescriptionRaw != null) + { + result.Description = JsonConvert.DeserializeObject<IList<string>>(source.Event.DescriptionRaw, + new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.Utc + }); + } + + result.UserName = (!string.IsNullOrEmpty(source.FirstName) && !string.IsNullOrEmpty(source.LastName)) + ? _userFormatter.GetUserName(source.FirstName, source.LastName) + : !string.IsNullOrWhiteSpace(source.Event.Login) + ? source.Event.Login + : source.Event.UserId == Core.Configuration.Constants.Guest.ID + ? AuditReportResource.GuestAccount + : AuditReportResource.UnknownAccount; + + result.ActionText = _auditActionMapper.GetActionText(result); + + return result; + } + + public AuditEvent Convert(AuditEventQuery source, AuditEvent destination, ResolutionContext context) + { + var result = context.Mapper.Map<AuditEvent>(source.Event); + + if (source.Event.DescriptionRaw != null) + { + result.Description = JsonConvert.DeserializeObject<IList<string>>( + JsonConvert.ToString(source.Event.DescriptionRaw), + new JsonSerializerSettings + { + DateTimeZoneHandling = DateTimeZoneHandling.Utc + }); + } + + result.Target = _messageTarget.Parse(source.Event.Target); + + result.UserName = (source.FirstName != null && source.LastName != null) ? _userFormatter.GetUserName(source.FirstName, source.LastName) : + source.Event.UserId == Core.Configuration.Constants.CoreSystem.ID ? AuditReportResource.SystemAccount : + source.Event.UserId == Core.Configuration.Constants.Guest.ID ? AuditReportResource.GuestAccount : + source.Event.Initiator ?? AuditReportResource.UnknownAccount; + + result.ActionText = _auditActionMapper.GetActionText(result); + result.ActionTypeText = _auditActionMapper.GetActionTypeText(result); + result.Product = _auditActionMapper.GetProductText(result); + result.Module = _auditActionMapper.GetModuleText(result); + + return result; + } +} diff --git a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs index c8a85ad337..96ab6f83ad 100644 --- a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs @@ -90,6 +90,6 @@ public class AuditEventsRepository query = query.Take((int)limit); } - return _mapper.Map<List<AuditEventQuery>, List<AuditEvent>>(query.ToList()); + return _mapper.Map<List<AuditEventQuery>, IEnumerable<AuditEvent>>(query.ToList()); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs index 7e2fd4b323..eae0e1667d 100644 --- a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs @@ -57,7 +57,7 @@ public class LoginEventsRepository }) .Take(chunk); - return _mapper.Map<List<LoginEventQuery>, List<LoginEvent>>(query.ToList()); + return _mapper.Map<List<LoginEventQuery>, IEnumerable<LoginEvent>>(query.ToList()); } public IEnumerable<LoginEvent> Get(int tenant, DateTime fromDate, DateTime to) @@ -77,7 +77,7 @@ public class LoginEventsRepository LastName = p.LastName }; - return _mapper.Map<List<LoginEventQuery>, List<LoginEvent>>(query.ToList()); + return _mapper.Map<List<LoginEventQuery>, IEnumerable<LoginEvent>>(query.ToList()); } public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) From 147377ab650ee5885171c7337c1d92195a39003a Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 9 Feb 2022 13:32:01 +0300 Subject: [PATCH 159/167] bugfix: crash when string == null --- common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs | 5 +++-- common/ASC.Core.Common/Context/Impl/UserManager.cs | 4 ++-- .../ASC.Core.Common/Security/EmailValidationKeyProvider.cs | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs index d3f4eb1e7f..ba0b124145 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -76,13 +76,14 @@ namespace ASC.Core get { //TODO:if (CustomMode && HttpContext.Current != null && HttpContext.Current.Request.SailfishApp()) return true; - return personal ?? (bool)(personal = Configuration["core:personal"].Equals("true", StringComparison.OrdinalIgnoreCase)); + return personal ?? (bool)(personal = string.Equals(Configuration["core:personal"], "true", StringComparison.OrdinalIgnoreCase)); } } public bool CustomMode { - get { return customMode ?? (bool)(customMode = Configuration["core:custom-mode"].Equals("true", StringComparison.OrdinalIgnoreCase)); } + get { return customMode ?? (bool)(customMode = string.Equals(Configuration["core:custom-mode"], "true", StringComparison.OrdinalIgnoreCase));} + } } diff --git a/common/ASC.Core.Common/Context/Impl/UserManager.cs b/common/ASC.Core.Common/Context/Impl/UserManager.cs index bec401d493..e30e6b035d 100644 --- a/common/ASC.Core.Common/Context/Impl/UserManager.cs +++ b/common/ASC.Core.Common/Context/Impl/UserManager.cs @@ -175,13 +175,13 @@ namespace ASC.Core public UserInfo GetUserBySid(string sid) { return GetUsersInternal() - .FirstOrDefault(u => u.Sid != null && u.Sid.Equals(sid, StringComparison.CurrentCultureIgnoreCase)) ?? Constants.LostUser; + .FirstOrDefault(u => u.Sid != null && string.Equals(u.Sid , sid, StringComparison.CurrentCultureIgnoreCase)) ?? Constants.LostUser; } public UserInfo GetSsoUserByNameId(string nameId) { return GetUsersInternal() - .FirstOrDefault(u => !string.IsNullOrEmpty(u.SsoNameId) && u.SsoNameId.Equals(nameId, StringComparison.CurrentCultureIgnoreCase)) ?? Constants.LostUser; + .FirstOrDefault(u => !string.IsNullOrEmpty(u.SsoNameId) && string.Equals(u.SsoNameId, nameId, StringComparison.CurrentCultureIgnoreCase)) ?? Constants.LostUser; } public bool IsUserNameExists(string username) { diff --git a/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs b/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs index 820fbe17e5..57cf988b48 100644 --- a/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs +++ b/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs @@ -134,7 +134,7 @@ namespace ASC.Security.Cryptography var hash = GetMashineHashedData(BitConverter.GetBytes(ms), Encoding.ASCII.GetBytes(email)); var key2 = DoStringFromBytes(hash); - var key2_good = parts[1].Equals(key2, StringComparison.OrdinalIgnoreCase); + var key2_good = string.Equals(parts[1], key2, StringComparison.OrdinalIgnoreCase); if (!key2_good) return ValidationResult.Invalid; var ms_current = (long)(DateTime.UtcNow - _from).TotalMilliseconds; return validInterval >= TimeSpan.FromMilliseconds(ms_current - ms) ? ValidationResult.Ok : ValidationResult.Expired; From c20a470508803c74feb0c02bd5f4ceead8698d39 Mon Sep 17 00:00:00 2001 From: pavelbannov <pavel.bannov@onlyoffice.com> Date: Thu, 10 Feb 2022 14:00:53 +0300 Subject: [PATCH 160/167] People: fix --- products/ASC.People/Server/PeopleProduct.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/ASC.People/Server/PeopleProduct.cs b/products/ASC.People/Server/PeopleProduct.cs index 84e80c8092..f010ff87e8 100644 --- a/products/ASC.People/Server/PeopleProduct.cs +++ b/products/ASC.People/Server/PeopleProduct.cs @@ -8,7 +8,7 @@ public static Guid ID { - get { return new Guid("{F4D98AFD-D336-4332 -8778-3C6945C81EA0}"); } + get { return new Guid("{F4D98AFD-D336-4332-8778-3C6945C81EA0}"); } } public override bool Visible { get { return true; } } From 599b5b9a73a4faf78181164dc1792b81bc8fbb23 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 10 Feb 2022 15:10:27 +0300 Subject: [PATCH 161/167] ApiCore: removed 's' prefix --- common/ASC.Api.Core/Core/ApiContext.cs | 6 +++--- common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs | 8 ++++---- .../Middleware/WebhooksGlobalFilterAttribute.cs | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/common/ASC.Api.Core/Core/ApiContext.cs b/common/ASC.Api.Core/Core/ApiContext.cs index 767b6b78cf..9b74f6754a 100644 --- a/common/ASC.Api.Core/Core/ApiContext.cs +++ b/common/ASC.Api.Core/Core/ApiContext.cs @@ -110,7 +110,7 @@ public class ApiContext : ICloneable internal long SpecifiedStartIndex { get; set; } private Tenant _tenant; - private static int s_maxCount = 1000; + private static int _maxCount = 1000; private readonly SecurityContext _securityContext; private readonly TenantManager _tenantManager; @@ -124,14 +124,14 @@ public class ApiContext : ICloneable return; } - Count = s_maxCount; + Count = _maxCount; var query = HttpContextAccessor.HttpContext.Request.Query; //Try parse values var count = query.GetRequestValue("count"); if (!string.IsNullOrEmpty(count) && ulong.TryParse(count, out var countParsed)) { //Count specified and valid - Count = Math.Min((long)countParsed, s_maxCount); + Count = Math.Min((long)countParsed, _maxCount); } var startIndex = query.GetRequestValue("startIndex"); diff --git a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs index ced0a22bea..e62754f21a 100644 --- a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs +++ b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs @@ -3,7 +3,7 @@ [Scope] public class ProductSecurityFilter : IResourceFilter { - private static readonly IDictionary<string, Guid> s_products; + private static readonly IDictionary<string, Guid> _products; private readonly ILog _logger; private readonly WebItemSecurity _webItemSecurity; private readonly AuthContext _authContext; @@ -17,7 +17,7 @@ public class ProductSecurityFilter : IResourceFilter var wiki = new Guid("742cf945-cbbc-4a57-82d6-1600a12cf8ca"); var photo = new Guid("9d51954f-db9b-4aed-94e3-ed70b914e101"); - s_products = new Dictionary<string, Guid> + _products = new Dictionary<string, Guid> { { "blog", blog }, { "bookmark", bookmark }, @@ -88,14 +88,14 @@ public class ProductSecurityFilter : IResourceFilter if (!string.IsNullOrEmpty(url)) { var module = url.Split('/')[0]; - if (s_products.TryGetValue(module, out var communityProduct)) + if (_products.TryGetValue(module, out var communityProduct)) { return communityProduct; } } } - if (s_products.TryGetValue(name, out var product)) + if (_products.TryGetValue(name, out var product)) { return product; } diff --git a/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs b/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs index 8086ff97ea..1252a1c864 100644 --- a/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs +++ b/common/ASC.Api.Core/Middleware/WebhooksGlobalFilterAttribute.cs @@ -7,7 +7,7 @@ public class WebhooksGlobalFilterAttribute : ResultFilterAttribute { private readonly IWebhookPublisher _webhookPublisher; private readonly JsonSerializerOptions _jsonSerializerOptions; - private static List<string> s_methodList = new List<string> { "POST", "UPDATE", "DELETE" }; + private static List<string> _methodList = new List<string> { "POST", "UPDATE", "DELETE" }; public WebhooksGlobalFilterAttribute(IWebhookPublisher webhookPublisher, Action<JsonOptions> projectJsonOptions) { @@ -22,7 +22,7 @@ public class WebhooksGlobalFilterAttribute : ResultFilterAttribute { var method = context.HttpContext.Request.Method; - if (!s_methodList.Contains(method) || context.Canceled) + if (!_methodList.Contains(method) || context.Canceled) { base.OnResultExecuted(context); From a06903129eccb808d71ee8fd213e558628258a69 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 10 Feb 2022 15:14:50 +0300 Subject: [PATCH 162/167] Common: removed 's' prefix --- .../Logging/SelfCleaningAppender.cs | 18 ++++++------ .../ASC.Common/Logging/SelfCleaningTarget.cs | 18 ++++++------ .../Security/Authorizing/AzObjectIdHelper.cs | 4 +-- common/ASC.Common/Utils/CrossPlatformUtils.cs | 4 +-- common/ASC.Common/Utils/HtmlUtil.cs | 16 +++++------ common/ASC.Common/Web/MimeMapping.cs | 28 +++++++++---------- 6 files changed, 44 insertions(+), 44 deletions(-) diff --git a/common/ASC.Common/Logging/SelfCleaningAppender.cs b/common/ASC.Common/Logging/SelfCleaningAppender.cs index 5eca630b79..a790bacf4d 100644 --- a/common/ASC.Common/Logging/SelfCleaningAppender.cs +++ b/common/ASC.Common/Logging/SelfCleaningAppender.cs @@ -27,14 +27,14 @@ namespace ASC.Common.Logging; public class SelfCleaningAppender : RollingFileAppender { - private static DateTime s_lastCleanDate; - private static int? s_cleanPeriod; + private static DateTime _lastCleanDate; + private static int? _cleanPeriod; protected override void Append(LoggingEvent loggingEvent) { - if (DateTime.UtcNow.Date > s_lastCleanDate.Date) + if (DateTime.UtcNow.Date > _lastCleanDate.Date) { - s_lastCleanDate = DateTime.UtcNow.Date; + _lastCleanDate = DateTime.UtcNow.Date; Clean(); } @@ -43,9 +43,9 @@ public class SelfCleaningAppender : RollingFileAppender protected override void Append(LoggingEvent[] loggingEvents) { - if (DateTime.UtcNow.Date > s_lastCleanDate.Date) + if (DateTime.UtcNow.Date > _lastCleanDate.Date) { - s_lastCleanDate = DateTime.UtcNow.Date; + _lastCleanDate = DateTime.UtcNow.Date; Clean(); } @@ -54,9 +54,9 @@ public class SelfCleaningAppender : RollingFileAppender private static int GetCleanPeriod() { - if (s_cleanPeriod != null) + if (_cleanPeriod != null) { - return s_cleanPeriod.Value; + return _cleanPeriod.Value; } const string key = "CleanPeriod"; @@ -69,7 +69,7 @@ public class SelfCleaningAppender : RollingFileAppender int.TryParse(repo.Properties[key].ToString(), out value); } - s_cleanPeriod = value; + _cleanPeriod = value; return value; } diff --git a/common/ASC.Common/Logging/SelfCleaningTarget.cs b/common/ASC.Common/Logging/SelfCleaningTarget.cs index 6be0839189..4a97e0c3d1 100644 --- a/common/ASC.Common/Logging/SelfCleaningTarget.cs +++ b/common/ASC.Common/Logging/SelfCleaningTarget.cs @@ -30,14 +30,14 @@ namespace ASC.Common.Logging; [Target("SelfCleaning")] public class SelfCleaningTarget : FileTarget { - private static DateTime s_lastCleanDate; - private static int? s_cleanPeriod; + private static DateTime _lastCleanDate; + private static int? _cleanPeriod; protected override void Write(IList<AsyncLogEventInfo> logEvents) { - if (DateTime.UtcNow.Date > s_lastCleanDate.Date) + if (DateTime.UtcNow.Date > _lastCleanDate.Date) { - s_lastCleanDate = DateTime.UtcNow.Date; + _lastCleanDate = DateTime.UtcNow.Date; Clean(); } @@ -60,9 +60,9 @@ public class SelfCleaningTarget : FileTarget protected override void Write(LogEventInfo logEvent) { - if (DateTime.UtcNow.Date > s_lastCleanDate.Date) + if (DateTime.UtcNow.Date > _lastCleanDate.Date) { - s_lastCleanDate = DateTime.UtcNow.Date; + _lastCleanDate = DateTime.UtcNow.Date; Clean(); } @@ -71,9 +71,9 @@ public class SelfCleaningTarget : FileTarget private static int GetCleanPeriod() { - if (s_cleanPeriod != null) + if (_cleanPeriod != null) { - return s_cleanPeriod.Value; + return _cleanPeriod.Value; } var value = 30; @@ -90,7 +90,7 @@ public class SelfCleaningTarget : FileTarget } } - s_cleanPeriod = value; + _cleanPeriod = value; return value; } diff --git a/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs b/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs index 69dd7dc877..5cd96a1c1c 100644 --- a/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs +++ b/common/ASC.Common/Security/Authorizing/AzObjectIdHelper.cs @@ -28,7 +28,7 @@ namespace ASC.Common.Security.Authorizing; public static class AzObjectIdHelper { - private static readonly string s_separator = "|"; + private static readonly string _separator = "|"; public static string GetFullObjectId(ISecurityObjectId objectId) { @@ -37,6 +37,6 @@ public static class AzObjectIdHelper return null; } - return $"{objectId.ObjectType.FullName}{s_separator}{objectId.SecurityId}"; + return $"{objectId.ObjectType.FullName}{_separator}{objectId.SecurityId}"; } } diff --git a/common/ASC.Common/Utils/CrossPlatformUtils.cs b/common/ASC.Common/Utils/CrossPlatformUtils.cs index b4bfe15b68..b26ac4ddfc 100644 --- a/common/ASC.Common/Utils/CrossPlatformUtils.cs +++ b/common/ASC.Common/Utils/CrossPlatformUtils.cs @@ -27,11 +27,11 @@ namespace ASC.Common.Utils; public static class CrossPlatform { - private static char[] s_pathSplitCharacters = new char[] { '/', '\\' }; + private static char[] _pathSplitCharacters = new char[] { '/', '\\' }; public static string PathCombine(string basePath, params string[] additional) { - var splits = additional.Select(s => s.Split(s_pathSplitCharacters)).ToArray(); + var splits = additional.Select(s => s.Split(_pathSplitCharacters)).ToArray(); var totalLength = splits.Sum(arr => arr.Length); var segments = new string[totalLength + 1]; segments[0] = basePath; diff --git a/common/ASC.Common/Utils/HtmlUtil.cs b/common/ASC.Common/Utils/HtmlUtil.cs index 80763c5a5c..b82050af93 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -27,17 +27,17 @@ namespace ASC.Common.Utils; public static class HtmlUtil { - private static readonly Regex s_tagReplacer + private static readonly Regex _tagReplacer = new Regex("<[^>]*>", RegexOptions.Multiline | RegexOptions.Compiled); - private static readonly Regex s_commentsReplacer + private static readonly Regex _commentsReplacer = new Regex("<!--(?s).*?-->", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex s_xssReplacer + private static readonly Regex _xssReplacer = new Regex(@"<\s*(style|script)[^>]*>(.*?)<\s*/\s*(style|script)>", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Singleline); - private static readonly Regex s_worder = + private static readonly Regex _worder = new Regex(@"\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); public static string GetText(string html, int maxLength = 0, string endBlockTemplate = "...") @@ -46,19 +46,19 @@ public static class HtmlUtil if (!string.IsNullOrEmpty(html)) { - html = s_xssReplacer.Replace(html, string.Empty); //Clean malicious tags. <script> <style> + html = _xssReplacer.Replace(html, string.Empty); //Clean malicious tags. <script> <style> if (string.IsNullOrEmpty(html)) { return html; } - unformatedText = s_tagReplacer.Replace(html, string.Empty); + unformatedText = _tagReplacer.Replace(html, string.Empty); if (!string.IsNullOrEmpty(unformatedText)) { // kill comments - unformatedText = s_commentsReplacer.Replace(unformatedText, string.Empty); + unformatedText = _commentsReplacer.Replace(unformatedText, string.Empty); unformatedText = unformatedText.Trim(); if (!string.IsNullOrEmpty(unformatedText)) @@ -109,7 +109,7 @@ public static class HtmlUtil return htmlText; } - var regexpstr = s_worder.Matches(searchText).Cast<Match>().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); + var regexpstr = _worder.Matches(searchText).Cast<Match>().Select(m => m.Value).Distinct().Aggregate((r, n) => r + "|" + n); var wordsFinder = new Regex(Regex.Escape(regexpstr), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline); return wordsFinder.Replace(htmlText, m => string.Format("<span class='searchTextHighlight{1}'>{0}</span>", m.Value, withoutLink ? " bold" : string.Empty)); diff --git a/common/ASC.Common/Web/MimeMapping.cs b/common/ASC.Common/Web/MimeMapping.cs index a6af276230..7ebd83b1f7 100644 --- a/common/ASC.Common/Web/MimeMapping.cs +++ b/common/ASC.Common/Web/MimeMapping.cs @@ -27,8 +27,8 @@ namespace ASC.Common.Web; public static class MimeMapping { - private static readonly Hashtable s_extensionToMimeMappingTable = new Hashtable(200, StringComparer.CurrentCultureIgnoreCase); - private static readonly IDictionary<string, IList<string>> s_mimeSynonyms = new Dictionary<string, IList<string>>(); + private static readonly Hashtable _extensionToMimeMappingTable = new Hashtable(200, StringComparer.CurrentCultureIgnoreCase); + private static readonly IDictionary<string, IList<string>> _mimeSynonyms = new Dictionary<string, IList<string>>(); static MimeMapping() { @@ -810,12 +810,12 @@ public static class MimeMapping { if (string.IsNullOrEmpty(mimeMapping)) return null; - foreach (DictionaryEntry entry in s_extensionToMimeMappingTable) + foreach (DictionaryEntry entry in _extensionToMimeMappingTable) { var mime = (string)entry.Value; if (mime == mimeMapping.ToLowerInvariant()) return (string)entry.Key; - if (!s_mimeSynonyms.ContainsKey(mime)) continue; - if (s_mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; + if (!_mimeSynonyms.ContainsKey(mime)) continue; + if (_mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; } return null; @@ -827,27 +827,27 @@ public static class MimeMapping var startIndex = fileName.LastIndexOf('.'); if (0 <= startIndex && fileName.LastIndexOf('\\') < startIndex) - str = (string)s_extensionToMimeMappingTable[fileName.Substring(startIndex)]; + str = (string)_extensionToMimeMappingTable[fileName.Substring(startIndex)]; - if (str == null) str = (string)s_extensionToMimeMappingTable[".*"]; + if (str == null) str = (string)_extensionToMimeMappingTable[".*"]; return str; } private static void AddMimeMapping(string extension, string MimeType) { - if (s_extensionToMimeMappingTable.ContainsKey(extension)) - AddMimeSynonym((string)s_extensionToMimeMappingTable[extension], MimeType); + if (_extensionToMimeMappingTable.ContainsKey(extension)) + AddMimeSynonym((string)_extensionToMimeMappingTable[extension], MimeType); - else s_extensionToMimeMappingTable.Add(extension, MimeType); + else _extensionToMimeMappingTable.Add(extension, MimeType); } private static void AddMimeSynonym(string mime, string synonym) { - if (!s_mimeSynonyms.ContainsKey(mime)) - s_mimeSynonyms[mime] = new List<string>(); + if (!_mimeSynonyms.ContainsKey(mime)) + _mimeSynonyms[mime] = new List<string>(); - if (!s_mimeSynonyms[mime].Contains(synonym)) - s_mimeSynonyms[mime].Add(synonym); + if (!_mimeSynonyms[mime].Contains(synonym)) + _mimeSynonyms[mime].Add(synonym); } } From 77e14da2180af075c491b5e5446f2ec114105134 Mon Sep 17 00:00:00 2001 From: pavelbannov <pavel.bannov@onlyoffice.com> Date: Thu, 10 Feb 2022 16:24:55 +0300 Subject: [PATCH 163/167] fixed tests --- .../Tests/ASC.Common.Tests/ASC.Common.Tests.csproj | 2 +- .../ClientPaymentManagerTest.cs | 2 +- products/ASC.Files/Tests/ASC.Files.Tests.csproj | 14 +++++++------- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/common/Tests/ASC.Common.Tests/ASC.Common.Tests.csproj b/common/Tests/ASC.Common.Tests/ASC.Common.Tests.csproj index d6737b9aa7..5305bfe58f 100644 --- a/common/Tests/ASC.Common.Tests/ASC.Common.Tests.csproj +++ b/common/Tests/ASC.Common.Tests/ASC.Common.Tests.csproj @@ -5,7 +5,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="log4net" Version="2.0.11" /> + <PackageReference Include="log4net" Version="2.0.14" /> <PackageReference Include="MSTest.TestFramework" Version="2.1.2" /> <PackageReference Include="NUnit" Version="3.13.1" /> </ItemGroup> diff --git a/common/Tests/ASC.Core.Common.Tests/ClientPaymentManagerTest.cs b/common/Tests/ASC.Core.Common.Tests/ClientPaymentManagerTest.cs index 596741cae8..effc546276 100644 --- a/common/Tests/ASC.Core.Common.Tests/ClientPaymentManagerTest.cs +++ b/common/Tests/ASC.Core.Common.Tests/ClientPaymentManagerTest.cs @@ -36,7 +36,7 @@ namespace ASC.Core.Common.Tests [TestFixture] public class ClientPaymentManagerTest { - private readonly PaymentManager paymentManager = new PaymentManager(null, null, null); + private readonly PaymentManager paymentManager = new PaymentManager(null, null, null, null); private readonly IServiceProvider serviceProvider; [Test] diff --git a/products/ASC.Files/Tests/ASC.Files.Tests.csproj b/products/ASC.Files/Tests/ASC.Files.Tests.csproj index c5c4c9ec46..c5cfbc28e7 100644 --- a/products/ASC.Files/Tests/ASC.Files.Tests.csproj +++ b/products/ASC.Files/Tests/ASC.Files.Tests.csproj @@ -14,12 +14,12 @@ <PackageReference Include="Autofac.Configuration" Version="6.0.0" /> <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.2.0" /> <PackageReference Include="Box.V2.Core" Version="3.24.0" /> - <PackageReference Include="Confluent.Kafka" Version="1.5.2" /> + <PackageReference Include="Confluent.Kafka" Version="1.8.2" /> <PackageReference Include="Dropbox.Api" Version="4.10.0" /> <PackageReference Include="EntityFramework" Version="6.4.4" /> - <PackageReference Include="Google.Apis.Drive.v3" Version="1.49.0.2111" /> - <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" /> - <PackageReference Include="Google.Protobuf" Version="3.19.1" /> + <PackageReference Include="Google.Apis.Drive.v3" Version="1.55.0.2566" /> + <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.1" /> + <PackageReference Include="Google.Protobuf" Version="3.19.4" /> <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" /> @@ -28,13 +28,13 @@ <PackageReference Include="Microsoft.SharePoint.Client" Version="14.0.4762.1000" /> <PackageReference Include="Moq" Version="4.14.7" /> <PackageReference Include="MSTest.TestFramework" Version="2.1.2" /> - <PackageReference Include="NEST" Version="7.9.0" /> - <PackageReference Include="NLog" Version="4.7.10" /> + <PackageReference Include="NEST" Version="7.15.2" /> + <PackageReference Include="NLog" Version="4.7.13" /> <PackageReference Include="nunit" Version="3.13.1" /> <PackageReference Include="NUnit3TestAdapter" Version="3.17.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" /> <PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.0" /> - <PackageReference Include="UAParser" Version="3.1.44" /> + <PackageReference Include="UAParser" Version="3.1.47" /> </ItemGroup> <ItemGroup> From 0a1c864c4e14fd04451e4cbdb4f4cc8873cb3c2a Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Thu, 10 Feb 2022 18:10:43 +0300 Subject: [PATCH 164/167] ClearEvents: fix dispose --- .../ASC.ClearEvents/Services/ClearEventsService.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/common/services/ASC.ClearEvents/Services/ClearEventsService.cs b/common/services/ASC.ClearEvents/Services/ClearEventsService.cs index 467f750579..91db22cfbd 100644 --- a/common/services/ASC.ClearEvents/Services/ClearEventsService.cs +++ b/common/services/ASC.ClearEvents/Services/ClearEventsService.cs @@ -30,7 +30,7 @@ public class ClearEventsService : IHostedService, IDisposable { private readonly ILog _logger; private readonly IServiceScopeFactory _serviceScopeFactory; - private Timer _timer = null!; + private Timer _timer; public ClearEventsService(IOptionsMonitor<ILog> options, IServiceScopeFactory serviceScopeFactory) { @@ -59,9 +59,14 @@ public class ClearEventsService : IHostedService, IDisposable public void Dispose() { + if (_timer == null) + { + return; + } + var handle = new AutoResetEvent(false); - if ((bool)!(_timer?.Dispose(handle))) + if (!_timer.Dispose(handle)) { throw new Exception("Timer already disposed"); } From 577b5af0f70ca77505ff8cdcb55e984ddf68943a Mon Sep 17 00:00:00 2001 From: pavelbannov <pavel.bannov@onlyoffice.com> Date: Thu, 10 Feb 2022 22:02:42 +0300 Subject: [PATCH 165/167] Audit: fix --- .../Mappers/DocumentsActionMapper.cs | 767 +++++++++--------- 1 file changed, 388 insertions(+), 379 deletions(-) diff --git a/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs index dced5d6282..3cb24647b0 100644 --- a/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs @@ -29,384 +29,393 @@ internal static class DocumentsActionMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() => new Dictionary<MessageAction, MessageMaps> - { - { - MessageAction.FileRenamed, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "FileRenamed", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileUpdated, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "FileUpdated", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.UserFileUpdated, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "UserFileUpdated", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileCreatedVersion, new MessageMaps - { - ActionTypeTextResourceName = "CreateActionType", - ActionTextResourceName = "FileCreatedVersion", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileDeletedVersion, new MessageMaps - { - ActionTypeTextResourceName = "DeleteActionType", - ActionTextResourceName = "FileDeletedVersion", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileRestoreVersion, new MessageMaps - { - ActionTypeTextResourceName = "CreateActionType", - ActionTextResourceName = "FileRestoreVersion", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileUpdatedRevisionComment, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "FileUpdatedRevisionComment", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileLocked, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "FileLocked", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileUnlocked, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "FileUnlocked", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileUpdatedAccess, new MessageMaps - { - ActionTypeTextResourceName = "UpdateAccessActionType", - ActionTextResourceName = "FileUpdatedAccess", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileDownloaded, new MessageMaps - { - ActionTypeTextResourceName = "DownloadActionType", - ActionTextResourceName = "FileDownloaded", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileDownloadedAs, new MessageMaps - { - ActionTypeTextResourceName = "DownloadActionType", - ActionTextResourceName = "FileDownloadedAs", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileUploaded, new MessageMaps - { - ActionTypeTextResourceName = "UploadActionType", - ActionTextResourceName = "FileUploaded", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileImported, new MessageMaps - { - ActionTypeTextResourceName = "ImportActionType", - ActionTextResourceName = "FileImported", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileCopied, new MessageMaps - { - ActionTypeTextResourceName = "CopyActionType", - ActionTextResourceName = "FileCopied", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileCopiedWithOverwriting, new MessageMaps - { - ActionTypeTextResourceName = "CopyActionType", - ActionTextResourceName = "FileCopiedWithOverwriting", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileMoved, new MessageMaps - { - ActionTypeTextResourceName = "MoveActionType", - ActionTextResourceName = "FileMoved", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileMovedWithOverwriting, new MessageMaps - { - ActionTypeTextResourceName = "MoveActionType", - ActionTextResourceName = "FileMovedWithOverwriting", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileMovedToTrash, new MessageMaps - { - ActionTypeTextResourceName = "MoveActionType", - ActionTextResourceName = "FileMovedToTrash", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileDeleted, new MessageMaps - { - ActionTypeTextResourceName = "DeleteActionType", - ActionTextResourceName = "FileDeleted", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FolderCreated, new MessageMaps - { - ActionTypeTextResourceName = "CreateActionType", - ActionTextResourceName = "FolderCreated", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FoldersModule" - } - }, - { - MessageAction.FolderRenamed, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "FolderRenamed", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FoldersModule" - } - }, - { - MessageAction.FolderUpdatedAccess, new MessageMaps - { - ActionTypeTextResourceName = "UpdateAccessActionType", - ActionTextResourceName = "FolderUpdatedAccess", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FoldersModule" - } - }, - { - MessageAction.FolderCopied, new MessageMaps - { - ActionTypeTextResourceName = "CopyActionType", - ActionTextResourceName = "FolderCopied", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FoldersModule" - } - }, - { - MessageAction.FolderCopiedWithOverwriting, new MessageMaps - { - ActionTypeTextResourceName = "CopyActionType", - ActionTextResourceName = "FolderCopiedWithOverwriting", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FoldersModule" - } - }, - { - MessageAction.FolderMoved, new MessageMaps - { - ActionTypeTextResourceName = "MoveActionType", - ActionTextResourceName = "FolderMoved", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FoldersModule" - } - }, - { - MessageAction.FolderMovedWithOverwriting, new MessageMaps - { - ActionTypeTextResourceName = "MoveActionType", - ActionTextResourceName = "FolderMovedWithOverwriting", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FoldersModule" - } - }, - { - MessageAction.FolderMovedToTrash, new MessageMaps - { - ActionTypeTextResourceName = "MoveActionType", - ActionTextResourceName = "FolderMovedToTrash", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FoldersModule" - } - }, - { - MessageAction.FolderDeleted, new MessageMaps - { - ActionTypeTextResourceName = "DeleteActionType", - ActionTextResourceName = "FolderDeleted", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FoldersModule" - } - }, - { - MessageAction.ThirdPartyCreated, new MessageMaps - { - ActionTypeTextResourceName = "CreateActionType", - ActionTextResourceName = "ThirdPartyCreated", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "DocumentsSettingsModule" - } - }, - { - MessageAction.ThirdPartyUpdated, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "ThirdPartyUpdated", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "DocumentsSettingsModule" - } - }, - { - MessageAction.ThirdPartyDeleted, new MessageMaps - { - ActionTypeTextResourceName = "DeleteActionType", - ActionTextResourceName = "ThirdPartyDeleted", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "DocumentsSettingsModule" - } - }, - { - MessageAction.DocumentsThirdPartySettingsUpdated, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "DocumentsThirdPartySettingsUpdated", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "DocumentsSettingsModule" - } - }, - { - MessageAction.DocumentsOverwritingSettingsUpdated, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "DocumentsOverwritingSettingsUpdated", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "DocumentsSettingsModule" - } - }, - { - MessageAction.DocumentsForcesave, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "DocumentsForcesave", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "DocumentsSettingsModule" - } - }, - { - MessageAction.DocumentsStoreForcesave, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "DocumentsStoreForcesave", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "DocumentsSettingsModule" - } - }, - { - MessageAction.DocumentsUploadingFormatsSettingsUpdated, new MessageMaps - { - ActionTypeTextResourceName = "UpdateActionType", - ActionTextResourceName = "DocumentsUploadingFormatsSettingsUpdated", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "DocumentsSettingsModule" - } - }, - { - MessageAction.FileConverted, new MessageMaps - { - ActionTypeTextResourceName = "CreateActionType", - ActionTextResourceName = "FileConverted", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileSendAccessLink, new MessageMaps - { - ActionTypeTextResourceName = "SendActionType", - ActionTextResourceName = "FileSendAccessLink", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.FileChangeOwner, new MessageMaps - { - ActionTypeTextResourceName = "SendActionType", - ActionTextResourceName = "FileChangeOwner", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.DocumentSignComplete, new MessageMaps - { - ActionTypeTextResourceName = "SendActionType", - ActionTextResourceName = "FilesDocumentSigned", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, - { - MessageAction.DocumentSendToSign, new MessageMaps - { - ActionTypeTextResourceName = "SendActionType", - ActionTextResourceName = "FilesRequestSign", - ProductResourceName = "DocumentsProduct", - ModuleResourceName = "FilesModule" - } - }, + { + { + MessageAction.FileCreated, new MessageMaps + { + ActionTypeTextResourceName = "CreateActionType", + ActionTextResourceName = "FileCreated", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileRenamed, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "FileRenamed", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileUpdated, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "FileUpdated", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.UserFileUpdated, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "UserFileUpdated", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileCreatedVersion, new MessageMaps + { + ActionTypeTextResourceName = "CreateActionType", + ActionTextResourceName = "FileCreatedVersion", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileDeletedVersion, new MessageMaps + { + ActionTypeTextResourceName = "DeleteActionType", + ActionTextResourceName = "FileDeletedVersion", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileRestoreVersion, new MessageMaps + { + ActionTypeTextResourceName = "CreateActionType", + ActionTextResourceName = "FileRestoreVersion", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileUpdatedRevisionComment, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "FileUpdatedRevisionComment", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileLocked, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "FileLocked", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileUnlocked, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "FileUnlocked", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileUpdatedAccess, new MessageMaps + { + ActionTypeTextResourceName = "UpdateAccessActionType", + ActionTextResourceName = "FileUpdatedAccess", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileDownloaded, new MessageMaps + { + ActionTypeTextResourceName = "DownloadActionType", + ActionTextResourceName = "FileDownloaded", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileDownloadedAs, new MessageMaps + { + ActionTypeTextResourceName = "DownloadActionType", + ActionTextResourceName = "FileDownloadedAs", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileUploaded, new MessageMaps + { + ActionTypeTextResourceName = "UploadActionType", + ActionTextResourceName = "FileUploaded", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileImported, new MessageMaps + { + ActionTypeTextResourceName = "ImportActionType", + ActionTextResourceName = "FileImported", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileCopied, new MessageMaps + { + ActionTypeTextResourceName = "CopyActionType", + ActionTextResourceName = "FileCopied", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileCopiedWithOverwriting, new MessageMaps + { + ActionTypeTextResourceName = "CopyActionType", + ActionTextResourceName = "FileCopiedWithOverwriting", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileMoved, new MessageMaps + { + ActionTypeTextResourceName = "MoveActionType", + ActionTextResourceName = "FileMoved", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileMovedWithOverwriting, new MessageMaps + { + ActionTypeTextResourceName = "MoveActionType", + ActionTextResourceName = "FileMovedWithOverwriting", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileMovedToTrash, new MessageMaps + { + ActionTypeTextResourceName = "MoveActionType", + ActionTextResourceName = "FileMovedToTrash", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileDeleted, new MessageMaps + { + ActionTypeTextResourceName = "DeleteActionType", + ActionTextResourceName = "FileDeleted", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FolderCreated, new MessageMaps + { + ActionTypeTextResourceName = "CreateActionType", + ActionTextResourceName = "FolderCreated", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FoldersModule" + } + }, + { + MessageAction.FolderRenamed, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "FolderRenamed", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FoldersModule" + } + }, + { + MessageAction.FolderUpdatedAccess, new MessageMaps + { + ActionTypeTextResourceName = "UpdateAccessActionType", + ActionTextResourceName = "FolderUpdatedAccess", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FoldersModule" + } + }, + { + MessageAction.FolderCopied, new MessageMaps + { + ActionTypeTextResourceName = "CopyActionType", + ActionTextResourceName = "FolderCopied", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FoldersModule" + } + }, + { + MessageAction.FolderCopiedWithOverwriting, new MessageMaps + { + ActionTypeTextResourceName = "CopyActionType", + ActionTextResourceName = "FolderCopiedWithOverwriting", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FoldersModule" + } + }, + { + MessageAction.FolderMoved, new MessageMaps + { + ActionTypeTextResourceName = "MoveActionType", + ActionTextResourceName = "FolderMoved", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FoldersModule" + } + }, + { + MessageAction.FolderMovedWithOverwriting, new MessageMaps + { + ActionTypeTextResourceName = "MoveActionType", + ActionTextResourceName = "FolderMovedWithOverwriting", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FoldersModule" + } + }, + { + MessageAction.FolderMovedToTrash, new MessageMaps + { + ActionTypeTextResourceName = "MoveActionType", + ActionTextResourceName = "FolderMovedToTrash", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FoldersModule" + } + }, + { + MessageAction.FolderDeleted, new MessageMaps + { + ActionTypeTextResourceName = "DeleteActionType", + ActionTextResourceName = "FolderDeleted", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FoldersModule" + } + }, + { + MessageAction.ThirdPartyCreated, new MessageMaps + { + ActionTypeTextResourceName = "CreateActionType", + ActionTextResourceName = "ThirdPartyCreated", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "DocumentsSettingsModule" + } + }, + { + MessageAction.ThirdPartyUpdated, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "ThirdPartyUpdated", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "DocumentsSettingsModule" + } + }, + { + MessageAction.ThirdPartyDeleted, new MessageMaps + { + ActionTypeTextResourceName = "DeleteActionType", + ActionTextResourceName = "ThirdPartyDeleted", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "DocumentsSettingsModule" + } + }, + { + MessageAction.DocumentsThirdPartySettingsUpdated, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "DocumentsThirdPartySettingsUpdated", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "DocumentsSettingsModule" + } + }, + { + MessageAction.DocumentsOverwritingSettingsUpdated, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "DocumentsOverwritingSettingsUpdated", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "DocumentsSettingsModule" + } + }, + { + MessageAction.DocumentsForcesave, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "DocumentsForcesave", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "DocumentsSettingsModule" + } + }, + { + MessageAction.DocumentsStoreForcesave, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "DocumentsStoreForcesave", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "DocumentsSettingsModule" + } + }, + { + MessageAction.DocumentsUploadingFormatsSettingsUpdated, new MessageMaps + { + ActionTypeTextResourceName = "UpdateActionType", + ActionTextResourceName = "DocumentsUploadingFormatsSettingsUpdated", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "DocumentsSettingsModule" + } + }, + { + MessageAction.FileConverted, new MessageMaps + { + ActionTypeTextResourceName = "CreateActionType", + ActionTextResourceName = "FileConverted", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileSendAccessLink, new MessageMaps + { + ActionTypeTextResourceName = "SendActionType", + ActionTextResourceName = "FileSendAccessLink", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.FileChangeOwner, new MessageMaps + { + ActionTypeTextResourceName = "SendActionType", + ActionTextResourceName = "FileChangeOwner", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.DocumentSignComplete, new MessageMaps + { + ActionTypeTextResourceName = "SendActionType", + ActionTextResourceName = "FilesDocumentSigned", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + }, + { + MessageAction.DocumentSendToSign, new MessageMaps + { + ActionTypeTextResourceName = "SendActionType", + ActionTextResourceName = "FilesRequestSign", + ProductResourceName = "DocumentsProduct", + ModuleResourceName = "FilesModule" + } + } }; } \ No newline at end of file From 37c1cd7d11c0052fdb72b38dbddd269c33a50795 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Fri, 11 Feb 2022 12:27:08 +0300 Subject: [PATCH 166/167] AuditTrail: removed Db prefix, added Dto ending --- .../ASC.Core.Common/EF/Context/AuditTrailContext.cs | 2 +- common/ASC.Core.Common/EF/Context/MessagesContext.cs | 4 ++-- .../Model/Audit/{DbAuditEvent.cs => AuditEvent.cs} | 6 +++--- .../Model/Audit/{DbLoginEvent.cs => LoginEvent.cs} | 6 +++--- .../DbSender/MessagesRepository.cs | 4 ++-- .../ASC.AuditTrail/Mappers/AuditActionMapper.cs | 10 +++++----- .../Models/{AuditEvent.cs => AuditEventDto.cs} | 6 +++--- .../ASC.AuditTrail/Models/AuditEventQuery.cs | 2 +- .../Models/{LoginEvent.cs => LoginEventDto.cs} | 6 +++--- .../ASC.AuditTrail/Models/LoginEventQuery.cs | 2 +- .../Models/Mappings/EventTypeConverter.cs | 12 ++++++------ .../Repositories/AuditEventsRepository.cs | 10 +++++----- .../Repositories/LoginEventsRepository.cs | 8 ++++---- 13 files changed, 39 insertions(+), 39 deletions(-) rename common/ASC.Core.Common/EF/Model/Audit/{DbAuditEvent.cs => AuditEvent.cs} (97%) rename common/ASC.Core.Common/EF/Model/Audit/{DbLoginEvent.cs => LoginEvent.cs} (96%) rename common/services/ASC.AuditTrail/Models/{AuditEvent.cs => AuditEventDto.cs} (91%) rename common/services/ASC.AuditTrail/Models/{LoginEvent.cs => LoginEventDto.cs} (90%) diff --git a/common/ASC.Core.Common/EF/Context/AuditTrailContext.cs b/common/ASC.Core.Common/EF/Context/AuditTrailContext.cs index 5fb1776c26..72f83381ff 100644 --- a/common/ASC.Core.Common/EF/Context/AuditTrailContext.cs +++ b/common/ASC.Core.Common/EF/Context/AuditTrailContext.cs @@ -4,7 +4,7 @@ public class PostgreSqlAuditTrailContext : AuditTrailContext { } public class AuditTrailContext : BaseDbContext { - public DbSet<DbAuditEvent> AuditEvents { get; set; } + public DbSet<AuditEvent> AuditEvents { get; set; } public DbSet<User> Users { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) diff --git a/common/ASC.Core.Common/EF/Context/MessagesContext.cs b/common/ASC.Core.Common/EF/Context/MessagesContext.cs index dcfb88fc8a..200cfcf56f 100644 --- a/common/ASC.Core.Common/EF/Context/MessagesContext.cs +++ b/common/ASC.Core.Common/EF/Context/MessagesContext.cs @@ -4,8 +4,8 @@ public class PostgreSqlMessagesContext : MessagesContext { } public class MessagesContext : BaseDbContext { - public DbSet<DbAuditEvent> AuditEvents { get; set; } - public DbSet<DbLoginEvent> LoginEvents { get; set; } + public DbSet<AuditEvent> AuditEvents { get; set; } + public DbSet<LoginEvent> LoginEvents { get; set; } public DbSet<User> Users { get; set; } protected override Dictionary<Provider, Func<BaseDbContext>> ProviderContext diff --git a/common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs b/common/ASC.Core.Common/EF/Model/Audit/AuditEvent.cs similarity index 97% rename from common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs rename to common/ASC.Core.Common/EF/Model/Audit/AuditEvent.cs index 3075f4a3c9..a2d237b7d3 100644 --- a/common/ASC.Core.Common/EF/Model/Audit/DbAuditEvent.cs +++ b/common/ASC.Core.Common/EF/Model/Audit/AuditEvent.cs @@ -1,6 +1,6 @@ namespace ASC.Core.Common.EF.Model { - public class DbAuditEvent : MessageEvent + public class AuditEvent : MessageEvent { public string Initiator { get; set; } public string Target { get; set; } @@ -16,7 +16,7 @@ } public static void MySqlAddAuditEvent(this ModelBuilder modelBuilder) { - modelBuilder.Entity<DbAuditEvent>(entity => + modelBuilder.Entity<AuditEvent>(entity => { entity.ToTable("audit_events"); @@ -87,7 +87,7 @@ } public static void PgSqlAddAuditEvent(this ModelBuilder modelBuilder) { - modelBuilder.Entity<DbAuditEvent>(entity => + modelBuilder.Entity<AuditEvent>(entity => { entity.ToTable("audit_events", "onlyoffice"); diff --git a/common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs b/common/ASC.Core.Common/EF/Model/Audit/LoginEvent.cs similarity index 96% rename from common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs rename to common/ASC.Core.Common/EF/Model/Audit/LoginEvent.cs index 33de6b9ec8..03246beb95 100644 --- a/common/ASC.Core.Common/EF/Model/Audit/DbLoginEvent.cs +++ b/common/ASC.Core.Common/EF/Model/Audit/LoginEvent.cs @@ -1,6 +1,6 @@ namespace ASC.Core.Common.EF.Model { - public class DbLoginEvent : MessageEvent + public class LoginEvent : MessageEvent { public string Login { get; set; } } @@ -16,7 +16,7 @@ } public static void MySqlAddLoginEvents(this ModelBuilder modelBuilder) { - modelBuilder.Entity<DbLoginEvent>(entity => + modelBuilder.Entity<LoginEvent>(entity => { entity.ToTable("login_events"); @@ -82,7 +82,7 @@ } public static void PgSqlAddLoginEvents(this ModelBuilder modelBuilder) { - modelBuilder.Entity<DbLoginEvent>(entity => + modelBuilder.Entity<LoginEvent>(entity => { entity.ToTable("login_events", "onlyoffice"); diff --git a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs index bcebdf480b..a6df1abe93 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -149,7 +149,7 @@ namespace ASC.MessagingSystem.DbSender private static void AddLoginEvent(EventMessage message, MessagesContext dbContext) { - var le = new DbLoginEvent + var le = new LoginEvent { Ip = message.IP, Login = message.Initiator, @@ -177,7 +177,7 @@ namespace ASC.MessagingSystem.DbSender private static void AddAuditEvent(EventMessage message, Messages dbContext) { - var ae = new DbAuditEvent + var ae = new AuditEvent { Ip = message.IP, Initiator = message.Initiator, diff --git a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs index a71f696ded..8e0fc425a9 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -47,7 +47,7 @@ public class AuditActionMapper .ToDictionary(x => x.Key, x => x.Value); } - public string GetActionText(AuditEvent evt) + public string GetActionText(AuditEventDto evt) { var action = (MessageAction)evt.Action; if (!_actions.ContainsKey(action)) @@ -77,7 +77,7 @@ public class AuditActionMapper } } - public string GetActionText(LoginEvent evt) + public string GetActionText(LoginEventDto evt) { var action = (MessageAction)evt.Action; if (!_actions.ContainsKey(action)) @@ -105,7 +105,7 @@ public class AuditActionMapper } } - public string GetActionTypeText(AuditEvent evt) + public string GetActionTypeText(AuditEventDto evt) { var action = (MessageAction)evt.Action; @@ -114,7 +114,7 @@ public class AuditActionMapper : _actions[(MessageAction)evt.Action].GetActionTypeText(); } - public string GetProductText(AuditEvent evt) + public string GetProductText(AuditEventDto evt) { var action = (MessageAction)evt.Action; @@ -123,7 +123,7 @@ public class AuditActionMapper : _actions[(MessageAction)evt.Action].GetProduct(); } - public string GetModuleText(AuditEvent evt) + public string GetModuleText(AuditEventDto evt) { var action = (MessageAction)evt.Action; diff --git a/common/services/ASC.AuditTrail/Models/AuditEvent.cs b/common/services/ASC.AuditTrail/Models/AuditEventDto.cs similarity index 91% rename from common/services/ASC.AuditTrail/Models/AuditEvent.cs rename to common/services/ASC.AuditTrail/Models/AuditEventDto.cs index ef0c460261..37f337d24a 100644 --- a/common/services/ASC.AuditTrail/Models/AuditEvent.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEventDto.cs @@ -25,7 +25,7 @@ namespace ASC.AuditTrail.Models; -public class AuditEvent : BaseEvent, IMapFrom<AuditEventQuery> +public class AuditEventDto : BaseEvent, IMapFrom<AuditEventQuery> { public string Initiator { get; set; } @@ -46,9 +46,9 @@ public class AuditEvent : BaseEvent, IMapFrom<AuditEventQuery> public void Mapping(Profile profile) { - profile.CreateMap<DbAuditEvent, AuditEvent>(); + profile.CreateMap<AuditEvent, AuditEventDto>(); - profile.CreateMap<AuditEventQuery, AuditEvent>() + profile.CreateMap<AuditEventQuery, AuditEventDto>() .ConvertUsing<EventTypeConverter>(); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs b/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs index 9ca296a7d1..a5949af98f 100644 --- a/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs +++ b/common/services/ASC.AuditTrail/Models/AuditEventQuery.cs @@ -2,7 +2,7 @@ public class AuditEventQuery { - public DbAuditEvent Event { get; set; } + public AuditEvent Event { get; set; } public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } diff --git a/common/services/ASC.AuditTrail/Models/LoginEvent.cs b/common/services/ASC.AuditTrail/Models/LoginEventDto.cs similarity index 90% rename from common/services/ASC.AuditTrail/Models/LoginEvent.cs rename to common/services/ASC.AuditTrail/Models/LoginEventDto.cs index bf2de24e20..501eddd858 100644 --- a/common/services/ASC.AuditTrail/Models/LoginEvent.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEventDto.cs @@ -25,16 +25,16 @@ namespace ASC.AuditTrail.Models; -public class LoginEvent : BaseEvent, IMapFrom<LoginEventQuery> +public class LoginEventDto : BaseEvent, IMapFrom<LoginEventQuery> { public string Login { get; set; } public int Action { get; set; } public void Mapping(Profile profile) { - profile.CreateMap<DbLoginEvent, LoginEvent>(); + profile.CreateMap<LoginEvent, LoginEventDto>(); - profile.CreateMap<LoginEventQuery, LoginEvent>() + profile.CreateMap<LoginEventQuery, LoginEventDto>() .ConvertUsing<EventTypeConverter>(); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs b/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs index e68d511581..8cb4760fbc 100644 --- a/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs +++ b/common/services/ASC.AuditTrail/Models/LoginEventQuery.cs @@ -2,7 +2,7 @@ public class LoginEventQuery { - public DbLoginEvent Event { get; set; } + public LoginEvent Event { get; set; } public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } diff --git a/common/services/ASC.AuditTrail/Models/Mappings/EventTypeConverter.cs b/common/services/ASC.AuditTrail/Models/Mappings/EventTypeConverter.cs index 58af3287a7..aa966f0ce7 100644 --- a/common/services/ASC.AuditTrail/Models/Mappings/EventTypeConverter.cs +++ b/common/services/ASC.AuditTrail/Models/Mappings/EventTypeConverter.cs @@ -1,7 +1,7 @@ namespace ASC.AuditTrail.Models.Mappings; -public class EventTypeConverter : ITypeConverter<LoginEventQuery, LoginEvent>, - ITypeConverter<AuditEventQuery, AuditEvent> +public class EventTypeConverter : ITypeConverter<LoginEventQuery, LoginEventDto>, + ITypeConverter<AuditEventQuery, AuditEventDto> { private readonly UserFormatter _userFormatter; private readonly AuditActionMapper _auditActionMapper; @@ -17,9 +17,9 @@ public class EventTypeConverter : ITypeConverter<LoginEventQuery, LoginEvent>, _messageTarget = messageTarget; } - public LoginEvent Convert(LoginEventQuery source, LoginEvent destination, ResolutionContext context) + public LoginEventDto Convert(LoginEventQuery source, LoginEventDto destination, ResolutionContext context) { - var result = context.Mapper.Map<LoginEvent>(source.Event); + var result = context.Mapper.Map<LoginEventDto>(source.Event); if (source.Event.DescriptionRaw != null) { @@ -43,9 +43,9 @@ public class EventTypeConverter : ITypeConverter<LoginEventQuery, LoginEvent>, return result; } - public AuditEvent Convert(AuditEventQuery source, AuditEvent destination, ResolutionContext context) + public AuditEventDto Convert(AuditEventQuery source, AuditEventDto destination, ResolutionContext context) { - var result = context.Mapper.Map<AuditEvent>(source.Event); + var result = context.Mapper.Map<AuditEventDto>(source.Event); if (source.Event.DescriptionRaw != null) { diff --git a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs index 96ab6f83ad..185d2771cf 100644 --- a/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/AuditEventsRepository.cs @@ -41,19 +41,19 @@ public class AuditEventsRepository _mapper = mapper; } - public IEnumerable<AuditEvent> GetLast(int tenant, int chunk) + public IEnumerable<AuditEventDto> GetLast(int tenant, int chunk) { return Get(tenant, null, null, chunk); } - public IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) + public IEnumerable<AuditEventDto> Get(int tenant, DateTime from, DateTime to) { return Get(tenant, from, to, null); } public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) { - IQueryable<DbAuditEvent> query = AuditTrailContext.AuditEvents + IQueryable<AuditEvent> query = AuditTrailContext.AuditEvents .Where(a => a.TenantId == tenant) .OrderByDescending(a => a.Date); @@ -65,7 +65,7 @@ public class AuditEventsRepository return query.Count(); } - private IEnumerable<AuditEvent> Get(int tenant, DateTime? fromDate, DateTime? to, int? limit) + private IEnumerable<AuditEventDto> Get(int tenant, DateTime? fromDate, DateTime? to, int? limit) { var query = from q in AuditTrailContext.AuditEvents @@ -90,6 +90,6 @@ public class AuditEventsRepository query = query.Take((int)limit); } - return _mapper.Map<List<AuditEventQuery>, IEnumerable<AuditEvent>>(query.ToList()); + return _mapper.Map<List<AuditEventQuery>, IEnumerable<AuditEventDto>>(query.ToList()); } } \ No newline at end of file diff --git a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs index eae0e1667d..9b7e1622b0 100644 --- a/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/Repositories/LoginEventsRepository.cs @@ -41,7 +41,7 @@ public class LoginEventsRepository _mapper = mapper; } - public IEnumerable<LoginEvent> GetLast(int tenant, int chunk) + public IEnumerable<LoginEventDto> GetLast(int tenant, int chunk) { var query = (from b in MessagesContext.LoginEvents @@ -57,10 +57,10 @@ public class LoginEventsRepository }) .Take(chunk); - return _mapper.Map<List<LoginEventQuery>, IEnumerable<LoginEvent>>(query.ToList()); + return _mapper.Map<List<LoginEventQuery>, IEnumerable<LoginEventDto>>(query.ToList()); } - public IEnumerable<LoginEvent> Get(int tenant, DateTime fromDate, DateTime to) + public IEnumerable<LoginEventDto> Get(int tenant, DateTime fromDate, DateTime to) { var query = from q in MessagesContext.LoginEvents @@ -77,7 +77,7 @@ public class LoginEventsRepository LastName = p.LastName }; - return _mapper.Map<List<LoginEventQuery>, IEnumerable<LoginEvent>>(query.ToList()); + return _mapper.Map<List<LoginEventQuery>, IEnumerable<LoginEventDto>>(query.ToList()); } public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) From 8288f3c4cac0cc0e2a8b7a0355fe2279998d69a9 Mon Sep 17 00:00:00 2001 From: MaksimChegulov <maksim.chegulov@onlyoffice.com> Date: Mon, 14 Feb 2022 12:05:05 +0300 Subject: [PATCH 167/167] Common: return IEventBust to ICacheNotify --- common/ASC.Api.Core/Core/BaseStartup.cs | 6 +-- common/ASC.Common/Caching/AscCache.cs | 10 ++-- .../{EventType.cs => CacheNotifyAction.cs} | 2 +- .../ASC.Common/Caching/EventBusMemoryCache.cs | 39 --------------- .../Caching/{IEventBus.cs => ICacheNotify.cs} | 8 ++-- .../{EventBusKafka.cs => KafkaCacheNotify.cs} | 22 ++++----- .../ASC.Common/Caching/MemoryCacheNotify.cs | 39 +++++++++++++++ .../{EventBusRedis.cs => RedisCacheNotify.cs} | 16 +++---- .../Threading/DistributedTaskQueue.cs | 30 ++++++------ .../ASC.Core.Common/Billing/TariffService.cs | 10 ++-- .../Caching/CachedAzService.cs | 14 +++--- .../Caching/CachedQuotaService.cs | 12 ++--- .../Caching/CachedSubscriptionService.cs | 24 +++++----- .../Caching/CachedTenantService.cs | 22 ++++----- .../Caching/CachedUserService.cs | 48 +++++++++---------- .../ASC.Core.Common/Configuration/Consumer.cs | 16 +++---- common/ASC.Core.Common/Context/WorkContext.cs | 4 +- .../ASC.Core.Common/Data/DbSettingsManager.cs | 8 ++-- .../Notify/NotifyServiceClient.cs | 12 ++--- .../Notify/Senders/NotifyServiceSender.cs | 2 +- .../Notify/Telegram/TelegramServiceClient.cs | 24 +++++----- .../Service/BackupWorker.cs | 4 +- .../Configuration/StorageSettings.cs | 14 +++--- .../Encryption/EncryptionServiceClient.cs | 12 ++--- .../Migration/MigrateServiceClient.cs | 20 ++++---- common/ASC.Data.Storage/StorageUploader.cs | 10 ++-- common/ASC.FederatedLogin/AccountLinker.cs | 8 ++-- .../LoginProviders/BaseLoginProvider.cs | 2 +- .../LoginProviders/BitlyLoginProvider.cs | 2 +- .../LoginProviders/BoxLoginProvider.cs | 2 +- .../LoginProviders/DocuSignLoginProvider.cs | 2 +- .../LoginProviders/DropboxLoginProvider.cs | 2 +- .../LoginProviders/FacebookLoginProvider.cs | 2 +- .../LoginProviders/GoogleLoginProvider.cs | 2 +- .../LoginProviders/GosUslugiLoginProvider.cs | 2 +- .../LoginProviders/LinkedInLoginProvider.cs | 2 +- .../LoginProviders/MailRuLoginProvider.cs | 2 +- .../LoginProviders/OneDriveLoginProvider.cs | 2 +- .../LoginProviders/TelegramLoginProvider.cs | 2 +- .../LoginProviders/VKLoginProvider.cs | 2 +- .../LoginProviders/WordpressLoginProvider.cs | 2 +- .../LoginProviders/YahooLoginProvider.cs | 2 +- .../LoginProviders/YandexLoginProvider.cs | 2 +- .../ASC.IPSecurity/IPRestrictionsService.cs | 10 ++-- common/ASC.VoipService/Dao/CachedVoipDao.cs | 8 ++-- common/ASC.Webhooks.Core/WebhookPublisher.cs | 6 +-- common/services/ASC.ClearEvents/Program.cs | 6 +-- .../Services/BackupListenerService.cs | 8 ++-- .../ASC.ElasticSearch/Core/SearchSettings.cs | 6 +-- .../ASC.ElasticSearch/Engine/BaseIndexer.cs | 8 ++-- .../Engine/FactoryIndexer.cs | 4 +- .../ASC.ElasticSearch/Service/Launcher.cs | 14 +++--- .../ASC.ElasticSearch/Service/Service.cs | 6 +-- common/services/ASC.Notify/NotifyService.cs | 16 +++---- common/services/ASC.Notify/Program.cs | 6 +-- common/services/ASC.Studio.Notify/Program.cs | 6 +-- .../ASC.TelegramService/TelegramListener.cs | 32 ++++++------- .../ASC.Webhooks.Service/BuildQueueService.cs | 8 ++-- .../services/ASC.Webhooks.Service/Program.cs | 6 +-- .../ASC.Files/Core/Core/FileStorageService.cs | 6 +-- .../Core/Thirdparty/Box/BoxProviderInfo.cs | 12 ++--- .../Thirdparty/Dropbox/DropboxProviderInfo.cs | 12 ++--- .../GoogleDrive/GoogleDriveProviderInfo.cs | 14 +++--- .../OneDrive/OneDriveProviderInfo.cs | 10 ++-- .../SharePoint/SharePointProviderInfo.cs | 12 ++--- .../ASC.Files/Core/Helpers/EasyBibHelper.cs | 2 +- products/ASC.Files/Core/Helpers/Global.cs | 6 +-- .../ASC.Files/Core/ThirdPartyApp/BoxApp.cs | 2 +- .../Core/ThirdPartyApp/GoogleDriveApp.cs | 2 +- products/ASC.Files/Service/Program.cs | 6 +-- .../ASC.Files/Service/Thumbnail/Service.cs | 8 ++-- .../Controllers/SettingsController.cs | 6 +-- web/ASC.Web.Core/Jabber/FireBase.cs | 2 +- web/ASC.Web.Core/Mail/MailServiceHelper.cs | 8 ++-- .../Notify/StudioNotifyServiceHelper.cs | 6 +-- .../Notify/StudioNotifyServiceSender.cs | 4 +- web/ASC.Web.Core/Sms/SmsKeyStorage.cs | 8 ++-- web/ASC.Web.Core/Sms/SmsProvider.cs | 12 ++--- web/ASC.Web.Core/Users/UserPhotoManager.cs | 12 ++--- web/ASC.Web.Core/WebItemSecurity.cs | 8 ++-- .../WhiteLabel/TenantLogoManager.cs | 6 +-- 81 files changed, 391 insertions(+), 391 deletions(-) rename common/ASC.Common/Caching/{EventType.cs => CacheNotifyAction.cs} (98%) delete mode 100644 common/ASC.Common/Caching/EventBusMemoryCache.cs rename common/ASC.Common/Caching/{IEventBus.cs => ICacheNotify.cs} (87%) rename common/ASC.Common/Caching/{EventBusKafka.cs => KafkaCacheNotify.cs} (88%) create mode 100644 common/ASC.Common/Caching/MemoryCacheNotify.cs rename common/ASC.Common/Caching/{EventBusRedis.cs => RedisCacheNotify.cs} (75%) diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index 0e07d73608..864bd13b99 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -76,17 +76,17 @@ public abstract class BaseStartup if (kafkaConfiguration != null) { - DIHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); + DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCacheNotify<>)); } else if (redisConfiguration != null) { - DIHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); + DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCacheNotify<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - DIHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); + DIHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); } DIHelper.TryAdd(typeof(IWebhookPublisher), typeof(WebhookPublisher)); diff --git a/common/ASC.Common/Caching/AscCache.cs b/common/ASC.Common/Caching/AscCache.cs index 2641b6a643..5542d98d70 100644 --- a/common/ASC.Common/Caching/AscCache.cs +++ b/common/ASC.Common/Caching/AscCache.cs @@ -28,16 +28,16 @@ namespace ASC.Common.Caching; [Singletone] public class AscCacheNotify { - private readonly IEventBus<AscCacheItem> _eventBus; + private readonly ICacheNotify<AscCacheItem> _cacheNotify; - public AscCacheNotify(IEventBus<AscCacheItem> eventBus) + public AscCacheNotify(ICacheNotify<AscCacheItem> cacheNotify) { - _eventBus = eventBus; + _cacheNotify = cacheNotify; - _eventBus.Subscribe((item) => { OnClearCache(); }, EventType.Any); + _cacheNotify.Subscribe((item) => { OnClearCache(); }, CacheNotifyAction.Any); } - public void ClearCache() => _eventBus.Publish(new AscCacheItem { Id = Guid.NewGuid().ToString() }, EventType.Any); + public void ClearCache() => _cacheNotify.Publish(new AscCacheItem { Id = Guid.NewGuid().ToString() }, CacheNotifyAction.Any); public static void OnClearCache() { diff --git a/common/ASC.Common/Caching/EventType.cs b/common/ASC.Common/Caching/CacheNotifyAction.cs similarity index 98% rename from common/ASC.Common/Caching/EventType.cs rename to common/ASC.Common/Caching/CacheNotifyAction.cs index 1c0134f723..ea9303960a 100644 --- a/common/ASC.Common/Caching/EventType.cs +++ b/common/ASC.Common/Caching/CacheNotifyAction.cs @@ -26,7 +26,7 @@ namespace ASC.Common.Caching; [Flags] -public enum EventType +public enum CacheNotifyAction { Insert = 1, Update = 2, diff --git a/common/ASC.Common/Caching/EventBusMemoryCache.cs b/common/ASC.Common/Caching/EventBusMemoryCache.cs deleted file mode 100644 index ae664b0a39..0000000000 --- a/common/ASC.Common/Caching/EventBusMemoryCache.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace ASC.Common.Caching; - -[Singletone] -public class EventBusMemoryCache<T> : IEventBus<T> where T : IMessage<T>, new() -{ - private readonly ConcurrentDictionary<string, List<Action<T>>> _actions; - - public EventBusMemoryCache() - { - _actions = new ConcurrentDictionary<string, List<Action<T>>>(); - } - - public void Publish(T obj, EventType action) - { - if (_actions.TryGetValue(GetKey(action), out var onchange) && onchange != null) - { - Parallel.ForEach(onchange, a => a(obj)); - } - } - - public void Subscribe(Action<T> onchange, EventType notifyAction) - { - if (onchange != null) - { - _actions.GetOrAdd(GetKey(notifyAction), new List<Action<T>>()) - .Add(onchange); - } - } - - public void Unsubscribe(EventType action) - { - _actions.TryRemove(GetKey(action), out _); - } - - private string GetKey(EventType cacheNotifyAction) - { - return $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); - } -} \ No newline at end of file diff --git a/common/ASC.Common/Caching/IEventBus.cs b/common/ASC.Common/Caching/ICacheNotify.cs similarity index 87% rename from common/ASC.Common/Caching/IEventBus.cs rename to common/ASC.Common/Caching/ICacheNotify.cs index 25e61b703d..90e6214d5d 100644 --- a/common/ASC.Common/Caching/IEventBus.cs +++ b/common/ASC.Common/Caching/ICacheNotify.cs @@ -26,11 +26,11 @@ namespace ASC.Common.Caching; [Singletone] -public interface IEventBus<T> where T : IMessage<T>, new() +public interface ICacheNotify<T> where T : IMessage<T>, new() { - void Publish(T obj, EventType action); + void Publish(T obj, CacheNotifyAction action); - void Subscribe(Action<T> onchange, EventType action); + void Subscribe(Action<T> onchange, CacheNotifyAction action); - void Unsubscribe(EventType action); + void Unsubscribe(CacheNotifyAction action); } \ No newline at end of file diff --git a/common/ASC.Common/Caching/EventBusKafka.cs b/common/ASC.Common/Caching/KafkaCacheNotify.cs similarity index 88% rename from common/ASC.Common/Caching/EventBusKafka.cs rename to common/ASC.Common/Caching/KafkaCacheNotify.cs index c6724b1987..75556c5994 100644 --- a/common/ASC.Common/Caching/EventBusKafka.cs +++ b/common/ASC.Common/Caching/KafkaCacheNotify.cs @@ -1,7 +1,7 @@ namespace ASC.Common.Caching; [Singletone] -public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, new() +public class KafkaCacheNotify<T> : IDisposable, ICacheNotify<T> where T : IMessage<T>, new() { private IProducer<AscCacheItem, T> _producer; @@ -17,7 +17,7 @@ public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, private readonly ProtobufDeserializer<AscCacheItem> _keyDeserializer = new ProtobufDeserializer<AscCacheItem>(); private readonly Guid _key; - public EventBusKafka(ConfigurationExtension configuration, IOptionsMonitor<ILog> options) + public KafkaCacheNotify(ConfigurationExtension configuration, IOptionsMonitor<ILog> options) { _logger = options.CurrentValue; _cancelationToken = new ConcurrentDictionary<string, CancellationTokenSource>(); @@ -30,7 +30,7 @@ public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, _adminClientConfig = new AdminClientConfig { BootstrapServers = settings.BootstrapServers }; } - public void Publish(T obj, EventType eventType) + public void Publish(T obj, CacheNotifyAction notifyAction) { try { @@ -43,7 +43,7 @@ public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, .Build(); } - var channelName = GetChannelName(eventType); + var channelName = GetChannelName(notifyAction); if (_actions.TryGetValue(channelName, out var onchange)) { @@ -71,9 +71,9 @@ public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, } } - public void Subscribe(Action<T> onchange, EventType eventType) + public void Subscribe(Action<T> onchange, CacheNotifyAction notifyAction) { - var channelName = GetChannelName(eventType); + var channelName = GetChannelName(notifyAction); _cancelationToken[channelName] = new CancellationTokenSource(); _actions[channelName] = onchange; @@ -150,9 +150,9 @@ public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, task.Start(); } - public void Unsubscribe(EventType eventType) + public void Unsubscribe(CacheNotifyAction notifyAction) { - _cancelationToken.TryGetValue(GetChannelName(eventType), out var source); + _cancelationToken.TryGetValue(GetChannelName(notifyAction), out var source); if (source != null) { @@ -179,14 +179,14 @@ public class EventBusKafka<T> : IDisposable, IEventBus<T> where T : IMessage<T>, } } - ~EventBusKafka() + ~KafkaCacheNotify() { Dispose(false); } - private string GetChannelName(EventType eventType) + private string GetChannelName(CacheNotifyAction notifyAction) { - return $"ascchannel{eventType}{typeof(T).FullName}".ToLower(); + return $"ascchannel{notifyAction}{typeof(T).FullName}".ToLower(); } } diff --git a/common/ASC.Common/Caching/MemoryCacheNotify.cs b/common/ASC.Common/Caching/MemoryCacheNotify.cs new file mode 100644 index 0000000000..222b072ca7 --- /dev/null +++ b/common/ASC.Common/Caching/MemoryCacheNotify.cs @@ -0,0 +1,39 @@ +namespace ASC.Common.Caching; + +[Singletone] +public class MemoryCacheNotify<T> : ICacheNotify<T> where T : IMessage<T>, new() +{ + private readonly ConcurrentDictionary<string, List<Action<T>>> _actions; + + public MemoryCacheNotify() + { + _actions = new ConcurrentDictionary<string, List<Action<T>>>(); + } + + public void Publish(T obj, CacheNotifyAction notifyAction) + { + if (_actions.TryGetValue(GetKey(notifyAction), out var onchange) && onchange != null) + { + Parallel.ForEach(onchange, a => a(obj)); + } + } + + public void Subscribe(Action<T> onchange, CacheNotifyAction notifyAction) + { + if (onchange != null) + { + _actions.GetOrAdd(GetKey(notifyAction), new List<Action<T>>()) + .Add(onchange); + } + } + + public void Unsubscribe(CacheNotifyAction notifyAction) + { + _actions.TryRemove(GetKey(notifyAction), out _); + } + + private string GetKey(CacheNotifyAction notifyAction) + { + return $"asc:channel:{notifyAction}:{typeof(T).FullName}".ToLower(); + } +} \ No newline at end of file diff --git a/common/ASC.Common/Caching/EventBusRedis.cs b/common/ASC.Common/Caching/RedisCacheNotify.cs similarity index 75% rename from common/ASC.Common/Caching/EventBusRedis.cs rename to common/ASC.Common/Caching/RedisCacheNotify.cs index 6cda191cb5..3a12998f16 100644 --- a/common/ASC.Common/Caching/EventBusRedis.cs +++ b/common/ASC.Common/Caching/RedisCacheNotify.cs @@ -17,23 +17,23 @@ namespace ASC.Common.Caching; [Singletone] -public class EventBusRedis<T> : IEventBus<T> where T : IMessage<T>, new() +public class RedisCacheNotify<T> : ICacheNotify<T> where T : IMessage<T>, new() { private readonly IRedisDatabase _redis; - public EventBusRedis(IRedisCacheClient redisCacheClient) + public RedisCacheNotify(IRedisCacheClient redisCacheClient) { _redis = redisCacheClient.GetDbFromConfiguration(); } - public void Publish(T obj, EventType action) + public void Publish(T obj, CacheNotifyAction action) { Task.Run(() => _redis.PublishAsync(GetChannelName(action), new RedisCachePubSubItem<T>() { Object = obj, Action = action })) .GetAwaiter() .GetResult(); } - public void Subscribe(Action<T> onchange, EventType action) + public void Subscribe(Action<T> onchange, CacheNotifyAction action) { Task.Run(() => _redis.SubscribeAsync<RedisCachePubSubItem<T>>(GetChannelName(action), (i) => { @@ -44,7 +44,7 @@ public class EventBusRedis<T> : IEventBus<T> where T : IMessage<T>, new() .GetResult(); } - public void Unsubscribe(EventType action) + public void Unsubscribe(CacheNotifyAction action) { Task.Run(() => _redis.UnsubscribeAsync<RedisCachePubSubItem<T>>(GetChannelName(action), (i) => { @@ -53,15 +53,15 @@ public class EventBusRedis<T> : IEventBus<T> where T : IMessage<T>, new() .GetResult(); } - private string GetChannelName(EventType cacheNotifyAction) + private string GetChannelName(CacheNotifyAction action) { - return $"asc:channel:{cacheNotifyAction}:{typeof(T).FullName}".ToLower(); + return $"asc:channel:{action}:{typeof(T).FullName}".ToLower(); } class RedisCachePubSubItem<T0> { public T0 Object { get; set; } - public EventType Action { get; set; } + public CacheNotifyAction Action { get; set; } } } \ No newline at end of file diff --git a/common/ASC.Common/Threading/DistributedTaskQueue.cs b/common/ASC.Common/Threading/DistributedTaskQueue.cs index 53329e3a0d..7a70b7638e 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -31,54 +31,54 @@ public class DistributedTaskCacheNotify public ConcurrentDictionary<string, CancellationTokenSource> Cancelations { get; } public ICache Cache { get; } - private readonly IEventBus<DistributedTaskCancelation> _eventBusNotify; - private readonly IEventBus<DistributedTaskCache> _eventBusCache; + private readonly ICacheNotify<DistributedTaskCancelation> _cancelTaskNotify; + private readonly ICacheNotify<DistributedTaskCache> _taskCacheNotify; public DistributedTaskCacheNotify( - IEventBus<DistributedTaskCancelation> eventBusNotify, - IEventBus<DistributedTaskCache> eventBusCache, + ICacheNotify<DistributedTaskCancelation> cancelTaskNotify, + ICacheNotify<DistributedTaskCache> taskCacheNotify, ICache cache) { Cancelations = new ConcurrentDictionary<string, CancellationTokenSource>(); Cache = cache; - _eventBusNotify = eventBusNotify; + _cancelTaskNotify = cancelTaskNotify; - eventBusNotify.Subscribe((c) => + cancelTaskNotify.Subscribe((c) => { if (Cancelations.TryGetValue(c.Id, out var s)) { s.Cancel(); } - }, EventType.Remove); + }, CacheNotifyAction.Remove); - _eventBusCache = eventBusCache; + _taskCacheNotify = taskCacheNotify; - eventBusCache.Subscribe((c) => + taskCacheNotify.Subscribe((c) => { Cache.HashSet(c.Key, c.Id, (DistributedTaskCache)null); - }, EventType.Remove); + }, CacheNotifyAction.Remove); - eventBusCache.Subscribe((c) => + taskCacheNotify.Subscribe((c) => { Cache.HashSet(c.Key, c.Id, c); - }, EventType.InsertOrUpdate); + }, CacheNotifyAction.InsertOrUpdate); } public void CancelTask(string id) { - _eventBusNotify.Publish(new DistributedTaskCancelation() { Id = id }, EventType.Remove); + _cancelTaskNotify.Publish(new DistributedTaskCancelation() { Id = id }, CacheNotifyAction.Remove); } public void SetTask(DistributedTask task) { - _eventBusCache.Publish(task.DistributedTaskCache, EventType.InsertOrUpdate); + _taskCacheNotify.Publish(task.DistributedTaskCache, CacheNotifyAction.InsertOrUpdate); } public void RemoveTask(string id, string key) { - _eventBusCache.Publish(new DistributedTaskCache() { Id = id, Key = key }, EventType.Remove); + _taskCacheNotify.Publish(new DistributedTaskCache() { Id = id, Key = key }, CacheNotifyAction.Remove); } } diff --git a/common/ASC.Core.Common/Billing/TariffService.cs b/common/ASC.Core.Common/Billing/TariffService.cs index 92fcfd1e5a..abecf124df 100644 --- a/common/ASC.Core.Common/Billing/TariffService.cs +++ b/common/ASC.Core.Common/Billing/TariffService.cs @@ -29,9 +29,9 @@ namespace ASC.Core.Billing public class TariffServiceStorage { public ICache Cache { get; } - internal IEventBus<TariffCacheItem> Notify { get; } + internal ICacheNotify<TariffCacheItem> Notify { get; } - public TariffServiceStorage(IEventBus<TariffCacheItem> notify, ICache cache) + public TariffServiceStorage(ICacheNotify<TariffCacheItem> notify, ICache cache) { Cache = cache; Notify = notify; @@ -40,7 +40,7 @@ namespace ASC.Core.Billing Cache.Remove(TariffService.GetTariffCacheKey(i.TenantId)); Cache.Remove(TariffService.GetBillingUrlCacheKey(i.TenantId)); Cache.Remove(TariffService.GetBillingPaymentCacheKey(i.TenantId)); // clear all payments - }, ASC.Common.Caching.EventType.Remove); + }, ASC.Common.Caching.CacheNotifyAction.Remove); //TODO: Change code of WCF -> not supported in .NET standard/.Net Core /*try @@ -126,7 +126,7 @@ namespace ASC.Core.Billing private static readonly TimeSpan STANDALONE_CACHE_EXPIRATION = TimeSpan.FromMinutes(15); internal ICache Cache { get; set; } - internal IEventBus<TariffCacheItem> Notify { get; set; } + internal ICacheNotify<TariffCacheItem> Notify { get; set; } internal ILog Log { get; set; } internal IQuotaService QuotaService { get; set; } internal ITenantService TenantService { get; set; } @@ -297,7 +297,7 @@ namespace ASC.Core.Billing public void ClearCache(int tenantId) { - Notify.Publish(new TariffCacheItem { TenantId = tenantId }, ASC.Common.Caching.EventType.Remove); + Notify.Publish(new TariffCacheItem { TenantId = tenantId }, ASC.Common.Caching.CacheNotifyAction.Remove); } public IEnumerable<PaymentInfo> GetPayments(int tenantId) diff --git a/common/ASC.Core.Common/Caching/CachedAzService.cs b/common/ASC.Core.Common/Caching/CachedAzService.cs index 7bb63c80bd..48fb5d14bd 100644 --- a/common/ASC.Core.Common/Caching/CachedAzService.cs +++ b/common/ASC.Core.Common/Caching/CachedAzService.cs @@ -29,15 +29,15 @@ namespace ASC.Core.Caching class AzServiceCache { internal ICache Cache { get; } - internal IEventBus<AzRecordCache> CacheNotify { get; } + internal ICacheNotify<AzRecordCache> CacheNotify { get; } - public AzServiceCache(IEventBus<AzRecordCache> cacheNotify, ICache cache) + public AzServiceCache(ICacheNotify<AzRecordCache> cacheNotify, ICache cache) { CacheNotify = cacheNotify; Cache = cache; - cacheNotify.Subscribe((r) => UpdateCache(r, true), ASC.Common.Caching.EventType.Remove); - cacheNotify.Subscribe((r) => UpdateCache(r, false), ASC.Common.Caching.EventType.InsertOrUpdate); + cacheNotify.Subscribe((r) => UpdateCache(r, true), ASC.Common.Caching.CacheNotifyAction.Remove); + cacheNotify.Subscribe((r) => UpdateCache(r, false), ASC.Common.Caching.CacheNotifyAction.InsertOrUpdate); } private void UpdateCache(AzRecord r, bool remove) @@ -70,7 +70,7 @@ namespace ASC.Core.Caching { private readonly IAzService service; - private readonly IEventBus<AzRecordCache> cacheNotify; + private readonly ICacheNotify<AzRecordCache> cacheNotify; private ICache Cache { get; } @@ -102,14 +102,14 @@ namespace ASC.Core.Caching public AzRecord SaveAce(int tenant, AzRecord r) { r = service.SaveAce(tenant, r); - cacheNotify.Publish(r, ASC.Common.Caching.EventType.InsertOrUpdate); + cacheNotify.Publish(r, ASC.Common.Caching.CacheNotifyAction.InsertOrUpdate); return r; } public void RemoveAce(int tenant, AzRecord r) { service.RemoveAce(tenant, r); - cacheNotify.Publish(r, ASC.Common.Caching.EventType.Remove); + cacheNotify.Publish(r, ASC.Common.Caching.CacheNotifyAction.Remove); } } } \ No newline at end of file diff --git a/common/ASC.Core.Common/Caching/CachedQuotaService.cs b/common/ASC.Core.Common/Caching/CachedQuotaService.cs index 3b6310f8b7..3bcb121e6c 100644 --- a/common/ASC.Core.Common/Caching/CachedQuotaService.cs +++ b/common/ASC.Core.Common/Caching/CachedQuotaService.cs @@ -33,11 +33,11 @@ namespace ASC.Core.Caching internal TrustInterval Interval { get; set; } internal ICache Cache { get; } - internal IEventBus<QuotaCacheItem> CacheNotify { get; } + internal ICacheNotify<QuotaCacheItem> CacheNotify { get; } internal bool QuotaCacheEnabled { get; } - public QuotaServiceCache(IConfiguration Configuration, IEventBus<QuotaCacheItem> cacheNotify, ICache cache) + public QuotaServiceCache(IConfiguration Configuration, ICacheNotify<QuotaCacheItem> cacheNotify, ICache cache) { if (Configuration["core:enable-quota-cache"] == null) { @@ -62,7 +62,7 @@ namespace ASC.Core.Caching { Cache.Remove(i.Key); } - }, ASC.Common.Caching.EventType.Any); + }, ASC.Common.Caching.CacheNotifyAction.Any); } } @@ -100,7 +100,7 @@ namespace ASC.Core.Caching { internal IQuotaService Service { get; set; } internal ICache Cache { get; set; } - internal IEventBus<QuotaCacheItem> CacheNotify { get; set; } + internal ICacheNotify<QuotaCacheItem> CacheNotify { get; set; } internal TrustInterval Interval { get; set; } internal TimeSpan CacheExpiration { get; set; } @@ -142,7 +142,7 @@ namespace ASC.Core.Caching public TenantQuota SaveTenantQuota(TenantQuota quota) { var q = Service.SaveTenantQuota(quota); - CacheNotify.Publish(new QuotaCacheItem { Key = QuotaServiceCache.KEY_QUOTA }, ASC.Common.Caching.EventType.Any); + CacheNotify.Publish(new QuotaCacheItem { Key = QuotaServiceCache.KEY_QUOTA }, ASC.Common.Caching.CacheNotifyAction.Any); return q; } @@ -155,7 +155,7 @@ namespace ASC.Core.Caching public void SetTenantQuotaRow(TenantQuotaRow row, bool exchange) { Service.SetTenantQuotaRow(row, exchange); - CacheNotify.Publish(new QuotaCacheItem { Key = GetKey(row.Tenant) }, ASC.Common.Caching.EventType.InsertOrUpdate); + CacheNotify.Publish(new QuotaCacheItem { Key = GetKey(row.Tenant) }, ASC.Common.Caching.CacheNotifyAction.InsertOrUpdate); } public IEnumerable<TenantQuotaRow> FindTenantQuotaRows(int tenantId) diff --git a/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs b/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs index 98e186df80..4e9840483e 100644 --- a/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs +++ b/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs @@ -29,10 +29,10 @@ namespace ASC.Core.Caching class SubscriptionServiceCache { internal ICache Cache { get; } - internal IEventBus<SubscriptionRecord> NotifyRecord { get; } - internal IEventBus<SubscriptionMethodCache> NotifyMethod { get; } + internal ICacheNotify<SubscriptionRecord> NotifyRecord { get; } + internal ICacheNotify<SubscriptionMethodCache> NotifyMethod { get; } - public SubscriptionServiceCache(IEventBus<SubscriptionRecord> notifyRecord, IEventBus<SubscriptionMethodCache> notifyMethod, ICache cache) + public SubscriptionServiceCache(ICacheNotify<SubscriptionRecord> notifyRecord, ICacheNotify<SubscriptionMethodCache> notifyMethod, ICache cache) { Cache = cache; NotifyRecord = notifyRecord; @@ -48,7 +48,7 @@ namespace ASC.Core.Caching store.SaveSubscription(s); } } - }, ASC.Common.Caching.EventType.InsertOrUpdate); + }, ASC.Common.Caching.CacheNotifyAction.InsertOrUpdate); notifyRecord.Subscribe((s) => { @@ -67,7 +67,7 @@ namespace ASC.Core.Caching } } } - }, ASC.Common.Caching.EventType.Remove); + }, ASC.Common.Caching.CacheNotifyAction.Remove); notifyMethod.Subscribe((m) => { @@ -79,7 +79,7 @@ namespace ASC.Core.Caching store.SetSubscriptionMethod(m); } } - }, ASC.Common.Caching.EventType.Any); + }, ASC.Common.Caching.CacheNotifyAction.Any); } private SubsciptionsStore GetSubsciptionsStore(int tenant, string sourceId, string actionId) @@ -98,8 +98,8 @@ namespace ASC.Core.Caching { private readonly ISubscriptionService service; private readonly ICache cache; - private readonly IEventBus<SubscriptionRecord> notifyRecord; - private readonly IEventBus<SubscriptionMethodCache> notifyMethod; + private readonly ICacheNotify<SubscriptionRecord> notifyRecord; + private readonly ICacheNotify<SubscriptionMethodCache> notifyMethod; private TimeSpan CacheExpiration { get; set; } @@ -153,19 +153,19 @@ namespace ASC.Core.Caching public void SaveSubscription(SubscriptionRecord s) { service.SaveSubscription(s); - notifyRecord.Publish(s, ASC.Common.Caching.EventType.InsertOrUpdate); + notifyRecord.Publish(s, ASC.Common.Caching.CacheNotifyAction.InsertOrUpdate); } public void RemoveSubscriptions(int tenant, string sourceId, string actionId) { service.RemoveSubscriptions(tenant, sourceId, actionId); - notifyRecord.Publish(new SubscriptionRecord { Tenant = tenant, SourceId = sourceId, ActionId = actionId }, ASC.Common.Caching.EventType.Remove); + notifyRecord.Publish(new SubscriptionRecord { Tenant = tenant, SourceId = sourceId, ActionId = actionId }, ASC.Common.Caching.CacheNotifyAction.Remove); } public void RemoveSubscriptions(int tenant, string sourceId, string actionId, string objectId) { service.RemoveSubscriptions(tenant, sourceId, actionId, objectId); - notifyRecord.Publish(new SubscriptionRecord { Tenant = tenant, SourceId = sourceId, ActionId = actionId, ObjectId = objectId }, ASC.Common.Caching.EventType.Remove); + notifyRecord.Publish(new SubscriptionRecord { Tenant = tenant, SourceId = sourceId, ActionId = actionId, ObjectId = objectId }, ASC.Common.Caching.CacheNotifyAction.Remove); } public IEnumerable<SubscriptionMethod> GetSubscriptionMethods(int tenant, string sourceId, string actionId, string recipientId) @@ -180,7 +180,7 @@ namespace ASC.Core.Caching public void SetSubscriptionMethod(SubscriptionMethod m) { service.SetSubscriptionMethod(m); - notifyMethod.Publish(m, ASC.Common.Caching.EventType.Any); + notifyMethod.Publish(m, ASC.Common.Caching.CacheNotifyAction.Any); } diff --git a/common/ASC.Core.Common/Caching/CachedTenantService.cs b/common/ASC.Core.Common/Caching/CachedTenantService.cs index d4751bf28e..a3a4d8228a 100644 --- a/common/ASC.Core.Common/Caching/CachedTenantService.cs +++ b/common/ASC.Core.Common/Caching/CachedTenantService.cs @@ -31,13 +31,13 @@ namespace ASC.Core.Caching private const string KEY = "tenants"; private TimeSpan CacheExpiration { get; set; } internal ICache Cache { get; } - internal IEventBus<TenantCacheItem> CacheNotifyItem { get; } - internal IEventBus<TenantSetting> CacheNotifySettings { get; } + internal ICacheNotify<TenantCacheItem> CacheNotifyItem { get; } + internal ICacheNotify<TenantSetting> CacheNotifySettings { get; } public TenantServiceCache( CoreBaseSettings coreBaseSettings, - IEventBus<TenantCacheItem> cacheNotifyItem, - IEventBus<TenantSetting> cacheNotifySettings, + ICacheNotify<TenantCacheItem> cacheNotifyItem, + ICacheNotify<TenantSetting> cacheNotifySettings, ICache cache) { CacheNotifyItem = cacheNotifyItem; @@ -50,12 +50,12 @@ namespace ASC.Core.Caching var tenants = GetTenantStore(); tenants.Remove(t.TenantId); tenants.Clear(coreBaseSettings); - }, ASC.Common.Caching.EventType.InsertOrUpdate); + }, ASC.Common.Caching.CacheNotifyAction.InsertOrUpdate); cacheNotifySettings.Subscribe((s) => { Cache.Remove(s.Key); - }, ASC.Common.Caching.EventType.Remove); + }, ASC.Common.Caching.CacheNotifyAction.Remove); } internal TenantStore GetTenantStore() @@ -180,8 +180,8 @@ namespace ASC.Core.Caching internal ITenantService Service { get; set; } private readonly ICache cache; - internal IEventBus<TenantSetting> CacheNotifySettings { get; set; } - internal IEventBus<TenantCacheItem> CacheNotifyItem { get; set; } + internal ICacheNotify<TenantSetting> CacheNotifySettings { get; set; } + internal ICacheNotify<TenantCacheItem> CacheNotifyItem { get; set; } private TimeSpan SettingsExpiration { get; set; } internal TenantServiceCache TenantServiceCache { get; set; } @@ -267,14 +267,14 @@ namespace ASC.Core.Caching public Tenant SaveTenant(CoreSettings coreSettings, Tenant tenant) { tenant = Service.SaveTenant(coreSettings, tenant); - CacheNotifyItem.Publish(new TenantCacheItem() { TenantId = tenant.TenantId }, ASC.Common.Caching.EventType.InsertOrUpdate); + CacheNotifyItem.Publish(new TenantCacheItem() { TenantId = tenant.TenantId }, ASC.Common.Caching.CacheNotifyAction.InsertOrUpdate); return tenant; } public void RemoveTenant(int id, bool auto = false) { Service.RemoveTenant(id, auto); - CacheNotifyItem.Publish(new TenantCacheItem() { TenantId = id }, ASC.Common.Caching.EventType.InsertOrUpdate); + CacheNotifyItem.Publish(new TenantCacheItem() { TenantId = id }, ASC.Common.Caching.CacheNotifyAction.InsertOrUpdate); } public IEnumerable<TenantVersion> GetTenantVersions() @@ -299,7 +299,7 @@ namespace ASC.Core.Caching { Service.SetTenantSettings(tenant, key, data); var cacheKey = string.Format("settings/{0}/{1}", tenant, key); - CacheNotifySettings.Publish(new TenantSetting { Key = cacheKey }, ASC.Common.Caching.EventType.Remove); + CacheNotifySettings.Publish(new TenantSetting { Key = cacheKey }, ASC.Common.Caching.CacheNotifyAction.Remove); } } } diff --git a/common/ASC.Core.Common/Caching/CachedUserService.cs b/common/ASC.Core.Common/Caching/CachedUserService.cs index a3db0935fe..30de580659 100644 --- a/common/ASC.Core.Common/Caching/CachedUserService.cs +++ b/common/ASC.Core.Common/Caching/CachedUserService.cs @@ -34,17 +34,17 @@ namespace ASC.Core.Caching internal ICache Cache { get; } internal CoreBaseSettings CoreBaseSettings { get; } - internal IEventBus<UserInfoCacheItem> CacheUserInfoItem { get; } - internal IEventBus<UserPhotoCacheItem> CacheUserPhotoItem { get; } - internal IEventBus<GroupCacheItem> CacheGroupCacheItem { get; } - internal IEventBus<UserGroupRefCacheItem> CacheUserGroupRefItem { get; } + internal ICacheNotify<UserInfoCacheItem> CacheUserInfoItem { get; } + internal ICacheNotify<UserPhotoCacheItem> CacheUserPhotoItem { get; } + internal ICacheNotify<GroupCacheItem> CacheGroupCacheItem { get; } + internal ICacheNotify<UserGroupRefCacheItem> CacheUserGroupRefItem { get; } public UserServiceCache( CoreBaseSettings coreBaseSettings, - IEventBus<UserInfoCacheItem> cacheUserInfoItem, - IEventBus<UserPhotoCacheItem> cacheUserPhotoItem, - IEventBus<GroupCacheItem> cacheGroupCacheItem, - IEventBus<UserGroupRefCacheItem> cacheUserGroupRefItem, + ICacheNotify<UserInfoCacheItem> cacheUserInfoItem, + ICacheNotify<UserPhotoCacheItem> cacheUserPhotoItem, + ICacheNotify<GroupCacheItem> cacheGroupCacheItem, + ICacheNotify<UserGroupRefCacheItem> cacheUserGroupRefItem, ICache cache) { Cache = cache; @@ -54,12 +54,12 @@ namespace ASC.Core.Caching CacheGroupCacheItem = cacheGroupCacheItem; CacheUserGroupRefItem = cacheUserGroupRefItem; - cacheUserInfoItem.Subscribe((u) => InvalidateCache(u), ASC.Common.Caching.EventType.Any); - cacheUserPhotoItem.Subscribe((p) => Cache.Remove(p.Key), ASC.Common.Caching.EventType.Remove); - cacheGroupCacheItem.Subscribe((g) => InvalidateCache(), ASC.Common.Caching.EventType.Any); + cacheUserInfoItem.Subscribe((u) => InvalidateCache(u), ASC.Common.Caching.CacheNotifyAction.Any); + cacheUserPhotoItem.Subscribe((p) => Cache.Remove(p.Key), ASC.Common.Caching.CacheNotifyAction.Remove); + cacheGroupCacheItem.Subscribe((g) => InvalidateCache(), ASC.Common.Caching.CacheNotifyAction.Any); - cacheUserGroupRefItem.Subscribe((r) => UpdateUserGroupRefCache(r, true), ASC.Common.Caching.EventType.Remove); - cacheUserGroupRefItem.Subscribe((r) => UpdateUserGroupRefCache(r, false), ASC.Common.Caching.EventType.InsertOrUpdate); + cacheUserGroupRefItem.Subscribe((r) => UpdateUserGroupRefCache(r, true), ASC.Common.Caching.CacheNotifyAction.Remove); + cacheUserGroupRefItem.Subscribe((r) => UpdateUserGroupRefCache(r, false), ASC.Common.Caching.CacheNotifyAction.InsertOrUpdate); } public void InvalidateCache() @@ -176,10 +176,10 @@ namespace ASC.Core.Caching private TimeSpan PhotoExpiration { get; set; } internal CoreBaseSettings CoreBaseSettings { get; set; } internal UserServiceCache UserServiceCache { get; set; } - internal IEventBus<UserInfoCacheItem> CacheUserInfoItem { get; set; } - internal IEventBus<UserPhotoCacheItem> CacheUserPhotoItem { get; set; } - internal IEventBus<GroupCacheItem> CacheGroupCacheItem { get; set; } - internal IEventBus<UserGroupRefCacheItem> CacheUserGroupRefItem { get; set; } + internal ICacheNotify<UserInfoCacheItem> CacheUserInfoItem { get; set; } + internal ICacheNotify<UserPhotoCacheItem> CacheUserPhotoItem { get; set; } + internal ICacheNotify<GroupCacheItem> CacheGroupCacheItem { get; set; } + internal ICacheNotify<UserGroupRefCacheItem> CacheUserGroupRefItem { get; set; } public CachedUserService() { @@ -261,14 +261,14 @@ namespace ASC.Core.Caching public UserInfo SaveUser(int tenant, UserInfo user) { user = Service.SaveUser(tenant, user); - CacheUserInfoItem.Publish(new UserInfoCacheItem { Id = user.ID.ToString(), Tenant = tenant }, ASC.Common.Caching.EventType.Any); + CacheUserInfoItem.Publish(new UserInfoCacheItem { Id = user.ID.ToString(), Tenant = tenant }, ASC.Common.Caching.CacheNotifyAction.Any); return user; } public void RemoveUser(int tenant, Guid id) { Service.RemoveUser(tenant, id); - CacheUserInfoItem.Publish(new UserInfoCacheItem { Tenant = tenant, Id = id.ToString() }, ASC.Common.Caching.EventType.Any); + CacheUserInfoItem.Publish(new UserInfoCacheItem { Tenant = tenant, Id = id.ToString() }, ASC.Common.Caching.CacheNotifyAction.Any); } public byte[] GetUserPhoto(int tenant, Guid id) @@ -285,7 +285,7 @@ namespace ASC.Core.Caching public void SetUserPhoto(int tenant, Guid id, byte[] photo) { Service.SetUserPhoto(tenant, id, photo); - CacheUserPhotoItem.Publish(new UserPhotoCacheItem { Key = UserServiceCache.GetUserPhotoCacheKey(tenant, id) }, ASC.Common.Caching.EventType.Remove); + CacheUserPhotoItem.Publish(new UserPhotoCacheItem { Key = UserServiceCache.GetUserPhotoCacheKey(tenant, id) }, ASC.Common.Caching.CacheNotifyAction.Remove); } public DateTime GetUserPasswordStamp(int tenant, Guid id) @@ -316,14 +316,14 @@ namespace ASC.Core.Caching public Group SaveGroup(int tenant, Group group) { group = Service.SaveGroup(tenant, group); - CacheGroupCacheItem.Publish(new GroupCacheItem { Id = group.Id.ToString() }, ASC.Common.Caching.EventType.Any); + CacheGroupCacheItem.Publish(new GroupCacheItem { Id = group.Id.ToString() }, ASC.Common.Caching.CacheNotifyAction.Any); return group; } public void RemoveGroup(int tenant, Guid id) { Service.RemoveGroup(tenant, id); - CacheGroupCacheItem.Publish(new GroupCacheItem { Id = id.ToString() }, ASC.Common.Caching.EventType.Any); + CacheGroupCacheItem.Publish(new GroupCacheItem { Id = id.ToString() }, ASC.Common.Caching.CacheNotifyAction.Any); } @@ -357,7 +357,7 @@ namespace ASC.Core.Caching public UserGroupRef SaveUserGroupRef(int tenant, UserGroupRef r) { r = Service.SaveUserGroupRef(tenant, r); - CacheUserGroupRefItem.Publish(r, ASC.Common.Caching.EventType.InsertOrUpdate); + CacheUserGroupRefItem.Publish(r, ASC.Common.Caching.CacheNotifyAction.InsertOrUpdate); return r; } @@ -366,7 +366,7 @@ namespace ASC.Core.Caching Service.RemoveUserGroupRef(tenant, userId, groupId, refType); var r = new UserGroupRef(userId, groupId, refType) { Tenant = tenant }; - CacheUserGroupRefItem.Publish(r, ASC.Common.Caching.EventType.Remove); + CacheUserGroupRefItem.Publish(r, ASC.Common.Caching.CacheNotifyAction.Remove); } diff --git a/common/ASC.Core.Common/Configuration/Consumer.cs b/common/ASC.Core.Common/Configuration/Consumer.cs index b62ccd0d81..6103d68561 100644 --- a/common/ASC.Core.Common/Configuration/Consumer.cs +++ b/common/ASC.Core.Common/Configuration/Consumer.cs @@ -70,7 +70,7 @@ namespace ASC.Core.Common.Configuration internal protected CoreSettings CoreSettings { get; set; } internal protected ConsumerFactory ConsumerFactory { get; set; } internal protected IConfiguration Configuration { get; } - internal protected IEventBus<ConsumerCacheItem> Cache { get; } + internal protected ICacheNotify<ConsumerCacheItem> Cache { get; } public bool IsSet { @@ -93,7 +93,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory) : this() { TenantManager = tenantManager; @@ -112,7 +112,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> additional) : this(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory) @@ -128,7 +128,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : this(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory) @@ -170,7 +170,7 @@ namespace ASC.Core.Common.Configuration this[providerProp.Key] = null; } - Cache.Publish(new ConsumerCacheItem() { Name = this.Name }, ASC.Common.Caching.EventType.Remove); + Cache.Publish(new ConsumerCacheItem() { Name = this.Name }, ASC.Common.Caching.CacheNotifyAction.Remove); } public bool Contains(KeyValuePair<string, string> item) @@ -287,7 +287,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory) { @@ -299,7 +299,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) @@ -312,7 +312,7 @@ namespace ASC.Core.Common.Configuration CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.Core.Common/Context/WorkContext.cs b/common/ASC.Core.Common/Context/WorkContext.cs index b593ba469e..ba62320c42 100644 --- a/common/ASC.Core.Common/Context/WorkContext.cs +++ b/common/ASC.Core.Common/Context/WorkContext.cs @@ -84,8 +84,8 @@ namespace ASC.Core if (notifyStarted) return; var configuration = serviceProvider.GetService<IConfiguration>(); - var cacheNotify = serviceProvider.GetService<IEventBus<NotifyMessage>>(); - var cacheInvoke = serviceProvider.GetService<IEventBus<NotifyInvoke>>(); + var cacheNotify = serviceProvider.GetService<ICacheNotify<NotifyMessage>>(); + var cacheInvoke = serviceProvider.GetService<ICacheNotify<NotifyInvoke>>(); var options = serviceProvider.GetService<IOptionsMonitor<ILog>>(); NotifyContext = new NotifyContext(serviceProvider); diff --git a/common/ASC.Core.Common/Data/DbSettingsManager.cs b/common/ASC.Core.Common/Data/DbSettingsManager.cs index bcff5cf20b..aa57a3d7c8 100644 --- a/common/ASC.Core.Common/Data/DbSettingsManager.cs +++ b/common/ASC.Core.Common/Data/DbSettingsManager.cs @@ -31,18 +31,18 @@ namespace ASC.Core.Data public class DbSettingsManagerCache { public ICache Cache { get; } - private IEventBus<SettingsCacheItem> Notify { get; } + private ICacheNotify<SettingsCacheItem> Notify { get; } - public DbSettingsManagerCache(IEventBus<SettingsCacheItem> notify, ICache cache) + public DbSettingsManagerCache(ICacheNotify<SettingsCacheItem> notify, ICache cache) { Cache = cache; Notify = notify; - Notify.Subscribe((i) => Cache.Remove(i.Key), ASC.Common.Caching.EventType.Remove); + Notify.Subscribe((i) => Cache.Remove(i.Key), ASC.Common.Caching.CacheNotifyAction.Remove); } public void Remove(string key) { - Notify.Publish(new SettingsCacheItem { Key = key }, ASC.Common.Caching.EventType.Remove); + Notify.Publish(new SettingsCacheItem { Key = key }, ASC.Common.Caching.CacheNotifyAction.Remove); } } diff --git a/common/ASC.Core.Common/Notify/NotifyServiceClient.cs b/common/ASC.Core.Common/Notify/NotifyServiceClient.cs index 6e65168722..371bc5453a 100644 --- a/common/ASC.Core.Common/Notify/NotifyServiceClient.cs +++ b/common/ASC.Core.Common/Notify/NotifyServiceClient.cs @@ -23,16 +23,16 @@ * */ -using EventType = ASC.Common.Caching.EventType; +using CacheNotifyAction = ASC.Common.Caching.CacheNotifyAction; namespace ASC.Core.Notify { [Scope] public class NotifyServiceClient : INotifyService { - private readonly IEventBus<NotifyMessage> СacheNotify; - private readonly IEventBus<NotifyInvoke> NotifyInvoke; - public NotifyServiceClient(IEventBus<NotifyMessage> cacheNotify, IEventBus<NotifyInvoke> notifyInvoke) + private readonly ICacheNotify<NotifyMessage> СacheNotify; + private readonly ICacheNotify<NotifyInvoke> NotifyInvoke; + public NotifyServiceClient(ICacheNotify<NotifyMessage> cacheNotify, ICacheNotify<NotifyInvoke> notifyInvoke) { СacheNotify = cacheNotify; NotifyInvoke = notifyInvoke; @@ -40,12 +40,12 @@ namespace ASC.Core.Notify public void SendNotifyMessage(NotifyMessage m) { - СacheNotify.Publish(m, EventType.InsertOrUpdate); + СacheNotify.Publish(m, CacheNotifyAction.InsertOrUpdate); } public void InvokeSendMethod(NotifyInvoke notifyInvoke) { - NotifyInvoke.Publish(notifyInvoke, EventType.InsertOrUpdate); + NotifyInvoke.Publish(notifyInvoke, CacheNotifyAction.InsertOrUpdate); } } } diff --git a/common/ASC.Core.Common/Notify/Senders/NotifyServiceSender.cs b/common/ASC.Core.Common/Notify/Senders/NotifyServiceSender.cs index 6c520cf823..9cc9f9efcb 100644 --- a/common/ASC.Core.Common/Notify/Senders/NotifyServiceSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/NotifyServiceSender.cs @@ -28,7 +28,7 @@ namespace ASC.Core.Notify.Senders public class NotifyServiceSender : INotifySender { public NotifyServiceClient NotifyServiceClient { get; } - public NotifyServiceSender(IEventBus<NotifyMessage> cacheNotify, IEventBus<NotifyInvoke> notifyInvoke) + public NotifyServiceSender(ICacheNotify<NotifyMessage> cacheNotify, ICacheNotify<NotifyInvoke> notifyInvoke) { NotifyServiceClient = new NotifyServiceClient(cacheNotify, notifyInvoke); } diff --git a/common/ASC.Core.Common/Notify/Telegram/TelegramServiceClient.cs b/common/ASC.Core.Common/Notify/Telegram/TelegramServiceClient.cs index 18da291fc2..e92e7d6d7d 100644 --- a/common/ASC.Core.Common/Notify/Telegram/TelegramServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Telegram/TelegramServiceClient.cs @@ -28,17 +28,17 @@ namespace ASC.Core.Common.Notify [Singletone] public class TelegramServiceClient : ITelegramService { - private IEventBus<NotifyMessage> CacheMessage { get; } - private IEventBus<RegisterUserProto> CacheRegisterUser { get; } - private IEventBus<CreateClientProto> CacheCreateClient { get; } - private IEventBus<DisableClientProto> CacheDisableClient { get; } + private ICacheNotify<NotifyMessage> CacheMessage { get; } + private ICacheNotify<RegisterUserProto> CacheRegisterUser { get; } + private ICacheNotify<CreateClientProto> CacheCreateClient { get; } + private ICacheNotify<DisableClientProto> CacheDisableClient { get; } private ICache Cache { get; } - public TelegramServiceClient(IEventBus<NotifyMessage> cacheMessage, - IEventBus<RegisterUserProto> cacheRegisterUser, - IEventBus<CreateClientProto> cacheCreateClient, - IEventBus<DisableClientProto> cacheDisableClient, + public TelegramServiceClient(ICacheNotify<NotifyMessage> cacheMessage, + ICacheNotify<RegisterUserProto> cacheRegisterUser, + ICacheNotify<CreateClientProto> cacheCreateClient, + ICacheNotify<DisableClientProto> cacheDisableClient, ICache cache) { CacheMessage = cacheMessage; @@ -50,7 +50,7 @@ namespace ASC.Core.Common.Notify public void SendMessage(NotifyMessage m) { - CacheMessage.Publish(m, ASC.Common.Caching.EventType.Insert); + CacheMessage.Publish(m, ASC.Common.Caching.CacheNotifyAction.Insert); } public void RegisterUser(string userId, int tenantId, string token) @@ -61,7 +61,7 @@ namespace ASC.Core.Common.Notify UserId = userId, TenantId = tenantId, Token = token - }, ASC.Common.Caching.EventType.Insert); + }, ASC.Common.Caching.CacheNotifyAction.Insert); } public void CreateOrUpdateClient(int tenantId, string token, int tokenLifespan, string proxy) @@ -72,12 +72,12 @@ namespace ASC.Core.Common.Notify Token = token, TokenLifespan = tokenLifespan, Proxy = proxy - }, ASC.Common.Caching.EventType.Insert); + }, ASC.Common.Caching.CacheNotifyAction.Insert); } public void DisableClient(int tenantId) { - CacheDisableClient.Publish(new DisableClientProto() { TenantId = tenantId }, ASC.Common.Caching.EventType.Insert); + CacheDisableClient.Publish(new DisableClientProto() { TenantId = tenantId }, ASC.Common.Caching.CacheNotifyAction.Insert); } public string RegistrationToken(string userId, int tenantId) diff --git a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs index f0e77461ed..3a01425d7d 100644 --- a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs +++ b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs @@ -38,7 +38,7 @@ namespace ASC.Data.Backup.Services private Dictionary<string, string> ConfigPaths { get; set; } private int Limit { get; set; } private string UpgradesPath { get; set; } - private IEventBus<BackupProgress> CacheBackupProgress { get; } + private ICacheNotify<BackupProgress> CacheBackupProgress { get; } private FactoryProgressItem FactoryProgressItem { get; set; } private TempPath TempPath { get; } @@ -46,7 +46,7 @@ namespace ASC.Data.Backup.Services public BackupWorker( IOptionsMonitor<ILog> options, - IEventBus<BackupProgress> cacheBackupProgress, + ICacheNotify<BackupProgress> cacheBackupProgress, DistributedTaskQueueOptionsManager progressQueue, FactoryProgressItem factoryProgressItem, TempPath tempPath) diff --git a/common/ASC.Data.Storage/Configuration/StorageSettings.cs b/common/ASC.Data.Storage/Configuration/StorageSettings.cs index a75a5b2f86..267e6dd47d 100644 --- a/common/ASC.Data.Storage/Configuration/StorageSettings.cs +++ b/common/ASC.Data.Storage/Configuration/StorageSettings.cs @@ -48,7 +48,7 @@ namespace ASC.Data.Storage.Configuration Subscribed = true; - ServiceProvider.GetService<IEventBus<ConsumerCacheItem>>().Subscribe((i) => + ServiceProvider.GetService<ICacheNotify<ConsumerCacheItem>>().Subscribe((i) => { using var scope = ServiceProvider.CreateScope(); @@ -65,7 +65,7 @@ namespace ASC.Data.Storage.Configuration { storageSettingsHelper.Clear(cdnSettings); } - }, Common.Caching.EventType.Remove); + }, Common.Caching.CacheNotifyAction.Remove); } } } @@ -84,7 +84,7 @@ namespace ASC.Data.Storage.Configuration public virtual Func<DataStoreConsumer, DataStoreConsumer> Switch { get { return d => d; } } - internal IEventBus<DataStoreCacheItem> Cache { get; set; } + internal ICacheNotify<DataStoreCacheItem> Cache { get; set; } public abstract Guid ID { get; } } @@ -115,7 +115,7 @@ namespace ASC.Data.Storage.Configuration { private StorageFactoryConfig StorageFactoryConfig { get; } private PathUtils PathUtils { get; } - private IEventBus<DataStoreCacheItem> Cache { get; } + private ICacheNotify<DataStoreCacheItem> Cache { get; } private IOptionsMonitor<ILog> Options { get; } private TenantManager TenantManager { get; } private SettingsManager SettingsManager { get; } @@ -126,7 +126,7 @@ namespace ASC.Data.Storage.Configuration BaseStorageSettingsListener baseStorageSettingsListener, StorageFactoryConfig storageFactoryConfig, PathUtils pathUtils, - IEventBus<DataStoreCacheItem> cache, + ICacheNotify<DataStoreCacheItem> cache, IOptionsMonitor<ILog> options, TenantManager tenantManager, SettingsManager settingsManager, @@ -145,7 +145,7 @@ namespace ASC.Data.Storage.Configuration BaseStorageSettingsListener baseStorageSettingsListener, StorageFactoryConfig storageFactoryConfig, PathUtils pathUtils, - IEventBus<DataStoreCacheItem> cache, + ICacheNotify<DataStoreCacheItem> cache, IOptionsMonitor<ILog> options, TenantManager tenantManager, SettingsManager settingsManager, @@ -168,7 +168,7 @@ namespace ASC.Data.Storage.Configuration var path = TenantPath.CreatePath(tenantId); foreach (var module in StorageFactoryConfig.GetModuleList("", true)) { - Cache.Publish(new DataStoreCacheItem() { TenantId = path, Module = module }, Common.Caching.EventType.Remove); + Cache.Publish(new DataStoreCacheItem() { TenantId = path, Module = module }, Common.Caching.CacheNotifyAction.Remove); } } diff --git a/common/ASC.Data.Storage/Encryption/EncryptionServiceClient.cs b/common/ASC.Data.Storage/Encryption/EncryptionServiceClient.cs index a5ef287c72..8560252cd8 100644 --- a/common/ASC.Data.Storage/Encryption/EncryptionServiceClient.cs +++ b/common/ASC.Data.Storage/Encryption/EncryptionServiceClient.cs @@ -23,7 +23,7 @@ * */ -using EventType = ASC.Common.Caching.EventType; +using CacheNotifyAction = ASC.Common.Caching.CacheNotifyAction; namespace ASC.Data.Storage.Encryption { @@ -31,11 +31,11 @@ namespace ASC.Data.Storage.Encryption public class EncryptionServiceClient : IEncryptionService { - private IEventBus<EncryptionSettingsProto> NotifySetting { get; } - private IEventBus<EncryptionStop> NotifyStop { get; } + private ICacheNotify<EncryptionSettingsProto> NotifySetting { get; } + private ICacheNotify<EncryptionStop> NotifyStop { get; } public EncryptionServiceClient( - IEventBus<EncryptionSettingsProto> notifySetting, IEventBus<EncryptionStop> notifyStop) + ICacheNotify<EncryptionSettingsProto> notifySetting, ICacheNotify<EncryptionStop> notifyStop) { NotifySetting = notifySetting; NotifyStop = notifyStop; @@ -43,12 +43,12 @@ namespace ASC.Data.Storage.Encryption public void Start(EncryptionSettingsProto encryptionSettingsProto) { - NotifySetting.Publish(encryptionSettingsProto, EventType.Insert); + NotifySetting.Publish(encryptionSettingsProto, CacheNotifyAction.Insert); } public void Stop() { - NotifyStop.Publish(new EncryptionStop(), EventType.Insert); + NotifyStop.Publish(new EncryptionStop(), CacheNotifyAction.Insert); } } diff --git a/common/ASC.Data.Storage/Migration/MigrateServiceClient.cs b/common/ASC.Data.Storage/Migration/MigrateServiceClient.cs index 7b3b03d242..0aaaae5a6b 100644 --- a/common/ASC.Data.Storage/Migration/MigrateServiceClient.cs +++ b/common/ASC.Data.Storage/Migration/MigrateServiceClient.cs @@ -28,12 +28,12 @@ namespace ASC.Data.Storage.Migration [Singletone] public class ServiceClientListener { - private IEventBus<MigrationProgress> ProgressMigrationNotify { get; } + private ICacheNotify<MigrationProgress> ProgressMigrationNotify { get; } private IServiceProvider ServiceProvider { get; } private ICache Cache { get; } public ServiceClientListener( - IEventBus<MigrationProgress> progressMigrationNotify, + ICacheNotify<MigrationProgress> progressMigrationNotify, IServiceProvider serviceProvider, ICache cache) { @@ -63,7 +63,7 @@ namespace ASC.Data.Storage.Migration Cache.Insert(GetCacheKey(n.TenantId), migrationProgress, DateTime.MaxValue); }, - Common.Caching.EventType.Insert); + Common.Caching.CacheNotifyAction.Insert); } private string GetCacheKey(int tenantId) @@ -76,14 +76,14 @@ namespace ASC.Data.Storage.Migration public class ServiceClient : IService { public ServiceClientListener ServiceClientListener { get; } - public IEventBus<MigrationCache> CacheMigrationNotify { get; } - public IEventBus<MigrationUploadCdn> UploadCdnMigrationNotify { get; } + public ICacheNotify<MigrationCache> CacheMigrationNotify { get; } + public ICacheNotify<MigrationUploadCdn> UploadCdnMigrationNotify { get; } public IServiceProvider ServiceProvider { get; } public ServiceClient( ServiceClientListener serviceClientListener, - IEventBus<MigrationCache> cacheMigrationNotify, - IEventBus<MigrationUploadCdn> uploadCdnMigrationNotify, + ICacheNotify<MigrationCache> cacheMigrationNotify, + ICacheNotify<MigrationUploadCdn> uploadCdnMigrationNotify, IServiceProvider serviceProvider) { ServiceClientListener = serviceClientListener; @@ -101,7 +101,7 @@ namespace ASC.Data.Storage.Migration TenantId = tenant, StorSettings = storSettings }, - Common.Caching.EventType.Insert); + Common.Caching.CacheNotifyAction.Insert); } public void UploadCdn(int tenantId, string relativePath, string mappedPath, CdnStorageSettings settings = null) @@ -115,7 +115,7 @@ namespace ASC.Data.Storage.Migration MappedPath = mappedPath, CdnStorSettings = cdnStorSettings }, - Common.Caching.EventType.Insert); + Common.Caching.CacheNotifyAction.Insert); } public double GetProgress(int tenant) @@ -127,7 +127,7 @@ namespace ASC.Data.Storage.Migration public void StopMigrate() { - CacheMigrationNotify.Publish(new MigrationCache(), Common.Caching.EventType.InsertOrUpdate); + CacheMigrationNotify.Publish(new MigrationCache(), Common.Caching.CacheNotifyAction.InsertOrUpdate); } } } diff --git a/common/ASC.Data.Storage/StorageUploader.cs b/common/ASC.Data.Storage/StorageUploader.cs index 19f97a0867..a9c11e2148 100644 --- a/common/ASC.Data.Storage/StorageUploader.cs +++ b/common/ASC.Data.Storage/StorageUploader.cs @@ -34,14 +34,14 @@ namespace ASC.Data.Storage private IServiceProvider ServiceProvider { get; } private TempStream TempStream { get; } - private IEventBus<MigrationProgress> CacheMigrationNotify { get; } + private ICacheNotify<MigrationProgress> CacheMigrationNotify { get; } static StorageUploader() { Locker = new object(); } - public StorageUploader(IServiceProvider serviceProvider, TempStream tempStream, IEventBus<MigrationProgress> cacheMigrationNotify, DistributedTaskQueueOptionsManager options) + public StorageUploader(IServiceProvider serviceProvider, TempStream tempStream, ICacheNotify<MigrationProgress> cacheMigrationNotify, DistributedTaskQueueOptionsManager options) { ServiceProvider = serviceProvider; TempStream = tempStream; @@ -100,7 +100,7 @@ namespace ASC.Data.Storage public MigrateOperation( IServiceProvider serviceProvider, - IEventBus<MigrationProgress> cacheMigrationNotify, + ICacheNotify<MigrationProgress> cacheMigrationNotify, string id, int tenantId, StorageSettings settings, @@ -124,7 +124,7 @@ namespace ASC.Data.Storage private IServiceProvider ServiceProvider { get; } private StorageFactoryConfig StorageFactoryConfig { get; } private TempStream TempStream { get; } - private IEventBus<MigrationProgress> CacheMigrationNotify { get; } + private ICacheNotify<MigrationProgress> CacheMigrationNotify { get; } protected override void DoJob() { @@ -211,7 +211,7 @@ namespace ASC.Data.Storage Error = Exception.ToString(), IsCompleted = IsCompleted }, - Common.Caching.EventType.Insert); + Common.Caching.CacheNotifyAction.Insert); } } diff --git a/common/ASC.FederatedLogin/AccountLinker.cs b/common/ASC.FederatedLogin/AccountLinker.cs index 1e9cdb76f3..0fb16cd97f 100644 --- a/common/ASC.FederatedLogin/AccountLinker.cs +++ b/common/ASC.FederatedLogin/AccountLinker.cs @@ -29,18 +29,18 @@ namespace ASC.FederatedLogin public class AccountLinkerStorage { private readonly ICache cache; - private readonly IEventBus<LinkerCacheItem> notify; + private readonly ICacheNotify<LinkerCacheItem> notify; - public AccountLinkerStorage(IEventBus<LinkerCacheItem> notify, ICache cache) + public AccountLinkerStorage(ICacheNotify<LinkerCacheItem> notify, ICache cache) { this.cache = cache; this.notify = notify; - notify.Subscribe((c) => cache.Remove(c.Obj), Common.Caching.EventType.Remove); + notify.Subscribe((c) => cache.Remove(c.Obj), Common.Caching.CacheNotifyAction.Remove); } public void RemoveFromCache(string obj) { - notify.Publish(new LinkerCacheItem { Obj = obj }, Common.Caching.EventType.Remove); + notify.Publish(new LinkerCacheItem { Obj = obj }, Common.Caching.CacheNotifyAction.Remove); } public List<LoginProfile> GetFromCache(string obj, Func<string, List<LoginProfile>> fromDb) { diff --git a/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs index 48e6352d26..365b9c0d60 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs @@ -84,7 +84,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/BitlyLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/BitlyLoginProvider.cs index aa88d2e769..b14603ad32 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BitlyLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BitlyLoginProvider.cs @@ -50,7 +50,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/BoxLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/BoxLoginProvider.cs index 90cb589f6f..3bd6340296 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BoxLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BoxLoginProvider.cs @@ -52,7 +52,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs index 87d6c5d258..540e20fb2a 100644 --- a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs @@ -54,7 +54,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/DropboxLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/DropboxLoginProvider.cs index b500f50661..09aead4b46 100644 --- a/common/ASC.FederatedLogin/LoginProviders/DropboxLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/DropboxLoginProvider.cs @@ -52,7 +52,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs index e7df6f8d0e..a9ccad3d94 100644 --- a/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs @@ -44,7 +44,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs index 0048d770b2..61e1bd8845 100644 --- a/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs @@ -57,7 +57,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs index c5f26b539c..ae2122b270 100644 --- a/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs @@ -78,7 +78,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/LinkedInLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/LinkedInLoginProvider.cs index 9823fec6d5..e1fdd59838 100644 --- a/common/ASC.FederatedLogin/LoginProviders/LinkedInLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/LinkedInLoginProvider.cs @@ -68,7 +68,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs index 5ff4e5dbd0..bfe089d620 100644 --- a/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs @@ -68,7 +68,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/OneDriveLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/OneDriveLoginProvider.cs index 942e49a2e4..8f735496f1 100644 --- a/common/ASC.FederatedLogin/LoginProviders/OneDriveLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/OneDriveLoginProvider.cs @@ -56,7 +56,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs index a511346858..7c53d73780 100644 --- a/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs @@ -62,7 +62,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs index c336944030..f9e0f245ec 100644 --- a/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs @@ -71,7 +71,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/WordpressLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/WordpressLoginProvider.cs index 55200a919f..a5f188c114 100644 --- a/common/ASC.FederatedLogin/LoginProviders/WordpressLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/WordpressLoginProvider.cs @@ -41,7 +41,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/YahooLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/YahooLoginProvider.cs index af3157cfd6..3e7b9a5098 100644 --- a/common/ASC.FederatedLogin/LoginProviders/YahooLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/YahooLoginProvider.cs @@ -45,7 +45,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs b/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs index c89fd12660..3c68a1512a 100644 --- a/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs @@ -66,7 +66,7 @@ namespace ASC.FederatedLogin.LoginProviders CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, Signature signature, InstanceCrypto instanceCrypto, diff --git a/common/ASC.IPSecurity/IPRestrictionsService.cs b/common/ASC.IPSecurity/IPRestrictionsService.cs index a4b8463023..e7e43cee63 100644 --- a/common/ASC.IPSecurity/IPRestrictionsService.cs +++ b/common/ASC.IPSecurity/IPRestrictionsService.cs @@ -31,12 +31,12 @@ namespace ASC.IPSecurity private const string cacheKey = "iprestrictions"; public ICache Cache { get; set; } - internal IEventBus<IPRestrictionItem> Notify { get; } + internal ICacheNotify<IPRestrictionItem> Notify { get; } - public IPRestrictionsServiceCache(IEventBus<IPRestrictionItem> notify, ICache cache) + public IPRestrictionsServiceCache(ICacheNotify<IPRestrictionItem> notify, ICache cache) { Cache = cache; - notify.Subscribe((r) => Cache.Remove(GetCacheKey(r.TenantId)), Common.Caching.EventType.Any); + notify.Subscribe((r) => Cache.Remove(GetCacheKey(r.TenantId)), Common.Caching.CacheNotifyAction.Any); Notify = notify; } @@ -50,7 +50,7 @@ namespace ASC.IPSecurity public class IPRestrictionsService { private readonly ICache cache; - private readonly IEventBus<IPRestrictionItem> notify; + private readonly ICacheNotify<IPRestrictionItem> notify; private static readonly TimeSpan timeout = TimeSpan.FromMinutes(5); private IPRestrictionsRepository IPRestrictionsRepository { get; } @@ -79,7 +79,7 @@ namespace ASC.IPSecurity public IEnumerable<string> Save(IEnumerable<string> ips, int tenant) { var restrictions = IPRestrictionsRepository.Save(ips, tenant); - notify.Publish(new IPRestrictionItem { TenantId = tenant }, Common.Caching.EventType.InsertOrUpdate); + notify.Publish(new IPRestrictionItem { TenantId = tenant }, Common.Caching.CacheNotifyAction.InsertOrUpdate); return restrictions; } } diff --git a/common/ASC.VoipService/Dao/CachedVoipDao.cs b/common/ASC.VoipService/Dao/CachedVoipDao.cs index e54e029a3d..3635caeefe 100644 --- a/common/ASC.VoipService/Dao/CachedVoipDao.cs +++ b/common/ASC.VoipService/Dao/CachedVoipDao.cs @@ -29,18 +29,18 @@ namespace ASC.VoipService.Dao public class VoipDaoCache { internal ICache Cache { get; } - private IEventBus<CachedVoipItem> Notify { get; } + private ICacheNotify<CachedVoipItem> Notify { get; } - public VoipDaoCache(IEventBus<CachedVoipItem> notify, ICache cache) + public VoipDaoCache(ICacheNotify<CachedVoipItem> notify, ICache cache) { Cache = cache; Notify = notify; - Notify.Subscribe((c) => Cache.Remove(CachedVoipDao.GetCacheKey(c.Tenant)), Common.Caching.EventType.Any); + Notify.Subscribe((c) => Cache.Remove(CachedVoipDao.GetCacheKey(c.Tenant)), Common.Caching.CacheNotifyAction.Any); } public void ResetCache(int tenant) { - Notify.Publish(new CachedVoipItem { Tenant = tenant }, Common.Caching.EventType.Any); + Notify.Publish(new CachedVoipItem { Tenant = tenant }, Common.Caching.CacheNotifyAction.Any); } } diff --git a/common/ASC.Webhooks.Core/WebhookPublisher.cs b/common/ASC.Webhooks.Core/WebhookPublisher.cs index f09023da25..83ddab4b37 100644 --- a/common/ASC.Webhooks.Core/WebhookPublisher.cs +++ b/common/ASC.Webhooks.Core/WebhookPublisher.cs @@ -5,13 +5,13 @@ { private DbWorker DbWorker { get; } private TenantManager TenantManager { get; } - private IEventBus<WebhookRequest> WebhookNotify { get; } + private ICacheNotify<WebhookRequest> WebhookNotify { get; } public WebhookPublisher( DbWorker dbWorker, TenantManager tenantManager, IOptionsMonitor<ILog> options, - IEventBus<WebhookRequest> webhookNotify) + ICacheNotify<WebhookRequest> webhookNotify) { DbWorker = dbWorker; TenantManager = tenantManager; @@ -42,7 +42,7 @@ Id = DbId }; - WebhookNotify.Publish(request, Common.Caching.EventType.Update); + WebhookNotify.Publish(request, Common.Caching.CacheNotifyAction.Update); } } } diff --git a/common/services/ASC.ClearEvents/Program.cs b/common/services/ASC.ClearEvents/Program.cs index 159b477035..8bd2c5ae48 100644 --- a/common/services/ASC.ClearEvents/Program.cs +++ b/common/services/ASC.ClearEvents/Program.cs @@ -63,15 +63,15 @@ builder.Host.ConfigureServices((hostContext, services) => if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCacheNotify<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCacheNotify<>)); } else { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); } services.AddHostedService<ClearEventsService>(); diff --git a/common/services/ASC.Data.Backup/Services/BackupListenerService.cs b/common/services/ASC.Data.Backup/Services/BackupListenerService.cs index 6a36d9e686..4a8a27401d 100644 --- a/common/services/ASC.Data.Backup/Services/BackupListenerService.cs +++ b/common/services/ASC.Data.Backup/Services/BackupListenerService.cs @@ -3,10 +3,10 @@ [Singletone] internal sealed class BackupListenerService : IHostedService { - private readonly IEventBus<DeleteSchedule> _cacheDeleteSchedule; + private readonly ICacheNotify<DeleteSchedule> _cacheDeleteSchedule; private readonly IServiceScopeFactory _scopeFactory; - public BackupListenerService(IEventBus<DeleteSchedule> cacheDeleteSchedule, + public BackupListenerService(ICacheNotify<DeleteSchedule> cacheDeleteSchedule, IServiceScopeFactory scopeFactory) { _cacheDeleteSchedule = cacheDeleteSchedule; @@ -25,14 +25,14 @@ internal sealed class BackupListenerService : IHostedService public Task StartAsync(CancellationToken cancellationToken) { - _cacheDeleteSchedule.Subscribe((n) => DeleteScheldure(n), Common.Caching.EventType.Insert); + _cacheDeleteSchedule.Subscribe((n) => DeleteScheldure(n), Common.Caching.CacheNotifyAction.Insert); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { - _cacheDeleteSchedule.Unsubscribe(Common.Caching.EventType.Insert); + _cacheDeleteSchedule.Unsubscribe(Common.Caching.CacheNotifyAction.Insert); return Task.CompletedTask; } diff --git a/common/services/ASC.ElasticSearch/Core/SearchSettings.cs b/common/services/ASC.ElasticSearch/Core/SearchSettings.cs index ac2beaef8f..6830fe4f1f 100644 --- a/common/services/ASC.ElasticSearch/Core/SearchSettings.cs +++ b/common/services/ASC.ElasticSearch/Core/SearchSettings.cs @@ -69,7 +69,7 @@ namespace ASC.ElasticSearch.Core private TenantManager TenantManager { get; } private SettingsManager SettingsManager { get; } private CoreBaseSettings CoreBaseSettings { get; } - private IEventBus<ReIndexAction> CacheNotify { get; } + private ICacheNotify<ReIndexAction> CacheNotify { get; } private IServiceProvider ServiceProvider { get; } public IConfiguration Configuration { get; } @@ -77,7 +77,7 @@ namespace ASC.ElasticSearch.Core TenantManager tenantManager, SettingsManager settingsManager, CoreBaseSettings coreBaseSettings, - IEventBus<ReIndexAction> cacheNotify, + ICacheNotify<ReIndexAction> cacheNotify, IServiceProvider serviceProvider, IConfiguration configuration) { @@ -128,7 +128,7 @@ namespace ASC.ElasticSearch.Core var action = new ReIndexAction() { Tenant = TenantManager.GetCurrentTenant().TenantId }; action.Names.AddRange(toReIndex.Select(r => r.ID).ToList()); - CacheNotify.Publish(action, Common.Caching.EventType.Any); + CacheNotify.Publish(action, Common.Caching.CacheNotifyAction.Any); } public bool CanIndexByContent<T>(int tenantId) where T : class, ISearchItem diff --git a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs index 633c36161e..201745e1a2 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -29,21 +29,21 @@ namespace ASC.ElasticSearch public class BaseIndexerHelper { public ConcurrentDictionary<string, bool> IsExist { get; set; } - private readonly IEventBus<ClearIndexAction> Notify; + private readonly ICacheNotify<ClearIndexAction> Notify; - public BaseIndexerHelper(IEventBus<ClearIndexAction> cacheNotify) + public BaseIndexerHelper(ICacheNotify<ClearIndexAction> cacheNotify) { IsExist = new ConcurrentDictionary<string, bool>(); Notify = cacheNotify; Notify.Subscribe((a) => { IsExist.AddOrUpdate(a.Id, false, (string q, bool w) => false); - }, Common.Caching.EventType.Any); + }, Common.Caching.CacheNotifyAction.Any); } public void Clear<T>(T t) where T : class, ISearchItem { - Notify.Publish(new ClearIndexAction() { Id = t.IndexName }, Common.Caching.EventType.Any); + Notify.Publish(new ClearIndexAction() { Id = t.IndexName }, Common.Caching.CacheNotifyAction.Any); } } diff --git a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs index d5325b19bf..87d78b2ad1 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -31,7 +31,7 @@ namespace ASC.ElasticSearch public DateTime LastIndexed { get; set; } public string Indexing { get; set; } - public FactoryIndexerHelper(IEventBus<IndexAction> cacheNotify) + public FactoryIndexerHelper(ICacheNotify<IndexAction> cacheNotify) { cacheNotify.Subscribe((a) => { @@ -40,7 +40,7 @@ namespace ASC.ElasticSearch LastIndexed = new DateTime(a.LastIndexed); } Indexing = a.Indexing; - }, Common.Caching.EventType.Any); + }, Common.Caching.CacheNotifyAction.Any); } } diff --git a/common/services/ASC.ElasticSearch/Service/Launcher.cs b/common/services/ASC.ElasticSearch/Service/Launcher.cs index 0a4230613e..86fc08c173 100644 --- a/common/services/ASC.ElasticSearch/Service/Launcher.cs +++ b/common/services/ASC.ElasticSearch/Service/Launcher.cs @@ -29,8 +29,8 @@ namespace ASC.ElasticSearch public class ServiceLauncher : IHostedService { private ILog Log { get; } - private IEventBus<AscCacheItem> Notify { get; } - private IEventBus<IndexAction> IndexNotify { get; } + private ICacheNotify<AscCacheItem> Notify { get; } + private ICacheNotify<IndexAction> IndexNotify { get; } private IServiceProvider ServiceProvider { get; } private bool IsStarted { get; set; } private CancellationTokenSource CancellationTokenSource { get; set; } @@ -39,8 +39,8 @@ namespace ASC.ElasticSearch public ServiceLauncher( IOptionsMonitor<ILog> options, - IEventBus<AscCacheItem> notify, - IEventBus<IndexAction> indexNotify, + ICacheNotify<AscCacheItem> notify, + ICacheNotify<IndexAction> indexNotify, IServiceProvider serviceProvider, Settings settings) { @@ -63,7 +63,7 @@ namespace ASC.ElasticSearch await Task.Delay(10000); } IndexAll(true); - }, Common.Caching.EventType.Any); + }, Common.Caching.CacheNotifyAction.Any); } catch (Exception e) { @@ -132,7 +132,7 @@ namespace ASC.ElasticSearch } Timer.Change(Period, Period); - IndexNotify.Publish(new IndexAction() { Indexing = "", LastIndexed = DateTime.Now.Ticks }, Common.Caching.EventType.Any); + IndexNotify.Publish(new IndexAction() { Indexing = "", LastIndexed = DateTime.Now.Ticks }, Common.Caching.CacheNotifyAction.Any); IsStarted = false; } catch (Exception e) @@ -165,7 +165,7 @@ namespace ASC.ElasticSearch if (!IsStarted) return; Log.DebugFormat("Product {0}", product.IndexName); - IndexNotify.Publish(new IndexAction() { Indexing = product.IndexName, LastIndexed = 0 }, Common.Caching.EventType.Any); + IndexNotify.Publish(new IndexAction() { Indexing = product.IndexName, LastIndexed = 0 }, Common.Caching.CacheNotifyAction.Any); product.IndexAll(); } catch (Exception e) diff --git a/common/services/ASC.ElasticSearch/Service/Service.cs b/common/services/ASC.ElasticSearch/Service/Service.cs index ed05c76000..aa2fa43deb 100644 --- a/common/services/ASC.ElasticSearch/Service/Service.cs +++ b/common/services/ASC.ElasticSearch/Service/Service.cs @@ -29,9 +29,9 @@ namespace ASC.ElasticSearch.Service public class Service { private IServiceProvider ServiceProvider { get; } - private IEventBus<ReIndexAction> CacheNotify { get; } + private ICacheNotify<ReIndexAction> CacheNotify { get; } - public Service(IServiceProvider serviceProvider, IEventBus<ReIndexAction> cacheNotify) + public Service(IServiceProvider serviceProvider, ICacheNotify<ReIndexAction> cacheNotify) { ServiceProvider = serviceProvider; CacheNotify = cacheNotify; @@ -42,7 +42,7 @@ namespace ASC.ElasticSearch.Service CacheNotify.Subscribe((a) => { ReIndex(a.Names.ToList(), a.Tenant); - }, Common.Caching.EventType.Any); + }, Common.Caching.CacheNotifyAction.Any); } public bool Support(string table) diff --git a/common/services/ASC.Notify/NotifyService.cs b/common/services/ASC.Notify/NotifyService.cs index 13dd5aceca..7e7cc96081 100644 --- a/common/services/ASC.Notify/NotifyService.cs +++ b/common/services/ASC.Notify/NotifyService.cs @@ -30,12 +30,12 @@ namespace ASC.Notify { private ILog Log { get; } - private IEventBus<NotifyMessage> CacheNotify { get; } - private IEventBus<NotifyInvoke> CacheInvoke { get; } + private ICacheNotify<NotifyMessage> CacheNotify { get; } + private ICacheNotify<NotifyInvoke> CacheInvoke { get; } private DbWorker Db { get; } private IServiceProvider ServiceProvider { get; } - public NotifyService(DbWorker db, IServiceProvider serviceProvider, IEventBus<NotifyMessage> cacheNotify, IEventBus<NotifyInvoke> cacheInvoke, IOptionsMonitor<ILog> options) + public NotifyService(DbWorker db, IServiceProvider serviceProvider, ICacheNotify<NotifyMessage> cacheNotify, ICacheNotify<NotifyInvoke> cacheInvoke, IOptionsMonitor<ILog> options) { Db = db; ServiceProvider = serviceProvider; @@ -46,13 +46,13 @@ namespace ASC.Notify public void Start() { - CacheNotify.Subscribe((n) => SendNotifyMessage(n), Common.Caching.EventType.InsertOrUpdate); - CacheInvoke.Subscribe((n) => InvokeSendMethod(n), Common.Caching.EventType.InsertOrUpdate); + CacheNotify.Subscribe((n) => SendNotifyMessage(n), Common.Caching.CacheNotifyAction.InsertOrUpdate); + CacheInvoke.Subscribe((n) => InvokeSendMethod(n), Common.Caching.CacheNotifyAction.InsertOrUpdate); } public void Stop() { - CacheNotify.Unsubscribe(Common.Caching.EventType.InsertOrUpdate); + CacheNotify.Unsubscribe(Common.Caching.CacheNotifyAction.InsertOrUpdate); } public void SendNotifyMessage(NotifyMessage notifyMessage) @@ -100,8 +100,8 @@ namespace ASC.Notify public void Dispose() { - CacheNotify.Unsubscribe(Common.Caching.EventType.InsertOrUpdate); - CacheInvoke.Unsubscribe(Common.Caching.EventType.InsertOrUpdate); + CacheNotify.Unsubscribe(Common.Caching.CacheNotifyAction.InsertOrUpdate); + CacheInvoke.Unsubscribe(Common.Caching.CacheNotifyAction.InsertOrUpdate); } } diff --git a/common/services/ASC.Notify/Program.cs b/common/services/ASC.Notify/Program.cs index 8998baa319..5751dd6f66 100644 --- a/common/services/ASC.Notify/Program.cs +++ b/common/services/ASC.Notify/Program.cs @@ -54,17 +54,17 @@ if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCacheNotify<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCacheNotify<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); } diHelper.RegisterProducts(hostContext.Configuration, hostContext.HostingEnvironment.ContentRootPath); diff --git a/common/services/ASC.Studio.Notify/Program.cs b/common/services/ASC.Studio.Notify/Program.cs index 24ab179a7c..5a93530288 100644 --- a/common/services/ASC.Studio.Notify/Program.cs +++ b/common/services/ASC.Studio.Notify/Program.cs @@ -54,17 +54,17 @@ if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCacheNotify<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCacheNotify<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); } diHelper.RegisterProducts(hostContext.Configuration, hostContext.HostingEnvironment.ContentRootPath); diff --git a/common/services/ASC.TelegramService/TelegramListener.cs b/common/services/ASC.TelegramService/TelegramListener.cs index ba3eb4b87b..bd7ef699ee 100644 --- a/common/services/ASC.TelegramService/TelegramListener.cs +++ b/common/services/ASC.TelegramService/TelegramListener.cs @@ -28,18 +28,18 @@ namespace ASC.TelegramService [Singletone] public class TelegramListener { - private IEventBus<NotifyMessage> CacheMessage { get; } - private IEventBus<RegisterUserProto> CacheRegisterUser { get; } - private IEventBus<CreateClientProto> CacheCreateClient { get; } - private IEventBus<DisableClientProto> CacheDisableClient { get; } + private ICacheNotify<NotifyMessage> CacheMessage { get; } + private ICacheNotify<RegisterUserProto> CacheRegisterUser { get; } + private ICacheNotify<CreateClientProto> CacheCreateClient { get; } + private ICacheNotify<DisableClientProto> CacheDisableClient { get; } private TelegramHandler TelegramHandler { get; set; } - public TelegramListener(IEventBus<NotifyMessage> cacheMessage, - IEventBus<RegisterUserProto> cacheRegisterUser, - IEventBus<CreateClientProto> cacheCreateClient, + public TelegramListener(ICacheNotify<NotifyMessage> cacheMessage, + ICacheNotify<RegisterUserProto> cacheRegisterUser, + ICacheNotify<CreateClientProto> cacheCreateClient, TelegramHandler telegramHandler, - IEventBus<DisableClientProto> cacheDisableClient) + ICacheNotify<DisableClientProto> cacheDisableClient) { CacheMessage = cacheMessage; CacheRegisterUser = cacheRegisterUser; @@ -51,19 +51,19 @@ namespace ASC.TelegramService public void Start() { - CacheMessage.Subscribe(async n => await SendMessage(n), EventType.Insert); - CacheRegisterUser.Subscribe(n => RegisterUser(n), EventType.Insert); - CacheCreateClient.Subscribe(n => CreateOrUpdateClient(n), EventType.Insert); - CacheDisableClient.Subscribe(n => DisableClient(n), EventType.Insert); + CacheMessage.Subscribe(async n => await SendMessage(n), CacheNotifyAction.Insert); + CacheRegisterUser.Subscribe(n => RegisterUser(n), CacheNotifyAction.Insert); + CacheCreateClient.Subscribe(n => CreateOrUpdateClient(n), CacheNotifyAction.Insert); + CacheDisableClient.Subscribe(n => DisableClient(n), CacheNotifyAction.Insert); } public void Stop() { - CacheMessage.Unsubscribe(EventType.Insert); - CacheRegisterUser.Unsubscribe(EventType.Insert); - CacheCreateClient.Unsubscribe(EventType.Insert); - CacheDisableClient.Unsubscribe(EventType.Insert); + CacheMessage.Unsubscribe(CacheNotifyAction.Insert); + CacheRegisterUser.Unsubscribe(CacheNotifyAction.Insert); + CacheCreateClient.Unsubscribe(CacheNotifyAction.Insert); + CacheDisableClient.Unsubscribe(CacheNotifyAction.Insert); } private void DisableClient(DisableClientProto n) diff --git a/common/services/ASC.Webhooks.Service/BuildQueueService.cs b/common/services/ASC.Webhooks.Service/BuildQueueService.cs index 9c44f4bf76..e213b8a8d4 100644 --- a/common/services/ASC.Webhooks.Service/BuildQueueService.cs +++ b/common/services/ASC.Webhooks.Service/BuildQueueService.cs @@ -4,9 +4,9 @@ public class BuildQueueService { internal ConcurrentQueue<WebhookRequest> Queue { get; } - private IEventBus<WebhookRequest> WebhookNotify { get; } + private ICacheNotify<WebhookRequest> WebhookNotify { get; } - public BuildQueueService(IEventBus<WebhookRequest> webhookNotify) + public BuildQueueService(ICacheNotify<WebhookRequest> webhookNotify) { WebhookNotify = webhookNotify; Queue = new ConcurrentQueue<WebhookRequest>(); @@ -14,12 +14,12 @@ public void Start() { - WebhookNotify.Subscribe(BuildWebhooksQueue, EventType.Update); + WebhookNotify.Subscribe(BuildWebhooksQueue, CacheNotifyAction.Update); } public void Stop() { - WebhookNotify.Unsubscribe(EventType.Update); + WebhookNotify.Unsubscribe(CacheNotifyAction.Update); } public void BuildWebhooksQueue(WebhookRequest request) diff --git a/common/services/ASC.Webhooks.Service/Program.cs b/common/services/ASC.Webhooks.Service/Program.cs index ee46096cd1..7a78f6d46b 100644 --- a/common/services/ASC.Webhooks.Service/Program.cs +++ b/common/services/ASC.Webhooks.Service/Program.cs @@ -53,17 +53,17 @@ namespace ASC.Webhooks.Service if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCacheNotify<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCacheNotify<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); } diHelper.TryAdd<DbWorker>(); diff --git a/products/ASC.Files/Core/Core/FileStorageService.cs b/products/ASC.Files/Core/Core/FileStorageService.cs index 7743db549b..16e1715c7c 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -71,7 +71,7 @@ namespace ASC.Web.Files.Services.WCFService private FileOperationsManager FileOperationsManager { get; } private TenantManager TenantManager { get; } private FileTrackerHelper FileTracker { get; } - private IEventBus<ThumbnailRequest> ThumbnailNotify { get; } + private ICacheNotify<ThumbnailRequest> ThumbnailNotify { get; } private EntryStatusManager EntryStatusManager { get; } public CompressToArchive CompressToArchive { get; } private ILog Logger { get; set; } @@ -117,7 +117,7 @@ namespace ASC.Web.Files.Services.WCFService FileOperationsManager fileOperationsManager, TenantManager tenantManager, FileTrackerHelper fileTracker, - IEventBus<ThumbnailRequest> thumbnailNotify, + ICacheNotify<ThumbnailRequest> thumbnailNotify, EntryStatusManager entryStatusManager, CompressToArchive compressToArchive) { @@ -2322,7 +2322,7 @@ namespace ASC.Web.Files.Services.WCFService req.Files.Add(f); } - ThumbnailNotify.Publish(req, Common.Caching.EventType.Insert); + ThumbnailNotify.Publish(req, Common.Caching.CacheNotifyAction.Insert); } catch (Exception e) { diff --git a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxProviderInfo.cs index a82f91c23f..38dc3d41e7 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Box/BoxProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Box/BoxProviderInfo.cs @@ -204,9 +204,9 @@ namespace ASC.Files.Thirdparty.Box private readonly ICache CacheFile; private readonly ICache CacheFolder; private readonly ICache CacheChildItems; - private readonly IEventBus<BoxCacheItem> CacheNotify; + private readonly ICacheNotify<BoxCacheItem> CacheNotify; - public BoxProviderInfoHelper(IEventBus<BoxCacheItem> cacheNotify, ICache cache) + public BoxProviderInfoHelper(ICacheNotify<BoxCacheItem> cacheNotify, ICache cache) { CacheFile = cache; CacheFolder = cache; @@ -238,7 +238,7 @@ namespace ASC.Files.Thirdparty.Box CacheFolder.Remove("boxd-" + i.Key); } } - }, Common.Caching.EventType.Remove); + }, Common.Caching.CacheNotifyAction.Remove); } internal BoxFolder GetBoxFolder(BoxStorage storage, int id, string boxFolderId) @@ -281,7 +281,7 @@ namespace ASC.Files.Thirdparty.Box { if (boxItem != null) { - CacheNotify.Publish(new BoxCacheItem { IsFile = boxItem is BoxFile, Key = id + "-" + boxItem.Id }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new BoxCacheItem { IsFile = boxItem is BoxFile, Key = id + "-" + boxItem.Id }, Common.Caching.CacheNotifyAction.Remove); } } @@ -290,7 +290,7 @@ namespace ASC.Files.Thirdparty.Box var key = id + "-"; if (boxId == null) { - CacheNotify.Publish(new BoxCacheItem { ResetAll = true, Key = key }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new BoxCacheItem { ResetAll = true, Key = key }, Common.Caching.CacheNotifyAction.Remove); } else { @@ -300,7 +300,7 @@ namespace ASC.Files.Thirdparty.Box } key += boxId; - CacheNotify.Publish(new BoxCacheItem { IsFile = isFile ?? false, IsFileExists = isFile.HasValue, Key = key }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new BoxCacheItem { IsFile = isFile ?? false, IsFileExists = isFile.HasValue, Key = key }, Common.Caching.CacheNotifyAction.Remove); } } } diff --git a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxProviderInfo.cs index 41eb2d8380..e30131a16d 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/Dropbox/DropboxProviderInfo.cs @@ -171,9 +171,9 @@ namespace ASC.Files.Thirdparty.Dropbox private readonly ICache CacheFile; private readonly ICache CacheFolder; private readonly ICache CacheChildItems; - private readonly IEventBus<DropboxCacheItem> CacheNotify; + private readonly ICacheNotify<DropboxCacheItem> CacheNotify; - public DropboxProviderInfoHelper(IEventBus<DropboxCacheItem> cacheNotify, ICache cache) + public DropboxProviderInfoHelper(ICacheNotify<DropboxCacheItem> cacheNotify, ICache cache) { CacheExpiration = TimeSpan.FromMinutes(1); CacheFile = cache; @@ -207,7 +207,7 @@ namespace ASC.Files.Thirdparty.Dropbox CacheFolder.Remove("dropboxd-" + i.Key); } } - }, Common.Caching.EventType.Remove); + }, Common.Caching.CacheNotifyAction.Remove); } internal FolderMetadata GetDropboxFolder(DropboxStorage storage, int id, string dropboxFolderPath) @@ -250,7 +250,7 @@ namespace ASC.Files.Thirdparty.Dropbox { if (dropboxItem != null) { - CacheNotify.Publish(new DropboxCacheItem { IsFile = dropboxItem.AsFolder != null, Key = id + "-" + dropboxItem.PathDisplay }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new DropboxCacheItem { IsFile = dropboxItem.AsFolder != null, Key = id + "-" + dropboxItem.PathDisplay }, Common.Caching.CacheNotifyAction.Remove); } } @@ -259,13 +259,13 @@ namespace ASC.Files.Thirdparty.Dropbox var key = id + "-"; if (dropboxPath == null) { - CacheNotify.Publish(new DropboxCacheItem { ResetAll = true, Key = key }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new DropboxCacheItem { ResetAll = true, Key = key }, Common.Caching.CacheNotifyAction.Remove); } else { key += dropboxPath; - CacheNotify.Publish(new DropboxCacheItem { IsFile = isFile ?? false, IsFileExists = isFile.HasValue, Key = key }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new DropboxCacheItem { IsFile = isFile ?? false, IsFileExists = isFile.HasValue, Key = key }, Common.Caching.CacheNotifyAction.Remove); } } } diff --git a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs index cf5be340ff..d8229d79cb 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/GoogleDrive/GoogleDriveProviderInfo.cs @@ -213,9 +213,9 @@ namespace ASC.Files.Thirdparty.GoogleDrive private readonly ICache CacheEntry; private readonly ICache CacheChildFiles; private readonly ICache CacheChildFolders; - private readonly IEventBus<GoogleDriveCacheItem> CacheNotify; + private readonly ICacheNotify<GoogleDriveCacheItem> CacheNotify; - public GoogleDriveProviderInfoHelper(IEventBus<GoogleDriveCacheItem> cacheNotify, ICache cache) + public GoogleDriveProviderInfoHelper(ICacheNotify<GoogleDriveCacheItem> cacheNotify, ICache cache) { CacheExpiration = TimeSpan.FromMinutes(1); CacheEntry = cache; @@ -246,7 +246,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive CacheChildFolders.Remove("drived-" + i.Key); } } - }, Common.Caching.EventType.Remove); + }, Common.Caching.CacheNotifyAction.Remove); } internal DriveFile GetDriveEntry(GoogleDriveStorage storage, int id, string driveId) @@ -319,7 +319,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive { if (driveEntry != null) { - CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, Key = id + "-" + driveEntry.Id }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, Key = id + "-" + driveEntry.Id }, Common.Caching.CacheNotifyAction.Remove); } } @@ -328,7 +328,7 @@ namespace ASC.Files.Thirdparty.GoogleDrive var key = id + "-"; if (driveId == null) { - CacheNotify.Publish(new GoogleDriveCacheItem { ResetAll = true, Key = key }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new GoogleDriveCacheItem { ResetAll = true, Key = key }, Common.Caching.CacheNotifyAction.Remove); } else { @@ -338,13 +338,13 @@ namespace ASC.Files.Thirdparty.GoogleDrive } key += driveId; - CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, ResetChilds = true, Key = key, ChildFolder = childFolder ?? false, ChildFolderExist = childFolder.HasValue }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new GoogleDriveCacheItem { ResetEntry = true, ResetChilds = true, Key = key, ChildFolder = childFolder ?? false, ChildFolderExist = childFolder.HasValue }, Common.Caching.CacheNotifyAction.Remove); } } internal void CacheResetChilds(int id, string parentDriveId, bool? childFolder = null) { - CacheNotify.Publish(new GoogleDriveCacheItem { ResetChilds = true, Key = id + "-" + parentDriveId, ChildFolder = childFolder ?? false, ChildFolderExist = childFolder.HasValue }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new GoogleDriveCacheItem { ResetChilds = true, Key = id + "-" + parentDriveId, ChildFolder = childFolder ?? false, ChildFolderExist = childFolder.HasValue }, Common.Caching.CacheNotifyAction.Remove); } } diff --git a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs index 3640144d08..48498b1bf4 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/OneDrive/OneDriveProviderInfo.cs @@ -178,9 +178,9 @@ namespace ASC.Files.Thirdparty.OneDrive private readonly TimeSpan CacheExpiration; private readonly ICache CacheItem; private readonly ICache CacheChildItems; - private readonly IEventBus<OneDriveCacheItem> CacheNotify; + private readonly ICacheNotify<OneDriveCacheItem> CacheNotify; - public OneDriveProviderInfoHelper(IEventBus<OneDriveCacheItem> cacheNotify, ICache cache) + public OneDriveProviderInfoHelper(ICacheNotify<OneDriveCacheItem> cacheNotify, ICache cache) { CacheExpiration = TimeSpan.FromMinutes(1); CacheItem = cache; @@ -199,7 +199,7 @@ namespace ASC.Files.Thirdparty.OneDrive CacheChildItems.Remove(new Regex("onedrivei-" + i.Key)); CacheItem.Remove("onedrive-" + i.Key); } - }, Common.Caching.EventType.Remove); + }, Common.Caching.CacheNotifyAction.Remove); } internal Item GetOneDriveItem(OneDriveStorage storage, int id, string itemId) @@ -231,13 +231,13 @@ namespace ASC.Files.Thirdparty.OneDrive var key = id + "-"; if (string.IsNullOrEmpty(onedriveId)) { - CacheNotify.Publish(new OneDriveCacheItem { ResetAll = true, Key = key }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new OneDriveCacheItem { ResetAll = true, Key = key }, Common.Caching.CacheNotifyAction.Remove); } else { key += onedriveId; - CacheNotify.Publish(new OneDriveCacheItem { Key = key }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new OneDriveCacheItem { Key = key }, Common.Caching.CacheNotifyAction.Remove); } } } diff --git a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs index 40e53f76e1..394eeccdd9 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/SharePoint/SharePointProviderInfo.cs @@ -587,9 +587,9 @@ namespace ASC.Files.Thirdparty.SharePoint private readonly TimeSpan CacheExpiration; private readonly ICache FileCache; private readonly ICache FolderCache; - private readonly IEventBus<SharePointProviderCacheItem> Notify; + private readonly ICacheNotify<SharePointProviderCacheItem> Notify; - public SharePointProviderInfoHelper(IEventBus<SharePointProviderCacheItem> notify, ICache cache) + public SharePointProviderInfoHelper(ICacheNotify<SharePointProviderCacheItem> notify, ICache cache) { CacheExpiration = TimeSpan.FromMinutes(1); FileCache = cache; @@ -611,16 +611,16 @@ namespace ASC.Files.Thirdparty.SharePoint FileCache.Remove(new Regex("^spointf-.*")); FolderCache.Remove(new Regex("^spointd-.*")); } - }, Common.Caching.EventType.Remove); + }, Common.Caching.CacheNotifyAction.Remove); } public void Invalidate() { - Notify.Publish(new SharePointProviderCacheItem { }, Common.Caching.EventType.Remove); + Notify.Publish(new SharePointProviderCacheItem { }, Common.Caching.CacheNotifyAction.Remove); } public void PublishFolder(string id) { - Notify.Publish(new SharePointProviderCacheItem { FolderKey = id }, Common.Caching.EventType.Remove); + Notify.Publish(new SharePointProviderCacheItem { FolderKey = id }, Common.Caching.CacheNotifyAction.Remove); } public void PublishFolder(string id1, string id2) @@ -637,7 +637,7 @@ namespace ASC.Files.Thirdparty.SharePoint public void PublishFile(string fileId, string folderId) { - Notify.Publish(new SharePointProviderCacheItem { FileKey = fileId, FolderKey = folderId }, Common.Caching.EventType.Remove); + Notify.Publish(new SharePointProviderCacheItem { FileKey = fileId, FolderKey = folderId }, Common.Caching.CacheNotifyAction.Remove); } public void CreateFolder(string id, string parentFolderId, Folder folder) diff --git a/products/ASC.Files/Core/Helpers/EasyBibHelper.cs b/products/ASC.Files/Core/Helpers/EasyBibHelper.cs index c7850ff515..ad7465cc24 100644 --- a/products/ASC.Files/Core/Helpers/EasyBibHelper.cs +++ b/products/ASC.Files/Core/Helpers/EasyBibHelper.cs @@ -58,7 +58,7 @@ namespace ASC.Web.Files.Helpers CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory factory, string name, int order, diff --git a/products/ASC.Files/Core/Helpers/Global.cs b/products/ASC.Files/Core/Helpers/Global.cs index 5d30d85f78..ff509d5452 100644 --- a/products/ASC.Files/Core/Helpers/Global.cs +++ b/products/ASC.Files/Core/Helpers/Global.cs @@ -28,10 +28,10 @@ namespace ASC.Web.Files.Classes [Singletone] public class GlobalNotify { - private IEventBus<AscCacheItem> Notify { get; set; } + private ICacheNotify<AscCacheItem> Notify { get; set; } public ILog Logger { get; set; } - public GlobalNotify(IEventBus<AscCacheItem> notify, IOptionsMonitor<ILog> options, CoreBaseSettings coreBaseSettings) + public GlobalNotify(ICacheNotify<AscCacheItem> notify, IOptionsMonitor<ILog> options, CoreBaseSettings coreBaseSettings) { Notify = notify; Logger = options.Get("ASC.Files"); @@ -63,7 +63,7 @@ namespace ASC.Web.Files.Classes { Logger.Fatal("ClearCache action", e); } - }, Common.Caching.EventType.Any); + }, Common.Caching.CacheNotifyAction.Any); } catch (Exception e) { diff --git a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs index c8e01bec22..964e055884 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -98,7 +98,7 @@ namespace ASC.Web.Files.ThirdPartyApp CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IHttpClientFactory clientFactory, string name, int order, Dictionary<string, string> additional) diff --git a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs index 1a06dcf2fd..6d237f4af0 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -109,7 +109,7 @@ namespace ASC.Web.Files.ThirdPartyApp CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IHttpClientFactory clientFactory, string name, int order, Dictionary<string, string> additional) diff --git a/products/ASC.Files/Service/Program.cs b/products/ASC.Files/Service/Program.cs index c0cb59b358..3ce086e66e 100644 --- a/products/ASC.Files/Service/Program.cs +++ b/products/ASC.Files/Service/Program.cs @@ -56,17 +56,17 @@ if (kafkaConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusKafka<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(KafkaCacheNotify<>)); } else if (redisConfiguration != null) { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusRedis<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(RedisCacheNotify<>)); services.AddStackExchangeRedisExtensions<NewtonsoftSerializer>(redisConfiguration); } else { - diHelper.TryAdd(typeof(IEventBus<>), typeof(EventBusMemoryCache<>)); + diHelper.TryAdd(typeof(ICacheNotify<>), typeof(MemoryCacheNotify<>)); } diff --git a/products/ASC.Files/Service/Thumbnail/Service.cs b/products/ASC.Files/Service/Thumbnail/Service.cs index 46108fe50a..a8858f7623 100644 --- a/products/ASC.Files/Service/Thumbnail/Service.cs +++ b/products/ASC.Files/Service/Thumbnail/Service.cs @@ -19,22 +19,22 @@ namespace ASC.Files.ThumbnailBuilder [Singletone] public class Service { - private IEventBus<ThumbnailRequest> CacheNotify { get; } + private ICacheNotify<ThumbnailRequest> CacheNotify { get; } - public Service(IEventBus<ThumbnailRequest> cacheNotify) + public Service(ICacheNotify<ThumbnailRequest> cacheNotify) { CacheNotify = cacheNotify; } public void Start() { - CacheNotify.Subscribe(BuildThumbnails, EventType.Insert); + CacheNotify.Subscribe(BuildThumbnails, CacheNotifyAction.Insert); //Cache.Subscribe } public void Stop() { - CacheNotify.Unsubscribe(EventType.Insert); + CacheNotify.Unsubscribe(CacheNotifyAction.Insert); //Cache.Subscribe } diff --git a/web/ASC.Web.Api/Controllers/SettingsController.cs b/web/ASC.Web.Api/Controllers/SettingsController.cs index 29c03bf466..f1125defd5 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -91,7 +91,7 @@ namespace ASC.Api.Settings private EncryptionServiceClient EncryptionServiceClient { get; } private EncryptionSettingsHelper EncryptionSettingsHelper { get; } private BackupAjaxHandler BackupAjaxHandler { get; } - private IEventBus<DeleteSchedule> CacheDeleteSchedule { get; } + private ICacheNotify<DeleteSchedule> CacheDeleteSchedule { get; } private EncryptionWorker EncryptionWorker { get; } private PasswordHasher PasswordHasher { get; } private ILog Log { get; set; } @@ -159,7 +159,7 @@ namespace ASC.Api.Settings EncryptionServiceClient encryptionServiceClient, EncryptionSettingsHelper encryptionSettingsHelper, BackupAjaxHandler backupAjaxHandler, - IEventBus<DeleteSchedule> cacheDeleteSchedule, + ICacheNotify<DeleteSchedule> cacheDeleteSchedule, EncryptionWorker encryptionWorker, PasswordHasher passwordHasher, PaymentManager paymentManager, @@ -2260,7 +2260,7 @@ namespace ASC.Api.Settings foreach (var tenant in tenants) { - CacheDeleteSchedule.Publish(new DeleteSchedule() { TenantId = tenant.TenantId }, Common.Caching.EventType.Insert); + CacheDeleteSchedule.Publish(new DeleteSchedule() { TenantId = tenant.TenantId }, Common.Caching.CacheNotifyAction.Insert); } var settings = EncryptionSettingsHelper.Load(); diff --git a/web/ASC.Web.Core/Jabber/FireBase.cs b/web/ASC.Web.Core/Jabber/FireBase.cs index dcab09516e..57b4fef6dc 100644 --- a/web/ASC.Web.Core/Jabber/FireBase.cs +++ b/web/ASC.Web.Core/Jabber/FireBase.cs @@ -56,7 +56,7 @@ namespace ASC.Web.Core.Jabber CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, string name, int order, Dictionary<string, string> props, Dictionary<string, string> additional = null) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, props, additional) diff --git a/web/ASC.Web.Core/Mail/MailServiceHelper.cs b/web/ASC.Web.Core/Mail/MailServiceHelper.cs index bec4505216..10c417da16 100644 --- a/web/ASC.Web.Core/Mail/MailServiceHelper.cs +++ b/web/ASC.Web.Core/Mail/MailServiceHelper.cs @@ -29,18 +29,18 @@ namespace ASC.Web.Core.Mail { public class MailServiceHelperStorage { - private IEventBus<MailServiceHelperCache> CacheNotify { get; } + private ICacheNotify<MailServiceHelperCache> CacheNotify { get; } public ICache Cache { get; } - public MailServiceHelperStorage(IEventBus<MailServiceHelperCache> cacheNotify, ICache cache) + public MailServiceHelperStorage(ICacheNotify<MailServiceHelperCache> cacheNotify, ICache cache) { Cache = cache; CacheNotify = cacheNotify; - CacheNotify.Subscribe(r => Cache.Remove(r.Key), Common.Caching.EventType.Remove); + CacheNotify.Subscribe(r => Cache.Remove(r.Key), Common.Caching.CacheNotifyAction.Remove); } public void Remove() { - CacheNotify.Publish(new MailServiceHelperCache() { Key = MailServiceHelper.CacheKey }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new MailServiceHelperCache() { Key = MailServiceHelper.CacheKey }, Common.Caching.CacheNotifyAction.Remove); } } diff --git a/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs b/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs index d87341a429..93a0053070 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyServiceHelper.cs @@ -3,7 +3,7 @@ [Scope] public class StudioNotifyServiceHelper { - private IEventBus<NotifyItem> Cache { get; } + private ICacheNotify<NotifyItem> Cache { get; } private StudioNotifyHelper StudioNotifyHelper { get; } private AuthContext AuthContext { get; } private TenantManager TenantManager { get; } @@ -14,7 +14,7 @@ AuthContext authContext, TenantManager tenantManager, CommonLinkUtility commonLinkUtility, - IEventBus<NotifyItem> cache) + ICacheNotify<NotifyItem> cache) { StudioNotifyHelper = studioNotifyHelper; AuthContext = authContext; @@ -107,7 +107,7 @@ item.Tags.AddRange(args.Select(r => new Tag { Tag_ = r.Tag, Value = r.Value.ToString() })); } - Cache.Publish(item, EventType.Any); + Cache.Publish(item, CacheNotifyAction.Any); } } } \ No newline at end of file diff --git a/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs b/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs index 24e50e39d3..4569f704cf 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs @@ -35,9 +35,9 @@ namespace ASC.Web.Studio.Core.Notify private IServiceProvider ServiceProvider { get; } private IConfiguration Configuration { get; } - public StudioNotifyServiceSender(IServiceProvider serviceProvider, IConfiguration configuration, IEventBus<NotifyItem> cache) + public StudioNotifyServiceSender(IServiceProvider serviceProvider, IConfiguration configuration, ICacheNotify<NotifyItem> cache) { - cache.Subscribe(this.OnMessage, Common.Caching.EventType.Any); + cache.Subscribe(this.OnMessage, Common.Caching.CacheNotifyAction.Any); ServiceProvider = serviceProvider; Configuration = configuration; } diff --git a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs index 0e26f1838d..2d3aaf64c7 100644 --- a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs +++ b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs @@ -28,21 +28,21 @@ namespace ASC.Web.Core.Sms [Singletone] public class SmsKeyStorageCache { - private IEventBus<SmsKeyCacheKey> KeyCacheNotify { get; } + private ICacheNotify<SmsKeyCacheKey> KeyCacheNotify { get; } public ICache KeyCache { get; } public ICache CheckCache { get; } - public SmsKeyStorageCache(IEventBus<SmsKeyCacheKey> keyCacheNotify, ICache cache) + public SmsKeyStorageCache(ICacheNotify<SmsKeyCacheKey> keyCacheNotify, ICache cache) { CheckCache = cache; KeyCache = cache; KeyCacheNotify = keyCacheNotify; - KeyCacheNotify.Subscribe(r => KeyCache.Remove(r.Key), Common.Caching.EventType.Remove); + KeyCacheNotify.Subscribe(r => KeyCache.Remove(r.Key), Common.Caching.CacheNotifyAction.Remove); } public void RemoveFromCache(string cacheKey) { - KeyCacheNotify.Publish(new SmsKeyCacheKey { Key = cacheKey }, Common.Caching.EventType.Remove); + KeyCacheNotify.Publish(new SmsKeyCacheKey { Key = cacheKey }, Common.Caching.CacheNotifyAction.Remove); } } diff --git a/web/ASC.Web.Core/Sms/SmsProvider.cs b/web/ASC.Web.Core/Sms/SmsProvider.cs index 72019cf29e..4f1b77e6b4 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -111,7 +111,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, IHttpClientFactory clientFactory, @@ -180,7 +180,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, IHttpClientFactory clientFactory, @@ -317,7 +317,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, IHttpClientFactory clientFactory, @@ -339,7 +339,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, IHttpClientFactory clientFactory, @@ -419,7 +419,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, IHttpClientFactory clientFactory, @@ -471,7 +471,7 @@ namespace ASC.Web.Core.Sms CoreBaseSettings coreBaseSettings, CoreSettings coreSettings, IConfiguration configuration, - IEventBus<ConsumerCacheItem> cache, + ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, IHttpClientFactory clientFactory, diff --git a/web/ASC.Web.Core/Users/UserPhotoManager.cs b/web/ASC.Web.Core/Users/UserPhotoManager.cs index 81acf800f7..6f9251c716 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -80,10 +80,10 @@ namespace ASC.Web.Core.Users public class UserPhotoManagerCache { private readonly ConcurrentDictionary<CacheSize, ConcurrentDictionary<Guid, string>> Photofiles; - private readonly IEventBus<UserPhotoManagerCacheItem> CacheNotify; + private readonly ICacheNotify<UserPhotoManagerCacheItem> CacheNotify; private readonly HashSet<int> TenantDiskCache; - public UserPhotoManagerCache(IEventBus<UserPhotoManagerCacheItem> notify) + public UserPhotoManagerCache(ICacheNotify<UserPhotoManagerCacheItem> notify) { try { @@ -95,7 +95,7 @@ namespace ASC.Web.Core.Users { var userId = new Guid(data.UserId); Photofiles.GetOrAdd(data.Size, (r) => new ConcurrentDictionary<Guid, string>())[userId] = data.FileName; - }, Common.Caching.EventType.InsertOrUpdate); + }, Common.Caching.CacheNotifyAction.InsertOrUpdate); CacheNotify.Subscribe((data) => { @@ -111,7 +111,7 @@ namespace ASC.Web.Core.Users SetCacheLoadedForTenant(false, data.TenantId); } catch { } - }, Common.Caching.EventType.Remove); + }, Common.Caching.CacheNotifyAction.Remove); } catch (Exception) { @@ -133,7 +133,7 @@ namespace ASC.Web.Core.Users { if (CacheNotify != null) { - CacheNotify.Publish(new UserPhotoManagerCacheItem { UserId = userID.ToString(), TenantId = tenantId }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new UserPhotoManagerCacheItem { UserId = userID.ToString(), TenantId = tenantId }, Common.Caching.CacheNotifyAction.Remove); } } @@ -141,7 +141,7 @@ namespace ASC.Web.Core.Users { if (CacheNotify != null) { - CacheNotify.Publish(new UserPhotoManagerCacheItem { UserId = userID.ToString(), Size = UserPhotoManager.ToCache(size), FileName = fileName, TenantId = tenantId }, Common.Caching.EventType.InsertOrUpdate); + CacheNotify.Publish(new UserPhotoManagerCacheItem { UserId = userID.ToString(), Size = UserPhotoManager.ToCache(size), FileName = fileName, TenantId = tenantId }, Common.Caching.CacheNotifyAction.InsertOrUpdate); } } diff --git a/web/ASC.Web.Core/WebItemSecurity.cs b/web/ASC.Web.Core/WebItemSecurity.cs index fe91d59df5..3361ca2e29 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -32,16 +32,16 @@ namespace ASC.Web.Core public class WebItemSecurityCache { private ICache Cache { get; } - private IEventBus<WebItemSecurityNotifier> CacheNotify { get; } + private ICacheNotify<WebItemSecurityNotifier> CacheNotify { get; } - public WebItemSecurityCache(IEventBus<WebItemSecurityNotifier> cacheNotify, ICache cache) + public WebItemSecurityCache(ICacheNotify<WebItemSecurityNotifier> cacheNotify, ICache cache) { Cache = cache; CacheNotify = cacheNotify; CacheNotify.Subscribe((r) => { ClearCache(r.Tenant); - }, Common.Caching.EventType.Any); + }, Common.Caching.CacheNotifyAction.Any); } public void ClearCache(int tenantId) @@ -56,7 +56,7 @@ namespace ASC.Web.Core public void Publish(int tenantId) { - CacheNotify.Publish(new WebItemSecurityNotifier { Tenant = tenantId }, Common.Caching.EventType.Any); + CacheNotify.Publish(new WebItemSecurityNotifier { Tenant = tenantId }, Common.Caching.CacheNotifyAction.Any); } public Dictionary<string, bool> Get(int tenantId) diff --git a/web/ASC.Web.Core/WhiteLabel/TenantLogoManager.cs b/web/ASC.Web.Core/WhiteLabel/TenantLogoManager.cs index df17f2ee77..6884e4cc44 100644 --- a/web/ASC.Web.Core/WhiteLabel/TenantLogoManager.cs +++ b/web/ASC.Web.Core/WhiteLabel/TenantLogoManager.cs @@ -40,7 +40,7 @@ namespace ASC.Web.Core.WhiteLabel } private ICache Cache { get; } - private IEventBus<TenantLogoCacheItem> CacheNotify { get; } + private ICacheNotify<TenantLogoCacheItem> CacheNotify { get; } public TenantLogoManager( TenantWhiteLabelSettingsHelper tenantWhiteLabelSettingsHelper, @@ -49,7 +49,7 @@ namespace ASC.Web.Core.WhiteLabel TenantManager tenantManager, AuthContext authContext, IConfiguration configuration, - IEventBus<TenantLogoCacheItem> cacheNotify, + ICacheNotify<TenantLogoCacheItem> cacheNotify, ICache cache) { TenantWhiteLabelSettingsHelper = tenantWhiteLabelSettingsHelper; @@ -203,7 +203,7 @@ namespace ASC.Web.Core.WhiteLabel public void RemoveMailLogoDataFromCache() { - CacheNotify.Publish(new TenantLogoCacheItem() { Key = CacheKey }, Common.Caching.EventType.Remove); + CacheNotify.Publish(new TenantLogoCacheItem() { Key = CacheKey }, Common.Caching.CacheNotifyAction.Remove); } } } \ No newline at end of file