From 352a8b61ff2dfa7a6f3d5fd90f30aea0b2e83771 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 14:54:10 +0300 Subject: [PATCH 001/105] 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 12d60adc64f..dbf971f48f0 100644 --- a/products/ASC.Files/Core/Core/Entries/ChunkedUploadSession.cs +++ b/products/ASC.Files/Core/Core/Entries/ChunkedUploadSession.cs @@ -76,7 +76,7 @@ public override Stream Serialize() public static ChunkedUploadSession<T> Deserialize(Stream stream, FileHelper fileHelper) { - var chunkedUploadSession = JsonSerializer.DeserializeAsync<ChunkedUploadSession<T>>(stream).Result; + var chunkedUploadSession = JsonSerializer.Deserialize<ChunkedUploadSession<T>>(stream); chunkedUploadSession.File.FileHelper = fileHelper; chunkedUploadSession.TransformItems(); return chunkedUploadSession; From 0a786bbfa3231a951bb8b6f0c0130321d5a5e0a1 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 15:00:48 +0300 Subject: [PATCH 002/105] 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 5fd7cc11d71..059a69b4da4 100644 --- a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs @@ -288,9 +288,6 @@ private MailKit.Net.Smtp.SmtpClient GetSmtpClient() { 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 0a17496f970..7575a48260f 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -1177,15 +1177,7 @@ private File<T> CreateFileFromUri<T>(Folder<T> folder, string fileUri, string fi 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<T>(); 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 2cab654676e..7278d24d28e 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -498,12 +498,6 @@ private TrackResponse ProcessMailMerge<T>(T fileId, TrackerData fileData) 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 @@ private TrackResponse ProcessMailMerge<T>(T fileId, TrackerData fileData) 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 @@ private void StoringFileAfterError<T>(T fileId, string userId, string downloadUr 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 @@ private void SaveHistory<T>(File<T> file, string changes, string differenceUrl) { var fileDao = DaoFactory.GetFileDao<T>(); 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 05f85564ba8..bc487297c70 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -1004,11 +1004,6 @@ public File<T> SaveEditing<T>(T fileId, string fileExtension, string downloadUri } 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 bff69bf7815..05c79adf4f3 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -680,11 +680,7 @@ public Stream Exec<T>(File<T> file, string toExtension) 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 @@ public File<T> SaveConvertedFile<T>(File<T> file, string convertedFileUrl) 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 34d67a08453..b08b2c9c938 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -140,12 +140,6 @@ private string AttachToMail(MailMergeTask mailMergeTask) 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 cc8e8bc7927..1ba4b8f40a1 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -270,12 +270,6 @@ public object CreateUploadSession(T folderId, string fileName, long fileSize, st 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 7770a93606c..653aea59082 100644 --- a/products/ASC.Files/Service/Thumbnail/Builder.cs +++ b/products/ASC.Files/Service/Thumbnail/Builder.cs @@ -287,13 +287,7 @@ private void SaveThumbnail(IFileDao<T> fileDao, File<T> file, string thumbnailUr 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 759ab0693a6..e678767dae1 100644 --- a/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs +++ b/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs @@ -229,9 +229,6 @@ public SmtpClient GetSmtpClient() 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 fbb78005e80..9ca0b2ef155 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -171,12 +171,6 @@ public static int GetConvertedUri( 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 @@ public static CommandResultTypes CommandRequest(FileUtility fileUtility, 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 @@ public static string DocbuilderRequest( 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 <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 15:03:12 +0300 Subject: [PATCH 003/105] 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 36aea724039..971a6246fc2 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs @@ -82,7 +82,7 @@ public Stream GetThumbnail(File<string> file) public Task<Stream> GetThumbnailAsync(File<string> file) { - return null; + return Task.FromResult<Stream>(null); } public virtual Stream GetFileStream(File<string> file) From c3321206bd72a477c683628d18f3e9c85dafab9b Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 16:08:11 +0300 Subject: [PATCH 004/105] 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 165bc97dfc8..c7a45cadb3b 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -30,15 +30,13 @@ public class DbHelper : IDisposable private readonly DataTable columns; private readonly bool mysql; private readonly IDictionary<string, string> whereExceptions = new Dictionary<string, string>(); - private readonly ILog log; - private readonly BackupsContext backupsContext; + private readonly ILog log; private readonly TenantDbContext tenantDbContext; private readonly CoreDbContext coreDbContext; - public DbHelper(IOptionsMonitor<ILog> options, ConnectionStringSettings connectionString, BackupsContext backupsContext, TenantDbContext tenantDbContext, CoreDbContext coreDbContext) + public DbHelper(IOptionsMonitor<ILog> 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 <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 16:19:53 +0300 Subject: [PATCH 005/105] 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 63e2a93e707..14686197a3d 100644 --- a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs +++ b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs @@ -33,11 +33,16 @@ public bool IsConvertable(string extension) return MustConvertable.Contains(extension.TrimStart('.')); } - public async Task<Stream> Convert(Stream inputStream, string inputFormat) + public Task<Stream> 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<Stream> ConvertInternal(Stream inputStream, string inputFormat) + { var startInfo = PrepareFFmpeg(inputFormat); Process process; @@ -50,7 +55,7 @@ public async Task<Stream> Convert(Stream inputStream, string inputFormat) await ProcessLog(process.StandardError.BaseStream); return process.StandardOutput.BaseStream; - } + } } public FFmpegService(IOptionsMonitor<ILog> optionsMonitor, IConfiguration configuration) @@ -116,13 +121,18 @@ private ProcessStartInfo PrepareFFmpeg(string inputFormat) return startInfo; } - private static async Task<int> StreamCopyToAsync(Stream srcStream, Stream dstStream, bool closeSrc = false, bool closeDst = false) + private static Task<int> 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<int> 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 @@ private static async Task<int> StreamCopyToAsync(Stream srcStream, Stream dstStr dstStream.Close(); } - return total; + return total; } private async Task ProcessLog(Stream stream) From 28e1c652d9a0f75dd043844ff71b6793fc4f2be4 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 16:39:44 +0300 Subject: [PATCH 006/105] 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 c8243c91047..23e6934fc41 100644 --- a/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs +++ b/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs @@ -86,6 +86,11 @@ public static IEnumerable<IEnumerable<TEntry>> MakeParts<TEntry>(this IEnumerabl if (partLength <= 0) throw new ArgumentOutOfRangeException("partLength", partLength, "Length must be positive integer"); + return MakePartsIterator(collection, partLength); + } + + private static IEnumerable<IEnumerable<TEntry>> MakePartsIterator<TEntry>(this IEnumerable<TEntry> collection, int partLength) + { var part = new List<TEntry>(partLength); foreach (var entry in collection) From 6cd3a7bfe188ecb6bf17f625ff2ccd2030e40257 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 17:03:05 +0300 Subject: [PATCH 007/105] 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 9f6b15018a1..6ffa5009cea 100644 --- a/common/ASC.Common/Collections/CachedDictionaryBase.cs +++ b/common/ASC.Common/Collections/CachedDictionaryBase.cs @@ -106,7 +106,7 @@ public T Get(Func<T> @default) 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<T> defaults) diff --git a/products/ASC.Files/Core/Utils/FileConverter.cs b/products/ASC.Files/Core/Utils/FileConverter.cs index 05c79adf4f3..92746740ab7 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -265,8 +265,7 @@ private void CheckConvertFilesStatus(object _) } 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 <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 17:04:52 +0300 Subject: [PATCH 008/105] 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 17d7da9cde8..613d88a16a7 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -892,26 +892,14 @@ public EmployeeWraperFull DeleteProfile() [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 <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 18:44:54 +0300 Subject: [PATCH 009/105] 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 8a4e79495e6..125aead66e8 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -37,7 +37,7 @@ namespace ASC.Api.Core { [TypeConverter(typeof(ApiDateTimeTypeConverter))] - public class ApiDateTime : IComparable<ApiDateTime>, IComparable + public sealed class ApiDateTime : IComparable<ApiDateTime>, IComparable { internal static readonly string[] Formats = new[] { diff --git a/common/ASC.VoipService/VoipModel.cs b/common/ASC.VoipService/VoipModel.cs index 035cc313886..670da6de85b 100644 --- a/common/ASC.VoipService/VoipModel.cs +++ b/common/ASC.VoipService/VoipModel.cs @@ -90,7 +90,7 @@ public Queue(string id, string name, int size, string waitUrl, int waitTime) } } - 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 7172fa396f5..e6702feaf50 100644 --- a/products/ASC.Files/Core/Core/Entries/FileEntry.cs +++ b/products/ASC.Files/Core/Core/Entries/FileEntry.cs @@ -155,7 +155,7 @@ public override bool Equals(object obj) return obj is FileEntry<T> f && Equals(f.ID, ID); } - public bool Equals(FileEntry<T> obj) + public virtual bool Equals(FileEntry<T> 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 8f4f8668e33..246c8245947 100644 --- a/products/ASC.Files/Core/Core/Entries/Tag.cs +++ b/products/ASC.Files/Core/Core/Entries/Tag.cs @@ -42,7 +42,7 @@ public enum TagType [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 e60b91b47a8..8680bd8e50a 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -50,7 +50,7 @@ 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 <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 18:50:54 +0300 Subject: [PATCH 010/105] 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 d38c6f4e748..87f0181094e 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 @@ public override void RunJob(DistributedTask distributedTask, CancellationToken c using var scope = ThirdPartyOperation.CreateScope(); var scopeClass = scope.ServiceProvider.GetService<FileDownloadOperationScope>(); var (globalStore, filesLinkUtility, _, _, _) = scopeClass; - var stream = TempStream.Create(); + using var stream = TempStream.Create(); (ThirdPartyOperation as FileDownloadOperation<string>).CompressToZip(stream, scope); (DaoOperation as FileDownloadOperation<int>).CompressToZip(stream, scope); @@ -294,8 +294,6 @@ internal void CompressToZip(Stream stream, IServiceScope scope) { if (CancellationToken.IsCancellationRequested) { - compressTo.Dispose(); - stream.Dispose(); CancellationToken.ThrowIfCancellationRequested(); } From a40b06648a998f5d717252a767af797968d3850e Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 28 Dec 2021 19:01:12 +0300 Subject: [PATCH 011/105] 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 dbe2954ada2..1801ead8322 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -135,7 +135,7 @@ public void Configure(string name, DistributedTaskQueue options) 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 @@ public int MaxThreadsCount 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 531267bd95a..c2a048e8929 100644 --- a/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs +++ b/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs @@ -42,19 +42,13 @@ public class SubscriptionManager private TenantManager TenantManager { get; } private ICache Cache { get; set; } - public static readonly object CacheLocker; - public static readonly List<Guid> Groups; - - static SubscriptionManager() - { - CacheLocker = new object(); - Groups = new List<Guid> + public static readonly object CacheLocker = new object(); + public static readonly List<Guid> Groups = Groups = new List<Guid> { 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 b7000b5c1a6..0793bde6184 100644 --- a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs @@ -106,7 +106,7 @@ public void Configure(SignalrServiceClient options) [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 @@ public class SignalrServiceClient 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 00000000000..f05963afcc0 --- /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 7d16a6d47d8..512f33a7c8f 100644 --- a/web/ASC.Web.Core/Users/CustomNamingPeople.cs +++ b/web/ASC.Web.Core/Users/CustomNamingPeople.cs @@ -164,19 +164,12 @@ private static string GetResourceValue(string resourceKey) [Scope] public class CustomNamingPeople { - private static object Locked; + private static object Locked = new object(); private static bool loaded = false; private static readonly List<PeopleNamesItem> items = new List<PeopleNamesItem>(); private SettingsManager SettingsManager { get; } - static CustomNamingPeople() - { - Locked = new object(); - loaded = false; - items = new List<PeopleNamesItem>(); - } - public CustomNamingPeople(SettingsManager settingsManager) { SettingsManager = settingsManager; From 877095f5259ed64620de41dda4eb4e380d92a921 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 29 Dec 2021 17:40:19 +0300 Subject: [PATCH 012/105] 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 87f0181094e..61dc933b5bb 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 @@ public override void PublishChanges(DistributedTask task) 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 <anton.sukhorukov@onlyoffice.com> Date: Wed, 29 Dec 2021 17:41:02 +0300 Subject: [PATCH 013/105] 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 6c801e33f09..b3b990122f4 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -153,7 +153,6 @@ internal async Task<IEnumerable<AvangateProduct>> GetProducts() 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 <anton.sukhorukov@onlyoffice.com> Date: Wed, 29 Dec 2021 18:12:39 +0300 Subject: [PATCH 014/105] 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 76f919a932c..ade6cd21b58 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 @@ public void Configure(CoreSettings options) [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 687f2dcbe57..13bc6274b54 100644 --- a/products/ASC.Files/Core/Core/Entries/File.cs +++ b/products/ASC.Files/Core/Core/Entries/File.cs @@ -30,6 +30,7 @@ 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 @@ public File() 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 e6702feaf50..1370b91d3e3 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.Text.Json.Serialization; using ASC.Files.Core.Security; +using ASC.Web.Files.Classes; namespace ASC.Files.Core { @@ -37,14 +38,18 @@ public abstract class FileEntry : ICloneable [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 @@ public FileEntry(FileHelper fileHelper) 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 @@ public bool ProviderEntry public FileEntryType FileEntryType; - public string _modifiedByString; - public string _createByString; + private string _modifiedByString; + private string _createByString; public override string ToString() { @@ -127,7 +140,7 @@ protected FileEntry() } - 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 07700232a1e..db899371b39 100644 --- a/products/ASC.Files/Core/Core/Entries/FileHelper.cs +++ b/products/ASC.Files/Core/Core/Entries/FileHelper.cs @@ -54,16 +54,6 @@ public FileHelper(FileTrackerHelper fileTracker, FilesLinkUtility filesLinkUtili 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<T>(File<T> 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 2040de017bc..6a68c1b62d0 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.Diagnostics; using ASC.Common; +using ASC.Web.Files.Classes; namespace ASC.Files.Core { @@ -89,9 +90,10 @@ public Folder() 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 839c78c43ea..5f4209567cb 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -219,13 +219,13 @@ public File<string> GetFile(string fileId, out bool editable) var modifiedBy = jsonFile.Value<JObject>("modified_by"); if (modifiedBy != null) { - file._modifiedByString = modifiedBy.Value<string>("name"); + file.ModifiedByString = modifiedBy.Value<string>("name"); } var createdBy = jsonFile.Value<JObject>("created_by"); if (createdBy != null) { - file._createByString = createdBy.Value<string>("name"); + file.CreateByString = createdBy.Value<string>("name"); } diff --git a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs index 929d38b689c..63461d7b7e0 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -234,13 +234,13 @@ public File<string> GetFile(string fileId, out bool editable) file.CreateOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("createdTime")); file.ModifiedOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("modifiedTime")); file.ContentLength = Convert.ToInt64(jsonFile.Value<string>("size")); - file._modifiedByString = jsonFile["lastModifyingUser"]["displayName"].Value<string>(); + file.ModifiedByString = jsonFile["lastModifyingUser"]["displayName"].Value<string>(); file.ProviderKey = "Google"; var owners = jsonFile["owners"]; if (owners != null) { - file._createByString = owners[0]["displayName"].Value<string>(); + file.CreateByString = owners[0]["displayName"].Value<string>(); } editable = jsonFile["capabilities"]["canEdit"].Value<bool>(); From 973f8a41b9ae020cfd511cf8a449a6b747585d47 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 29 Dec 2021 18:47:35 +0300 Subject: [PATCH 015/105] 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 75c153b4149..f2a63c9f0c5 100644 --- a/common/ASC.Core.Common/BaseCommonLinkUtility.cs +++ b/common/ASC.Core.Common/BaseCommonLinkUtility.cs @@ -90,6 +90,9 @@ public BaseCommonLinkUtility( 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 @@ public string ServerRootPath 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 <anton.sukhorukov@onlyoffice.com> Date: Wed, 29 Dec 2021 18:49:02 +0300 Subject: [PATCH 016/105] analizators/s3903 --- common/ASC.Common/Data/StreamExtension.cs | 36 +++++++++++++---------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/common/ASC.Common/Data/StreamExtension.cs b/common/ASC.Common/Data/StreamExtension.cs index c856976971b..c27b05eee19 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 + +namespace ASC.Common.Data { - 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) + public static class StreamExtension { - 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) + 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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 30 Dec 2021 12:44:25 +0300 Subject: [PATCH 017/105] 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 297c40b75ed..43deeb9523d 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -272,7 +272,7 @@ private string Request(string method, string portalId, params Tuple<string, stri return result; } - var @params = (parameters ?? Enumerable.Empty<Tuple<string, string>>()).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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 30 Dec 2021 12:52:44 +0300 Subject: [PATCH 018/105] 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 b3b990122f4..fc8bcd932c7 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -154,7 +154,7 @@ internal async Task<IEnumerable<AvangateProduct>> GetProducts() 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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 30 Dec 2021 13:23:01 +0300 Subject: [PATCH 019/105] 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 b0ca20ff205..b602aed346d 100644 --- a/common/ASC.Core.Common/Context/SecurityContext.cs +++ b/common/ASC.Core.Common/Context/SecurityContext.cs @@ -134,6 +134,9 @@ public bool AuthenticateMe(string cookie) 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 @@ public bool AuthenticateMe(string cookie) 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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 30 Dec 2021 14:00:03 +0300 Subject: [PATCH 020/105] 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 8eda9406700..8a04954c49b 100644 --- a/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs +++ b/common/ASC.Api.Core/Middleware/TenantStatusFilter.cs @@ -34,7 +34,7 @@ public void OnResourceExecuting(ResourceExecutingContext context) 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 2bf1429307f..4c54aa06a24 100644 --- a/common/ASC.MessagingSystem/MessageFactory.cs +++ b/common/ASC.MessagingSystem/MessageFactory.cs @@ -73,7 +73,7 @@ public EventMessage Create(HttpRequest request, string initiator, MessageAction 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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 30 Dec 2021 14:03:05 +0300 Subject: [PATCH 021/105] 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 59b26e36c8e..d703aa1ffb5 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -231,9 +231,8 @@ IQueryable<TenantUserSecurity> query() => TenantsQuery() //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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 30 Dec 2021 14:03:50 +0300 Subject: [PATCH 022/105] 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 5666d809418..900beb4513e 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -357,8 +357,6 @@ internal bool CheckExist(T data) 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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 30 Dec 2021 15:01:20 +0300 Subject: [PATCH 023/105] 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 1075f469480..716b9963281 100644 --- a/products/ASC.Calendar/Server/BusinessObjects/Calendar.cs +++ b/products/ASC.Calendar/Server/BusinessObjects/Calendar.cs @@ -81,7 +81,7 @@ public static BaseCalendar GetUserCalendar(this BaseCalendar calendar, UserViewS } public static List<EventWrapper> GetEventWrappers(this BaseCalendar calendar, Guid userId, ApiDateTime startDate, ApiDateTime endDate, EventWrapperHelper eventWrapperHelper) - {new List<EventWrapper>(); + { var result = new List<EventWrapper>(); if (calendar != null) { From 6c32e34b409ba3fd4c66b069a6117b552fb9824f Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Thu, 30 Dec 2021 15:04:47 +0300 Subject: [PATCH 024/105] 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 4d3264e78f6..e0eb541fe13 100644 --- a/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs +++ b/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs @@ -349,14 +349,11 @@ public void DeletePhoto(int contactID, bool isTmpDir, string tmpDirName, bool re lock (locker) { - _resizeQueue.GetTasks<ResizeWorkerItem>().Where(item => item.ContactID == contactID) - .All(item => - { - _resizeQueue.RemoveTask(item.Id); - - return true; - }); - + foreach(var item in _resizeQueue.GetTasks<ResizeWorkerItem>().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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 30 Dec 2021 15:12:44 +0300 Subject: [PATCH 025/105] 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 99804b5f7e7..b8b095a5fc2 100644 --- a/products/ASC.CRM/Server/Core/Dao/ContactDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/ContactDao.cs @@ -929,7 +929,7 @@ public List<Contact> GetContactsByName(String title, bool isCompany) } } - 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 f1a6ef22622..9ceaee8d810 100644 --- a/products/ASC.CRM/Server/Mapping/TypeConverter/ContactDtoTypeConverter.cs +++ b/products/ASC.CRM/Server/Mapping/TypeConverter/ContactDtoTypeConverter.cs @@ -219,8 +219,6 @@ public ContactBaseWithPhoneDto Convert(Contact source, ContactBaseWithPhoneDto d { if (source == null) return null; - if (source == null) return null; - var contactBaseDto = context.Mapper.Map<ContactBaseDto>(source); var result = new ContactBaseWithPhoneDto diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index 613d88a16a7..06143f600a3 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -1484,8 +1484,6 @@ private IEnumerable<EmployeeWraperFull> ResendUserInvites(UpdateMembersModel mod 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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 30 Dec 2021 15:28:14 +0300 Subject: [PATCH 026/105] 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 6cf7eed67d6..198f1f7e0ce 100644 --- a/products/ASC.CRM/Server/Utils/ReportHelper.cs +++ b/products/ASC.CRM/Server/Utils/ReportHelper.cs @@ -28,6 +28,7 @@ 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 @@ private string GetReportScript(object data, ReportType type, string fileName) .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 <anton.sukhorukov@onlyoffice.com> Date: Mon, 10 Jan 2022 11:18:55 +0300 Subject: [PATCH 027/105] 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 3f623307800..1ea0b2a1b60 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs @@ -63,13 +63,13 @@ public class ReportStateData public string Script { get; } public int ReportType { get; } public ReportOrigin Origin { get; } - public Action<ReportState, string> SaveFileAction { get; } + public Func<ReportState, string, Task> 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<ReportState, string> saveFileAction, object obj, + Func<ReportState, string, Task> saveFileAction, object obj, int tenantId, Guid userId) { FileName = fileName; @@ -98,7 +98,7 @@ public class ReportState internal string BuilderKey { get; set; } internal string Script { get; set; } internal string TmpFileName { get; set; } - internal Action<ReportState, string> SaveFileAction { get; set; } + internal Func<ReportState, string, Task> SaveFileAction { get; set; } internal int TenantId { get; set; } internal Guid UserId { get; set; } From d7a1f73c4899fd338845401292d4aed72e77498b Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Mon, 10 Jan 2022 11:45:40 +0300 Subject: [PATCH 028/105] 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 670da6de85b..13c4b5498a0 100644 --- a/common/ASC.VoipService/VoipModel.cs +++ b/common/ASC.VoipService/VoipModel.cs @@ -105,7 +105,7 @@ public WorkingHours(TimeSpan from, TimeSpan to) } - 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 <anton.sukhorukov@onlyoffice.com> Date: Mon, 10 Jan 2022 12:24:21 +0300 Subject: [PATCH 029/105] 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 2a8d3bd77f2..a7adf92428e 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 @@ public static string Generate(int length) { 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 cdac5e98a1b..559a939b45d 100644 --- a/common/ASC.Core.Common/Encryption/EncryptionSettings.cs +++ b/common/ASC.Core.Common/Encryption/EncryptionSettings.cs @@ -172,16 +172,15 @@ public string GeneratePassword(int length, int numberOfNonAlphanumericCharacters 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 74d64519b6a..e2ebfb5ff05 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -32,6 +32,7 @@ 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 @@ public override string UploadChunk(string domain, 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 39de1bef1b4..cc9160abed1 100644 --- a/products/ASC.Files/Core/Model/FileWrapper.cs +++ b/products/ASC.Files/Core/Model/FileWrapper.cs @@ -131,7 +131,7 @@ public static FileWrapper<int> GetSample() //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 55519827df4..6d5738bde67 100644 --- a/products/ASC.Files/Core/Model/FolderWrapper.cs +++ b/products/ASC.Files/Core/Model/FolderWrapper.cs @@ -80,14 +80,14 @@ public static FolderWrapper<int> GetSample() //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 c5dc7d9cf10..0d892d4398c 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 @@ public bool GenerateKey(string phone, out string key) 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 09133c0921f..0b058d1ffc7 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 @@ public static string GeneratePassword() 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 <anton.sukhorukov@onlyoffice.com> Date: Mon, 10 Jan 2022 18:13:30 +0300 Subject: [PATCH 030/105] 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 49f726766c8..486fbf9e3f2 100644 --- a/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs +++ b/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs @@ -71,7 +71,7 @@ protected override void AfterFormat(INoticeMessage message) 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 5a4265e0d5f..690defa0dbb 100644 --- a/common/ASC.Notify.Textile/JabberStyler.cs +++ b/common/ASC.Notify.Textile/JabberStyler.cs @@ -72,7 +72,7 @@ public void ApplyFormating(NoticeMessage message) message.Body = body; } - private static string EvalLink(Match match) + private string EvalLink(Match match) { if (match.Success) { @@ -88,7 +88,7 @@ private static string EvalLink(Match match) 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 546621a5bd8..800d52cc0ab 100644 --- a/common/ASC.Textile/Blocks/CapitalsBlockModifier.cs +++ b/common/ASC.Textile/Blocks/CapitalsBlockModifier.cs @@ -11,7 +11,7 @@ public override string ModifyLine(string line) return line; } - static private string CapitalsFormatMatchEvaluator(Match m) + private string CapitalsFormatMatchEvaluator(Match m) { return @"<span class=""caps"">" + m.Groups["caps"].Value + @"</span>"; } diff --git a/common/ASC.Textile/Blocks/CodeBlockModifier.cs b/common/ASC.Textile/Blocks/CodeBlockModifier.cs index 476404a986d..efb6e635eec 100644 --- a/common/ASC.Textile/Blocks/CodeBlockModifier.cs +++ b/common/ASC.Textile/Blocks/CodeBlockModifier.cs @@ -49,7 +49,7 @@ public override string Conclude(string line) return line; } - static public string CodeFormatMatchEvaluator(Match m) + public string CodeFormatMatchEvaluator(Match m) { var res = m.Groups["before"].Value + "<code"; if (m.Groups["lang"].Length > 0) diff --git a/common/ASC.Textile/Blocks/ImageBlockModifier.cs b/common/ASC.Textile/Blocks/ImageBlockModifier.cs index a000ef4f76f..b5ea663f66f 100644 --- a/common/ASC.Textile/Blocks/ImageBlockModifier.cs +++ b/common/ASC.Textile/Blocks/ImageBlockModifier.cs @@ -36,7 +36,7 @@ public override string ModifyLine(string line) 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 bdefcc5b852..8ac80bf1e2d 100644 --- a/products/ASC.CRM/Server/Api/ContactInfosController.cs +++ b/products/ASC.CRM/Server/Api/ContactInfosController.cs @@ -537,7 +537,7 @@ public ContactInfoDto DeleteContactInfo(int contactid, int id) 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 4b1d290e9df..a3ef15ec091 100644 --- a/products/ASC.CRM/Server/Core/Dao/TagDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/TagDao.cs @@ -429,7 +429,7 @@ public void AddTagToEntity(EntityType entityType, int entityID, int[] tagIDs) 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 3a0346f7cfe..33ca8c75f7f 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 @@ protected string GetAvailableTitle(string requestTitle, string parentFolderId, F 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 cae4a21698e..f94366f4b49 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 @@ protected string GetAvailableTitle(string requestTitle, string parentFolderPath, 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 6d8c1ea2752..666c1e4f21d 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 @@ protected string GetAvailableTitle(string requestTitle, string parentFolderId, F 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 e495a3ed55b..c193facc125 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 @@ protected string GetAvailableTitle(string requestTitle, Folder parentFolderID, F 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 3cdc336b544..2216330cea5 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 @@ protected override IEnumerable<string> GetChildren(string folderId) 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 0cd3f549357..ed9ba6e6a40 100644 --- a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs +++ b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs @@ -88,7 +88,7 @@ public void Configure() } } - private static void NotifyClientRegisterCallback(Context context, INotifyClient client) + private void NotifyClientRegisterCallback(Context context, INotifyClient client) { #region url correction @@ -250,7 +250,7 @@ private static void NotifyClientRegisterCallback(Context context, INotifyClient #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 4a88999ee95..fe30c0aa20b 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyService.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyService.cs @@ -181,7 +181,7 @@ public void UserPasswordChange(UserInfo userInfo) 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 @@ public void SendEmailChangeInstructions(UserInfo user, string email) { 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 @@ public void SendEmailActivationInstructions(UserInfo user, string email) { 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 @@ public void SendMsgMobilePhoneChange(UserInfo userInfo) { 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 @@ public void SendMsgTfaReset(UserInfo userInfo) { 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 @@ public void SendJoinMsg(string email, EmployeeType emplType) 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 @@ public void UserInfoActivation(UserInfo newUserInfo) var confirmationUrl = GenerateActivationConfirmUrl(newUserInfo); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonAccept; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonAccept; client.SendNoticeToAsync( notifyAction, @@ -492,7 +492,7 @@ public void GuestInfoActivation(UserInfo newUserInfo) var confirmationUrl = GenerateActivationConfirmUrl(newUserInfo); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonAccept; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonAccept; client.SendNoticeToAsync( notifyAction, @@ -657,7 +657,7 @@ public void SendMsgPortalDeactivation(Tenant t, string deactivateUrl, string act { var u = UserManager.GetUsers(t.OwnerId); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonDeactivatePortal; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonDeactivatePortal; client.SendNoticeToAsync( Actions.PortalDeactivate, @@ -672,7 +672,7 @@ public void SendMsgPortalDeletion(Tenant t, string url, bool showAutoRenewText) { var u = UserManager.GetUsers(t.OwnerId); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonDeletePortal; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonDeletePortal; client.SendNoticeToAsync( Actions.PortalDelete, @@ -685,7 +685,7 @@ public void SendMsgPortalDeletion(Tenant t, string url, bool showAutoRenewText) public void SendMsgPortalDeletionSuccess(UserInfo owner, string url) { - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonLeaveFeedback; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonLeaveFeedback; client.SendNoticeToAsync( Actions.PortalDeleteSuccessV115, @@ -701,7 +701,7 @@ public void SendMsgDnsChange(Tenant t, string confirmDnsUpdateUrl, string portal { var u = UserManager.GetUsers(t.OwnerId); - static string greenButtonText() => WebstudioNotifyPatternResource.ButtonConfirmPortalAddressChange; + string greenButtonText() => WebstudioNotifyPatternResource.ButtonConfirmPortalAddressChange; client.SendNoticeToAsync( Actions.DnsChange, @@ -716,7 +716,7 @@ public void SendMsgDnsChange(Tenant t, string confirmDnsUpdateUrl, string portal 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 @@ public void SendCongratulations(UserInfo u) 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 8498d40d281..e1e8e5ac597 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -119,7 +119,7 @@ public void SendSaasLetters(string senderName, DateTime scheduleDate) Func<string> greenButtonText = () => string.Empty; - static string blueButtonText() => WebstudioNotifyPatternResource.ButtonRequestCallButton; + string blueButtonText() => WebstudioNotifyPatternResource.ButtonRequestCallButton; var greenButtonUrl = string.Empty; Func<string> tableItemText1 = () => string.Empty; @@ -156,17 +156,17 @@ public void SendSaasLetters(string senderName, DateTime scheduleDate) Func<string> 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 @@ public void SendEnterpriseLetters(string senderName, DateTime scheduleDate) Func<string> greenButtonText = () => string.Empty; - static string blueButtonText() => WebstudioNotifyPatternResource.ButtonRequestCallButton; + string blueButtonText() => WebstudioNotifyPatternResource.ButtonRequestCallButton; var greenButtonUrl = string.Empty; Func<string> tableItemText1 = () => string.Empty; @@ -555,17 +555,17 @@ public void SendEnterpriseLetters(string senderName, DateTime scheduleDate) Func<string> 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 <anton.sukhorukov@onlyoffice.com> Date: Mon, 10 Jan 2022 18:13:54 +0300 Subject: [PATCH 031/105] 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 f45781ddd41..1f90cd008a0 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -546,9 +546,9 @@ public bool Support(T t) } } - public async Task<bool> SupportAsync(T t) + public Task<bool> 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 c32b5d1ba76..21c92f37ea2 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 @@ public Stream GetFileStream(File<int> file) { return GetFileStream(file, 0); } - public async Task<Stream> GetFileStreamAsync(File<int> file) + public Task<Stream> GetFileStreamAsync(File<int> file) { - return await GlobalStore.GetStore().GetReadStreamAsync(string.Empty, GetUniqFilePath(file), 0); + return GlobalStore.GetStore().GetReadStreamAsync(string.Empty, GetUniqFilePath(file), 0); } public File<int> SaveFile(File<int> file, Stream fileStream) @@ -1157,9 +1157,9 @@ public bool IsExistOnStorage(File<int> file) return GlobalStore.GetStore().IsFile(GetUniqFilePath(file)); } - public async Task<bool> IsExistOnStorageAsync(File<int> file) + public Task<bool> IsExistOnStorageAsync(File<int> 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 <anton.sukhorukov@onlyoffice.com> Date: Tue, 11 Jan 2022 18:37:10 +0300 Subject: [PATCH 032/105] 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 2365f358c35..83e0bf608af 100644 --- a/common/ASC.Common/Threading/DistributedTask.cs +++ b/common/ASC.Common/Threading/DistributedTask.cs @@ -55,7 +55,7 @@ public string Id } 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 631455bf36f..c301c43ae47 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -102,7 +102,7 @@ public static string SearchTextHighlight(string searchText, string htmlText, boo { 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).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.Core.Common/BaseCommonLinkUtility.cs b/common/ASC.Core.Common/BaseCommonLinkUtility.cs index f2a63c9f0c5..a8e22097da9 100644 --- a/common/ASC.Core.Common/BaseCommonLinkUtility.cs +++ b/common/ASC.Core.Common/BaseCommonLinkUtility.cs @@ -217,7 +217,7 @@ public static string GetRegionalUrl(string url, string lang) if (string.IsNullOrEmpty(lang)) { - url = matches.Cast<Match>().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 1a13e337105..3df3e451c01 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -566,7 +566,7 @@ public override void DeleteDirectory(string domain, string path) 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 13d8113eb27..7a688178c9a 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -543,7 +543,7 @@ public override void DeleteFiles(string domain, string path, string pattern, boo client.DeleteObjectAsync(deleteRequest).Wait(); - QuotaUsedDelete(domain, Convert.ToInt64(s3Object.Size)); + QuotaUsedDelete(domain, s3Object.Size); } } @@ -565,7 +565,7 @@ public override void DeleteFiles(string domain, string path, DateTime fromDate, 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 66abd3d46af..2ffa9c4f3bc 100644 --- a/common/services/ASC.ApiSystem/Classes/CommonConstants.cs +++ b/common/services/ASC.ApiSystem/Classes/CommonConstants.cs @@ -61,9 +61,9 @@ public CommonConstants(IConfiguration configuration) 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 16bead0159b..00727d4ced3 100644 --- a/common/services/ASC.AuditTrail/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/AuditEventsRepository.cs @@ -132,7 +132,7 @@ private AuditEvent ToAuditEvent(Query query) if (query.AuditEvent.Description != null) { evt.Description = JsonConvert.DeserializeObject<IList<string>>( - 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 6e581a8079c..1978968edc7 100644 --- a/common/services/ASC.TelegramService/Core/Core.cs +++ b/common/services/ASC.TelegramService/Core/Core.cs @@ -107,7 +107,7 @@ private TelegramCommand ParseCommand(Message msg) 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<Match>().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 73f54fa0a2b..5e17356c9ec 100644 --- a/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs @@ -218,7 +218,7 @@ public NameValueCollection GetColors(ListType listType) .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 d168db971d2..15fc763700a 100644 --- a/products/ASC.CRM/Server/Core/Dao/RelationshipEventDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/RelationshipEventDao.cs @@ -259,7 +259,7 @@ public List<int> RemoveFile(File<int> file) } } - 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 5afce5d56c8..01ed9567f78 100644 --- a/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs @@ -112,7 +112,7 @@ public async System.Threading.Tasks.Task Invoke(HttpContext context, } 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 a346f49277c..8be1a4cc6d3 100644 --- a/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs +++ b/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs @@ -124,8 +124,8 @@ public List<UserViewSettings> GetUserViewSettings(Guid userId, List<string> cale 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 @@ public Guid RemoveCalendar(int calendarId) 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 @@ public List<Todo> GetTodosByIds(int[] todoIds, Guid userId, int tenantId = -1) 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 @@ public List<Todo> GetTodosByIds(int[] todoIds, Guid userId, int tenantId = -1) 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 @@ from cal in CalendarDb.CalendarCalendars }; 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<UserAlertType>(); @@ -1782,7 +1782,7 @@ from calUser in CalendarDb.CalendarCalendarUser 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 @@ from cpi in CalendarDb.CalendarCalendarItem 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 @@ from calUser in CalendarDb.CalendarCalendarUser 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 e5f79412194..ef175ed13b5 100644 --- a/products/ASC.Calendar/Server/Controllers/CalendarController.cs +++ b/products/ASC.Calendar/Server/Controllers/CalendarController.cs @@ -521,7 +521,7 @@ public string GetCalendarCalDavUrl(string calendarId) 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 @@ public string GetCalendarCalDavUrl(string calendarId) "Todo_calendar", "", BusinessObjects.Calendar.DefaultTodoBackgroundColor, - todoCalendars[0].calDavGuid.ToString(), + todoCalendars[0].calDavGuid, myUri, curCaldavUserName, userName @@ -2694,7 +2694,7 @@ public List<TodoWrapper> AddTodo(CreateTodoModel createTodoModel) 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 3d04903da25..94dc39872f1 100644 --- a/products/ASC.Calendar/Server/Models/PublicItemCollection.cs +++ b/products/ASC.Calendar/Server/Models/PublicItemCollection.cs @@ -86,10 +86,10 @@ public PublicItemCollection GetForCalendar(ICalendar calendar) 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 21c92f37ea2..6e98f63dbfb 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 @@ public bool UseTrashForRemove(File<int> file) 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<int> file) diff --git a/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs b/products/ASC.Files/Core/Core/Dao/TeamlabDao/FolderDao.cs index 8c123aa4744..a58c56714b6 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 @@ public int GetFolderID(string module, string bunch, string data, bool createIfNo 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 @@ public int GetFolderID(string module, string bunch, string data, bool createIfNo 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 b540cfaaf3b..d332c3e4af9 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -1319,7 +1319,7 @@ public object DeleteThirdParty(string providerId) } 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 d129bb39410..5a7c652ed6e 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 @@ private File<string> RestoreIds(File<string> file) 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 971a6246fc2..f420f61908a 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs @@ -270,7 +270,7 @@ protected string MappingID(string id, bool saveIfNotExist = false) 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 0c5f3b9ed34..f60c9a7c97a 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 @@ private File<string> RestoreIds(File<string> file) 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 f1cdd5ba5ea..43b626445ab 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs @@ -318,7 +318,7 @@ public virtual int UpdateProviderInfo(int linkId, string customerTitle, AuthData 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 393e6f4a3ca..86c68236cc6 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 @@ public File<string> SaveFile(File<string> file, Stream fileStream) 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 5f4209567cb..7c9df95b32b 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -197,11 +197,11 @@ public string GetRefreshUrl() public File<string> 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 @@ public void SaveFile(string fileId, string fileType, string downloadUrl, Stream (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 63461d7b7e0..c56d3da2183 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -251,7 +251,7 @@ public string GetFileStreamUrl(File<string> file) { 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 facfb661f5b..1de062bcdf1 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -126,7 +126,7 @@ public FileMarker( internal void ExecMarkFileAsNew<T>(AsyncTaskData<T> obj) { - TenantManager.SetCurrentTenant(Convert.ToInt32(obj.TenantID)); + TenantManager.SetCurrentTenant(obj.TenantID); var folderDao = DaoFactory.GetFolderDao<T>(); T parentFolderId; diff --git a/products/ASC.People/Server/Controllers/PeopleController.cs b/products/ASC.People/Server/Controllers/PeopleController.cs index 06143f600a3..29ffb632965 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -562,8 +562,8 @@ private EmployeeWraperFull AddMember(MemberModel memberModel) ? 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 @@ private EmployeeWraperFull AddMemberAsActivated(MemberModel memberModel) ? 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 @@ private EmployeeWraperFull UpdateMember(string userid, UpdateMemberModel memberM ? 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 1388b56f57b..cd8af9da708 100644 --- a/web/ASC.Web.Core/WebItemManager.cs +++ b/web/ASC.Web.Core/WebItemManager.cs @@ -261,9 +261,7 @@ public List<IWebItem> GetSubItems(Guid parentItemID) public List<IWebItem> GetSubItems(Guid parentItemID, ItemAvailableState avaliableState) { - return GetItems(WebZoneType.All, avaliableState).OfType<IModule>() - .Where(p => p.ProjectId == parentItemID) - .Cast<IWebItem>() + return GetItems(WebZoneType.All, avaliableState).Where(p => ((IModule)p).ProjectId == parentItemID) .ToList(); } } From 50c0596efffadb42e69a36af6ebb9dd5a650dd15 Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Tue, 11 Jan 2022 18:37:19 +0300 Subject: [PATCH 033/105] analizators/U2U1009 --- .../ASC.Core.Common/Billing/CouponManager.cs | 14 ++- .../EF/Context/BaseDbContext.cs | 10 +- .../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, 178 insertions(+), 81 deletions(-) diff --git a/common/ASC.Core.Common/Billing/CouponManager.cs b/common/ASC.Core.Common/Billing/CouponManager.cs index fc8bcd932c7..eb1c9c41802 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -112,19 +112,23 @@ private async Task<string> CreatePromotionAsync(TenantManager tenantManager) Log.Error(ex.Message, ex); throw; } + } + + internal Task<IEnumerable<AvangateProduct>> GetProducts() + { + if (Products != null) return Task.FromResult(Products); + return InternalGetProducts(); } - internal async Task<IEnumerable<AvangateProduct>> GetProducts() - { - if (Products != null) return Products; - + private async Task<IEnumerable<AvangateProduct>> 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 771201928cc..e61b9536c20 100644 --- a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs @@ -133,10 +133,16 @@ public void Dispose() } } } - public async ValueTask DisposeAsync() + + public ValueTask DisposeAsync() { - if (Context == null) return; + 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 079bcdba695..d5de8af201b 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -280,11 +280,15 @@ protected void RunMysqlFile(string file, bool db = false) 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 b36f22aba88..6a26f7c3e89 100644 --- a/common/ASC.Data.Storage/StorageHandler.cs +++ b/common/ASC.Data.Storage/StorageHandler.cs @@ -63,9 +63,9 @@ public StorageHandler(IServiceProvider serviceProvider, string path, string modu } 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<StorageHandlerScope>(); var (tenantManager, securityContext, storageFactory, emailValidationKeyProvider) = scopeClass; @@ -73,11 +73,11 @@ public async Task Invoke(HttpContext context) 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 @@ public async Task Invoke(HttpContext context) 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 @@ public async Task Invoke(HttpContext context) //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 @@ public async Task Invoke(HttpContext context) 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 1f90cd008a0..4c23f20347b 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -271,13 +271,18 @@ public void Index(List<T> data, bool immediately = true, int retry = 0) throw; } } - } + } - public async Task IndexAsync(List<T> data, bool immediately = true, int retry = 0) + public Task IndexAsync(List<T> data, bool immediately = true, int retry = 0) { var t = ServiceProvider.GetService<T>(); - if (!Support(t) || !data.Any()) return; + if (!Support(t) || !data.Any()) return Task.CompletedTask; + + return InternalIndexAsync(data, immediately, retry); + } + private async Task InternalIndexAsync(List<T> data, bool immediately, int retry) + { try { await Indexer.IndexAsync(data, immediately).ConfigureAwait(false); @@ -627,9 +632,9 @@ public bool CheckState(bool cacheState = true) return false; } } - - public async Task<bool> CheckStateAsync(bool cacheState = true) - { + + public Task<bool> CheckStateAsync(bool cacheState = true) + { const string key = "elasticsearch"; if (cacheState) @@ -637,10 +642,15 @@ public async Task<bool> CheckStateAsync(bool cacheState = true) var cacheValue = cache.Get<string>(key); if (!string.IsNullOrEmpty(cacheValue)) { - return Convert.ToBoolean(cacheValue); + return Task.FromResult(Convert.ToBoolean(cacheValue)); } - } + } + + return InternalCheckStateAsync(cacheState, key); + } + private async Task<bool> 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 01ed9567f78..450e5b23169 100644 --- a/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/ContactPhotoHandlerMiddleware.cs @@ -54,7 +54,7 @@ public ContactPhotoHandlerMiddleware(RequestDelegate next) 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 @@ public async System.Threading.Tasks.Task Invoke(HttpContext context, MessageTarget messageTarget, MessageService messageService, DaoFactory daoFactory, - ContactPhotoManager contactPhotoManager) - { + ContactPhotoManager contactPhotoManager){ if (!webItemSecurity.IsAvailableForMe(ProductEntryPoint.ID)) throw crmSecurity.CreateSecurityException(); @@ -82,6 +81,18 @@ public async System.Threading.Tasks.Task Invoke(HttpContext context, 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 1e495a831ba..cdc1d252197 100644 --- a/products/ASC.CRM/Server/Middlewares/ImportFileHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/ImportFileHandlerMiddleware.cs @@ -50,7 +50,7 @@ public ImportFileHandlerMiddleware( _next = next; } - public async Task Invoke(HttpContext context, + public Task Invoke(HttpContext context, WebItemSecurity webItemSecurity, CrmSecurity crmSecurity, Global global, @@ -59,6 +59,15 @@ public async Task Invoke(HttpContext context, 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 78916654254..8e8a1e8d754 100644 --- a/products/ASC.CRM/Server/Middlewares/OrganisationLogoHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/OrganisationLogoHandlerMiddleware.cs @@ -50,7 +50,7 @@ RequestDelegate next _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 @@ public async System.Threading.Tasks.Task Invoke(HttpContext context, 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 6e98f63dbfb..b636462f6e9 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 @@ internal protected DbFile InitDocument(DbFile dbFile) return dbFile; } - internal protected async Task<DbFile> InitDocumentAsync(DbFile dbFile) + internal protected Task<DbFile> InitDocumentAsync(DbFile dbFile) { if (!FactoryIndexer.CanIndexByContent(dbFile)) { @@ -1515,9 +1515,14 @@ internal protected async Task<DbFile> InitDocumentAsync(DbFile dbFile) { Data = Convert.ToBase64String(Encoding.UTF8.GetBytes("")) }; - return dbFile; + return Task.FromResult(dbFile); } + return InernalInitDocumentAsync(dbFile); + } + + private async Task<DbFile> InernalInitDocumentAsync(DbFile dbFile) + { var file = ServiceProvider.GetService<File<int>>(); 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 7575a48260f..4ed9f1b5f8e 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.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 @@ public FileHandlerService( 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 @@ public async Task Invoke(HttpContext context) 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 @@ private async Task BulkDownloadFile(HttpContext context) { 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 @@ private static string GetEtag<T>(File<T> file) { 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 @@ private async Task CreateFile(HttpContext context) //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 @@ private async Task CreateFile(HttpContext context) await CreateFile(context, folderId); } } - } - - private async Task CreateFile<T>(HttpContext context, T folderId) - { - var responseMessage = context.Request.Query["response"] == "message"; + } + + private Task CreateFile<T>(HttpContext context, T folderId) + { + var responseMessage = context.Request.Query["response"] == "message"; + Folder<T> folder; var folderDao = DaoFactory.GetFolderDao<T>(); @@ -1100,28 +1116,40 @@ private async Task CreateFile<T>(HttpContext context, T folderId) } 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<T>(HttpContext context, Folder<T> folder) + { + await context.Response.WriteAsync("ok: " + string.Format(FilesCommonResource.MessageFileCreated, folder.Title)); } private File<T> CreateFileFromTemplate<T>(Folder<T> folder, string fileTitle, string docType) @@ -1264,10 +1292,10 @@ private async Task TrackFile(HttpContext context) { await TrackFile(context, q.FirstOrDefault() ?? ""); } - } - - private async Task TrackFile<T>(HttpContext context, T fileId) - { + } + + private Task TrackFile<T>(HttpContext context, T fileId) + { var auth = context.Request.Query[FilesLinkUtility.AuthKey].FirstOrDefault(); Logger.Debug("DocService track fileid: " + fileId); @@ -1277,8 +1305,13 @@ private async Task TrackFile<T>(HttpContext context, T fileId) { 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<T>(HttpContext context, T fileId) + { DocumentServiceTracker.TrackerData fileData; try { From 610c45fed36a67356d87e33d594a708c0ac8d83a Mon Sep 17 00:00:00 2001 From: SuhorukovAnton <anton.sukhorukov@onlyoffice.com> Date: Wed, 12 Jan 2022 12:56:00 +0300 Subject: [PATCH 034/105] 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 c1ee72a456c..1cd072b2f61 100644 --- a/common/services/ASC.TelegramService/Commands/UserCommands.cs +++ b/common/services/ASC.TelegramService/Commands/UserCommands.cs @@ -45,11 +45,16 @@ public UserCommands(IOptionsSnapshot<CachedTelegramDao> cachedTelegramDao) 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 0bddd8cf869..6237cc91c7e 100644 --- a/common/services/ASC.TelegramService/TelegramHandler.cs +++ b/common/services/ASC.TelegramService/TelegramHandler.cs @@ -61,13 +61,19 @@ public TelegramHandler(CommandModule command, IOptionsMonitor<ILog> option, ISer Clients = new Dictionary<int, TenantTgClient>(); 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<IOptionsSnapshot<CachedTelegramDao>>().Value; - if (string.IsNullOrEmpty(msg.To)) return; - if (!Clients.ContainsKey(msg.Tenant)) return; + var cachedTelegramDao = scope.ServiceProvider.GetService<IOptionsSnapshot<CachedTelegramDao>>().Value; var client = Clients[msg.Tenant].Client; @@ -156,10 +162,14 @@ public void RegisterUser(string userId, int tenantId, string token) 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 <anton.sukhorukov@onlyoffice.com> Date: Wed, 12 Jan 2022 13:27:06 +0300 Subject: [PATCH 035/105] 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 e1ab1be442a..def62d1821b 100644 --- a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs +++ b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs @@ -98,15 +98,19 @@ internal static string FormatErrorMessage(ISubject subject, IAction[] actions, I 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 2d89d272a1d..4fec7e0177d 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -410,7 +410,8 @@ private void SaveToFile(string path, string t, IReadOnlyCollection<string> colum 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 @@ private void SaveToFile(string path, string t, IReadOnlyCollection<string> colum 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 a9fa0caf1ae..8052978b4fc 100644 --- a/common/ASC.IPSecurity/IPAddressRange.cs +++ b/common/ASC.IPSecurity/IPAddressRange.cs @@ -56,13 +56,18 @@ public bool IsInRange(IPAddress address) 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 690defa0dbb..3848314906d 100644 --- a/common/ASC.Notify.Textile/JabberStyler.cs +++ b/common/ASC.Notify.Textile/JabberStyler.cs @@ -58,12 +58,15 @@ public void ApplyFormating(NoticeMessage message) 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 900beb4513e..b5589c2b0b3 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -518,12 +518,13 @@ private Func<ScriptDescriptor, IScript> GetScriptUpdateByQuery(T data, params Ex var parameters = new Dictionary<string, object>(); 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 d448f30de37..2ab517eca92 100644 --- a/products/ASC.Calendar/Server/iCalParser/Token.cs +++ b/products/ASC.Calendar/Server/iCalParser/Token.cs @@ -139,7 +139,9 @@ public static string CamelCase(string str) for (int i = 0; i < lstr.Length; ++i) { - if (lstr[i] == '-') + var c = lstr[i]; + + if (c == '-') { upper = true; } @@ -147,12 +149,12 @@ public static string CamelCase(string str) { 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 <anton.sukhorukov@onlyoffice.com> Date: Wed, 12 Jan 2022 15:34:58 +0300 Subject: [PATCH 036/105] 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 4af584677fb..dbb8dcee3ff 100644 --- a/common/ASC.Common/DIHelper.cs +++ b/common/ASC.Common/DIHelper.cs @@ -233,7 +233,7 @@ public bool TryAdd(Type service, Type implementation = null) } else { - Type c = null; + Type c; var a1 = a.GetGenericTypeDefinition(); var b = a.GetGenericArguments().FirstOrDefault(); @@ -297,7 +297,7 @@ public bool TryAdd(Type service, Type implementation = null) } 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 def62d1821b..952ce416615 100644 --- a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs +++ b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs @@ -102,7 +102,7 @@ internal static string FormatErrorMessage(ISubject subject, IAction[] actions, I 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 559a939b45d..8494e71c410 100644 --- a/common/ASC.Core.Common/Encryption/EncryptionSettings.cs +++ b/common/ASC.Core.Common/Encryption/EncryptionSettings.cs @@ -139,11 +139,10 @@ public string GeneratePassword(int length, int numberOfNonAlphanumericCharacters 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 41ed08dc5d2..a514d10fb82 100644 --- a/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs +++ b/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs @@ -119,7 +119,7 @@ private void AddInternal(ISendInterceptor interceptor, Dictionary<string, ISendI private ISendInterceptor GetInternal(string name, Dictionary<string, ISendInterceptor> 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 23c6c7fe8d3..9e30f75da1d 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -254,7 +254,7 @@ private NotifyResult SendNotify(NotifyRequest request, IServiceScope serviceScop 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 4d2f6d4bf6b..6d4788ff94e 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -57,8 +57,7 @@ public virtual IRecipient[] GetGroupEntries(IRecipientsGroup group) if (group == null) throw new ArgumentNullException("group"); var result = new List<IRecipient>(); - 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 8b157647a2f..01790c82ae5 100644 --- a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs +++ b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs @@ -160,7 +160,7 @@ private List<XElement> BackupDatabase(int tenant, ConnectionStringSettings conne } 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 2ff9ef461cf..38baee80fbf 100644 --- a/common/ASC.Data.Backup.Core/Storage/DocumentsBackupStorage.cs +++ b/common/ASC.Data.Backup.Core/Storage/DocumentsBackupStorage.cs @@ -155,7 +155,7 @@ private T Upload<T>(T folderId, string localPath) 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 4fec7e0177d..80c0bb0b600 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -284,7 +284,7 @@ private void DumpTableData(string t, string dir, int count) } 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 3eacb6f69f1..dd54560f00e 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 @@ public TableInfo(string name, string tenantColumn = null, string idColumn = null IdColumn = idColumn; IdType = idType; TenantColumn = tenantColumn; - UserIDColumns = new string[0]; DateColumns = new Dictionary<string, bool>(); InsertMethod = InsertMethod.Insert; } diff --git a/common/ASC.Data.Encryption/Metadata.cs b/common/ASC.Data.Encryption/Metadata.cs index 5dfc16e51e4..73cc75ac7ad 100644 --- a/common/ASC.Data.Encryption/Metadata.cs +++ b/common/ASC.Data.Encryption/Metadata.cs @@ -242,16 +242,14 @@ public int GetMetadataLength() 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 @@ private byte[] GenerateKey() private byte[] GenerateHmacKey() { - var hmacKey = new byte[hmacKeyLength]; + byte[] hmacKey; using (var sha512 = SHA512.Create()) { @@ -274,8 +272,8 @@ private byte[] GenerateHmacKey() } 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 f038f227a26..b8892a79dae 100644 --- a/common/ASC.Data.Storage/Extensions.cs +++ b/common/ASC.Data.Storage/Extensions.cs @@ -59,7 +59,7 @@ public static void IronReadToStream(this IDataStore store, string domain, string 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 3df3e451c01..4c66b702aac 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -527,11 +527,9 @@ public override string[] ListDirectoriesRelative(string domain, string path, boo public override string[] ListFilesRelative(string domain, string path, string pattern, bool recursive) { - var paths = new List<string>(); - 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 739d2a14f5e..5c39e98b200 100644 --- a/products/ASC.CRM/Server/Classes/CSVReader.cs +++ b/products/ASC.CRM/Server/Classes/CSVReader.cs @@ -177,7 +177,7 @@ private object ReadNextObject() 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 @@ public DataTable CreateDataTable(bool headerRow) { // Read the CSV data into rows List<List<object>> rows = new List<List<object>>(); - List<object> readRow = null; + List<object> 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 5bc7022eb3b..bc3eea5866d 100644 --- a/products/ASC.CRM/Server/Classes/Global.cs +++ b/products/ASC.CRM/Server/Classes/Global.cs @@ -206,7 +206,7 @@ public static byte[] ToByteArray(Stream inputStream) { 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 24875c55e58..f3b44114748 100644 --- a/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs +++ b/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs @@ -87,7 +87,7 @@ private class LookupTable : Dictionary<string, object> { } /// <returns></returns> private LookupTable GetLookupTable(CultureInfo culture) { - LookupTable result = null; + LookupTable result; if (culture == null) culture = CultureInfo.CurrentCulture; @@ -191,7 +191,7 @@ private string GetFlagValueText(CultureInfo culture, object value) 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 @@ private object GetFlagValue(CultureInfo culture, string text) 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 b8b095a5fc2..2792add0eea 100644 --- a/products/ASC.CRM/Server/Core/Dao/ContactDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/ContactDao.cs @@ -1138,7 +1138,7 @@ private void UpdateContactFromDb(Contact contact) String title; int companyID; - var displayName = String.Empty; + string displayName; if (contact is Company) { @@ -1346,7 +1346,7 @@ private int SaveContactToDb(Contact contact) 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 65c9a5c1e21..3ef6b6623de 100644 --- a/products/ASC.CRM/Server/Core/Dao/TaskDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/TaskDao.cs @@ -333,7 +333,7 @@ public int GetTasksCount( 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 23433df7bd0..02380327320 100644 --- a/products/ASC.CRM/Server/Middlewares/FileHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/FileHandlerMiddleware.cs @@ -89,7 +89,7 @@ public async Task Invoke(HttpContext context, 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 1da79cc7e05..6f7855824d9 100644 --- a/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs @@ -152,7 +152,7 @@ public async System.Threading.Tasks.Task Invoke(HttpContext context, 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 7cee5ecc149..bc933ca3116 100644 --- a/products/ASC.CRM/Server/Services/NotifyService/NotifyClient.cs +++ b/products/ASC.CRM/Server/Services/NotifyService/NotifyClient.cs @@ -246,8 +246,8 @@ public void SendAboutImportCompleted(Guid recipientID, EntityType entityType) 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 524482846b2..c839237986a 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 @@ private void ImportTaskData(DaoFactory _daoFactory) } 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 e4e93840623..42968cfb722 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 @@ public void Transfer(ResumableUploadSession googleDriveSession, Stream stream, l 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 61dc933b5bb..4c827fbd898 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 @@ public override void RunJob(DistributedTask distributedTask, CancellationToken c if (stream != null) { - var archiveExtension = ""; + string archiveExtension; using(var zip = scope.ServiceProvider.GetService<CompressToArchive>()) { diff --git a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs index 1ba4b8f40a1..580f128df56 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -431,8 +431,8 @@ public IEnumerable<FileOperationWraper> DeleteFolder(T folderId, bool deleteAfte public IEnumerable<FileEntryWrapper> MoveOrCopyBatchCheck(BatchModel batchModel) { - var checkedFiles = new List<object>(); - var checkedFolders = new List<object>(); + List<object> checkedFiles; + List<object> checkedFolders; if (batchModel.DestFolderId.ValueKind == JsonValueKind.Number) { diff --git a/web/ASC.Web.Core/CommonPhotoManager.cs b/web/ASC.Web.Core/CommonPhotoManager.cs index 6140715abd9..073bfa5d9fe 100644 --- a/web/ASC.Web.Core/CommonPhotoManager.cs +++ b/web/ASC.Web.Core/CommonPhotoManager.cs @@ -51,9 +51,7 @@ public static Image DoThumbnail(Image image, Size size, bool crop, bool transpar 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 e1e8e5ac597..2b36a1479d1 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -941,7 +941,7 @@ public void SendPersonalLetters(string senderName, DateTime scheduleDate) Log.Info("Start SendLettersPersonal..."); - var activeTenants = new List<Tenant>(); + List<Tenant> activeTenants; using (var scope = ServiceProvider.CreateScope()) { diff --git a/web/ASC.Web.Core/WebItemSecurity.cs b/web/ASC.Web.Core/WebItemSecurity.cs index 49c20ae1164..f49c21d0686 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -140,7 +140,7 @@ public bool IsAvailableForMe(Guid id) 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 97a881646d4..2b9280f4435 100644 --- a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs +++ b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs @@ -385,7 +385,7 @@ public void SetLogo(TenantWhiteLabelSettings tenantWhiteLabelSettings, Dictionar 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 <anton.sukhorukov@onlyoffice.com> Date: Wed, 12 Jan 2022 18:42:03 +0300 Subject: [PATCH 037/105] 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 e96bdfcd354..4d63ed3da6e 100644 --- a/common/ASC.Common/Logging/SpecialFolderPathConverter.cs +++ b/common/ASC.Common/Logging/SpecialFolderPathConverter.cs @@ -49,7 +49,7 @@ protected override void Convert(TextWriter writer, object state) 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 ade6cd21b58..562cfa32ccc 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -76,13 +76,13 @@ public bool Personal 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 3a2ffe8fff6..bec401d4936 100644 --- a/common/ASC.Core.Common/Context/Impl/UserManager.cs +++ b/common/ASC.Core.Common/Context/Impl/UserManager.cs @@ -175,13 +175,13 @@ public UserInfo GetUserByUserName(string username) 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 @@ public UserInfo[] Search(string text, EmployeeStatus status) 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 1420c3a2dfc..c97f98f1977 100644 --- a/common/ASC.Core.Common/Data/DbSubscriptionService.cs +++ b/common/ASC.Core.Common/Data/DbSubscriptionService.cs @@ -195,7 +195,7 @@ public void RemoveSubscriptions(int tenant, string sourceId, string actionId, st .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 aebb788ec95..c2959d56b33 100644 --- a/common/ASC.Core.Common/EF/LinqExtensions.cs +++ b/common/ASC.Core.Common/EF/LinqExtensions.cs @@ -31,7 +31,7 @@ public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> query, st 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 0793bde6184..d85e0519365 100644 --- a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs @@ -136,7 +136,7 @@ public void SendMessage(string callerUserName, string calleeUserName, string mes 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 4b184ebe98b..0dbf3d80690 100644 --- a/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs +++ b/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs @@ -106,7 +106,7 @@ public RegStatus UserIsConnected(Guid userId, int tenantId) 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 3d623608761..36da33b5455 100644 --- a/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs +++ b/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs @@ -134,7 +134,7 @@ private ValidationResult ValidateEmailKeyInternal(string email, string key, Time 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 01790c82ae5..e2b17a03a07 100644 --- a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs +++ b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs @@ -106,7 +106,7 @@ private Configuration GetConfiguration(string config) { 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 @@ private List<XElement> BackupDatabase(int tenant, ConnectionStringSettings conne private void RestoreDatabase(ConnectionStringSettings connectionString, IEnumerable<XElement> 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 c7a45cadb3b..5149a347423 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -52,7 +52,7 @@ public DbHelper(IOptionsMonitor<ILog> options, ConnectionStringSettings connecti 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 @@ private string GetWhere(string tableName, int tenant) { 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 801bae651bd..80168ce3187 100644 --- a/products/ASC.CRM/Server/Api/InvoicesController.cs +++ b/products/ASC.CRM/Server/Api/InvoicesController.cs @@ -192,9 +192,9 @@ String currency ) { 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<InvoiceBaseDto> result; diff --git a/products/ASC.CRM/Server/Api/RelationshipEventsController.cs b/products/ASC.CRM/Server/Api/RelationshipEventsController.cs index 945a90d51d1..fb115d8da9e 100644 --- a/products/ASC.CRM/Server/Api/RelationshipEventsController.cs +++ b/products/ASC.CRM/Server/Api/RelationshipEventsController.cs @@ -387,8 +387,8 @@ public RelationshipEventDto AddHistoryTo([FromBody] AddHistoryToRequestDto inDto 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 7c4775c80d8..170ae0720d0 100644 --- a/products/ASC.CRM/Server/Api/TasksController.cs +++ b/products/ASC.CRM/Server/Api/TasksController.cs @@ -103,9 +103,9 @@ public IEnumerable<TaskDto> GetAllTasks( 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 @@ public TaskDto CreateTask( 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 @@ public IEnumerable<TaskDto> CreateTaskGroup([FromBody] CreateTaskGroupRequestDto 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 @@ public TaskDto UpdateTask( 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 e88f7d54a67..15b2a2ca197 100644 --- a/products/ASC.CRM/Server/Classes/CRMSettings.cs +++ b/products/ASC.CRM/Server/Classes/CRMSettings.cs @@ -162,7 +162,7 @@ public ISettings GetDefault(IServiceProvider serviceProvider) 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 5c39e98b200..636a5721c64 100644 --- a/products/ASC.CRM/Server/Classes/CSVReader.cs +++ b/products/ASC.CRM/Server/Classes/CSVReader.cs @@ -157,7 +157,7 @@ public List<object> ReadRow() // Build the list of objects in the line List<object> objects = new List<object>(); - while (currentLine != "") + while (currentLine.Length != 0) objects.Add(ReadNextObject()); return objects; } @@ -185,10 +185,10 @@ private object ReadNextObject() { // 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 6a75bd75a7e..b4bf24a4d64 100644 --- a/products/ASC.CRM/Server/Core/Dao/CustomFieldDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/CustomFieldDao.cs @@ -349,7 +349,7 @@ public void EditItem(CustomField customField) 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 63375828526..48a7a9d93a5 100644 --- a/products/ASC.CRM/Server/Core/Entities/CurrencyInfo.cs +++ b/products/ASC.CRM/Server/Core/Entities/CurrencyInfo.cs @@ -73,7 +73,7 @@ public String Title 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 6f7855824d9..593be935001 100644 --- a/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs @@ -313,7 +313,7 @@ public async System.Threading.Tasks.Task Invoke(HttpContext context, 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 a0823e282bd..e6fa13f3881 100644 --- a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs +++ b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs @@ -142,7 +142,7 @@ public Dictionary<CurrencyInfo, Decimal> MoneyConvert(CurrencyInfo baseCurrency) 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 @@ public bool IsConvertable(String abbreviation) 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 9cbf155a79e..51a194bc21c 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 @@ private String GetPropertyValue(String propertyName) 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 92fe4b6a69b..4f210104372 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 @@ private void ImportOpportunityData(DaoFactory _daoFactory) 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 @@ private void ImportOpportunityData(DaoFactory _daoFactory) 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 c839237986a..bc60a84bbc3 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 @@ private void ImportTaskData(DaoFactory _daoFactory) 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 @@ private void ImportTaskData(DaoFactory _daoFactory) 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 b120ca72a38..ae898d1adf1 100644 --- a/products/ASC.CRM/Server/Utils/MailSender.cs +++ b/products/ASC.CRM/Server/Utils/MailSender.cs @@ -693,7 +693,7 @@ private IEnumerable<MailTemplateTag> GetTagsFrom(String template) 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 ef175ed13b5..547200dd531 100644 --- a/products/ASC.Calendar/Server/Controllers/CalendarController.cs +++ b/products/ASC.Calendar/Server/Controllers/CalendarController.cs @@ -541,7 +541,7 @@ public string GetCalendarCalDavUrl(string calendarId) 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 @@ public string GetCalendarCalDavUrl(string calendarId) { 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 @@ public string GetCalendarCalDavUrl(string calendarId) var calendar = GetUserCaldavCalendar(sharedCalUrl, userName); - if (calendar != "") + if (calendar.Length != 0) { if (calendar == "NotFound") { @@ -631,7 +631,7 @@ public string GetCalendarCalDavUrl(string calendarId) true ); } - if (sharedCalUrl != "") + if (sharedCalUrl.Length != 0) { var calendarIcs = GetCalendariCalString(calendarId, true); @@ -653,7 +653,7 @@ public string GetCalendarCalDavUrl(string calendarId) 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 @@ public string GetCalendarCalDavUrl(string calendarId) var caldavCalendar = GetUserCaldavCalendar(calUrl, userName); - if (caldavCalendar != "") + if (caldavCalendar.Length != 0) { if (caldavCalendar == "NotFound") { @@ -1746,7 +1746,7 @@ private void deleteEvent(string uid, string calendarId, string email, Uri myUri, сaldavGuid = calendarId; } - if (сaldavGuid != "") + if (сaldavGuid.Length != 0) { var calDavServerUrl = myUri.Scheme + "://" + myUri.Host + "/caldav"; @@ -3554,10 +3554,10 @@ private string GetRRuleString(Ical.Net.CalendarComponents.CalendarEvent evt) 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 @@ private string GetRRuleString(Ical.Net.CalendarComponents.CalendarEvent evt) } } //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 @@ private void updateCaldavEvent( { try { - if (guid != null && guid != "") + if (guid != null && guid.Length != 0) { var calDavServerUrl = myUri.Scheme + "://" + myUri.Host + "/caldav"; @@ -4647,7 +4647,7 @@ private void ReplaceSharingEvent( 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 9130e13efc1..d8c6b36cb33 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 @@ protected virtual bool parseValue() } 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 2ab517eca92..22766b3bf5c 100644 --- a/products/ASC.Calendar/Server/iCalParser/Token.cs +++ b/products/ASC.Calendar/Server/iCalParser/Token.cs @@ -181,8 +181,8 @@ public static DateTime ParseDateTime(string icalDate, out bool isDate, out bool - 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 b16d11f30bd..db7762e05eb 100644 --- a/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs +++ b/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs @@ -136,7 +136,7 @@ public void doValueProperty(Token t, Token iprop) || _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 d332c3e4af9..cfd0c2a3d77 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -433,7 +433,7 @@ public Folder<T> FolderRename(T folderId, string title) 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 666c1e4f21d..2a1f454dc46 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 @@ protected string MakeId(Item onedriveItem) 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 9c57234b6c8..9e4b374fee5 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 @@ public Folder GetFolderById(object id) 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 129d7e1c0e5..d16a341629c 100644 --- a/products/ASC.Files/Core/HttpHandlers/ThirdPartyAppHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/ThirdPartyAppHandler.ashx.cs @@ -115,7 +115,7 @@ public void Invoke(HttpContext context) 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 bc487297c70..d22a9dad78a 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -751,7 +751,7 @@ public IEnumerable<FileEntry<T>> FilterEntries<T>(IEnumerable<FileEntry<T>> entr 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 @@ public bool FileRename<T>(T fileId, string title, out File<T> file) 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 @@ public bool FileRename<T>(T fileId, string title, out File<T> file) 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 c3da2caf8bc..ec6137f96f6 100644 --- a/products/ASC.Files/Server/Controllers/FilesController.cs +++ b/products/ASC.Files/Server/Controllers/FilesController.cs @@ -2343,7 +2343,7 @@ public object WordpressSaveFromForm([FromForm] WordpressSaveModel model) 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 629326660d1..f72eb80707b 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -2613,7 +2613,7 @@ private void StartMigrate(StorageSettings 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 d89a288a287..baacd1b20d3 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -963,7 +963,7 @@ public static RecurrenceRule Parse(string serializedString) 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 5a590261b04..3ed1a568aa6 100644 --- a/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs +++ b/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs @@ -33,9 +33,7 @@ public class GrammaticalHelper 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 f0a1d81360f..e8bbd64422b 100644 --- a/web/ASC.Web.Core/Utility/CommonLinkUtility.cs +++ b/web/ASC.Web.Core/Utility/CommonLinkUtility.cs @@ -282,7 +282,7 @@ public IWebItem GetWebItemByUrl(string currentURL) 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 @@ public void GetLocationByUrl(string currentURL, out IProduct currentProduct, out 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 @@ public void GetLocationByUrl(string currentURL, out IProduct currentProduct, out 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 @@ private IProduct GetProductBySysName(string sysName) if (!string.IsNullOrEmpty(sysName)) foreach (var product in WebItemManager.GetItemsAll<IProduct>()) { - 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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 13 Jan 2022 14:19:39 +0300 Subject: [PATCH 038/105] 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 03472ef3f89..e9884d38c0f 100644 --- a/common/ASC.Core.Common/ASC.Core.Common.csproj +++ b/common/ASC.Core.Common/ASC.Core.Common.csproj @@ -56,6 +56,7 @@ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="MailKit" Version="2.5.1" /> + <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.0" /> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.0" /> <PackageReference Include="Telegram.Bot" Version="15.7.1" /> diff --git a/common/ASC.Core.Common/Billing/BillingClient.cs b/common/ASC.Core.Common/Billing/BillingClient.cs index 43deeb9523d..406b7edbec0 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -53,6 +53,8 @@ public class BillingClient private const int AvangatePaymentSystemId = 1; + static readonly HttpClient HttpClient = new HttpClient(); + public BillingClient(IConfiguration configuration) : this(false, configuration) @@ -226,8 +228,7 @@ private string Request(string method, string portalId, params Tuple<string, stri 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<string, List<string>>(); if (!string.IsNullOrEmpty(portalId)) @@ -250,7 +251,7 @@ private string Request(string method, string portalId, params Tuple<string, stri 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 eb1c9c41802..c5f433355ed 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<AvangateProduct> Products { get; set; } + private IEnumerable<AvangateProduct> Products { get; set; } + private IHttpClientFactory ClientFactory { get; } private IEnumerable<string> Groups { get; set; } private readonly int Percent; private readonly int Schedule; @@ -56,12 +57,14 @@ public class CouponManager 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<ILog> option) + public CouponManager(IOptionsMonitor<ILog> option, IHttpClientFactory clientFactory) { SemaphoreSlim = new SemaphoreSlim(1, 1); - Log = option.CurrentValue; + Log = option.CurrentValue; + ClientFactory = clientFactory; try { @@ -157,8 +160,12 @@ private async Task<IEnumerable<AvangateProduct>> InternalGetProducts() 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 37f3747262a..42909c8c1a3 100644 --- a/common/ASC.Core.Common/Configuration/AmiPublicDnsSyncService.cs +++ b/common/ASC.Core.Common/Configuration/AmiPublicDnsSyncService.cs @@ -54,13 +54,13 @@ public static void Synchronize() { using var scope = ServiceProvider.CreateScope(); var scopeClass = scope.ServiceProvider.GetService<AmiPublicDnsSyncServiceScope>(); - 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 @@ private static bool MappedDomainNotSettedByUser(string domain) 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 @@ private static string GetAmiPublicDnsName() 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 @@ public class AmiPublicDnsSyncServiceScope { 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 33b679222db..e6f1c09317e 100644 --- a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs +++ b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs @@ -50,15 +50,17 @@ public class PaymentManager 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 @@ public void ActivateKey(string key) 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 d85e0519365..9fcfc9d569f 100644 --- a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs @@ -52,20 +52,23 @@ public class ConfigureSignalrServiceClient : IConfigureNamedOptions<SignalrServi internal CoreSettings CoreSettings { get; } internal MachinePseudoKeys MachinePseudoKeys { get; } internal IConfiguration Configuration { get; } - internal IOptionsMonitor<ILog> Options { get; } + internal IOptionsMonitor<ILog> Options { get; } + internal IHttpClientFactory ClientFactory { get; } public ConfigureSignalrServiceClient( TenantManager tenantManager, CoreSettings coreSettings, MachinePseudoKeys machinePseudoKeys, IConfiguration configuration, - IOptionsMonitor<ILog> options) + IOptionsMonitor<ILog> 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 @@ public void Configure(string name, SignalrServiceClient options) 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 @@ public class SignalrServiceClient 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 @@ private string MakeRequest(string method, object data) 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 15049ae5d87..d3a0ade5253 100644 --- a/common/ASC.Data.Storage/BaseStorage.cs +++ b/common/ASC.Data.Storage/BaseStorage.cs @@ -29,6 +29,7 @@ using System.Globalization; using System.IO; using System.Linq; +using System.Net.Http; using System.Threading.Tasks; using System.Web; @@ -53,6 +54,7 @@ public abstract class BaseStorage : IDataStore protected EmailValidationKeyProvider EmailValidationKeyProvider { get; } protected IHttpContextAccessor HttpContextAccessor { get; } protected IOptionsMonitor<ILog> Options { get; } + protected IHttpClientFactory ClientFactory { get; } public BaseStorage( TempStream tempStream, @@ -60,7 +62,8 @@ public BaseStorage( PathUtils pathUtils, EmailValidationKeyProvider emailValidationKeyProvider, IHttpContextAccessor httpContextAccessor, - IOptionsMonitor<ILog> options) + IOptionsMonitor<ILog> options, + IHttpClientFactory clientFactory) { TempStream = tempStream; @@ -70,6 +73,7 @@ public BaseStorage( 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 249551c6953..8774b9170d2 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -28,6 +28,7 @@ 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 @@ public DiscDataStore( IHttpContextAccessor httpContextAccessor, IOptionsMonitor<ILog> 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 e2ebfb5ff05..178e7f4320a 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -78,7 +78,8 @@ public GoogleCloudStorage( PathUtils pathUtils, EmailValidationKeyProvider emailValidationKeyProvider, IHttpContextAccessor httpContextAccessor, - IOptionsMonitor<ILog> options) : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options) + IOptionsMonitor<ILog> options, + IHttpClientFactory clientFactory) : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options, clientFactory) { } @@ -781,7 +782,7 @@ public override string UploadChunk(string domain, 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 4c66b702aac..da7516dafd6 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -28,6 +28,7 @@ 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 @@ public RackspaceCloudStorage( PathUtils pathUtils, EmailValidationKeyProvider emailValidationKeyProvider, IHttpContextAccessor httpContextAccessor, - IOptionsMonitor<ILog> options) - : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options) + IOptionsMonitor<ILog> 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 7a688178c9a..78565501aad 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -29,6 +29,7 @@ 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 @@ public S3Storage( PathUtils pathUtils, EmailValidationKeyProvider emailValidationKeyProvider, IHttpContextAccessor httpContextAccessor, - IOptionsMonitor<ILog> options) - : base(tempStream, tenantManager, pathUtils, emailValidationKeyProvider, httpContextAccessor, options) + IOptionsMonitor<ILog> 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 4c89ff377f6..0e5f4e321fd 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -158,6 +158,7 @@ public class WebPath public IHostEnvironment HostEnvironment { get; } private CoreBaseSettings CoreBaseSettings { get; } private IOptionsMonitor<ILog> Options { get; } + private IHttpClientFactory ClientFactory { get; } public WebPath( WebPathSettings webPathSettings, @@ -166,7 +167,8 @@ public WebPath( StorageSettingsHelper storageSettingsHelper, IHostEnvironment hostEnvironment, CoreBaseSettings coreBaseSettings, - IOptionsMonitor<ILog> options) + IOptionsMonitor<ILog> options, + IHttpClientFactory clientFactory) { WebPathSettings = webPathSettings; ServiceProvider = serviceProvider; @@ -175,6 +177,7 @@ public WebPath( HostEnvironment = hostEnvironment; CoreBaseSettings = coreBaseSettings; Options = options; + ClientFactory = clientFactory; } public WebPath( @@ -186,8 +189,9 @@ public WebPath( IHttpContextAccessor httpContextAccessor, IHostEnvironment hostEnvironment, CoreBaseSettings coreBaseSettings, - IOptionsMonitor<ILog> options) - : this(webPathSettings, serviceProvider, settingsManager, storageSettingsHelper, hostEnvironment, coreBaseSettings, options) + IOptionsMonitor<ILog> options, + IHttpClientFactory clientFactory) + : this(webPathSettings, serviceProvider, settingsManager, storageSettingsHelper, hostEnvironment, coreBaseSettings, options, clientFactory) { HttpContextAccessor = httpContextAccessor; } @@ -241,7 +245,7 @@ private bool CheckWebPath(string path) 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 395b2ceb002..87585021621 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<string, string> headers = null, int timeout = 30000) { if (string.IsNullOrEmpty(uri)) throw new ArgumentNullException("uri"); @@ -42,8 +44,7 @@ public static string PerformRequest(string uri, string contentType = "", string 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 @@ public static string PerformRequest(string uri, string contentType = "", string } } - 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 e5d5eea92a6..df56cbd911f 100644 --- a/common/services/ASC.ApiSystem/Classes/CommonMethods.cs +++ b/common/services/ASC.ApiSystem/Classes/CommonMethods.cs @@ -81,6 +81,8 @@ public class CommonMethods private TenantManager TenantManager { get; } + private IHttpClientFactory ClientFactory { get; } + public CommonMethods( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, @@ -92,7 +94,8 @@ public CommonMethods( IMemoryCache memoryCache, IOptionsSnapshot<HostedSolution> hostedSolutionOptions, CoreBaseSettings coreBaseSettings, - TenantManager tenantManager) + TenantManager tenantManager, + IHttpClientFactory clientFactory) { HttpContextAccessor = httpContextAccessor; @@ -111,8 +114,13 @@ public CommonMethods( CommonConstants = commonConstants; MemoryCache = memoryCache; + CoreBaseSettings = coreBaseSettings; + TenantManager = tenantManager; + + ClientFactory = clientFactory; + HostedSolution = hostedSolutionOptions.Get(CommonConstants.BaseDbConnKeyString); } @@ -176,7 +184,7 @@ public bool SendCongratulations(string requestUriScheme, Tenant tenant, bool ski 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 @@ public bool ValidateRecaptcha(string response, string ip) 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 0bd087230b4..a4fe0e4849c 100644 --- a/common/services/ASC.ApiSystem/Controllers/CalDavController.cs +++ b/common/services/ASC.ApiSystem/Controllers/CalDavController.cs @@ -60,6 +60,7 @@ public class CalDavController : ControllerBase private CommonConstants CommonConstants { get; } public InstanceCrypto InstanceCrypto { get; } private ILog Log { get; } + private IHttpClientFactory ClientFactory { get; } public CalDavController( CommonMethods commonMethods, @@ -344,7 +345,7 @@ private void SendToApi(string requestUriScheme, 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 e0eb541fe13..1e5f55a9556 100644 --- a/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs +++ b/products/ASC.CRM/Server/Classes/ContactPhotoManager.cs @@ -84,7 +84,8 @@ public class ContactPhotoManager public readonly WebImageSupplier _webImageSupplier; private readonly DistributedTaskQueue _resizeQueue; private readonly ICacheNotify<ContactPhotoManagerCacheItem> _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 @@ public ContactPhotoManager(Global global, IOptionsMonitor<ILog> logger, ICache cache, ICacheNotify<ContactPhotoManagerCacheItem> cacheNotify, - DistributedTaskQueueOptionsManager optionsQueue) + DistributedTaskQueueOptionsManager optionsQueue, + IHttpClientFactory clientFactory) { _global = global; _webImageSupplier = webImageSupplier; _cacheNotify = cacheNotify; _cache = cache; _resizeQueue = optionsQueue.Get<ResizeWorkerItem>(); - _logger = logger.Get("ASC.CRM"); + _logger = logger.Get("ASC.CRM"); + _clientFactory = clientFactory; _cacheNotify.Subscribe((x) => { @@ -541,7 +544,7 @@ public PhotoData UploadPhoto(String imageUrl, int contactID, bool uploadOnly, bo 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 @@ public PhotoData UploadPhotoToTemp(String imageUrl, String tmpDirName, bool chec 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 e38fad6353a..4867f36f213 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 @@ public override void ConfigureServices(IServiceCollection services) base.ConfigureServices(services); + services.AddHttpClient("DownloadCurrencyPage").ConfigurePrimaryHttpMessageHandler(() => + { + return new HttpClientHandler() + { + AllowAutoRedirect = true, + MaxAutomaticRedirections = 2, + UseDefaultCredentials = true + }; + }); + DIHelper.TryAdd<EntryPointApiController>(); DIHelper.TryAdd<CasesController>(); DIHelper.TryAdd<ContactInfosController>(); diff --git a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs index e6fa13f3881..a75ffe54851 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<String, CurrencyInfo> _currencies; private Dictionary<string, decimal> _exchangeRates; @@ -56,7 +57,8 @@ public class CurrencyProvider public CurrencyProvider(IOptionsMonitor<ILog> logger, IConfiguration configuration, SettingsManager settingsManager, - DaoFactory daoFactory) + DaoFactory daoFactory, + IHttpClientFactory clientFactory) { _log = logger.Get("ASC"); Configuration = configuration; @@ -73,8 +75,8 @@ public CurrencyProvider(IOptionsMonitor<ILog> logger, }; } - _currencies = currencies.ToDictionary(c => c.Abbreviation); - + _currencies = currencies.ToDictionary(c => c.Abbreviation); + _clientFactory = clientFactory; } public IConfiguration Configuration { get; } @@ -339,7 +341,8 @@ private void DownloadCurrencyPage(string currency, string filepath) 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 d45abb0c694..cdec421bb00 100644 --- a/products/ASC.CRM/Server/Utils/PdfCreator.cs +++ b/products/ASC.CRM/Server/Utils/PdfCreator.cs @@ -57,7 +57,8 @@ public class PdfCreator private DocumentServiceConnector _documentServiceConnector; private OrganisationLogoManager _organisationLogoManager; private Files.Classes.PathProvider _filesPathProvider; - private ILog _logger; + private ILog _logger; + private IHttpClientFactory _clientFactory; public PdfCreator(IOptionsMonitor<ILog> logger, @@ -66,7 +67,8 @@ public PdfCreator(IOptionsMonitor<ILog> logger, IServiceProvider serviceProvider, OrganisationLogoManager organisationLogoManager, DaoFactory daoFactory, - InvoiceFormattedData invoiceFormattedData) + InvoiceFormattedData invoiceFormattedData, + IHttpClientFactory clientFactory) { _filesPathProvider = filesPathProvider; @@ -76,7 +78,8 @@ public PdfCreator(IOptionsMonitor<ILog> logger, _serviceProvider = serviceProvider; _organisationLogoManager = organisationLogoManager; _daoFactory = daoFactory; - _invoiceFormattedData = invoiceFormattedData; + _invoiceFormattedData = invoiceFormattedData; + _clientFactory = clientFactory; } @@ -130,7 +133,7 @@ public void CreateAndSaveFile(int invoiceId) 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 @@ private File<int> SaveFile(Invoice data, string url, DaoFactory daoFactory) 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 198f1f7e0ce..f50bda60943 100644 --- a/products/ASC.CRM/Server/Utils/ReportHelper.cs +++ b/products/ASC.CRM/Server/Utils/ReportHelper.cs @@ -58,6 +58,7 @@ public class ReportHelper private SettingsManager _settingsManager; private TenantUtil _tenantUtil; private TenantManager _tenantManager; + private IHttpClientFactory _clientFactory; public ReportHelper(TenantManager tenantManager, TenantUtil tenantUtil, @@ -68,7 +69,8 @@ public ReportHelper(TenantManager tenantManager, SecurityContext securityContext, IServiceProvider serviceProvider, IHttpContextAccessor httpContextAccessor, - CurrencyProvider currencyProvider + CurrencyProvider currencyProvider, + IHttpClientFactory clientFactory ) { _tenantManager = tenantManager; @@ -81,6 +83,7 @@ CurrencyProvider currencyProvider _securityContext = securityContext; _httpContext = httpContextAccessor; _currencyProvider = currencyProvider; + _clientFactory = clientFactory; } private string GetFileName(ReportType reportType) @@ -224,7 +227,7 @@ private string GetReportScript(object data, ReportType type, string fileName) 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 8be1a4cc6d3..dde3267985b 100644 --- a/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs +++ b/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs @@ -81,6 +81,7 @@ public string UserId protected DDayICalParser DDayICalParser { get; } public ILog Log { get; } public InstanceCrypto InstanceCrypto { get; } + public IHttpClientFactory ClientFactory { get; } public DataProvider(DbContextManager<CalendarDbContext> calendarDbContext, AuthManager authentication, @@ -93,7 +94,8 @@ public DataProvider(DbContextManager<CalendarDbContext> calendarDbContext, UserManager userManager, DDayICalParser dDayICalParser, IOptionsMonitor<ILog> option, - InstanceCrypto instanceCrypto) + InstanceCrypto instanceCrypto, + IHttpClientFactory clientFactory) { Authentication = authentication; CalendarDb = calendarDbContext.Get("calendar"); @@ -107,7 +109,7 @@ public DataProvider(DbContextManager<CalendarDbContext> calendarDbContext, DDayICalParser = dDayICalParser; Log = option.Get("ASC.CalendarDataProvider"); InstanceCrypto = instanceCrypto; - + ClientFactory = clientFactory; } public List<UserViewSettings> GetUserViewSettings(Guid userId, List<string> calendarIds) @@ -335,7 +337,7 @@ where calIds.Contains(cc.Id) 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 @@ public void RemoveCaldavCalendar(string currentUserName, string email, string ca 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 @@ public List<Todo> GetTodosByIds(int[] todoIds, Guid userId, int tenantId = -1) 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 @@ public List<Todo> GetTodosByIds(int[] todoIds, Guid userId, int tenantId = -1) 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 @@ from ue in UserEvent.DefaultIfEmpty() 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 @@ from ue in UserEvent.DefaultIfEmpty() 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 547200dd531..478b020906b 100644 --- a/products/ASC.Calendar/Server/Controllers/CalendarController.cs +++ b/products/ASC.Calendar/Server/Controllers/CalendarController.cs @@ -111,7 +111,8 @@ public class CalendarController : ControllerBase 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 @@ public CalendarController( SetupInfo setupInfo, InstanceCrypto instanceCrypto, CalendarManager calendarManager, - ProductEntryPoint productEntryPoint) + ProductEntryPoint productEntryPoint, + IHttpClientFactory clientFactory) { AuthContext = authContext; Authentication = authentication; @@ -172,7 +174,8 @@ public CalendarController( 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 @@ public string GetCalendarCalDavUrl(string calendarId) 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 @@ private string GetUserCaldavCalendar(string calUrl, string encoded) 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 @@ private string CreateCalDavCalendar(string name, string description, string back 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 @@ public CalendarWrapper CreateCalendar(CalendarModel calendar) { 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 @@ public CalendarWrapper UpdateCalendar(string calendarId, CalendarModel calendar) 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 @@ private void deleteEvent(string uid, string calendarId, string email, Uri myUri, 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 @@ public List<TodoWrapper> AddTodo(CreateTodoModel createTodoModel) 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 @@ public CalendarWrapper CreateCalendarStream(СalendarUrlModel сalendarUrl) 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 @@ private void updateCaldavEvent( 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 @@ private void UpdateCalDavEvent(string change, Uri calDavUrl) 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 @@ private string UpdateCalDavCalendar(string name, string description, string back 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 @@ private void ReplaceSharingEvent( 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 @@ private void UpdateSharedEvent(UserInfo userSharingInfo, string guid, bool fullA 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 96a942a087c..2be4acbeadf 100644 --- a/products/ASC.Calendar/Server/Models/EventWrapper.cs +++ b/products/ASC.Calendar/Server/Models/EventWrapper.cs @@ -38,6 +38,7 @@ using ASC.Common; using ASC.Calendar.iCalParser; using ASC.Calendar.BusinessObjects; +using System.Net.Http; namespace ASC.Calendar.Models { @@ -140,6 +141,7 @@ public class EventWrapperHelper private AuthContext AuthContext { get; } private TimeZoneConverter TimeZoneConverter { get; } private DataProvider DataProvider { get; } + private IHttpClientFactory ClientFactory { get; } public EventWrapperHelper( UserManager userManager, @@ -150,7 +152,8 @@ public EventWrapperHelper( PublicItemCollectionHelper publicItemCollectionHelper, AuthContext context, TimeZoneConverter timeZoneConverter, - DataProvider dataProvider) + DataProvider dataProvider, + IHttpClientFactory clientFactory) { Authentication = authentication; TenantManager = tenantManager; @@ -161,6 +164,7 @@ public EventWrapperHelper( 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 @@ public EventWrapper Get(IEvent baseEvent, Guid userId, TimeZoneInfo timeZone) 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 7da6fef1a69..c0744159c19 100644 --- a/products/ASC.Calendar/Server/Models/PublicItemWrapper.cs +++ b/products/ASC.Calendar/Server/Models/PublicItemWrapper.cs @@ -35,6 +35,7 @@ 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 @@ public class PublicItemWrapperHelper 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 @@ public PublicItemWrapperHelper( TimeZoneConverter timeZoneConverter, PermissionContext permissionContext, DisplayUserSettingsHelper displayUserSettingsHelper, - DataProvider dataProvider) + DataProvider dataProvider, + IHttpClientFactory clientFactory) { UserManager = userManager; Authentication = authentication; @@ -106,6 +109,7 @@ public PublicItemWrapperHelper( 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 @@ protected void Init(ASC.Web.Core.Calendars.SharingOptions.PublicItem publicItem, 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 @@ protected void Init(ASC.Web.Core.Calendars.SharingOptions.PublicItem publicItem, } 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 d15296ce437..c2e429b1031 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 @@ public iCalendar GetFromUrl(string url) 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 @@ public iCalendar GetFromUrl(string url, string calendarId) 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 @@ public iCalendar GetFromUrl(string url, string calendarId) 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 94f8b9bbc32..9e1bbd389cf 100644 --- a/products/ASC.Calendar/Server/iCalParser/iCalendarCache.cs +++ b/products/ASC.Calendar/Server/iCalParser/iCalendarCache.cs @@ -28,6 +28,7 @@ using System.IO; using ASC.Core; using ASC.Common.Utils; +using System.Net.Http; namespace ASC.Calendar.iCalParser { @@ -58,21 +59,25 @@ internal class iCalendarCache 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 @@ public iCalendar GetCalendarFromCache(string calendarId) 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 db7762e05eb..a22ab26dec0 100644 --- a/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs +++ b/products/ASC.Calendar/Server/iCalParser/iCalendarEmitter.cs @@ -30,6 +30,7 @@ using ASC.Common.Utils; using ASC.Web.Core.Calendars; using ASC.Core; +using System.Net.Http; namespace ASC.Calendar.iCalParser { @@ -46,14 +47,17 @@ public class iCalendarEmitter : IEmitter 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 @@ public void doComponentBegin(Token t) 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 42968cfb722..f16d6dabcca 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<ILog> monitor, - TempStream tempStream) - { - ConsumerFactory = consumerFactory; - FileUtility = fileUtility; - Log = monitor.Get("ASC.Files"); - TempStream = tempStream; - } - + { private OAuth20Token _token; private string AccessToken @@ -94,9 +82,24 @@ private string AccessToken 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<ILog> 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 @@ public Stream DownloadStream(DriveFile file, int offset = 0) 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 @@ public ResumableUploadSession CreateResumableSession(DriveFile driveFile, long c 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 @@ public void Transfer(ResumableUploadSession googleDriveSession, Stream stream, l 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 4eea2afd8d2..4ac06117212 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 @@ private OneDriveClient OnedriveClient } 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 @@ public ResumableUploadSession CreateResumableSession(Item onedriveFile, long con 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 @@ public void Transfer(ResumableUploadSession oneDriveSession, Stream stream, long 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 @@ public void CancelTransfer(ResumableUploadSession oneDriveSession) 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 4ed9f1b5f8e..75ba36c129f 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -120,7 +120,8 @@ public string FileHandlerPath 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 @@ public FileHandlerService( FileConverter fileConverter, FFmpegService fFmpegService, IServiceProvider serviceProvider, - TempStream tempStream) + TempStream tempStream, + IHttpClientFactory clientFactory) { FilesLinkUtility = filesLinkUtility; TenantExtra = tenantExtra; @@ -172,7 +174,8 @@ public FileHandlerService( ServiceProvider = serviceProvider; TempStream = tempStream; UserManager = userManager; - Logger = optionsMonitor.CurrentValue; + Logger = optionsMonitor.CurrentValue; + ClientFactory = clientFactory; } public Task Invoke(HttpContext context) @@ -1208,7 +1211,7 @@ private File<T> CreateFileFromUri<T>(Folder<T> folder, string fileUri, string fi request.RequestUri = new Uri(fileUri); var fileDao = DaoFactory.GetFileDao<T>(); - 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 6f09cae6b8e..157805d7617 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs @@ -55,7 +55,8 @@ public class DocumentServiceConnector { 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 @@ public DocumentServiceConnector( BaseCommonLinkUtility baseCommonLinkUtility, TenantManager tenantManager, TenantExtra tenantExtra, - CoreSettings coreSettings) + CoreSettings coreSettings, + IHttpClientFactory clientFactory) { Logger = optionsMonitor.CurrentValue; FilesLinkUtility = filesLinkUtility; @@ -82,7 +84,8 @@ public DocumentServiceConnector( TenantManager = tenantManager; TenantExtra = tenantExtra; CoreSettings = coreSettings; - PathProvider = pathProvider; + PathProvider = pathProvider; + ClientFactory = clientFactory; } public static string GenerateRevisionId(string expectedKey) @@ -114,7 +117,8 @@ public int GetConvertedUri(string documentUri, thumbnail, spreadsheetLayout, isAsync, - FileUtility.SignatureSecret, + FileUtility.SignatureSecret, + ClientFactory, out convertedDocumentUri); } catch (Exception ex) @@ -141,7 +145,8 @@ public bool Command(CommandMethod method, callbackUrl, users, meta, - FileUtility.SignatureSecret, + FileUtility.SignatureSecret, + ClientFactory, out var version); if (result == Web.Core.Files.DocumentService.CommandResultTypes.NoError) @@ -187,7 +192,8 @@ public string DocbuilderRequest(string requestKey, GenerateRevisionId(requestKey), scriptUrl, isAsync, - FileUtility.SignatureSecret, + FileUtility.SignatureSecret, + ClientFactory, out urls); } catch (Exception ex) @@ -209,7 +215,8 @@ public string GetVersion() null, null, null, - FileUtility.SignatureSecret, + FileUtility.SignatureSecret, + ClientFactory, out var version); if (result == Web.Core.Files.DocumentService.CommandResultTypes.NoError) @@ -232,7 +239,7 @@ public void CheckDocServiceUrl() { 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 @@ public void CheckDocServiceUrl() 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 @@ public void CheckDocServiceUrl() 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 @@ public void CheckDocServiceUrl() 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 @@ public void CheckDocServiceUrl() 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 580f128df56..dfde169ca71 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -67,6 +67,7 @@ public class FilesControllerHelper<T> private EncryptionKeyPairHelper EncryptionKeyPairHelper { get; } private IHttpContextAccessor HttpContextAccessor { get; } private ILog Logger { get; set; } + private IHttpClientFactory ClientFactory { get; set; } /// <summary> /// </summary> @@ -93,7 +94,8 @@ public FilesControllerHelper( IOptionsMonitor<ILog> optionMonitor, SettingsManager settingsManager, EncryptionKeyPairHelper encryptionKeyPairHelper, - IHttpContextAccessor httpContextAccessor) + IHttpContextAccessor httpContextAccessor, + IHttpClientFactory clientFactory) { ApiContext = context; FileStorageService = fileStorageService; @@ -116,6 +118,7 @@ public FilesControllerHelper( EncryptionKeyPairHelper = encryptionKeyPairHelper; HttpContextAccessor = httpContextAccessor; Logger = optionMonitor.Get("ASC.Files"); + ClientFactory = clientFactory; } public FolderContentWrapper<T> GetFolder(T folderId, Guid userIdOrGroupId, FilterType filterType, bool withSubFolders) @@ -257,7 +260,7 @@ public object CreateUploadSession(T folderId, string fileName, long fileSize, st 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 653aea59082..c24fb691ea6 100644 --- a/products/ASC.Files/Service/Thumbnail/Builder.cs +++ b/products/ASC.Files/Service/Thumbnail/Builder.cs @@ -48,9 +48,12 @@ internal class BuilderQueue<T> { private readonly ThumbnailSettings config; private readonly ILog logger; + private readonly IHttpClientFactory clientFactory; private IServiceProvider ServiceProvider { get; } - public BuilderQueue(IServiceProvider serviceProvider, IOptionsMonitor<ILog> log, ASC.Common.Utils.ConfigurationExtension configurationExtension) + public BuilderQueue(IServiceProvider serviceProvider, + IOptionsMonitor<ILog> log, + Common.Utils.ConfigurationExtension configurationExtension) { logger = log.Get("ASC.Files.ThumbnailBuilder"); ServiceProvider = serviceProvider; @@ -94,6 +97,7 @@ internal class Builder<T> 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 @@ public Builder( DocumentServiceHelper documentServiceHelper, Global global, PathProvider pathProvider, - IOptionsMonitor<ILog> log) + IOptionsMonitor<ILog> log, + IHttpClientFactory clientFactory) { this.config = ThumbnailSettings.GetInstance(configurationExtension); TenantManager = tenantManager; @@ -112,7 +117,8 @@ public Builder( DocumentServiceHelper = documentServiceHelper; Global = global; PathProvider = pathProvider; - logger = log.Get("ASC.Files.ThumbnailBuilder"); + logger = log.Get("ASC.Files.ThumbnailBuilder"); + ClientFactory = clientFactory; } internal void BuildThumbnail(FileData<T> fileData) @@ -289,7 +295,7 @@ private void SaveThumbnail(IFileDao<T> fileDao, File<T> file, string thumbnailUr 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 29ffb632965..b48b26f846f 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -99,6 +99,7 @@ public class PeopleController : ControllerBase private Constants Constants { get; } private Recaptcha Recaptcha { get; } private ILog Log { get; } + private IHttpClientFactory ClientFactory { get; } public PeopleController( MessageService messageService, @@ -140,7 +141,8 @@ public PeopleController( MobileDetector mobileDetector, ProviderManager providerManager, Constants constants, - Recaptcha recaptcha + Recaptcha recaptcha, + IHttpClientFactory clientFactory ) { Log = option.Get("ASC.Api"); @@ -183,6 +185,7 @@ Recaptcha recaptcha ProviderManager = providerManager; Constants = constants; Recaptcha = recaptcha; + ClientFactory = clientFactory; } [Read("info")] @@ -1851,7 +1854,7 @@ private void SaveContactImage(Guid userID, string url) 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 @@ private void UpdatePhotoUrl(string files, UserInfo user) 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 7b4e13337e5..d4262ac59bd 100644 --- a/web/ASC.Web.Api/Controllers/PortalController.cs +++ b/web/ASC.Web.Api/Controllers/PortalController.cs @@ -55,6 +55,7 @@ public class PortalController : ControllerBase public SetupInfo SetupInfo { get; } private TenantExtra TenantExtra { get; set; } public ILog Log { get; } + public IHttpClientFactory ClientFactory { get; } public PortalController( @@ -74,7 +75,8 @@ public PortalController( IConfiguration configuration, CoreBaseSettings coreBaseSettings, LicenseReader licenseReader, - SetupInfo setupInfo + SetupInfo setupInfo, + IHttpClientFactory clientFactory ) { Log = options.CurrentValue; @@ -94,6 +96,7 @@ SetupInfo setupInfo LicenseReader = licenseReader; SetupInfo = setupInfo; TenantExtra = tenantExtra; + ClientFactory = clientFactory; } [Read("")] @@ -216,7 +219,7 @@ public FileResult GetThumb(string url) 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 f72eb80707b..4d3ea3fe800 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -172,6 +172,7 @@ public partial class SettingsController : ControllerBase private PaymentManager PaymentManager { get; } private DbWorker WebhookDbWorker { get; } public Constants Constants { get; } + public IHttpClientFactory ClientFactory { get; } public SettingsController( IOptionsMonitor<ILog> option, @@ -234,7 +235,8 @@ public SettingsController( PasswordHasher passwordHasher, PaymentManager paymentManager, DbWorker dbWorker, - Constants constants) + Constants constants, + IHttpClientFactory clientFactory) { Log = option.Get("ASC.Api"); WebHostEnvironment = webHostEnvironment; @@ -297,6 +299,7 @@ public SettingsController( PaymentManager = paymentManager; WebhookDbWorker = dbWorker; Constants = constants; + ClientFactory = clientFactory; } [Read("", Check = false)] @@ -1377,7 +1380,7 @@ private TipsSettings UpdateTipsSettings(SettingsModel model) 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 24cc65fec9e..8027e62eecf 100644 --- a/web/ASC.Web.Api/Core/FirstTimeTenantSettings.cs +++ b/web/ASC.Web.Api/Core/FirstTimeTenantSettings.cs @@ -70,6 +70,7 @@ public class FirstTimeTenantSettings private StudioNotifyService StudioNotifyService { get; } private TimeZoneConverter TimeZoneConverter { get; } public CoreBaseSettings CoreBaseSettings { get; } + public IHttpClientFactory ClientFactory { get; } public FirstTimeTenantSettings( IOptionsMonitor<ILog> options, @@ -84,7 +85,8 @@ public FirstTimeTenantSettings( LicenseReader licenseReader, StudioNotifyService studioNotifyService, TimeZoneConverter timeZoneConverter, - CoreBaseSettings coreBaseSettings) + CoreBaseSettings coreBaseSettings, + IHttpClientFactory clientFactory) { Log = options.CurrentValue; TenantManager = tenantManager; @@ -99,6 +101,7 @@ public FirstTimeTenantSettings( StudioNotifyService = studioNotifyService; TimeZoneConverter = timeZoneConverter; CoreBaseSettings = coreBaseSettings; + ClientFactory = clientFactory; } public WizardSettings SaveData(WizardModel wizardModel) @@ -247,7 +250,7 @@ private bool IncorrectAmiId(string customAmiId) 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 @@ private void SubscribeFromSite(UserInfo user) 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 9ca0b2ef155..16503371300 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -110,6 +110,7 @@ public static int GetConvertedUri( SpreadsheetLayout spreadsheetLayout, bool isAsync, string signatureSecret, + IHttpClientFactory clientFactory, out string convertedDocumentUri) { fromExtension = string.IsNullOrEmpty(fromExtension) ? Path.GetExtension(documentUri) : fromExtension; @@ -129,7 +130,7 @@ public static int GetConvertedUri( 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 @@ public static CommandResultTypes CommandRequest(FileUtility fileUtility, 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 @@ public static string DocbuilderRequest( string scriptUrl, bool isAsync, string signatureSecret, + IHttpClientFactory clientFactory, out Dictionary<string, string> urls) { if (string.IsNullOrEmpty(docbuilderUrl)) @@ -316,7 +319,7 @@ public static string DocbuilderRequest( 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 @@ public static string DocbuilderRequest( return responseFromService.Value<string>("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 @@ public static bool HealthcheckRequest(string healthcheckUrl) 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 ebb370dea2f..713972fa7f2 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 @@ private string SendToApi(string absoluteApiUrl, string apiPath, string httpMetho 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 6e017f9be7a..cccc9dd80fd 100644 --- a/web/ASC.Web.Core/Recaptcha.cs +++ b/web/ASC.Web.Core/Recaptcha.cs @@ -27,10 +27,12 @@ public RecaptchaException(string message) 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 @@ public bool ValidateRecaptcha(string response, string ip) 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 18d93d0272c..aaf04b470b1 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -118,7 +118,8 @@ public bool SendMessage(string number, string message) 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 @@ protected SmsProvider( ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order, Dictionary<string, string> props, Dictionary<string, string> 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 @@ public virtual bool SendMessage(string number, string message) 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 @@ public SmscProvider( ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order, Dictionary<string, string> props, Dictionary<string, string> 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 @@ public string GetBalance(Tenant tenant, bool eraseCache = false) 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 @@ public ClickatellProvider( ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order, Dictionary<string, string> props, Dictionary<string, string> 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 @@ public ClickatellUSAProvider( ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order, Dictionary<string, string> 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 @@ public TwilioProvider( ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> options, + IHttpClientFactory clientFactory, ICache memCache, string name, int order, Dictionary<string, string> 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 @@ public TwilioSaaSProvider( ICacheNotify<ConsumerCacheItem> cache, ConsumerFactory consumerFactory, IOptionsMonitor<ILog> 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 ac8f8ecd058..32f94f8eec3 100644 --- a/web/ASC.Web.Core/Utility/UrlShortener.cs +++ b/web/ASC.Web.Core/Utility/UrlShortener.cs @@ -38,7 +38,7 @@ public IUrlShortener Instance } 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 @@ public IUrlShortener Instance 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 @@ public class OnlyoShortener : IUrlShortener { 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 @@ public OnlyoShortener( 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 @@ public string GetShortenLink(string shareLink) 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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 13 Jan 2022 14:30:40 +0300 Subject: [PATCH 039/105] 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 7278d24d28e..572c7bf97a9 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -184,7 +184,8 @@ public class DocumentServiceTrackerHelper 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 @@ public DocumentServiceTrackerHelper( DocumentServiceConnector documentServiceConnector, NotifyClient notifyClient, MailMergeTaskRunner mailMergeTaskRunner, - FileTrackerHelper fileTracker) + FileTrackerHelper fileTracker, + IHttpClientFactory clientFactory) { SecurityContext = securityContext; UserManager = userManager; @@ -225,7 +227,8 @@ public DocumentServiceTrackerHelper( NotifyClient = notifyClient; MailMergeTaskRunner = mailMergeTaskRunner; FileTracker = fileTracker; - Logger = options.CurrentValue; + Logger = options.CurrentValue; + ClientFactory = clientFactory; } public string GetCallbackUrl<T>(T fileId) @@ -491,7 +494,7 @@ private TrackResponse ProcessMailMerge<T>(T fileId, TrackerData fileData) 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 @@ private TrackResponse ProcessMailMerge<T>(T fileId, TrackerData fileData) 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 @@ private void StoringFileAfterError<T>(T fileId, string userId, string downloadUr 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 @@ private void SaveHistory<T>(File<T> file, string changes, string differenceUrl) 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 7c9df95b32b..2532231761b 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -112,7 +112,8 @@ public bool IsEnabled 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 @@ public BoxApp( CoreSettings coreSettings, IConfiguration configuration, ICacheNotify<ConsumerCacheItem> cache, - ConsumerFactory consumerFactory, + ConsumerFactory consumerFactory, + IHttpClientFactory clientFactory, string name, int order, Dictionary<string, string> additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) { @@ -169,7 +171,8 @@ public BoxApp( DocumentServiceConnector = documentServiceConnector; ThirdPartyAppHandlerService = thirdPartyAppHandlerService; ServiceProvider = serviceProvider; - Logger = option.CurrentValue; + Logger = option.CurrentValue; + ClientFactory = clientFactory; } public bool Request(HttpContext context) @@ -310,7 +313,7 @@ public void SaveFile(string fileId, string fileType, string downloadUrl, Stream } } - 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 @@ private void StreamFile(HttpContext context) 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 c56d3da2183..88fc5610b74 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -118,7 +118,8 @@ public bool IsEnabled 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 @@ public GoogleDriveApp( CoreSettings coreSettings, IConfiguration configuration, ICacheNotify<ConsumerCacheItem> cache, - ConsumerFactory consumerFactory, + ConsumerFactory consumerFactory, + IHttpClientFactory clientFactory, string name, int order, Dictionary<string, string> additional) : base(tenantManager, coreBaseSettings, coreSettings, configuration, cache, consumerFactory, name, order, additional) { @@ -183,7 +185,8 @@ public GoogleDriveApp( TokenHelper = tokenHelper; DocumentServiceConnector = documentServiceConnector; ThirdPartyAppHandlerService = thirdPartyAppHandlerService; - ServiceProvider = serviceProvider; + ServiceProvider = serviceProvider; + ClientFactory = clientFactory; } public bool Request(HttpContext context) @@ -315,7 +318,7 @@ public void SaveFile(string fileId, string fileType, string downloadUrl, Stream } } - 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 @@ private void StreamFile(HttpContext context) 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 @@ private string CreateFile(string contentUrl, string fileName, string folderId, T 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 @@ private string CreateFile(Stream content, string fileName, string folderId, Toke { 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 @@ private string CreateConvertedFile(string driveFile, Token token) 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 d22a9dad78a..87e1fa8a715 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -267,7 +267,8 @@ public class EntryManager 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 @@ public EntryManager( IServiceProvider serviceProvider, ICache cache, FileTrackerHelper fileTracker, - EntryStatusManager entryStatusManager) + EntryStatusManager entryStatusManager, + IHttpClientFactory clientFactory) { DaoFactory = daoFactory; FileSecurity = fileSecurity; @@ -323,6 +325,7 @@ public EntryManager( Cache = cache; FileTracker = fileTracker; EntryStatusManager = entryStatusManager; + ClientFactory = clientFactory; } public IEnumerable<FileEntry> GetEntries<T>(Folder<T> 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 @@ public File<T> SaveEditing<T>(T fileId, string fileExtension, string downloadUri 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 92746740ab7..3c2d3f9e7cc 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -542,7 +542,8 @@ public class FileConverter 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 @@ public FileConverter( FileTrackerHelper fileTracker, BaseCommonLinkUtility baseCommonLinkUtility, EntryStatusManager entryStatusManager, - IServiceProvider serviceProvider) + IServiceProvider serviceProvider, + IHttpClientFactory clientFactory) { FileUtility = fileUtility; FilesLinkUtility = filesLinkUtility; @@ -585,7 +587,8 @@ public FileConverter( FileTracker = fileTracker; BaseCommonLinkUtility = baseCommonLinkUtility; EntryStatusManager = entryStatusManager; - ServiceProvider = serviceProvider; + ServiceProvider = serviceProvider; + ClientFactory = clientFactory; } public FileConverter( FileUtility fileUtility, @@ -608,11 +611,12 @@ public FileConverter( 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 @@ public Stream Exec<T>(File<T> file, string toExtension) 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 @@ public File<T> SaveConvertedFile<T>(File<T> file, string convertedFileUrl) 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 b08b2c9c938..c1e34a1964f 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -86,14 +86,14 @@ public MailMergeTaskRunner(SetupInfo setupInfo, SecurityContext securityContext, 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 @@ private void CreateDraftMail(MailMergeTask mailMergeTask) mailMergeTask.StreamId = responseCreate["response"]["streamId"].Value<string>(); } - private string AttachToMail(MailMergeTask mailMergeTask) + private string AttachToMail(MailMergeTask mailMergeTask, IHttpClientFactory clientFactory) { if (mailMergeTask.Attach == null) return string.Empty; @@ -141,7 +141,7 @@ private string AttachToMail(MailMergeTask mailMergeTask) 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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 13 Jan 2022 15:04:28 +0300 Subject: [PATCH 040/105] 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 57a8990396f..29b56aa66de 100644 --- a/common/ASC.Api.Core/Core/CustomHealthCheck.cs +++ b/common/ASC.Api.Core/Core/CustomHealthCheck.cs @@ -24,7 +24,7 @@ public static IServiceCollection AddCustomHealthCheck(this IServiceCollection se 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 @@ public static IServiceCollection AddCustomHealthCheck(this IServiceCollection se ); } - 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 e3cdf33aa06..5831431b2f3 100644 --- a/common/ASC.Common/Web/MimeMapping.cs +++ b/common/ASC.Common/Web/MimeMapping.cs @@ -852,7 +852,7 @@ public static string GetExtention(string mimeMapping) 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 3a863053406..a918e260147 100644 --- a/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/TelegramLoginProvider.cs @@ -83,7 +83,7 @@ public TelegramLoginProvider( 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 1ba89b26102..795f119e5a8 100644 --- a/common/ASC.Notify.Textile/TextileStyler.cs +++ b/common/ASC.Notify.Textile/TextileStyler.cs @@ -152,7 +152,7 @@ private string GetLogoImg(NoticeMessage message, string imagePath) 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 @@ private string GetLogoText(NoticeMessage message) 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 b48b26f846f..fb56fa28a65 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -1594,7 +1594,7 @@ public ICollection<AccountInfo> GetAuthProviders(bool inviteView, bool settingsV 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 <anton.sukhorukov@onlyoffice.com> Date: Thu, 13 Jan 2022 15:53:57 +0300 Subject: [PATCH 041/105] 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 125aead66e8..7e83a7d8346 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -97,7 +97,7 @@ public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tena { //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 8dec7cb5089..70cb4b75305 100644 --- a/common/ASC.Common/DependencyInjection/AutofacExtension.cs +++ b/common/ASC.Common/DependencyInjection/AutofacExtension.cs @@ -120,7 +120,7 @@ public static List<string> FindAndLoad(IConfiguration configuration, string curr 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 562cfa32ccc..dc54200caef 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -167,7 +167,7 @@ public string GetBaseDomain(string hostedRegion) { 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 0a0395a6a0d..88f41aa7275 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -341,7 +341,7 @@ internal string ReplaceLogo(TenantManager tenantManager, IHttpContextAccessor ht { 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 555266d4127..8d887eebc04 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -277,13 +277,13 @@ protected void BuildExpression(string expression) 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 5ab25c58378..985cc18bbc7 100644 --- a/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs +++ b/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs @@ -161,7 +161,7 @@ private string GetResource(XmlElement e) 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 d3a0ade5253..823a845089e 100644 --- a/common/ASC.Data.Storage/BaseStorage.cs +++ b/common/ASC.Data.Storage/BaseStorage.cs @@ -141,7 +141,7 @@ public Uri GetPreSignedUri(string domain, string path, TimeSpan expire, IEnumera 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 @@ public Uri GetPreSignedUri(string domain, string path, TimeSpan expire, IEnumera 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 795f119e5a8..baefd5ea3a9 100644 --- a/common/ASC.Notify.Textile/TextileStyler.cs +++ b/common/ASC.Notify.Textile/TextileStyler.cs @@ -299,7 +299,7 @@ private string GetPortalUnsubscribeLink(NoticeMessage message, MailWhiteLabelSet 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 0da996cb695..e679ccd55d0 100644 --- a/common/ASC.Textile/Blocks/NoTextileEncoder.cs +++ b/common/ASC.Textile/Blocks/NoTextileEncoder.cs @@ -39,7 +39,7 @@ public static string EncodeNoTextileZones(string tmp, string patternPrefix, stri 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 b789f9fb30f..985c506815f 100644 --- a/common/ASC.Textile/Blocks/PhraseBlockModifier.cs +++ b/common/ASC.Textile/Blocks/PhraseBlockModifier.cs @@ -35,7 +35,7 @@ protected string PhraseModifierFormat(string input, string modifier, string tag) 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 61b3602ff4c..a051f4fb6ac 100644 --- a/common/ASC.VoipService/Dao/AbstractDao.cs +++ b/common/ASC.VoipService/Dao/AbstractDao.cs @@ -54,7 +54,7 @@ protected int TenantID 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 bdd8d0f133d..72eabc0e72b 100644 --- a/common/services/ASC.ElasticSearch/Core/Selector.cs +++ b/common/services/ASC.ElasticSearch/Core/Selector.cs @@ -341,7 +341,7 @@ private QueryContainer Wrap(Field fieldSelector, Func<Field, QueryContainerDescr 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 @@ private string IsNested(Field selector) 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 @@ public static string WrapAsterisk(this string value) { 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 636a5721c64..f1e71f2a0ae 100644 --- a/products/ASC.CRM/Server/Classes/CSVReader.cs +++ b/products/ASC.CRM/Server/Classes/CSVReader.cs @@ -195,7 +195,7 @@ private object ReadNextObject() } 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 bf183d36be6..13914a7b153 100644 --- a/products/ASC.CRM/Server/Core/Dao/AbstractDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/AbstractDao.cs @@ -300,9 +300,9 @@ protected string GetTenantColumnName(string table) { 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 22766b3bf5c..4c09103c104 100644 --- a/products/ASC.Calendar/Server/iCalParser/Token.cs +++ b/products/ASC.Calendar/Server/iCalParser/Token.cs @@ -123,7 +123,7 @@ public static string CapsCamelCase(string str) { 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 33ca8c75f7f..7370d3b9560 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 @@ protected string GetAvailableTitle(string requestTitle, string parentFolderId, F 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 f94366f4b49..83329eaae87 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 @@ protected string GetAvailableTitle(string requestTitle, string parentFolderPath, 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 2a1f454dc46..a905fbf23cd 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 @@ protected string GetAvailableTitle(string requestTitle, string parentFolderId, F 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 c193facc125..002d6bedba9 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 @@ protected string GetAvailableTitle(string requestTitle, Folder parentFolderID, F 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 9e4b374fee5..8fd12c9e2f0 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 @@ public void InitClientContext(AuthData authData) 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 2216330cea5..1d8f659a00f 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 @@ protected string GetAvailableTitle(string requestTitle, ICloudDirectoryEntry par 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 65c975614c1..5808c024bf6 100644 --- a/web/ASC.Web.Api/Controllers/ThirdPartyController.cs +++ b/web/ASC.Web.Api/Controllers/ThirdPartyController.cs @@ -140,7 +140,7 @@ public object GetCode(string redirect, string code, string error) 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 126cc5569f7..fdee36c2666 100644 --- a/web/ASC.Web.Core/Extensions/StringExtension.cs +++ b/web/ASC.Web.Core/Extensions/StringExtension.cs @@ -52,7 +52,7 @@ public static string HtmlEncode(this string str) /// <returns></returns> 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 16503371300..73f1bbee1b2 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -118,7 +118,7 @@ public static int GetConvertedUri( 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 0b058d1ffc7..234745d4957 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -302,7 +302,7 @@ internal static string GeneratePassword(int minLength, int maxLength, string noi 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 8bffe180c54..40036983eef 100644 --- a/web/ASC.Web.Core/Utility/Skins/WebImageSupplier.cs +++ b/web/ASC.Web.Core/Utility/Skins/WebImageSupplier.cs @@ -111,8 +111,8 @@ private static string GetAppThemeVirtualPath(IWebItem webitem) 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 <anton.sukhorukov@onlyoffice.com> Date: Fri, 14 Jan 2022 16:12:37 +0300 Subject: [PATCH 042/105] 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 | 98 +++++++++---------- .../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, 424 insertions(+), 517 deletions(-) diff --git a/common/ASC.Common/Collections/CachedDictionaryBase.cs b/common/ASC.Common/Collections/CachedDictionaryBase.cs index 6ffa5009cea..68de00e0dff 100644 --- a/common/ASC.Common/Collections/CachedDictionaryBase.cs +++ b/common/ASC.Common/Collections/CachedDictionaryBase.cs @@ -89,7 +89,7 @@ public bool HasItem(string key) 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 bcf43b3c17f..613c1dd405a 100644 --- a/common/ASC.Common/Logging/SelfCleaningTarget.cs +++ b/common/ASC.Common/Logging/SelfCleaningTarget.cs @@ -111,7 +111,7 @@ private void Clean() { 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 952ce416615..3f980fb9948 100644 --- a/common/ASC.Common/Security/Authorizing/AuthorizingException.cs +++ b/common/ASC.Common/Security/Authorizing/AuthorizingException.cs @@ -104,25 +104,16 @@ internal static string FormatErrorMessage(ISubject subject, IAction[] actions, I 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 df93ff3b943..3099de7f86f 100644 --- a/common/ASC.Common/Security/Authorizing/Domain/Role.cs +++ b/common/ASC.Common/Security/Authorizing/Domain/Role.cs @@ -75,7 +75,7 @@ public override bool Equals(object obj) 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 c301c43ae47..ff90d5e5bb1 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -104,7 +104,7 @@ public static string SearchTextHighlight(string searchText, string htmlText, boo 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("<span class='searchTextHighlight{1}'>{0}</span>", m.Value, withoutLink ? " bold" : string.Empty)); + return wordsFinder.Replace(htmlText, m => "<span class='searchTextHighlight" + (withoutLink ? " bold" : string.Empty) + "'>{0}</span>"); } } } \ No newline at end of file diff --git a/common/ASC.Common/Utils/MailAddressUtils.cs b/common/ASC.Common/Utils/MailAddressUtils.cs index 96ef7ea071d..a8c08b9c072 100644 --- a/common/ASC.Common/Utils/MailAddressUtils.cs +++ b/common/ASC.Common/Utils/MailAddressUtils.cs @@ -66,7 +66,7 @@ public static string ToEncodedString(this MailAddress m) 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 6a3ab2d8ddd..28be6abef05 100644 --- a/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs +++ b/common/ASC.Common/Utils/TimeZoneConverter/TimeZoneConverter.cs @@ -122,7 +122,7 @@ public string OlsonTzId2WindowsTzId(string olsonTimeZoneId, bool defaultIfNoMatc 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 @@ public string WindowsTzId2OlsonTzId(string windowsTimeZoneId, bool defaultIfNoMa 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 406b7edbec0..dd07b0f1681 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -212,7 +212,7 @@ private string CreateAuthToken(string pkey, string machinekey) { 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 @@ private string Request(string method, string portalId, params Tuple<string, stri 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 c5f433355ed..9fd70561609 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -101,7 +101,7 @@ private async Task<string> CreatePromotionAsync(TenantManager tenantManager) { 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 @@ private async Task<IEnumerable<AvangateProduct>> InternalGetProducts() 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 @@ private string CreateAuthHeader() } 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 5deee5f5c15..8bfd0c5d511 100644 --- a/common/ASC.Core.Common/Billing/TariffService.cs +++ b/common/ASC.Core.Common/Billing/TariffService.cs @@ -239,7 +239,7 @@ public Tariff GetTariff(int tenantId, bool withRequestToPaymentSystem = true) 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 @@ public Uri GetShoppingUri(int? tenant, int quotaId, string affiliateId, string c 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<Dictionary<string, Tuple<Uri, Uri>>>(key) is IDictionary<string, Tuple<Uri, Uri>> urls)) { diff --git a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs index e6f1c09317e..12dcf9a9666 100644 --- a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs +++ b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs @@ -135,7 +135,7 @@ private string GetPartnerAuthHeader(string url) 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 88f41aa7275..b14ad1bba98 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -248,7 +248,7 @@ public override IDictionaryEnumerator GetEnumerator() private Dictionary<string, string> GetResources() { - var key = string.Format("{0}/{1}", filename, culture); + var key = $"{filename}/{culture}"; if (!(cache.Get(key) is Dictionary<string, string> dic)) { lock (locker) diff --git a/common/ASC.Core.Common/Core/UserInfo.cs b/common/ASC.Core.Common/Core/UserInfo.cs index 4bd972457dd..d13357cdf64 100644 --- a/common/ASC.Core.Common/Core/UserInfo.cs +++ b/common/ASC.Core.Common/Core/UserInfo.cs @@ -112,7 +112,7 @@ public bool IsActive public override string ToString() { - return string.Format("{0} {1}", FirstName, LastName).Trim(); + return $"{FirstName} {LastName}".Trim(); } public override int GetHashCode() @@ -168,7 +168,7 @@ internal string ContactsToString() 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 5f83c54ac81..ead6ec0a20e 100644 --- a/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs +++ b/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs @@ -50,7 +50,7 @@ public SenderChannel(Context context, string senderName, ISink decorateSink, ISi 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 c99517a4b5d..f158e3035f7 100644 --- a/common/ASC.Core.Common/Notify/Context.cs +++ b/common/ASC.Core.Common/Notify/Context.cs @@ -131,7 +131,7 @@ private void ValidateNotifySource(INotifySource source) 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 8d887eebc04..93111a8164b 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -350,8 +350,7 @@ protected virtual int StoreExpressionVals(int pos, string s, int type) 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 @@ protected virtual int StoreExpressionVals(int pos, string s, int type) 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 @@ protected virtual int StoreExpressionVals(int pos, string s, int type) 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 @@ protected virtual int StoreExpressionVals(int pos, string s, int type) 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 @@ protected virtual int StoreExpressionVals(int pos, string s, int type) } 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 9e30f75da1d..f031c7b886e 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -386,7 +386,7 @@ private List<SendResponse> SendDirectNotify(NotifyRequest request, IServiceScope } 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 @@ private void PrepareRequestFillPatterns(NotifyRequest request, IServiceScope ser 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 12ae7ef5c3e..1e34ce40cf0 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs @@ -118,7 +118,7 @@ internal IPattern GetSenderPattern(string senderName) 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 58318c2f440..ec0a449c6c6 100644 --- a/common/ASC.Core.Common/Notify/Model/NotifyAction.cs +++ b/common/ASC.Core.Common/Notify/Model/NotifyAction.cs @@ -69,7 +69,7 @@ public override int GetHashCode() 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 4a159920427..76917bcb217 100644 --- a/common/ASC.Core.Common/Notify/NotifySource.cs +++ b/common/ASC.Core.Common/Notify/NotifySource.cs @@ -132,12 +132,12 @@ protected virtual ISubscriptionProvider CreateSubscriptionProvider() { 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 486fbf9e3f2..1224a50232c 100644 --- a/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs +++ b/common/ASC.Core.Common/Notify/Patterns/NVelocityPatternFormatter.cs @@ -79,9 +79,9 @@ private void EventCartridgeReferenceInsertion(object sender, ReferenceInsertionE 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 985cc18bbc7..d15a021e9f0 100644 --- a/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs +++ b/common/ASC.Core.Common/Notify/Patterns/XmlPatternProvider2.cs @@ -155,7 +155,7 @@ private string GetResource(XmlElement e) 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 17c8447f0e1..39020b3bc7a 100644 --- a/common/ASC.Core.Common/Notify/Recipients/DirectRecipient.cs +++ b/common/ASC.Core.Common/Notify/Recipients/DirectRecipient.cs @@ -88,7 +88,7 @@ public override int GetHashCode() 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 bef149944a6..5baddc025e8 100644 --- a/common/ASC.Core.Common/Notify/Recipients/RecipientsGroup.cs +++ b/common/ASC.Core.Common/Notify/Recipients/RecipientsGroup.cs @@ -59,7 +59,7 @@ public override int GetHashCode() 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 8a2f746cc16..f2134536918 100644 --- a/common/ASC.Core.Common/Notify/ReplyToTagProvider.cs +++ b/common/ASC.Core.Common/Notify/ReplyToTagProvider.cs @@ -71,7 +71,7 @@ public TagValue Comment(string entity, string entityId, string parentId) 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}"); } /// <summary> diff --git a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs index 059a69b4da4..370e579f669 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 = - @"<!DOCTYPE html PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN""> -<html> -<head> -<meta content=""text/html;charset=UTF-8"" http-equiv=""Content-Type""> -</head> -<body>{0}</body> -</html>"; protected ILog Log { get; set; } protected IConfiguration Configuration { get; } @@ -276,7 +268,13 @@ private MimeMessage BuildMailMessage(NotifyMessage m) protected string GetHtmlView(string body) { - return string.Format(HTML_FORMAT, body); + return $@"<!DOCTYPE html PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN""> +<html> +<head> +<meta content=""text/html;charset=UTF-8"" http-equiv=""Content-Type""> +</head> +<body>{body}</body> +</html>"; } 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 9fcfc9d569f..558fd6a2826 100644 --- a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs @@ -397,7 +397,7 @@ private bool IsAvailable() 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 @@ public string CreateAuthToken(string pkey = "socketio") 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 0dbf3d80690..295aa0f3915 100644 --- a/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs +++ b/common/ASC.Core.Common/Notify/Telegram/TelegramHelper.cs @@ -149,7 +149,7 @@ private string GetLink(string token) 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 b074f961207..df277d6afdc 100644 --- a/common/ASC.Core.Common/Tenants/Tenant.cs +++ b/common/ASC.Core.Common/Tenants/Tenant.cs @@ -181,7 +181,7 @@ public string GetTenantDomain(CoreSettings coreSettings, bool allowMappedDomain } 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 e2b17a03a07..9c67a8c3ff6 100644 --- a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs +++ b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs @@ -183,7 +183,7 @@ private List<XElement> BackupDatabase(int tenant, ConnectionStringSettings conne 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 @@ private void RestoreDatabase(ConnectionStringSettings connectionString, IEnumera 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 5149a347423..f4637094d8a 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -185,13 +185,13 @@ public void SetTable(DataTable table) .Intersect(table.Columns.Cast<DataColumn>().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 @@ private IEnumerable<string> GetColumnsFrom(string table) } 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 5494183ad23..200731a0940 100644 --- a/common/ASC.Data.Backup.Core/Core/FileBackupProvider.cs +++ b/common/ASC.Data.Backup.Core/Core/FileBackupProvider.cs @@ -132,7 +132,7 @@ private IEnumerable<FileBackupInfo> ComposeFiles(int tenant, string config) 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 94dccdcb2ce..d88631c5ff3 100644 --- a/common/ASC.Data.Backup.Core/Exceptions/ThrowHelper.cs +++ b/common/ASC.Data.Backup.Core/Exceptions/ThrowHelper.cs @@ -34,32 +34,32 @@ internal static class ThrowHelper { 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<string> 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<Type> 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 80c0bb0b600..a858385af63 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -209,7 +209,7 @@ private IEnumerable<BackupFileInfo> GetFiles(int tenantId) { 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 @@ private void DumpTableScheme(string t, string dir) 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 @@ private void DumpTableData(string t, string dir, int count) 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 @@ private void DumpTableData(string t, string dir, int count) 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 @@ private void DumpTableData(string t, string dir, int count) { 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<int, int>(Convert.ToInt32(r[0]), Convert.ToInt32(r[1]))).FirstOrDefault(); primaryIndexStart = minMax.Item2; primaryIndexStep = (minMax.Item1 - minMax.Item2) / count; @@ -543,7 +543,7 @@ private List<IGrouping<string, BackupFileInfo>> GetFilesGroup() 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 e4e8829d77e..7e4bb6e1714 100644 --- a/common/ASC.Data.Backup.Core/Tasks/ColumnMapper.cs +++ b/common/ASC.Data.Backup.Core/Tasks/ColumnMapper.cs @@ -140,7 +140,7 @@ private bool HasMapping(string key) 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 445e94625ff..4a8556aa1dc 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 @@ public override string ToString() 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 e0666604c10..f9246cd14d3 100644 --- a/common/ASC.Data.Backup.Core/Tasks/KeyHelper.cs +++ b/common/ASC.Data.Backup.Core/Tasks/KeyHelper.cs @@ -40,27 +40,27 @@ public static string GetDumpKey() 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 @@ public static string GetStorage() } 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 b4e91652315..d276c1c46fe 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 @@ public DbCommand CreateSelectCommand(DbConnection connection, int tenantId, Tabl 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 @@ public DbCommand CreateInsertCommand(bool dump, DbConnection connection, ColumnM 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 d5de8af201b..d77348d209f 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -243,16 +243,16 @@ protected void RunMysqlFile(string file, bool db = false) { 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 419689d3cf4..06f36cbb434 100644 --- a/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs @@ -139,7 +139,7 @@ var rows in 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 bb1b900760c..7ff38c2187e 100644 --- a/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs @@ -221,18 +221,13 @@ private void SaveTenant(DbFactory dbFactory, string alias, TenantStatus status, 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 d8996677830..254888eb069 100644 --- a/common/ASC.Data.Encryption/Crypt.cs +++ b/common/ASC.Data.Encryption/Crypt.cs @@ -295,12 +295,12 @@ private string GetUniqFileName(string filePath, string ext) { 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 823a845089e..b0c8f49873d 100644 --- a/common/ASC.Data.Storage/BaseStorage.cs +++ b/common/ASC.Data.Storage/BaseStorage.cs @@ -140,20 +140,12 @@ public Uri GetPreSignedUri(string domain, string path, TimeSpan expire, IEnumera } 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 8774b9170d2..c5b86fde9e7 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -329,7 +329,7 @@ public override void DeleteFiles(string domain, string folderPath, string patter } else { - throw new DirectoryNotFoundException(string.Format("Directory '{0}' not found", targetDir)); + throw new DirectoryNotFoundException($"Directory '{targetDir}' not found"); } } @@ -355,7 +355,7 @@ public override void DeleteFiles(string domain, string folderPath, DateTime from } 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 1da1837d52f..8905fef52ff 100644 --- a/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs +++ b/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs @@ -147,7 +147,7 @@ private void EncryptStore(Tenant tenant, string module, DiscDataStore store, Sto 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 @@ private void EncryptFiles(DiscDataStore store, string domain, IEnumerable<string { 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 178e7f4320a..78cb2c1fc8b 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -113,12 +113,12 @@ public override IDataStore Configure(string tenant, Handler handlerConfig, Modul _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 @@ private string MakePath(string domain, string path) 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 @@ public override Uri Save(string domain, string path, System.IO.Stream stream, Co 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 @@ public override string UploadChunk(string domain, 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 6291a3e477e..7b5683395fc 100644 --- a/common/ASC.Data.Storage/PathUtils.cs +++ b/common/ASC.Data.Storage/PathUtils.cs @@ -70,9 +70,7 @@ public static string Normalize(string path, bool addTailingSeparator = false) 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 da7516dafd6..b76ea13260a 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -92,14 +92,10 @@ private string MakePath(string domain, string path) 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 @@ public override IDataStore Configure(string tenant, Handler handlerConfig, Modul { _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 @@ public override Uri Save(string domain, string path, Stream stream, ACL acl) 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 @@ public Uri Save(string domain, string path, Stream stream, string contentType, var headers = new Dictionary<string, string> { - { "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 78565501aad..7b4489040ff 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -157,7 +157,7 @@ public override Uri GetInternalUri(string domain, string path, TimeSpan expire, 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 @@ public override async Task<Stream> GetReadStreamAsync(string domain, string path 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 @@ public override string GetPostParams(string domain, string directoryPath, long m 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.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($"\"Content-Disposition\":\"{contentDisposition}\","); + + 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 @@ public override string GetUploadForm(string domain, string directoryPath, string out var sign); var formBuilder = new StringBuilder(); - formBuilder.AppendFormat("<form action=\"{0}\" method=\"post\" enctype=\"multipart/form-data\">", destBucket); - formBuilder.AppendFormat("<input type=\"hidden\" name=\"key\" value=\"{0}${{filename}}\" />", key); + formBuilder.Append($"<form action=\"{destBucket}\" method=\"post\" enctype=\"multipart/form-data\">"); + formBuilder.Append($"<input type=\"hidden\" name=\"key\" value=\"{key}${{filename}}\" />"); formBuilder.Append("<input type=\"hidden\" name=\"acl\" value=\"public-read\" />"); if (!string.IsNullOrEmpty(redirectTo)) - formBuilder.AppendFormat("<input type=\"hidden\" name=\"success_action_redirect\" value=\"{0}\" />", - redirectTo); + formBuilder.Append($"<input type=\"hidden\" name=\"success_action_redirect\" value=\"{redirectTo}\" />"); formBuilder.AppendFormat("<input type=\"hidden\" name=\"success_action_status\" value=\"{0}\" />", 201); if (!string.IsNullOrEmpty(contentType)) - formBuilder.AppendFormat("<input type=\"hidden\" name=\"Content-Type\" value=\"{0}\" />", contentType); + formBuilder.Append($"<input type=\"hidden\" name=\"Content-Type\" value=\"{contentType}\" />"); if (!string.IsNullOrEmpty(contentDisposition)) - formBuilder.AppendFormat("<input type=\"hidden\" name=\"Content-Disposition\" value=\"{0}\" />", - contentDisposition); - formBuilder.AppendFormat("<input type=\"hidden\" name=\"AWSAccessKeyId\" value=\"{0}\"/>", _accessKeyId); - formBuilder.AppendFormat("<input type=\"hidden\" name=\"Policy\" value=\"{0}\" />", policyBase64); - formBuilder.AppendFormat("<input type=\"hidden\" name=\"Signature\" value=\"{0}\" />", sign); - formBuilder.AppendFormat("<input type=\"hidden\" name=\"SignatureVersion\" value=\"{0}\" />", 2); - formBuilder.AppendFormat("<input type=\"hidden\" name=\"SignatureMethod\" value=\"{0}\" />", "HmacSHA1"); - formBuilder.AppendFormat("<input type=\"file\" name=\"file\" />"); - formBuilder.AppendFormat("<input type=\"submit\" name=\"submit\" value=\"{0}\" /></form>", submitLabel); + formBuilder.Append($"<input type=\"hidden\" name=\"Content-Disposition\" value=\"{contentDisposition}\" />"); + formBuilder.Append($"<input type=\"hidden\" name=\"AWSAccessKeyId\" value=\"{_accessKeyId}\"/>"); + formBuilder.Append($"<input type=\"hidden\" name=\"Policy\" value=\"{policyBase64}\" />"); + formBuilder.Append($"<input type=\"hidden\" name=\"Signature\" value=\"{sign}\" />"); + formBuilder.Append("<input type=\"hidden\" name=\"SignatureVersion\" value=\"2\" />"); + formBuilder.Append("<input type=\"hidden\" name=\"SignatureMethod\" value=\"HmacSHA1{0}\" />"); + formBuilder.Append("<input type=\"file\" name=\"file\" />"); + formBuilder.Append($"<input type=\"submit\" name=\"submit\" value=\"{submitLabel}\" /></form>"); return formBuilder.ToString(); } @@ -787,26 +783,28 @@ private string GetPolicyBase64(string key, string redirectTo, string contentType 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 @@ public override IDataStore Configure(string tenant, Handler handlerConfig, Modul { _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 @@ public override IDataStore Configure(string tenant, Handler handlerConfig, Modul _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 @@ private string MakePath(string domain, string path) 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 @@ private string MakePath(string domain, string path) 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 0f34fd4843a..12d8b43c8f1 100644 --- a/common/ASC.Data.Storage/TenantQuotaController.cs +++ b/common/ASC.Data.Storage/TenantQuotaController.cs @@ -129,7 +129,7 @@ public long QuotaCurrentGet() 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 0e5f4e321fd..9b8c5191861 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -65,7 +65,7 @@ public string GetRelativePath(HttpContext httpContext, IOptionsMonitor<ILog> opt { 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 @@ public string GetPath(HttpContext httpContext, IOptionsMonitor<ILog> options, st { 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 @@ public string GetPath(HttpContext httpContext, IOptionsMonitor<ILog> options, st //} //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 @@ public string GetPath(HttpContext httpContext, IOptionsMonitor<ILog> options, st //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 @@ public string GetPath(string relativePath) { 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<StaticUploader>().CanUpload()) //hack for skip resolve DistributedTaskQueueOptionsManager diff --git a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs index 1f2ec7bfa4a..37c15877862 100644 --- a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs @@ -107,10 +107,7 @@ public OAuth20TokenHelper(IHttpContextAccessor httpContextAccessor, ConsumerFact 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 @@ public static OAuth20Token RefreshToken(string requestUrl, OAuth20Token token) { 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 767691a7406..43932ad3f64 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 = @"<xrds:XRDS xmlns:xrds=""xri://$xrds"" xmlns:openid=""http://openid.net/xmlns/1.0"" " + @"xmlns=""xri://$xrd*($v*2.0)""><XRD><Service " + @"priority=""1""><Type>http://specs.openid.net/auth/2.0/return_to</Type><URI " + - @"priority=""1"">{0}</URI></Service><Service><Type>http://specs.openid.net/extensions/ui/icon</Type><UR" + - @"I>{1}</URI></Service></XRD></xrds:XRDS>"; - + $@"priority=""1"">{location}</URI></Service><Service><Type>http://specs.openid.net/extensions/ui/icon</Type><UR" + + $@"I>{iconlink}</URI></Service></XRD></xrds:XRDS>"; - 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 a5822378a35..58400b1b583 100644 --- a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs @@ -79,7 +79,7 @@ private string AuthHeader { 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 @@ public OAuth20Token GetAccessToken(string authCode) 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<string, string> { { "Authorization", AuthHeader } }; var json = RequestHelper.PerformRequest(AccessTokenUrl, "application/x-www-form-urlencoded", "POST", data, headers); @@ -117,7 +117,7 @@ public OAuth20Token RefreshToken(string refreshToken) 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<string, string> { { "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 8586df0b387..30d7d5590f8 100644 --- a/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/FacebookLoginProvider.cs @@ -100,7 +100,7 @@ internal LoginProfile ProfileFromFacebook(string facebookProfile) TimeZone = jProfile.Value<string>("timezone"), Locale = jProfile.Value<string>("locale"), Provider = ProviderConstants.Facebook, - Avatar = string.Format("http://graph.facebook.com/{0}/picture?type=large", jProfile.Value<string>("id")) + Avatar = "http://graph.facebook.com/" + jProfile.Value<string>("id") + "/picture?type=large" }; return profile; diff --git a/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs b/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs index a689447b597..cfb901392a8 100644 --- a/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs +++ b/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs @@ -48,7 +48,7 @@ private string GetDatabaseId(string hostedRegion) 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 9a1f6911f8b..bbed67d0df4 100644 --- a/common/ASC.FederatedLogin/Profile/LoginProfile.cs +++ b/common/ASC.FederatedLogin/Profile/LoginProfile.cs @@ -163,7 +163,7 @@ public string RealmUrl public string UniqueId { - get { return string.Format("{0}/{1}", Provider, Id); } + get { return $"{Provider}/{Id}"; } } public string HashId @@ -306,8 +306,7 @@ private static Uri AppendQueryParam(Uri uri, string keyvalue, string value) 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 45e9a5aee2b..9ee3ee7af79 100644 --- a/common/ASC.Feed/Core/Feed.cs +++ b/common/ASC.Feed/Core/Feed.cs @@ -53,7 +53,7 @@ public Feed(Guid author, DateTime date, bool variate = false) 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 32bf2ca09b0..d02ee8012a9 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -251,14 +251,14 @@ private static string GetBrowser(ClientInfo clientInfo) { 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 3848314906d..3a2f26c493c 100644 --- a/common/ASC.Notify.Textile/JabberStyler.cs +++ b/common/ASC.Notify.Textile/JabberStyler.cs @@ -85,7 +85,7 @@ private string EvalLink(Match match) { 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 a44dbe5d353..dab812c2ac4 100644 --- a/common/ASC.Textile/Blocks/HyperLinkBlockModifier.cs +++ b/common/ASC.Textile/Blocks/HyperLinkBlockModifier.cs @@ -33,7 +33,7 @@ public override string ModifyLine(string line) @"\s?" + @"(?:\((?<title>[^)]+)\)(?=""))?" + // 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 e679ccd55d0..7f717ee9808 100644 --- a/common/ASC.Textile/Blocks/NoTextileEncoder.cs +++ b/common/ASC.Textile/Blocks/NoTextileEncoder.cs @@ -52,7 +52,7 @@ string evaluator(Match m) } 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 @@ string evaluator(Match m) } 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 debabe18c7a..bd28563a05e 100644 --- a/common/ASC.Textile/States/HeaderFormatterState.cs +++ b/common/ASC.Textile/States/HeaderFormatterState.cs @@ -32,7 +32,7 @@ public override void Enter() { 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 @@ public HeaderFormatterState(TextileFormatter f) 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 fba026681bd..72b8b5510e3 100644 --- a/common/ASC.Textile/States/ListFormatterState.cs +++ b/common/ASC.Textile/States/ListFormatterState.cs @@ -72,7 +72,7 @@ public sealed override void FormatLine(string input) { 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 d2628dddc74..c7d83ae786c 100644 --- a/common/ASC.Textile/States/TableRowFormatterState.cs +++ b/common/ASC.Textile/States/TableRowFormatterState.cs @@ -18,7 +18,7 @@ public override string Consume(string input, Match m) { 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 f28f7792b6a..2ef0656245a 100644 --- a/common/ASC.VoipService/Dao/VoipDao.cs +++ b/common/ASC.VoipService/Dao/VoipDao.cs @@ -343,7 +343,7 @@ private VoipCall ToCall(CallContact dbVoipCall) { 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 df56cbd911f..298e27cc7df 100644 --- a/common/services/ASC.ApiSystem/Classes/CommonMethods.cs +++ b/common/services/ASC.ApiSystem/Classes/CommonMethods.cs @@ -146,17 +146,9 @@ public object ToTenantWrapper(Tenant t) } 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 @@ public bool ValidateRecaptcha(string response, string ip) { 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 a4fe0e4849c..35b1e907841 100644 --- a/common/services/ASC.ApiSystem/Controllers/CalDavController.cs +++ b/common/services/ASC.ApiSystem/Controllers/CalDavController.cs @@ -185,10 +185,7 @@ public IActionResult IsCaldavAuthenticated(UserPassword userPassword) 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 @@ private bool GetTenant(string calendarParam, out Tenant tenant, out object error 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 @@ private bool GetUserData(string userParam, out string email, out Tenant tenant, 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 @@ private bool GetUserData(string userParam, out string email, out Tenant tenant, 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 @@ private void SendToApi(string requestUriScheme, ? 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 81d95688a11..ce8ecda5284 100644 --- a/common/services/ASC.ApiSystem/Controllers/PortalController.cs +++ b/common/services/ASC.ApiSystem/Controllers/PortalController.cs @@ -673,7 +673,7 @@ private bool CheckRecaptcha(TenantModel model, string clientIP, Stopwatch sw, ou 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 d6d6be2612f..1dc54beeb27 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -142,7 +142,7 @@ public string GetModuleText(AuditEvent evt) 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 b5589c2b0b3..c5df10a50f5 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -544,12 +544,12 @@ private Func<ScriptDescriptor, IScript> GetScriptUpdateByQuery(T data, params Ex { 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 @@ private void UpdateByAction(UpdateAction action, IList newValue, string key, Dic 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 fc2a6bfddb0..018fc52e3f3 100644 --- a/common/services/ASC.Socket.IO.Svc/SocketServiceLauncher.cs +++ b/common/services/ASC.Socket.IO.Svc/SocketServiceLauncher.cs @@ -90,7 +90,7 @@ public Task StartAsync(CancellationToken cancellationToken) 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 @@ private void StartPing() 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 d1959577605..ca8d2e93c9b 100644 --- a/common/services/ASC.SsoAuth.Svc/Launcher.cs +++ b/common/services/ASC.SsoAuth.Svc/Launcher.cs @@ -69,7 +69,7 @@ public async Task StartAsync(CancellationToken cancellationToken) 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 1978968edc7..091a52f309c 100644 --- a/common/services/ASC.TelegramService/Core/Core.cs +++ b/common/services/ASC.TelegramService/Core/Core.cs @@ -141,7 +141,7 @@ public async Task HandleCommand(Message msg, TelegramBotClient client, int tenan { 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 3a2742a4ea1..572159d9fdf 100644 --- a/common/services/ASC.Thumbnails.Svc/ThumbnailsServiceLauncher.cs +++ b/common/services/ASC.Thumbnails.Svc/ThumbnailsServiceLauncher.cs @@ -67,7 +67,7 @@ public Task StartAsync(CancellationToken cancellationToken) 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 deb3c765619..a343f8dc5bd 100644 --- a/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs +++ b/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs @@ -116,7 +116,7 @@ private ProcessStartInfo GetProcessStartInfo() 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 fb115d8da9e..0194c26a640 100644 --- a/products/ASC.CRM/Server/Api/RelationshipEventsController.cs +++ b/products/ASC.CRM/Server/Api/RelationshipEventsController.cs @@ -458,14 +458,14 @@ public RelationshipEventDto AddHistoryTo([FromBody] AddHistoryToRequestDto inDto 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 8fee0d4dc94..be51671ae17 100644 --- a/products/ASC.CRM/Server/Classes/InvoiceFormattedData.cs +++ b/products/ASC.CRM/Server/Classes/InvoiceFormattedData.cs @@ -341,9 +341,7 @@ private InvoiceFormattedData CreateData(Invoice invoice, int billingAddressID, i //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 @@ private InvoiceFormattedData CreateDataAfterLinesUpdated(Invoice invoice, //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 f3b44114748..91d5a782971 100644 --- a/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs +++ b/products/ASC.CRM/Server/Classes/LocalizedEnumConverter.cs @@ -116,7 +116,7 @@ private LookupTable GetLookupTable(CultureInfo culture) 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 @@ private string GetFlagValueText(CultureInfo culture, object value) } 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 d8cf2635171..52f9274c9a7 100644 --- a/products/ASC.CRM/Server/Core/Dao/DealMilestoneDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/DealMilestoneDao.cs @@ -158,7 +158,7 @@ public void ChangeColor(int id, String newColor) 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 @@ public bool HaveContactLink(int id) 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 5e17356c9ec..317c9ef1f41 100644 --- a/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/ListItemDao.cs @@ -381,13 +381,13 @@ public void EditItem(ListType listType, ListItem enumItem) { 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 @@ public void DeleteItem(ListType listType, int itemID, int toItemID) { 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 a0218d701a4..32c1c44ec85 100644 --- a/products/ASC.CRM/Server/Core/Dao/ReportDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/ReportDao.cs @@ -241,7 +241,7 @@ private string GetTimePeriodText(ReportTimePeriod timePeriod) 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 @@ private string GetTimePeriodText(ReportTimePeriod timePeriod) 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 @@ private string SecondsToTimeFormat(int duration) { 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 85f10363a2c..7da8707ce19 100644 --- a/products/ASC.CRM/Server/Core/Dao/SearchDao.cs +++ b/products/ASC.CRM/Server/Core/Dao/SearchDao.cs @@ -345,7 +345,7 @@ private SearchResultItem[] GetSearchResultItems(String[] keywords) 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 6f03c0fc4e5..7b27ef3b346 100644 --- a/products/ASC.CRM/Server/Core/Entities/Contact.cs +++ b/products/ASC.CRM/Server/Core/Entities/Contact.cs @@ -75,7 +75,7 @@ public static String GetTitle(this Contact contact) 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 593be935001..9ae99dabb9c 100644 --- a/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs +++ b/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs @@ -267,7 +267,7 @@ public async System.Threading.Tasks.Task Invoke(HttpContext context, .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 @@ public async System.Threading.Tasks.Task Invoke(HttpContext context, 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 a75ffe54851..624b574c5e3 100644 --- a/products/ASC.CRM/Server/Utils/CurrencyProvider.cs +++ b/products/ASC.CRM/Server/Utils/CurrencyProvider.cs @@ -131,7 +131,7 @@ public Dictionary<CurrencyInfo, Decimal> MoneyConvert(CurrencyInfo baseCurrency) 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 @@ public Decimal MoneyConvert(decimal amount, string from, string to) 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 @@ private bool TryGetRatesFromFile(string filepath, CurrencyInfo curCI) { 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 @@ private void DownloadCurrencyPage(string currency, string filepath) 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 ad2fd70f9bc..0b09d02de03 100644 --- a/products/ASC.CRM/Server/Utils/ExportToCSV.cs +++ b/products/ASC.CRM/Server/Utils/ExportToCSV.cs @@ -473,7 +473,7 @@ private String ExportContactsToCsv(IReadOnlyCollection<Contact> contacts, String 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 @@ private String ExportHistoryToCsv(IEnumerable<RelationshipEvent> events, DaoFact 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 @@ private String ExportTasksToCsv(IEnumerable<Task> tasks, DaoFactory daoFactory) 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 ae898d1adf1..70ca2befc71 100644 --- a/products/ASC.CRM/Server/Utils/MailSender.cs +++ b/products/ASC.CRM/Server/Utils/MailSender.cs @@ -827,7 +827,7 @@ public String Apply(String template, int contactID) 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 @@ public List<MailTemplateTag> GetTags(bool isCompany) 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 cdec421bb00..86ce4a06668 100644 --- a/products/ASC.CRM/Server/Utils/PdfCreator.cs +++ b/products/ASC.CRM/Server/Utils/PdfCreator.cs @@ -127,7 +127,7 @@ public void CreateAndSaveFile(int invoiceId) 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 @@ private File<int> SaveFile(Invoice data, string url, DaoFactory daoFactory) { 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 f50bda60943..a728e7e6598 100644 --- a/products/ASC.CRM/Server/Utils/ReportHelper.cs +++ b/products/ASC.CRM/Server/Utils/ReportHelper.cs @@ -127,10 +127,7 @@ private string GetFileName(ReportType reportType) 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 dde3267985b..5e022aa5ffc 100644 --- a/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs +++ b/products/ASC.Calendar/Server/BusinessObjects/DataProvider.cs @@ -1615,7 +1615,7 @@ public static string GetEventUid(string uid, string id = null) 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 478b020906b..6cae0965725 100644 --- a/products/ASC.Calendar/Server/Controllers/CalendarController.cs +++ b/products/ASC.Calendar/Server/Controllers/CalendarController.cs @@ -747,7 +747,7 @@ public void DeleteCaldavCalendar(CaldavCalendarModel caldavCalendarModel) } 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 @@ public void DeleteCaldavEvent(CaldavEventModel caldavEventModel) } 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 @@ public void UpdateCaldavEvent(CaldavEventModel caldavEventModel) } catch (Exception ex) { - Log.Error(String.Format("Error: {0}", ex.Message)); + Log.Error($"Error: {ex.Message}"); } finally { @@ -911,7 +911,7 @@ public void UpdateCaldavEvent(CaldavEventModel caldavEventModel) } 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 @@ public CalendarWrapper CreateCalendar(CalendarModel calendar) } 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 @@ public CalendarWrapper UpdateCalendar(string calendarId, CalendarModel calendar) } 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 @@ public List<EventWrapper> CreateEvent(EventModel eventModel) 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 @@ public List<EventWrapper> AddEvent(EventModel eventData) { 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 @@ public List<EventWrapper> AddEvent(EventModel eventData) 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 @@ public List<TodoWrapper> AddTodo(CreateTodoModel createTodoModel) { 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 @@ public List<TodoWrapper> AddTodo(CreateTodoModel createTodoModel) 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 @@ public int ImportEvents(UploadModel uploadModel) 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 @@ public int ImportEvents(ImportModel importModel) } - 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 @@ private void UpdateCalDavEvent(string change, Uri calDavUrl) 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 @@ private void UpdateCalDavEvent(string change, Uri calDavUrl) { 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 b636462f6e9..399b54d6f2a 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 @@ public string GetUniqFilePath(File<int> file) 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 a58c56714b6..816ebd24bb5 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 @@ public IEnumerable<int> GetFolderIDs(string module, string bunch, IEnumerable<st 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 @@ public int GetFolderID(string module, string bunch, string data, bool createIfNo 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 7370d3b9560..59d16f94b4d 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 @@ protected string MakeId(BoxItem boxItem) } 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 83329eaae87..6f0bb681691 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 @@ protected string MakeId(Metadata dropboxItem) } 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 c1a4d7235e6..16e833a95d0 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 @@ protected string MakeId(DriveFile driveEntry) } 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 f16d6dabcca..8930f5d4c91 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 @@ public Stream DownloadStream(DriveFile file, int offset = 0) { 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 @@ public Stream DownloadStream(DriveFile file, int offset = 0) 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 @@ public ResumableUploadSession CreateResumableSession(DriveFile driveFile, long c } 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 a905fbf23cd..1cd4f28b609 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 @@ protected string MakeId(Item onedriveItem) } 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 8fd12c9e2f0..94e9b54d2af 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 @@ public Folder<string> ToFolder(Folder folder) 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 1d8f659a00f..a2cb4e3b167 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 @@ protected void UpdatePathInDB(string oldValue, string newValue) 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 @@ protected string MakeId(ICloudFileSystemEntry entry) { 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 157805d7617..04829daa84f 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs @@ -389,7 +389,7 @@ private Exception CustomizeError(Exception ex) { 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 9948023f534..0d6a4a09938 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs @@ -225,7 +225,7 @@ public File<T> GetParams<T>(File<T> file, bool lastVersion, FileShare linkRight, } - 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 @@ public File<T> GetParams<T>(File<T> file, bool lastVersion, FileShare linkRight, 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 572c7bf97a9..f8acf8736e5 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -592,10 +592,7 @@ private void StoringFileAfterError<T>(T fileId, string userId, string downloadUr 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 4c827fbd898..9ef7231d528 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 @@ public override void RunJob(DistributedTask distributedTask, CancellationToken c 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 2532231761b..e992d647711 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/BoxApp.cs @@ -322,8 +322,8 @@ public void SaveFile(string fileId, string fileType, string downloadUrl, Stream { 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 @@ public void SaveFile(string fileId, string fileType, string downloadUrl, Stream 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 @@ private void StreamFile(HttpContext context) 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 88fc5610b74..39ba1eba9dd 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -627,8 +627,8 @@ private Token GetToken(string code) 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 @@ private string CreateFile(Stream content, string fileName, string folderId, Toke { 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 @@ private string CreateConvertedFile(string driveFile, Token token) 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 3c2d3f9e7cc..9b9dd244994 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -866,13 +866,13 @@ public File<T> SaveConvertedFile<T>(File<T> file, string convertedFileUrl) } 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 c1e34a1964f..f23c194e370 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -100,7 +100,7 @@ public string Run(MailMergeTask mailMergeTask, IHttpClientFactory clientFactory) 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 @@ private string AttachToMail(MailMergeTask mailMergeTask, IHttpClientFactory clie 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 f3bd00f7dc6..a9b2ec8139c 100644 --- a/products/ASC.Files/Service/Core/FilesModule.cs +++ b/products/ASC.Files/Service/Core/FilesModule.cs @@ -147,7 +147,7 @@ private Feed.Aggregator.Feed ToFeed((File<int>, SmallShareRecord) tuple, Folder< 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 @@ private Feed.Aggregator.Feed ToFeed((File<int>, SmallShareRecord) tuple, Folder< 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 f22db52a5e2..949a499c400 100644 --- a/products/ASC.Files/Service/Core/FoldersModule.cs +++ b/products/ASC.Files/Service/Core/FoldersModule.cs @@ -110,7 +110,7 @@ private Feed.Aggregator.Feed ToFeed((Folder<int>, SmallShareRecord) tuple, Folde 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 @@ private Feed.Aggregator.Feed ToFeed((Folder<int>, SmallShareRecord) tuple, Folde 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 fb56fa28a65..2c42145526c 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -499,7 +499,7 @@ public string RegisterUserOnPersonal(RegisterPersonalUserModel model) } 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 7c83de70a3c..20550e58e1d 100644 --- a/web/ASC.Web.Api/Controllers/CapabilitiesController.cs +++ b/web/ASC.Web.Api/Controllers/CapabilitiesController.cs @@ -119,8 +119,7 @@ public CapabilitiesData GetPortalCapabilities() 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 4d3ea3fe800..f563dd5e996 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1370,7 +1370,7 @@ private TipsSettings UpdateTipsSettings(SettingsModel model) 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 @@ private object SendOwnerChangeInstructions(SettingsModel model) 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 d67a7a0b42f..fed61d05880 100644 --- a/web/ASC.Web.Core/Calendars/BaseCalendar.cs +++ b/web/ASC.Web.Core/Calendars/BaseCalendar.cs @@ -92,11 +92,11 @@ public string ToiCalFormat() 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 80d0ba2165b..17a4a895ffb 100644 --- a/web/ASC.Web.Core/Calendars/BaseEvent.cs +++ b/web/ASC.Web.Core/Calendars/BaseEvent.cs @@ -96,11 +96,14 @@ public virtual string ToiCalFormat() 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 @@ public virtual string ToiCalFormat() } 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 4b30e3e07a4..6dce6fff94a 100644 --- a/web/ASC.Web.Core/Calendars/BaseTodo.cs +++ b/web/ASC.Web.Core/Calendars/BaseTodo.cs @@ -80,19 +80,27 @@ public virtual string ToiCalFormat() { 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 baacd1b20d3..898e889757f 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -76,7 +76,7 @@ public static int GetDayOfWeekInMonth(this DateTime date) 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 @@ public string ToString(bool iCal) 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 @@ public string ToString(bool iCal) } 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 603170b1e15..a65d7e6a934 100644 --- a/web/ASC.Web.Core/Extensions/UserInfoExtension.cs +++ b/web/ASC.Web.Core/Extensions/UserInfoExtension.cs @@ -103,13 +103,13 @@ public static string RenderProfileLinkBase(this UserInfo userInfo, CommonLinkUti //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 c5a3e77ff7f..10823dfc6a4 100644 --- a/web/ASC.Web.Core/FileSizeComment.cs +++ b/web/ASC.Web.Core/FileSizeComment.cs @@ -57,12 +57,12 @@ public string FileImageSizeExceptionString 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 713972fa7f2..55678c7b925 100644 --- a/web/ASC.Web.Core/Helpers/ApiSystemHelper.cs +++ b/web/ASC.Web.Core/Helpers/ApiSystemHelper.cs @@ -74,7 +74,7 @@ public string CreateAuthToken(string pkey) 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 @@ public void ValidatePortalName(string domain, Guid userId) { 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 @@ public void ValidatePortalName(string domain, Guid userId) 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 @@ private string SendToApi(string absoluteApiUrl, string apiPath, string httpMetho 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 13378990f93..c83aa94c5e6 100644 --- a/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs +++ b/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs @@ -88,7 +88,7 @@ private LookupTable GetLookupTable(CultureInfo culture) 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 @@ private string GetFlagValueText(CultureInfo culture, object value) } 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 ed9ba6e6a40..87264845522 100644 --- a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs +++ b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs @@ -236,7 +236,7 @@ private void NotifyClientRegisterCallback(Context context, INotifyClient client) 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 fe30c0aa20b..6039ff24a66 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyService.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyService.cs @@ -253,8 +253,7 @@ public void SendMailboxCreated(List<string> toEmails, string username, string ad 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 2b36a1479d1..e11e034ee16 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -205,7 +205,7 @@ public void SendSaasLetters(string senderName, DateTime scheduleDate) toadmins = true; greenButtonText = () => WebstudioNotifyPatternResource.ButtonAccessYouWebOffice; - greenButtonUrl = String.Format("{0}/", commonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')); + greenButtonUrl = $"{commonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')}/"; } #endregion @@ -268,7 +268,7 @@ public void SendSaasLetters(string senderName, DateTime scheduleDate) 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 @@ public void SendEnterpriseLetters(string senderName, DateTime scheduleDate) 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 @@ public void SendEnterpriseLetters(string senderName, DateTime scheduleDate) 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 d37196f8106..06b09bb6828 100644 --- a/web/ASC.Web.Core/Notify/TagValues.cs +++ b/web/ASC.Web.Core/Notify/TagValues.cs @@ -53,14 +53,10 @@ public static ITagValue BlueButton(Func<string> btnTextFunc, string btnUrl) 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 @@ public static ITagValue GreenButton(Func<string> btnTextFunc, string btnUrl) 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 @@ string action() ? 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 @@ string action() { 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 @@ public static ITagValue Image(StudioNotifyHelper studioNotifyHelper, int id, str { 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 cccc9dd80fd..1b4207a7c1c 100644 --- a/web/ASC.Web.Core/Recaptcha.cs +++ b/web/ASC.Web.Core/Recaptcha.cs @@ -40,7 +40,7 @@ public bool ValidateRecaptcha(string response, string ip) { 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 234745d4957..e015bde1089 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -105,7 +105,7 @@ private string MakeUniqueName(UserInfo userInfo) 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 @@ internal static string GenerateErrorMessage(PasswordSettings passwordSettings) { 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 @@ public string GetPasswordHelpMessage() { 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 32f94f8eec3..2bdac1c3aab 100644 --- a/web/ASC.Web.Core/Utility/UrlShortener.cs +++ b/web/ASC.Web.Core/Utility/UrlShortener.cs @@ -134,7 +134,7 @@ private string CreateAuthToken(string pkey = "urlShortener") 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 cd8af9da708..fd15c79ec06 100644 --- a/web/ASC.Web.Core/WebItemManager.cs +++ b/web/ASC.Web.Core/WebItemManager.cs @@ -156,7 +156,7 @@ private ConcurrentDictionary<Guid, IWebItem> LoadItems() } 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 2b9280f4435..5c049aca8b5 100644 --- a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs +++ b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs @@ -500,7 +500,7 @@ private Stream GetPartnerStorageLogoData(WhiteLabelLogoTypeEnum type, bool gener 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/105] 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 93111a8164b..17ac36d4c7c 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -737,43 +737,43 @@ public virtual string GetExpressionSummary() 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 @@ protected virtual string GetExpressionSetSummary(ISet data) 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 a858385af63..4b7c73cd98c 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -230,7 +230,7 @@ private void DumpTableScheme(string t, string dir) 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 7b4489040ff..139a2a92a9f 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -727,7 +727,7 @@ public override string GetPostParams(string domain, string directoryPath, long m 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 898e889757f..314920d7bb6 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -989,7 +989,7 @@ public string ToiCalFormat() 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 @@ public string ToiCalFormat() 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 ba3afbfe63f..634b65d8810 100644 --- a/web/ASC.Web.Core/Sms/SmsSender.cs +++ b/web/ASC.Web.Core/Sms/SmsSender.cs @@ -106,11 +106,11 @@ public static string BuildPhoneNoise(string mobilePhone) 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 e015bde1089..032e7cb6f7a 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -235,12 +235,12 @@ public string GetPasswordRegex(PasswordSettings passwordSettings) 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/105] 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 634b65d8810..e903983ab90 100644 --- a/web/ASC.Web.Core/Sms/SmsSender.cs +++ b/web/ASC.Web.Core/Sms/SmsSender.cs @@ -107,12 +107,12 @@ public static string BuildPhoneNoise(string mobilePhone) 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/105] 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 9b4d611e27b..4b3bf08b289 100644 --- a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs @@ -53,7 +53,7 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync() { 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 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync() 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 1316ab31851..13590079a68 100644 --- a/common/ASC.Api.Core/Auth/CookieAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/CookieAuthHandler.cs @@ -50,7 +50,7 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync() 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 694fd05bf90..831849fcb5e 100644 --- a/common/ASC.Data.Backup.Core/BackupAjaxHandler.cs +++ b/common/ASC.Data.Backup.Core/BackupAjaxHandler.cs @@ -233,7 +233,7 @@ private void DemandPermissionsBackup() { 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 @@ private void DemandPermissionsTransfer() 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 d3119f27017..607ea5d4468 100644 --- a/common/services/ASC.ApiSystem/Classes/AuthHandler.cs +++ b/common/services/ASC.ApiSystem/Classes/AuthHandler.cs @@ -105,7 +105,7 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync() { 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 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync() { 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 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync() { 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 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync() { 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 c5df10a50f5..59ce729c99f 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -426,21 +426,21 @@ IPromise<IAnalyzers> analyzers(AnalyzersDescriptor b) 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 @@ IPromise<IAnalyzers> analyzers(AnalyzersDescriptor b) 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 cb8a780de17..63027453bd7 100644 --- a/products/ASC.CRM/Server/Api/UtilsController.cs +++ b/products/ASC.CRM/Server/Api/UtilsController.cs @@ -304,7 +304,7 @@ public String UpdateOrganisationSettingsCompanyAddress(String street, String cit 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 0e2dd31590c..8272fb092f6 100644 --- a/products/ASC.CRM/Server/Api/VoipController.cs +++ b/products/ASC.CRM/Server/Api/VoipController.cs @@ -390,7 +390,7 @@ public object GetVoipSettings() 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 6cae0965725..cc164019966 100644 --- a/products/ASC.Calendar/Server/Controllers/CalendarController.cs +++ b/products/ASC.Calendar/Server/Controllers/CalendarController.cs @@ -926,7 +926,7 @@ private Ical.Net.Calendar getEventIcs(int alert, CalendarWrapper calendar, Calen { 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 @@ int tenantId 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 22462212413..13f24d05a99 100644 --- a/products/ASC.Files/Core/Helpers/DocuSignHelper.cs +++ b/products/ASC.Files/Core/Helpers/DocuSignHelper.cs @@ -302,9 +302,9 @@ private string CreateEnvelope(string accountId, Document document, DocuSignData { //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 20550e58e1d..9a4f50d3262 100644 --- a/web/ASC.Web.Api/Controllers/CapabilitiesController.cs +++ b/web/ASC.Web.Api/Controllers/CapabilitiesController.cs @@ -77,7 +77,7 @@ public CapabilitiesData GetPortalCapabilities() 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 @@ public CapabilitiesData GetPortalCapabilities() 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 0b9a81ca5c9..b8d0f40bd56 100644 --- a/web/ASC.Web.Api/Controllers/SecurityController.cs +++ b/web/ASC.Web.Api/Controllers/SecurityController.cs @@ -60,7 +60,7 @@ public SecurityController( [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 @@ public IEnumerable<EventWrapper> GetLastLoginEvents() [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 @@ public object CreateLoginHistoryReport() 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 @@ public object CreateAuditTrailReport() 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 @@ public object CreateAuditTrailReport() [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 @@ public TenantAuditSettings SetAuditSettingsFromForm([FromForm] TenantAuditSettin 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 f563dd5e996..a1c50594de3 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1188,10 +1188,10 @@ public object GetWhiteLabelSizes() 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 @@ private bool SaveAuthKeys(AuthServiceModel model) 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 6b040484b6a..1476025ca0d 100644 --- a/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs @@ -231,7 +231,7 @@ private static SmtpSettingsWrapper ToSmtpSettings(SmtpSettings settingsConfig, b 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 eb5537bc974..e1cea08d239 100644 --- a/web/ASC.Web.Core/PrivacyRoomSettings.cs +++ b/web/ASC.Web.Core/PrivacyRoomSettings.cs @@ -67,7 +67,7 @@ public static void SetEnabled(TenantManager tenantManager, SettingsManager setti 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/105] 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 d77348d209f..af4a0a5cd9b 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -231,7 +231,7 @@ protected Dictionary<string, string> ParseConnectionString(string connectionStri 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 298e27cc7df..2ffc148a228 100644 --- a/common/services/ASC.ApiSystem/Classes/CommonMethods.cs +++ b/common/services/ASC.ApiSystem/Classes/CommonMethods.cs @@ -204,7 +204,7 @@ public bool SendCongratulations(string requestUriScheme, Tenant tenant, bool ski 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 @@ public bool GetTenant(IModel model, out Tenant tenant) 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 ce8ecda5284..d04822cca74 100644 --- a/common/services/ASC.ApiSystem/Controllers/PortalController.cs +++ b/common/services/ASC.ApiSystem/Controllers/PortalController.cs @@ -477,13 +477,13 @@ public IActionResult GetPortals([FromQuery] TenantModel model) 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/105] 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 607ea5d4468..e1763c18cb9 100644 --- a/common/services/ASC.ApiSystem/Classes/AuthHandler.cs +++ b/common/services/ASC.ApiSystem/Classes/AuthHandler.cs @@ -118,7 +118,7 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync() { 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/105] 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 5d03a133b47..63510288ce0 100644 --- a/common/ASC.Common/Utils/HttpRequestExtensions.cs +++ b/common/ASC.Common/Utils/HttpRequestExtensions.cs @@ -186,7 +186,7 @@ private static Uri ParseRewriterUrl(string s) } 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 @@ private static Uri ParseRewriterUrl(string s) { 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 a8e22097da9..495fc732bb0 100644 --- a/common/ASC.Core.Common/BaseCommonLinkUtility.cs +++ b/common/ASC.Core.Common/BaseCommonLinkUtility.cs @@ -185,7 +185,7 @@ public string GetFullAbsolutePath(string virtualPath) 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 @@ public string ToAbsolute(string virtualPath) 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 d57e1ccc4e1..1aaaa187fbf 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 @@ public override bool TryAdjustFilePath(bool dump, ColumnMapper columnMapper, ref { //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 d276c1c46fe..06066c8b1c1 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 @@ public DbCommand AddParameter(DbCommand command, string name, object value) 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 d3b4749aa5c..afd364f37b1 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 @@ protected override bool TryPrepareValue(bool dump, DbConnection connection, Colu 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 @@ protected override bool TryPrepareValue(bool dump, DbConnection connection, Colu 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 37c15877862..133a3421de6 100644 --- a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs @@ -117,7 +117,7 @@ public OAuth20TokenHelper(IHttpContextAccessor httpContextAccessor, ConsumerFact 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 58400b1b583..21549f20903 100644 --- a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs @@ -98,7 +98,7 @@ public OAuth20Token GetAccessToken(string authCode) 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 72eabc0e72b..3e3a835c279 100644 --- a/common/services/ASC.ElasticSearch/Core/Selector.cs +++ b/common/services/ASC.ElasticSearch/Core/Selector.cs @@ -382,7 +382,7 @@ private bool IsExactlyPhrase(string searchText) 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 98caa720464..e510341bf88 100644 --- a/products/ASC.Files/Core/Model/Binders.cs +++ b/products/ASC.Files/Core/Model/Binders.cs @@ -57,7 +57,7 @@ internal static List<JsonElement> ParseQuery(this ModelBindingContext bindingCon 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 a1c50594de3..e10239f87d5 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -2618,7 +2618,7 @@ public object GetSocketSettings() 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 aaf04b470b1..b7e1edc0a11 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -418,7 +418,7 @@ public override bool Enable() 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 2bdac1c3aab..5f80da9fbfd 100644 --- a/web/ASC.Web.Core/Utility/UrlShortener.cs +++ b/web/ASC.Web.Core/Utility/UrlShortener.cs @@ -109,7 +109,7 @@ public OnlyoShortener( 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/105] 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 aafc1dd7276..ddc5f1095c1 100644 --- a/common/ASC.Api.Core/Model/EmployeeWraperFull.cs +++ b/common/ASC.Api.Core/Model/EmployeeWraperFull.cs @@ -262,7 +262,7 @@ public EmployeeWraperFull GetFull(UserInfo userInfo) { var listAdminModules = userInfo.GetListAdminModules(WebItemSecurity); - if (listAdminModules.Any()) + if (listAdminModules.Count > 0) result.ListAdminModules = listAdminModules; } @@ -283,7 +283,7 @@ private void FillConacts(EmployeeWraperFull employeeWraperFull, UserInfo userInf } } - 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 c4f99322f4a..49eb2c398c7 100644 --- a/common/ASC.Common/Utils/DnsLookup.cs +++ b/common/ASC.Common/Utils/DnsLookup.cs @@ -101,7 +101,7 @@ public bool IsDomainExists(string domainName) 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 c8bb46ade04..bcb2518b1c4 100644 --- a/common/ASC.Core.Common/Billing/License/LicenseReader.cs +++ b/common/ASC.Core.Common/Billing/License/LicenseReader.cs @@ -189,7 +189,7 @@ private DateTime Validate(License license) { 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 8bfd0c5d511..aad10a1f67b 100644 --- a/common/ASC.Core.Common/Billing/TariffService.cs +++ b/common/ASC.Core.Common/Billing/TariffService.cs @@ -503,10 +503,10 @@ private bool SaveBillingInfo(int tenant, Tariff tariffInfo, bool renewal = true) 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 6ff6375c341..2a88d89c104 100644 --- a/common/ASC.Core.Common/Configuration/Consumer.cs +++ b/common/ASC.Core.Common/Configuration/Consumer.cs @@ -88,7 +88,7 @@ private Dictionary<string, string> AllProps 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 @@ public Consumer( 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 b14ad1bba98..2149e74eae2 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -125,7 +125,7 @@ public static void PatchAssembly(IOptionsMonitor<ILog> option, Assembly a, bool 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 b6a5d06f893..978ba30eab9 100644 --- a/common/ASC.Core.Common/Data/DbAzService.cs +++ b/common/ASC.Core.Common/Data/DbAzService.cs @@ -126,15 +126,13 @@ public void RemoveAce(int tenant, AzRecord r) 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 d703aa1ffb5..88c2a79111a 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -489,13 +489,13 @@ private void ValidateDomain(string domain, int tenantId, bool validateCharacters } 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 8905fef52ff..57649e96151 100644 --- a/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs +++ b/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs @@ -191,7 +191,7 @@ private IEnumerable<string> GetFiles(List<string> domains, List<string> progress { 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 78cb2c1fc8b..bdac9eefd48 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -390,7 +390,7 @@ public override void DeleteFiles(string domain, string folderPath, string patter 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 @@ public override void DeleteFiles(string domain, List<string> paths) } } - if (!keysToDel.Any()) return; + if (keysToDel.Count == 0) return; using var storage = GetStorage(); @@ -521,7 +521,7 @@ public override bool IsFile(string domain, string path) 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 @@ public override async Task<bool> IsFileAsync(string domain, string path) 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 b76ea13260a..a044e89d742 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -419,7 +419,7 @@ public override void DeleteFiles(string domain, string folderPath, string patter 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 @@ public override void DeleteFiles(string domain, List<string> paths) } } - if (!keysToDel.Any()) return; + if (keysToDel.Count == 0) return; var client = GetClient(); @@ -537,7 +537,7 @@ public override bool IsFile(string domain, string path) 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 139a2a92a9f..44eefb7c86b 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -328,7 +328,7 @@ private void InvalidateCloudFront(params string[] paths) Paths = new Paths { Items = paths.ToList(), - Quantity = paths.Count() + Quantity = paths.Length } } }; @@ -472,7 +472,7 @@ public override void Delete(string domain, string path) 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 @@ public override void DeleteFiles(string domain, List<string> paths) } } - 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 9b8c5191861..fba49e19d6b 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -91,7 +91,7 @@ public string GetPath(HttpContext httpContext, IOptionsMonitor<ILog> options, st 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 133a3421de6..9f4b8d006c5 100644 --- a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs @@ -70,7 +70,7 @@ public OAuth20TokenHelper(IHttpContextAccessor httpContextAccessor, ConsumerFact 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 5336453e109..f003f0fff71 100644 --- a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs +++ b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs @@ -94,7 +94,7 @@ public void SaveFeeds(IEnumerable<FeedRow> feeds, string key, DateTime value) 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 a9c2cea17c2..a4e7de46f6e 100644 --- a/common/ASC.IPSecurity/IPSecurity.cs +++ b/common/ASC.IPSecurity/IPSecurity.cs @@ -92,7 +92,7 @@ public bool Verify() { 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 d02ee8012a9..85a5709df9b 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -181,7 +181,7 @@ private static void AddLoginEvent(EventMessage message, MessagesContext dbContex 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 @@ private static void AddAuditEvent(EventMessage message, Messages dbContext) 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 c27d4720452..7fe9bee69c2 100644 --- a/common/ASC.MessagingSystem/MessageTarget.cs +++ b/common/ASC.MessagingSystem/MessageTarget.cs @@ -99,7 +99,7 @@ public MessageTarget Parse(string value) 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 0a39bf0031c..47b4f8566fd 100644 --- a/common/ASC.VoipService/Dao/CachedVoipDao.cs +++ b/common/ASC.VoipService/Dao/CachedVoipDao.cs @@ -104,7 +104,7 @@ public override IEnumerable<VoipPhone> GetNumbers(params string[] ids) 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 2ef0656245a..bb025abcaa5 100644 --- a/common/ASC.VoipService/Dao/VoipDao.cs +++ b/common/ASC.VoipService/Dao/VoipDao.cs @@ -101,7 +101,7 @@ public virtual IEnumerable<VoipPhone> GetNumbers(params string[] ids) { 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 1dc54beeb27..f0afbbb24bc 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -71,7 +71,7 @@ public string GetActionText(AuditEvent evt) { 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 @@ public string GetActionText(LoginEvent evt) { 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 b006aeafe9f..3933ee33423 100644 --- a/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs +++ b/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs @@ -115,12 +115,12 @@ private void GetOldEvents<T>(Expression<Func<Messages, DbSet<T>>> func, string s 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 eccf93f26dd..a6e548bb9eb 100644 --- a/common/services/ASC.Data.Backup/BackupCleanerService.cs +++ b/common/services/ASC.Data.Backup/BackupCleanerService.cs @@ -72,7 +72,7 @@ internal void DeleteExpiredBackups(BackupCleanerService backupCleanerService) 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 4838978bbd8..e39804b5682 100644 --- a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs +++ b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs @@ -136,7 +136,7 @@ private void AggregateFeeds(object interval) 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 091a52f309c..18df362629b 100644 --- a/common/services/ASC.TelegramService/Core/Core.cs +++ b/common/services/ASC.TelegramService/Core/Core.cs @@ -116,8 +116,8 @@ private object[] ParseParams(MethodInfo cmd, string[] args) 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 e510341bf88..291a7b29fc3 100644 --- a/products/ASC.Files/Core/Model/Binders.cs +++ b/products/ASC.Files/Core/Model/Binders.cs @@ -197,7 +197,7 @@ public Task BindModelAsync(ModelBindingContext bindingContext) 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 @@ public Task BindModelAsync(ModelBindingContext bindingContext) 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 ec6137f96f6..e7983d370df 100644 --- a/products/ASC.Files/Server/Controllers/FilesController.cs +++ b/products/ASC.Files/Server/Controllers/FilesController.cs @@ -207,7 +207,7 @@ public IEnumerable<FolderContentWrapper<int>> GetRootFolders(Guid userIdOrGroupI 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 a9b2ec8139c..5cbd9e9822c 100644 --- a/products/ASC.Files/Service/Core/FilesModule.cs +++ b/products/ASC.Files/Service/Core/FilesModule.cs @@ -65,7 +65,7 @@ public override bool VisibleFor(Feed.Aggregator.Feed feed, object data, Guid use 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 @@ private bool IsTarget(object target, Guid userId) 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 949a499c400..ee7150c2642 100644 --- a/products/ASC.Files/Service/Core/FoldersModule.cs +++ b/products/ASC.Files/Service/Core/FoldersModule.cs @@ -62,7 +62,7 @@ public override bool VisibleFor(Feed.Aggregator.Feed feed, object data, Guid use 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 093bbc06c35..0ce47f95d08 100644 --- a/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs +++ b/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs @@ -151,7 +151,7 @@ public IEnumerable<FileData<int>> GetFilesWithoutThumbnails() 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 f11031af3bc..663b7888534 100644 --- a/products/ASC.Files/Service/Thumbnail/Worker.cs +++ b/products/ASC.Files/Service/Thumbnail/Worker.cs @@ -81,7 +81,7 @@ private void Procedure(object _) 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 2c42145526c..35965fd2650 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -788,7 +788,7 @@ private EmployeeWraperFull UpdateMember(string userid, UpdateMemberModel memberM } // 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 @@ private IEnumerable<EmployeeWraperFull> UpdateUserType(EmployeeType type, Update 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 d4262ac59bd..b51f7e44166 100644 --- a/web/ASC.Web.Api/Controllers/PortalController.cs +++ b/web/ASC.Web.Api/Controllers/PortalController.cs @@ -170,7 +170,7 @@ public double GetUsedSpace() [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 e10239f87d5..ea0e8525f3d 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1128,7 +1128,7 @@ public bool SaveWhiteLabelSettingsFromFiles([FromQuery] WhiteLabelQuery query) 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 @@ private bool StartStorageEncryption(StorageEncryptionModel storageEncryption) { 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/105] 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 d19bc45af1f..908124d0026 100644 --- a/common/ASC.Data.Storage/StorageFactory.cs +++ b/common/ASC.Data.Storage/StorageFactory.cs @@ -56,8 +56,7 @@ public StorageFactoryConfig(IServiceProvider serviceProvider) 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/105] 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 88c2a79111a..54598f6ef4b 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -221,8 +221,7 @@ IQueryable<TenantUserSecurity> query() => TenantsQuery() .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 f003f0fff71..e718b5df939 100644 --- a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs +++ b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs @@ -244,7 +244,7 @@ private List<FeedResultItem> GetFeedsInternal(FeedApiFilter filter) 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 ea0e8525f3d..9332ee1608c 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -872,7 +872,6 @@ public object GetEnabledModules() { 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 @@ public List<StorageWrapper> GetAllStorages() 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 @@ public List<StorageWrapper> GetAllCdnStorages() 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 @@ public List<StorageWrapper> GetAllBackupStorages() }; } - 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/105] 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 | 47 ++++++++----------- .../Data/FeedAggregateDataProvider.cs | 4 +- .../DbSender/MessagesRepository.cs | 4 +- common/ASC.MessagingSystem/MessageTarget.cs | 2 +- .../Service/FeedAggregatorService.cs | 4 +- .../UrlShortenerService.cs | 4 +- 11 files changed, 46 insertions(+), 67 deletions(-) diff --git a/common/ASC.Common/Logging/SelfCleaningTarget.cs b/common/ASC.Common/Logging/SelfCleaningTarget.cs index 613c1dd405a..86a7f5c125b 100644 --- a/common/ASC.Common/Logging/SelfCleaningTarget.cs +++ b/common/ASC.Common/Logging/SelfCleaningTarget.cs @@ -53,10 +53,8 @@ private static int GetCleanPeriod() 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 2a88d89c104..59e5aaa4a5e 100644 --- a/common/ASC.Core.Common/Configuration/Consumer.cs +++ b/common/ASC.Core.Common/Configuration/Consumer.cs @@ -245,10 +245,7 @@ private string Get(string name) if (string.IsNullOrEmpty(value)) { - if (AllProps.ContainsKey(name)) - { - value = AllProps[name]; - } + AllProps.TryGetValue(name, out value); } return value; @@ -354,9 +351,9 @@ private void Init(IReadOnlyDictionary<string, string> additional) 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 978ba30eab9..b7feb320fd6 100644 --- a/common/ASC.Core.Common/Data/DbAzService.cs +++ b/common/ASC.Core.Common/Data/DbAzService.cs @@ -75,9 +75,8 @@ public IEnumerable<AzRecord> GetAces(int tenant, DateTime from) 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 bdac9eefd48..a62f12e517b 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -120,17 +120,14 @@ public override IDataStore Configure(string tenant, Handler handlerConfig, Modul ? 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 @@ private PredefinedObjectAcl GetDomainACL(string domain) 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 a044e89d742..27157bdb5c5 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -146,15 +146,12 @@ public override IDataStore Configure(string tenant, Handler handlerConfig, Modul _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 @@ public override Uri GetInternalUri(string domain, string path, TimeSpan expire, 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 @@ private ACL GetDomainACL(string domain) 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 44eefb7c86b..af7ce40e5d7 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -98,9 +98,9 @@ private S3CannedACL GetDomainACL(string domain) 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 @@ public override IDataStore Configure(string tenant, Handler handlerConfig, Modul _secretAccessKeyId = props["secretaccesskey"]; _bucket = props["bucket"]; - if (props.ContainsKey("recycleDir")) - { - _recycleDir = props["recycleDir"]; - } + props.TryGetValue("recycleDir", out _recycleDir); - if (props.ContainsKey("region") && !string.IsNullOrEmpty(props["region"])) + if (props.TryGetValue("region", out var region) && !string.IsNullOrEmpty(region)) { - _region = props["region"]; + _region = region; } - if (props.ContainsKey("serviceurl") && !string.IsNullOrEmpty(props["serviceurl"])) + if (props.TryGetValue("serviceurl", out var url) && !string.IsNullOrEmpty(url)) { - _serviceurl = props["serviceurl"]; + _serviceurl = url; } - if (props.ContainsKey("forcepathstyle")) + if (props.TryGetValue("forcepathstyle", out var style)) { - 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 @@ public override IDataStore Configure(string tenant, Handler handlerConfig, Modul ? new Uri(props["cnamessl"], UriKind.Absolute) : new Uri($"https://s3.{_region}.amazonaws.com/{_bucket}/", UriKind.Absolute); - if (props.ContainsKey("lower")) - { - bool.TryParse(props["lower"], out _lowerCasing); - } - if (props.ContainsKey("cloudfront")) + if (props.TryGetValue("lower", out var lower)) { - bool.TryParse(props["cloudfront"], out _revalidateCloudFront); + bool.TryParse(lower, out _lowerCasing); } - if (props.ContainsKey("distribution")) + if (props.TryGetValue("cloudfront", out var front)) { - _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 e718b5df939..9a9d1c41297 100644 --- a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs +++ b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs @@ -179,9 +179,9 @@ public List<FeedResultItem> GetFeeds(FeedApiFilter filter) 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 85a5709df9b..1cc81b31db9 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -133,9 +133,9 @@ private void FlushCache(object state) 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 7fe9bee69c2..ab8359fab20 100644 --- a/common/ASC.MessagingSystem/MessageTarget.cs +++ b/common/ASC.MessagingSystem/MessageTarget.cs @@ -99,7 +99,7 @@ public MessageTarget Parse(string value) 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 e39804b5682..738fedcc572 100644 --- a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs +++ b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs @@ -201,9 +201,9 @@ private void AggregateFeeds(object interval) { 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 a343f8dc5bd..a5cad6e13e0 100644 --- a/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs +++ b/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs @@ -140,9 +140,9 @@ private ProcessStartInfo GetProcessStartInfo() 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/105] 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 27157bdb5c5..3f024cd2605 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -404,8 +404,11 @@ public override void DeleteFiles(string domain, string folderPath, string patter .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 @@ public override void DeleteFiles(string domain, string folderPath, DateTime from 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 946609794d9..88b01e94b53 100644 --- a/common/ASC.FederatedLogin/AccountLinker.cs +++ b/common/ASC.FederatedLogin/AccountLinker.cs @@ -168,9 +168,8 @@ private List<LoginProfile> GetLinkedProfilesFromDB(string obj) //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 bb025abcaa5..650430d80a3 100644 --- a/common/ASC.VoipService/Dao/VoipDao.cs +++ b/common/ASC.VoipService/Dao/VoipDao.cs @@ -93,8 +93,7 @@ public virtual IEnumerable<VoipPhone> GetAllNumbers() { 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 @@ public virtual IEnumerable<VoipPhone> GetNumbers(params string[] ids) 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 @@ public IEnumerable<VoipCall> GetCalls(VoipCallFilter filter) 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 @@ public IEnumerable<VoipCall> GetMissedCalls(Guid agent, long count = 0, DateTime .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 94e9b54d2af..c9363e89423 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 @@ private Folder MoveFld(Folder folder, string newUrl, bool delete = true) 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 9ef7231d528..0740150d98b 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 @@ private ItemNameValueCollection<T> GetEntriesPathId(IServiceScope scope) } 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 f1e5a875c98..3b1c79f5892 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 @@ private void Do<TTo>(IServiceScope scope, TTo tto) 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 87e1fa8a715..2c879b4f35a 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -600,13 +600,14 @@ public IEnumerable<Folder<string>> GetThirpartyFolders<T>(Folder<T> parent, stri 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 9b9dd244994..2cac1a500f8 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -170,15 +170,15 @@ private void CheckConvertFilesStatus(object _) { 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 1de062bcdf1..35f84548c5c 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -172,23 +172,22 @@ internal void ExecMarkFileAsNew<T>(AsyncTaskData<T> obj) 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 159766f5e48..e158b1e58e4 100644 --- a/products/ASC.Files/Core/Utils/FileTracker.cs +++ b/products/ASC.Files/Core/Utils/FileTracker.cs @@ -168,17 +168,14 @@ public void ChangeRight<T>(T fileId, Guid userId, bool check) { 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 9332ee1608c..f9d837c52f0 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1106,7 +1106,11 @@ private void SaveWhiteLabelSettingsForTenant(TenantWhiteLabelSettings 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 314920d7bb6..064556c90db 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -238,7 +238,7 @@ private bool CheckDate(DateTime d) 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 @@ public List<DateTime> GetDates(DateTime utcStartDate, TimeZoneInfo eventTimeZone 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 b46a985db63..06a680c24e1 100644 --- a/web/ASC.Web.Core/Files/FileUtility.cs +++ b/web/ASC.Web.Core/Files/FileUtility.cs @@ -330,19 +330,18 @@ public Dictionary<string, List<string>> ExtsConvertible 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/105] 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 399b54d6f2a..83296e79faf 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 @@ private void DeleteFile(int fileId, bool deleteFolder) tx.Commit(); - fromFolders.ForEach(folderId => RecalculateFilesCount(folderId)); + foreach(var folderId in fromFolders) + { + RecalculateFilesCount(folderId); + } if (deleteFolder) DeleteFolder(fileId); @@ -770,7 +773,10 @@ public int MoveFile(int fileId, int toFolderId) 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 816ebd24bb5..a736f5ad770 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 @@ public IDictionary<int, string> CanMoveOrCopy(int[] folderIds, int to) 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 11c6380d202..33668e45ff5 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 @@ public IEnumerable<Tag> GetNewTags(Guid subject, Folder<T> parentFolder, bool de 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 63c88b4de43..70658a8de84 100644 --- a/products/ASC.Files/Core/Core/FilesIntegration.cs +++ b/products/ASC.Files/Core/Core/FilesIntegration.cs @@ -126,7 +126,11 @@ internal static Dictionary<object, IFileSecurity> GetFileSecurity(Dictionary<str 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 f6a4a4cd89d..780ee9b2864 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs @@ -86,12 +86,14 @@ public File<TTo> PerformCrossDaoFileCopy<TFrom, TTo>( 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 @@ public Folder<TTo> PerformCrossDaoFolderCopy<TFrom, TTo> .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 5995bafadce..b08a6482fbc 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 @@ public IDaoSelector GetSelector(string id) 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/105] 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 cbc2cd13b13..779a5ea9ab1 100644 --- a/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs +++ b/common/ASC.Api.Core/Middleware/ProductSecurityFilter.cs @@ -103,16 +103,16 @@ private static Guid FindProduct(ControllerActionDescriptor method) 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 dd07b0f1681..3fc3814246d 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -187,15 +187,13 @@ public IDictionary<string, Dictionary<string, decimal>> GetProductPriceInfo(para 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 d983357dda3..d1230f551dc 100644 --- a/common/ASC.Core.Common/Caching/AzRecordStore.cs +++ b/common/ASC.Core.Common/Caching/AzRecordStore.cs @@ -68,9 +68,9 @@ public void Remove(AzRecord r) 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 370e579f669..7091946bad4 100644 --- a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs @@ -80,11 +80,9 @@ public virtual void Init(IDictionary<string, string> properties) 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 9c67a8c3ff6..37ede1d5581 100644 --- a/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs +++ b/common/ASC.Data.Backup.Core/Core/DbBackupProvider.cs @@ -68,9 +68,9 @@ public IEnumerable<XElement> GetElements(int tenant, string[] configs, IDataWrit 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 f4637094d8a..8aca730396c 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -264,9 +264,9 @@ private string GetWhere(string tableName, int tenant) { 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 c5b86fde9e7..45f667da44c 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -666,9 +666,9 @@ private void CopyAll(DirectoryInfo source, DirectoryInfo target, string newdomai 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 285710cfdbb..fc6e24bd441 100644 --- a/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs @@ -66,8 +66,7 @@ public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, 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 @@ public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, 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 efd8e8a9d70..96947f5e277 100644 --- a/common/ASC.VoipService/Dao/VoIPCallFilter.cs +++ b/common/ASC.VoipService/Dao/VoIPCallFilter.cs @@ -62,7 +62,7 @@ public int? TypeStatus 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 6237cc91c7e..cae084da9d2 100644 --- a/common/services/ASC.TelegramService/TelegramHandler.cs +++ b/common/services/ASC.TelegramService/TelegramHandler.cs @@ -112,9 +112,8 @@ public void CreateOrUpdateClientForTenant(int tenantId, string token, int tokenL 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 8da56a2d799..4f7d0f4440a 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -755,9 +755,9 @@ private List<FileEntry> GetSharesForMe<T>(IEnumerable<FileShareRecord> records, 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 @@ private List<FileEntry> GetSharesForMe<T>(IEnumerable<FileShareRecord> records, } 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 @@ private List<FileEntry<T>> GetPrivacyForMe<T>(IEnumerable<FileShareRecord> recor 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 @@ private List<FileEntry<T>> GetPrivacyForMe<T>(IEnumerable<FileShareRecord> recor } 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 b4f42ceee23..f0653fec6c1 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs @@ -116,7 +116,7 @@ public virtual IFolderDao<string> GetFolderDao<T1>(string id) where T1 : ThirdPa 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 0740150d98b..58fdea4e414 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 @@ private ItemNameValueCollection<T> ExecPathFromFile(IServiceScope scope, File<T> 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 @@ internal void CompressToZip(Stream stream, IServiceScope scope) 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 2cac1a500f8..9e150f1e9d3 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -271,9 +271,8 @@ private void CheckConvertFilesStatus(object _) 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 @@ private void CheckConvertFilesStatus(object _) { 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 @@ private void CheckConvertFilesStatus(object _) { 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 35f84548c5c..5c590ec5172 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -153,8 +153,8 @@ internal void ExecMarkFileAsNew<T>(AsyncTaskData<T> obj) 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 @@ internal void ExecMarkFileAsNew<T>(AsyncTaskData<T> obj) 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 @@ internal void ExecMarkFileAsNew<T>(AsyncTaskData<T> obj) 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 @@ internal void ExecMarkFileAsNew<T>(AsyncTaskData<T> obj) 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 @@ internal void ExecMarkFileAsNew<T>(AsyncTaskData<T> obj) 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 e158b1e58e4..20c8596d80a 100644 --- a/products/ASC.Files/Core/Utils/FileTracker.cs +++ b/products/ASC.Files/Core/Utils/FileTracker.cs @@ -63,9 +63,9 @@ public bool ProlongEditing<T>(T fileId, Guid tabId, Guid userId, bool editingAlo 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 4932763ba9a..9e6634862a1 100644 --- a/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs +++ b/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs @@ -150,9 +150,9 @@ private int GetFieldsMapping(string firstLine, IEnumerable<PropertyInfo> infos, 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 f49c21d0686..3331287d359 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -148,9 +148,9 @@ public bool IsAvailableForUser(Guid itemId, Guid @for) { 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/105] 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 8b593c00f5f..056d8321c1a 100644 --- a/common/ASC.Common/Caching/AscCache.cs +++ b/common/ASC.Common/Caching/AscCache.cs @@ -55,7 +55,7 @@ public void ClearCache() 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 @@ public void Remove(string 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(); + 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 3d16f3f2282..dcd17805aea 100644 --- a/common/ASC.Common/Mapping/MappingProfile.cs +++ b/common/ASC.Common/Mapping/MappingProfile.cs @@ -44,8 +44,7 @@ private void ApplyMappingsFromAssembly(Assembly assembly) 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 5c590ec5172..9643d3cebfa 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -378,7 +378,7 @@ public void RemoveMarkAsNew<T>(FileEntry<T> fileEntry, Guid userID = default) 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 20c8596d80a..a4c3dc0d875 100644 --- a/products/ASC.Files/Core/Utils/FileTracker.cs +++ b/products/ASC.Files/Core/Utils/FileTracker.cs @@ -97,8 +97,8 @@ public void Remove<T>(T fileId, Guid tabId = default, Guid userId = default) 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 @@ public void RemoveAllOther<T>(Guid userId, T fileId) 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 @@ public bool IsEditing<T>(T fileId) 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/105] 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 59150689677..8b4bf71903e 100644 --- a/common/ASC.Core.Common/Data/DbUserService.cs +++ b/common/ASC.Core.Common/Data/DbUserService.cs @@ -701,7 +701,7 @@ private IQueryable<User> GetUserQueryForFilter( 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 @@ private IQueryable<User> GetUserQueryForFilter( } } - 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 2bb36d0b11c..7a488a6838d 100644 --- a/common/ASC.Core.Common/MultiRegionHostedSolution.cs +++ b/common/ASC.Core.Common/MultiRegionHostedSolution.cs @@ -107,7 +107,7 @@ public List<Tenant> FindTenants(string login, string password, string passwordHa 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 f031c7b886e..c5074392dce 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -205,7 +205,7 @@ private void NotifySender(object state) NotifyRequest request = null; lock (requests) { - if (requests.Any()) + if (requests.Count > 0) { request = requests.Dequeue(); } @@ -425,7 +425,7 @@ private SendResponse CreateNoticeMessageFromNotifyRequest(NotifyRequest request, 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 cbd06ee77db..23eebf1016a 100644 --- a/common/ASC.Core.Common/Notify/Model/ISubscriptionProvider.cs +++ b/common/ASC.Core.Common/Notify/Model/ISubscriptionProvider.cs @@ -69,7 +69,7 @@ public static bool IsSubscribed(this ISubscriptionProvider provider, ILog log, I 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 6d4788ff94e..d86468d01eb 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -125,7 +125,7 @@ public IDirectRecipient FilterRecipientAddresses(IDirectRecipient recipient) 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 aba43cb9b24..da2395908b0 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 @@ public List<TelegramUser> GetUser(int telegramId) 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 db8968d5c6e..dabab637f13 100644 --- a/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs @@ -145,7 +145,7 @@ private void MigrationNotify(Tenant tenant, INotifyAction action, string region, .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 4b7c73cd98c..050127ab148 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -393,7 +393,7 @@ private void SaveToFile(string path, string t, IReadOnlyCollection<string> colum { 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 dd54560f00e..c52d3835457 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 @@ public bool HasIdColumn() 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 cc049827d4e..667258ec70d 100644 --- a/common/services/ASC.ElasticSearch/Core/SearchSettings.cs +++ b/common/services/ASC.ElasticSearch/Core/SearchSettings.cs @@ -136,7 +136,7 @@ public void Set(List<SearchSettingsItem> items) 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 59ce729c99f..5841592e67a 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -122,7 +122,7 @@ internal void Index(T data, bool immediately = true) 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 @@ private IUpdateRequest<T, T> GetMetaForUpdate(UpdateDescriptor<T, T> request, T { 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 4c23f20347b..3d16cfe71a3 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -207,7 +207,7 @@ public bool Index(T data, bool immediately = true) 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 @@ public void Index(List<T> data, bool immediately = true, int retry = 0) 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 12a2b4462e4..214e73c7372 100644 --- a/common/services/ASC.ElasticSearch/Service/Service.cs +++ b/common/services/ASC.ElasticSearch/Service/Service.cs @@ -79,7 +79,7 @@ public void ReIndex(List<string> toReIndex, int tenant) 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 83296e79faf..89ad6fb6958 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 @@ public File<int> SaveFile(File<int> file, Stream fileStream, bool checkQuota = t 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 @@ public File<int> ReplaceFileVersion(File<int> file, Stream fileStream) 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 @@ public IEnumerable<int> GetTenantsWithFeeds(DateTime fromTime) 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 a736f5ad770..ea62a3f9a95 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 @@ public IEnumerable<int> GetTenantsWithFeedsForFolders(DateTime fromTime) 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 0f2e9d25b51..d54f60f935c 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 @@ private IEnumerable<FileShareRecord> GetPureShareRecordsDb(List<string> files, L 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 33668e45ff5..8766c941a12 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 @@ private void RemoveTagInDb(Tag tag) 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 @@ public IEnumerable<Tag> GetNewTags(Guid subject, IEnumerable<FileEntry<T>> fileE 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 @@ public IEnumerable<Tag> GetNewTags(Guid subject, Folder<T> parentFolder, bool de .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 cfd0c2a3d77..fa4915d6a25 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -306,7 +306,7 @@ public DataWrapper<T> GetFolderItems(T parentId, int from, int count, FilterType 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 @@ public File<T> LockFile(T fileId, bool lockfile) } 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 @@ public List<FileEntry> GetNewItems(T folderId) 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 @@ public List<FileEntry> GetNewItems(T folderId) 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 @@ public List<FileOperationResult> TerminateTasks() 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 @@ public List<FileOperationResult> BulkDownload(Dictionary<JsonElement, string> fo 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 @@ public List<FileOperationResult> BulkDownload(Dictionary<JsonElement, string> fo 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 8657ba9f830..bf8820cadee 100644 --- a/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs +++ b/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs @@ -171,7 +171,7 @@ IQueryable<FileTenant> GetBaseQuery(DateTime lastIndexed) => fileDao.FilesDbCont } } - 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 2b0b51931aa..0c2d8d54d39 100644 --- a/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs +++ b/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs @@ -155,7 +155,7 @@ IQueryable<FolderTenant> GetBaseQuery(DateTime lastIndexed) => folderDao.FilesDb } } - 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 4f7d0f4440a..2278b550405 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -817,7 +817,7 @@ private List<FileEntry> GetSharesForMe<T>(IEnumerable<FileShareRecord> records, 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 780ee9b2864..b04414464ca 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs @@ -100,7 +100,7 @@ public File<TTo> PerformCrossDaoFileCopy<TFrom, TTo>( 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 @@ public Folder<TTo> PerformCrossDaoFolderCopy<TFrom, TTo> 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 f420f61908a..fe1f4973c0f 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs @@ -495,7 +495,7 @@ public IEnumerable<Tag> GetNewTags(Guid subject, Folder<string> parentFolder, bo .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 fb81dd414da..7bb179e8b5e 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 @@ public List<File<string>> GetFiles(string parentId, OrderBy orderBy, FilterType .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 0e6a04e9dad..7794693459d 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 @@ public List<Folder<string>> GetFolders(string parentId, OrderBy orderBy, FilterT 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 @@ public List<Folder<string>> GetFolders(IEnumerable<string> folderIds, FilterType 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 @@ public IDictionary<string, string> CanMoveOrCopy(string[] folderIds, int to) 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 4ba1a889dd2..b377ffce770 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 @@ public IEnumerable<FileShareRecord> GetShares(IEnumerable<FileEntry<string>> ent 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 @@ private void GetFoldersForShare(string folderId, ICollection<FileEntry<string>> 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 @@ private List<FileShareRecord> GetShareForFolders(IReadOnlyCollection<FileEntry<s 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 75ba36c129f..6a687a9f520 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -535,7 +535,7 @@ private long ProcessRangeHeader(HttpContext context, long fullLength, ref long o 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 1ea0b2a1b60..44cabcb9aef 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs @@ -189,7 +189,7 @@ public void GenerateReport(DistributedTask task, CancellationToken cancellationT 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 0d6a4a09938..9d3baf7539a 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs @@ -371,7 +371,7 @@ public void CheckUsersForDrop<T>(File<T> file) }) .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 f8acf8736e5..7ba2b75fa25 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -326,7 +326,7 @@ private void ProcessEdit<T>(T fileId, TrackerData fileData) } } - 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 58fdea4e414..62ee115cfa1 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 @@ public FileDownloadOperation(IServiceProvider serviceProvider, FileDownloadOpera 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 b69b4e5595a..92314b7e830 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 @@ protected override void Do(IServiceScope scope) 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 ea9d56e9eb8..a537332643f 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 @@ public List<FileOperationResult> GetOperationResults(Guid userId) 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 2c879b4f35a..688c87a4aaa 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -597,7 +597,7 @@ public IEnumerable<Folder<string>> GetThirpartyFolders<T>(Folder<T> parent, stri .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 9e150f1e9d3..9823b5f0561 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -619,7 +619,7 @@ public FileConverter( 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 @@ public File<T> SaveConvertedFile<T>(File<T> file, string convertedFileUrl) 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 9643d3cebfa..c73370ba482 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -144,7 +144,7 @@ internal void ExecMarkFileAsNew<T>(AsyncTaskData<T> obj) 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 @@ internal void ExecMarkFileAsNew<T>(AsyncTaskData<T> obj) { 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 @@ internal void ExecMarkFileAsNew<T>(AsyncTaskData<T> obj) 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 @@ public void MarkAsNew<T>(FileEntry<T> fileEntry, List<Guid> userIDs = null) 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 @@ public void MarkAsNew<T>(FileEntry<T> fileEntry, List<Guid> userIDs = null) 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 @@ public void RemoveMarkAsNew<T>(FileEntry<T> fileEntry, Guid userID = default) 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 @@ public List<FileEntry> MarkedItems<T>(Folder<T> folder) 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 @@ public IEnumerable<FileEntry> SetTagsNew<T>(Folder<T> parent, IEnumerable<FileEn 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 @@ public IEnumerable<FileEntry> SetTagsNew<T>(Folder<T> parent, IEnumerable<FileEn 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 4b4c1189610..ba65129f43e 100644 --- a/products/ASC.Files/Core/Utils/FileSharing.cs +++ b/products/ASC.Files/Core/Utils/FileSharing.cs @@ -167,7 +167,7 @@ public bool SetAceObject(List<AceWrapper> aceWrappers, FileEntry<T> entry, bool 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 @@ public List<AceWrapper> GetSharedInfo<T>(IEnumerable<T> fileIds, IEnumerable<T> 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 dc8ed2e5c5f..594b2eee1a7 100644 --- a/products/ASC.Files/Core/Utils/FileUploader.cs +++ b/products/ASC.Files/Core/Utils/FileUploader.cs @@ -205,7 +205,7 @@ private T GetFolderId<T>(T folderId, IList<string> relativePath) 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 6de24e13021..ee47b36b5c6 100644 --- a/web/ASC.Web.Core/Mobile/MobileAppInstallRegistrator.cs +++ b/web/ASC.Web.Core/Mobile/MobileAppInstallRegistrator.cs @@ -69,7 +69,7 @@ public bool IsInstallRegistered(string userEmail, MobileAppType? appType) 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 0a438cd3a45..c163ee188e8 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyHelper.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyHelper.cs @@ -170,7 +170,7 @@ public IRecipient[] RecipientFromEmail(List<string> emails, bool checkActivation 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 2d03e70a641..09f70166d00 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyServiceSender.cs @@ -101,7 +101,7 @@ public void OnMessage(NotifyItem item) (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 e11e034ee16..5d82611ae7e 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -437,7 +437,7 @@ public void SendSaasLetters(string senderName, DateTime scheduleDate) 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 @@ public void SendEnterpriseLetters(string senderName, DateTime scheduleDate) #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 @@ public void SendEnterpriseLetters(string senderName, DateTime scheduleDate) 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 7ee1f26c4d5..081862b2c97 100644 --- a/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs @@ -174,7 +174,7 @@ public void SendMsgWhatsNew(DateTime scheduleDate) 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 1517b28bfce..ffd56d92005 100644 --- a/web/ASC.Web.Core/Tfa/TfaAppUserSettings.cs +++ b/web/ASC.Web.Core/Tfa/TfaAppUserSettings.cs @@ -80,7 +80,7 @@ public static void DisableCodeForUser(SettingsManager settingsManager, Guid user 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 3331287d359..9c47739209d 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -253,7 +253,7 @@ public WebItemSecurityInfo GetSecurityInfo(string id) { 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 @@ private IEnumerable<Tuple<Guid, bool>> GetSecurity(string id) .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/105] 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 18df362629b..5e4f66b4ca9 100644 --- a/common/services/ASC.TelegramService/Core/Core.cs +++ b/common/services/ASC.TelegramService/Core/Core.cs @@ -120,16 +120,16 @@ private object[] ParseParams(MethodInfo cmd, string[] args) 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/105] 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 04fc243e34b..8981515906f 100644 --- a/common/ASC.Core.Common/Caching/CachedTenantService.cs +++ b/common/ASC.Core.Common/Caching/CachedTenantService.cs @@ -294,8 +294,9 @@ public byte[] GetTenantSettings(int tenant, string key) 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 c2a048e8929..5a8d54f609d 100644 --- a/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs +++ b/common/ASC.Core.Common/Context/Impl/SubscriptionManager.cs @@ -117,7 +117,7 @@ public string[] GetSubscriptionMethod(string sourceID, string actionID, string r 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 d13357cdf64..f7dde013082 100644 --- a/common/ASC.Core.Common/Core/UserInfo.cs +++ b/common/ASC.Core.Common/Core/UserInfo.cs @@ -138,7 +138,7 @@ public CultureInfo GetCulture() 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 8b4bf71903e..2416310efa9 100644 --- a/common/ASC.Core.Common/Data/DbUserService.cs +++ b/common/ASC.Core.Common/Data/DbUserService.cs @@ -365,7 +365,7 @@ public byte[] GetUserPhoto(int tenant, Guid id) .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 c5074392dce..b8cb130cd86 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -507,7 +507,7 @@ private void PrepareRequestFillSenders(NotifyRequest request, IServiceScope serv 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 @@ private void PrepareRequestFillTags(NotifyRequest request, IServiceScope service { 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 7722248520e..40a0d196a69 100644 --- a/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs +++ b/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs @@ -98,7 +98,7 @@ protected virtual void AfterFormat(INoticeMessage message) 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 d86468d01eb..e57bbbd7ee8 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -111,7 +111,7 @@ public virtual string[] GetRecipientAddresses(IDirectRecipient recipient, string 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 1d8c92f0cb1..01351c226d8 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 @@ public virtual string[] GetSubscriptions(INotifyAction action, IRecipient recipi 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 32b0778d96d..a6b3a2070b2 100644 --- a/common/ASC.Core.Common/Tenants/TenantQuota.cs +++ b/common/ASC.Core.Common/Tenants/TenantQuota.cs @@ -307,7 +307,7 @@ public bool GetFeature(string feature) 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 45f667da44c..6bce910864c 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -543,7 +543,7 @@ public override string[] ListDirectoriesRelative(string domain, string path, boo 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 @@ public override string[] ListFilesRelative(string domain, string path, string pa 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 6a26f7c3e89..280e6597f4f 100644 --- a/common/ASC.Data.Storage/StorageHandler.cs +++ b/common/ASC.Data.Storage/StorageHandler.cs @@ -102,7 +102,7 @@ public Task Invoke(HttpContext context) 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 a4e7de46f6e..aedd7234668 100644 --- a/common/ASC.IPSecurity/IPSecurity.cs +++ b/common/ASC.IPSecurity/IPSecurity.cs @@ -101,7 +101,7 @@ public bool Verify() } 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 5ea1803eeb8..8637aa30aa5 100644 --- a/common/ASC.MessagingSystem/MessagePolicy.cs +++ b/common/ASC.MessagingSystem/MessagePolicy.cs @@ -43,7 +43,7 @@ public MessagePolicy(IConfiguration configuration) { 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 b8f1a4b192e..6234ca6a489 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 @@ public SharpBoxStorageDisposableWrapper() 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 201f6639507..741ed1b3d06 100644 --- a/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs +++ b/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs @@ -47,7 +47,7 @@ public List<string> ThirdPartyProviders { 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 14686197a3d..a5672a9ee89 100644 --- a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs +++ b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs @@ -64,7 +64,7 @@ public FFmpegService(IOptionsMonitor<ILog> optionsMonitor, IConfiguration config 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 06a680c24e1..39f569d493d 100644 --- a/web/ASC.Web.Core/Files/FileUtility.cs +++ b/web/ASC.Web.Core/Files/FileUtility.cs @@ -49,20 +49,20 @@ public FileUtilityConfiguration(IConfiguration configuration) } 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 @@ public List<string> ExtsWebEdited { 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 @@ public List<string> ExtsWebCustomFilterEditing { 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 @@ public List<string> ExtsWebRestrictedEditing { 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 @@ public List<string> ExtsWebCommented { 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 @@ public List<string> ExtsWebTemplate { 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 @@ public List<string> ExtsMustConvert { 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 081862b2c97..bee1e9770d3 100644 --- a/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioWhatsNewNotify.cs @@ -142,7 +142,7 @@ public void SendMsgWhatsNew(DateTime scheduleDate) 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 @@ public void SendMsgWhatsNew(DateTime scheduleDate) 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 @@ public void SendMsgWhatsNew(DateTime scheduleDate) 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 9e6634862a1..1f46253b113 100644 --- a/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs +++ b/web/ASC.Web.Core/Users/Import/TextFileUserImporter.cs @@ -115,7 +115,7 @@ private UserInfo GetExportedUser(string line, IDictionary<int, PropertyInfo> map 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/105] 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 5f0e9609f55..87ef0515ba0 100644 --- a/common/ASC.Core.Common/Context/Impl/AuthorizationManager.cs +++ b/common/ASC.Core.Common/Context/Impl/AuthorizationManager.cs @@ -100,7 +100,7 @@ public void RemoveAce(AzRecord r) 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 5cc08414418..2888a72d7b4 100644 --- a/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs @@ -89,7 +89,7 @@ private void DoDeleteStorage() 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 fa4915d6a25..88f8bb0308f 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -1602,7 +1602,7 @@ public void ReassignStorage(Guid userFromId, Guid userToId) 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 bfe2b7a48fc..de0cce7a79c 100644 --- a/web/ASC.Web.Core/QuotaSync.cs +++ b/web/ASC.Web.Core/QuotaSync.cs @@ -56,14 +56,14 @@ public void RunJob()//DistributedTask distributedTask, CancellationToken cancell 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/105] 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 89cefcaaede..95f3c2e24c1 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs @@ -113,7 +113,7 @@ protected BaseLoginProvider( 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 a9e477a798b..505932dddad 100644 --- a/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/GosUslugiLoginProvider.cs @@ -114,7 +114,7 @@ public GosUslugiLoginProvider( } - 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 6f73b71e5dd..70678a26bc9 100644 --- a/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/MailRuLoginProvider.cs @@ -97,7 +97,7 @@ public MailRuLoginProvider( { } - 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 fc6e24bd441..40edb0b444b 100644 --- a/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/OpenIdLoginProvider.cs @@ -53,7 +53,7 @@ public OpenIdLoginProvider(Signature signature, InstanceCrypto instanceCrypto, C 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 1a4f6b9516a..15450112c6a 100644 --- a/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/VKLoginProvider.cs @@ -102,7 +102,7 @@ public VKLoginProvider( } - 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 96a96c48403..d803e38c5b5 100644 --- a/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/YandexLoginProvider.cs @@ -94,7 +94,7 @@ public YandexLoginProvider( { } - 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 89ad6fb6958..3e760291e4b 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 @@ public List<File<int>> GetFiles(IEnumerable<int> parentIds, FilterType filterTyp 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 ea62a3f9a95..f3808eff58f 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 @@ public bool CanCalculateSubitems(int entryId) 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 @@ public void ReassignFolders(int[] folderIds, Guid newOwnerId) } - 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 dfd6f18af05..627b4ed8165 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 @@ public File<string> GetFile(string parentId, string title) .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 121493da3a1..99ee0e9a967 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 @@ public bool CanCalculateSubitems(string entryId) 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 5a7c652ed6e..540e57aaa96 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 @@ public File<string> GetFile(string parentId, string title) : 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 41953eb9230..d7751a8ad96 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 @@ public bool CanCalculateSubitems(string entryId) 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 715c0c8856d..ffaf005bb4b 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 @@ public File<string> GetFile(string parentId, string title) .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 eed396f844e..28b26accd36 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 @@ public bool CanCalculateSubitems(string entryId) 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 f60c9a7c97a..60f36ce492f 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 @@ public File<string> GetFile(string parentId, string title) .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 bfd01a065d1..7a0bfda7f47 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 @@ public bool CanCalculateSubitems(string entryId) 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 7794693459d..4a3b3a38b77 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 @@ public bool CanCalculateSubitems(string entryId) 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 86c68236cc6..86c11d40586 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 @@ public File<string> GetFile(string parentId, string title) 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 887438298a3..9b0e6829bcf 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 @@ public File<string> GetFile(string parentId, string title) 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 5f99a29e494..96877abb9b1 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 @@ public bool CanCalculateSubitems(string entryId) 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/105] 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 00727d4ced3..ca9c60a4fed 100644 --- a/common/services/ASC.AuditTrail/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/AuditEventsRepository.cs @@ -86,7 +86,7 @@ orderby q.Date descending 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 78b913da763..a364647bfba 100644 --- a/common/services/ASC.AuditTrail/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/LoginEventsRepository.cs @@ -101,7 +101,7 @@ public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) 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 8a357e95d57..ef33da36153 100644 --- a/products/ASC.Files/Core/Configuration/FilesSpaceUsageStatManager.cs +++ b/products/ASC.Files/Core/Configuration/FilesSpaceUsageStatManager.cs @@ -83,7 +83,7 @@ public override List<UsageSpaceStatItem> GetStatData() .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/105] 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 70161bcf61d..7348d06ef1d 100644 --- a/common/ASC.Core.Common/Configuration/SmtpSettings.cs +++ b/common/ASC.Core.Common/Configuration/SmtpSettings.cs @@ -54,7 +54,7 @@ public class SmtpSettings 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 2149e74eae2..9a17b26acb4 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 e61b9536c20..86509365cba 100644 --- a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs @@ -29,7 +29,7 @@ public BaseDbContext(DbContextOptions options) : base(options) 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 c23f69ef335..0a9036e2e7d 100644 --- a/common/ASC.Core.Common/Tenants/TenantAuditSettings.cs +++ b/common/ASC.Core.Common/Tenants/TenantAuditSettings.cs @@ -39,7 +39,7 @@ public class TenantAuditSettings : ISettings 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 97953837bc7..85ddffe722c 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 73f1bbee1b2..422e979f5d9 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -55,13 +55,13 @@ public static class DocumentService /// <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 f408fdee39d..058685ac9d6 100644 --- a/web/ASC.Web.Core/Notify/Tags.cs +++ b/web/ASC.Web.Core/Notify/Tags.cs @@ -112,9 +112,9 @@ public sealed class CommonTags 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/105] 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 ca9c60a4fed..80dcd7049a8 100644 --- a/common/services/ASC.AuditTrail/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/AuditEventsRepository.cs @@ -105,7 +105,7 @@ public int GetCount(int tenant, DateTime? from = null, DateTime? to = null) 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/105] 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 59e5aaa4a5e..a86dfba3731 100644 --- a/common/ASC.Core.Common/Configuration/Consumer.cs +++ b/common/ASC.Core.Common/Configuration/Consumer.cs @@ -50,13 +50,13 @@ public class Consumer : IDictionary<string, string> 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 @@ public DataStoreConsumer( 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 667258ec70d..9d9a111d1a4 100644 --- a/common/services/ASC.ElasticSearch/Core/SearchSettings.cs +++ b/common/services/ASC.ElasticSearch/Core/SearchSettings.cs @@ -120,12 +120,12 @@ public List<SearchSettingsItem> GetAllItems() }).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 39f569d493d..aaba482e558 100644 --- a/web/ASC.Web.Core/Files/FileUtility.cs +++ b/web/ASC.Web.Core/Files/FileUtility.cs @@ -49,20 +49,20 @@ public FileUtilityConfiguration(IConfiguration configuration) } 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 @@ public List<string> ExtsWebEdited { 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 @@ public List<string> ExtsWebCustomFilterEditing { 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 @@ public List<string> ExtsWebRestrictedEditing { 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 @@ public List<string> ExtsWebCommented { 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 @@ public List<string> ExtsWebTemplate { 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 @@ public List<string> ExtsMustConvert { 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/105] 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 aedd7234668..dda9889f255 100644 --- a/common/ASC.IPSecurity/IPSecurity.cs +++ b/common/ASC.IPSecurity/IPSecurity.cs @@ -122,7 +122,7 @@ public bool Verify() 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 3e3a835c279..8b0c33fdbc5 100644 --- a/common/services/ASC.ElasticSearch/Core/Selector.cs +++ b/common/services/ASC.ElasticSearch/Core/Selector.cs @@ -341,7 +341,7 @@ private QueryContainer Wrap(Field fieldSelector, Func<Field, QueryContainerDescr 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/105] 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 1cc81b31db9..ec60b04bd0c 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/105] 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 741ed1b3d06..cccc309a715 100644 --- a/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs +++ b/products/ASC.Files/Core/Helpers/ThirdpartyConfiguration.cs @@ -47,7 +47,7 @@ public List<string> ThirdPartyProviders { 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 a5672a9ee89..a69b74d3188 100644 --- a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs +++ b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs @@ -24,7 +24,7 @@ public List<string> MustConvertable 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/105] 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 f123c249b25..e8b7e6c87b6 100644 --- a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs +++ b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs @@ -99,7 +99,6 @@ public EditorType EditorType public string DocumentType { - set { } get { DocType.TryGetValue(GetFileType, out var documentType); @@ -119,7 +118,6 @@ public string Type internal FileType GetFileType { - set { } get { if (_fileTypeCache == FileType.Unknown) @@ -160,7 +158,6 @@ public DocumentConfig(DocumentServiceConnector documentServiceConnector, PathPro public string FileType { - set { } get { return Info.GetFile().ConvertedExtension.Trim('.'); } } @@ -218,7 +215,6 @@ public InfoConfig(BreadCrumbsManager breadCrumbsManager, FileSharing fileSharing public bool? Favorite { - set { } get { if (!SecurityContext.IsAuthenticated || UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor(UserManager)) return null; @@ -229,7 +225,6 @@ public bool? Favorite public string Folder { - set { } get { if (Type == EditorType.Embedded || Type == EditorType.External) return null; @@ -247,19 +242,16 @@ public string Folder 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 @@ public List<TemplatesConfig> GetTemplates(EntryManager entryManager) public string CreateUrl { - set { } get { if (_configuration.Document.Info.Type != EditorType.Desktop) return null; @@ -448,13 +439,11 @@ public EmbeddedConfig Embedded public string Lang { - set { } get { return _userInfo.GetCulture().Name; } } public string Mode { - set { } get { return ModeWrite ? "edit" : "view"; } } @@ -559,19 +548,16 @@ public class EmbeddedConfig 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 @@ public class PluginsConfig { public string[] PluginsData { - set { } get { var plugins = new List<string>(); @@ -693,7 +678,6 @@ internal void SetConfiguration(Configuration<T> configuration) public bool About { - set { } get { return !CoreBaseSettings.Standalone && !CoreBaseSettings.CustomMode; } } @@ -701,7 +685,6 @@ public bool About public FeedbackConfig Feedback { - set { } get { if (CoreBaseSettings.Standalone) return null; @@ -719,7 +702,6 @@ public FeedbackConfig Feedback public bool? Forcesave { - set { } get { return FileUtility.CanForcesave @@ -731,7 +713,6 @@ public bool? Forcesave public GobackConfig Goback { - set { } get { if (_configuration.EditorType == EditorType.Embedded || _configuration.EditorType == EditorType.External) return null; @@ -780,7 +761,6 @@ public GobackConfig Goback public bool MentionShare { - set { } get { return AuthContext.IsAuthenticated @@ -791,7 +771,6 @@ public bool MentionShare public string ReviewDisplay { - set { } get { return _configuration.EditorConfig.ModeWrite ? null : "markup"; } } @@ -828,13 +807,11 @@ internal void SetConfiguration(Configuration<T> configuration) 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 @@ internal void SetConfiguration(Configuration<T> configuration) public string Image { - set { } get { return @@ -892,7 +868,6 @@ public string Image public string ImageEmbedded { - set { } get { return @@ -904,7 +879,6 @@ public string ImageEmbedded 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 7ba2b75fa25..c5e26c8de92 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -138,7 +138,6 @@ public class TrackResponse { 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 eac97faedc4..0eb5785345f 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 @@ public class MentionWrapper 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 @@ public string Id 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 b7e1edc0a11..fd27730e5ca 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -219,13 +219,11 @@ public SmscProvider( 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 @@ public class ClickatellProvider : SmsProvider 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 @@ public class TwilioProvider : SmsProvider, IValidateKeysProvider 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/105] 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 064556c90db..1ddd5c5a8f3 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -160,7 +160,7 @@ public List<DateTime> GetDates(DateTime startDate, bool monthly) return dates; } - public static WeekDay Parse(string iCalStrValue) + public static WeekDay ParseWeekDay(string iCalStrValue) { var d = new WeekDay(); @@ -215,7 +215,7 @@ public RecurrenceRule() 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 @@ public static RecurrenceRule Parse(string serializedString) 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 @@ public static RecurrenceRule Parse(string serializedString) break; case "wkst": - rr.WKST = RecurrenceRule.WeekDay.Parse(val); + rr.WKST = RecurrenceRule.WeekDay.ParseWeekDay(val); break; case "exdates": @@ -1020,11 +1020,11 @@ public object Clone() { 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/105] 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 35965fd2650..f70a34b5485 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -2099,7 +2099,7 @@ private void UpdatePhotoUrl(string files, UserInfo user) 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/105] 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 d52237aaaf1..4447af379a0 100644 --- a/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/GoogleLoginProvider.cs @@ -58,9 +58,9 @@ public class GoogleLoginProvider : BaseLoginProvider<GoogleLoginProvider> 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 9627dc9c8f9..942f4b30154 100644 --- a/products/ASC.Files/Core/Core/Compress/CompressToArchive.cs +++ b/products/ASC.Files/Core/Core/Compress/CompressToArchive.cs @@ -33,8 +33,8 @@ public class CompressToArchive : ICompress { 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 4ac06117212..fd901dca45e 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 @@ public bool CheckAccess() } - 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 13f24d05a99..75e9d3c9917 100644 --- a/products/ASC.Files/Core/Helpers/DocuSignHelper.cs +++ b/products/ASC.Files/Core/Helpers/DocuSignHelper.cs @@ -149,9 +149,9 @@ public class DocuSignHelper ".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 e8b7e6c87b6..2aa61b54508 100644 --- a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs +++ b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs @@ -67,7 +67,7 @@ public enum EditorType 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/105] 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 62ee115cfa1..3decb776786 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 @@ internal void CompressToZip(Stream stream, IServiceScope scope) 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/105] 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 838cc814dd3..23f176a39b9 100644 --- a/common/ASC.Core.Common/Notify/Jabber/JabberServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Jabber/JabberServiceClient.cs @@ -94,7 +94,7 @@ public string GetVersion() 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 ffb0f0aa408..b7ac18be60d 100644 --- a/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs +++ b/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs @@ -52,7 +52,7 @@ public override SendResponse ProcessMessage(INoticeMessage message) { 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 a62f12e517b..915c3659c4e 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -764,7 +764,7 @@ public override string UploadChunk(string domain, 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 3f024cd2605..8c3b0eb24b6 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -709,7 +709,7 @@ public override string InitiateChunkedUpload(string domain, string path) 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 39d4cdc39b7..f65539a3722 100644 --- a/common/ASC.Data.Storage/StaticUploader.cs +++ b/common/ASC.Data.Storage/StaticUploader.cs @@ -255,7 +255,7 @@ public UploadOperationProgress(IServiceProvider serviceProvider, string key, int 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 8a2bbd69eb9..c722e4d8c9c 100644 --- a/products/ASC.Files/Core/Helpers/EasyBibHelper.cs +++ b/products/ASC.Files/Core/Helpers/EasyBibHelper.cs @@ -141,7 +141,7 @@ public object GetEasyBibCitation(string data) 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 6a687a9f520..867ec54e2fb 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -1062,7 +1062,7 @@ private Task CreateFile(HttpContext context) //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 688c87a4aaa..acddd669a5c 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -347,7 +347,7 @@ public IEnumerable<FileEntry> GetEntries<T>(Folder<T> parent, int from, int coun //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 @@ public IEnumerable<FileEntry> GetEntries<T>(Folder<T> parent, int from, int coun 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 f23c194e370..9c7dbc11b75 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -110,7 +110,7 @@ private void CreateDraftMail(MailMergeTask mailMergeTask) 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 @@ private string SendMail(MailMergeTask mailMergeTask, string bodySendAttach) 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 f9d837c52f0..2d5b62d7757 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1942,7 +1942,7 @@ public bool ActivateTrial() 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 06b09bb6828..a9c2b84ba85 100644 --- a/web/ASC.Web.Core/Notify/TagValues.cs +++ b/web/ASC.Web.Core/Notify/TagValues.cs @@ -53,8 +53,8 @@ public static ITagValue BlueButton(Func<string> btnTextFunc, string btnUrl) 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 @@ public static ITagValue GreenButton(Func<string> btnTextFunc, string btnUrl) 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/105] 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 6be6a6de18c..4dda7d23546 100644 --- a/common/ASC.Core.Common/Caching/CachedUserService.cs +++ b/common/ASC.Core.Common/Caching/CachedUserService.cs @@ -318,7 +318,7 @@ public Group GetGroup(int tenant, Guid id) 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 c97f98f1977..60fdd42fbf2 100644 --- a/common/ASC.Core.Common/Data/DbSubscriptionService.cs +++ b/common/ASC.Core.Common/Data/DbSubscriptionService.cs @@ -136,7 +136,7 @@ public bool IsUnsubscribe(int tenant, string sourceId, string actionId, string r } 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 17ac36d4c7c..0e36f0d3ffb 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -806,7 +806,7 @@ protected virtual int SkipWhiteSpace(int i, string s) { for (; i < s.Length && (s[i] == ' ' || s[i] == '\t'); i++) { - ; + } return i; } @@ -815,7 +815,7 @@ protected virtual int FindNextWhiteSpace(int i, string s) { 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 908124d0026..cfb0a16193f 100644 --- a/common/ASC.Data.Storage/StorageFactory.cs +++ b/common/ASC.Data.Storage/StorageFactory.cs @@ -251,7 +251,7 @@ private IDataStore GetDataStore(string tenant, string module, DataStoreConsumer 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 929d49bc8d0..0055177d9c8 100644 --- a/common/services/ASC.Webhooks.Service/WebhookSender.cs +++ b/common/services/ASC.Webhooks.Service/WebhookSender.cs @@ -111,7 +111,7 @@ private void UpdateDb(DbWorker dbWorker, int id, HttpResponseMessage response, H { 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 b2ea929c69a..f0e073e22ca 100644 --- a/web/ASC.Web.Api/Controllers/AuthenticationController.cs +++ b/web/ASC.Web.Api/Controllers/AuthenticationController.cs @@ -348,7 +348,7 @@ private AuthenticationTokenData AuthenticateMeWithCode(AuthModel auth) 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 1ddd5c5a8f3..e99749ff905 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -513,7 +513,7 @@ public List<DateTime> GetDates(DateTime utcStartDate, TimeZoneInfo eventTimeZone 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 8680bd8e50a..6619757da59 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -808,7 +808,7 @@ public void RemoveTempPhoto(string fileName) 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/105] 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 62f61ba1baa..09215626e26 100644 --- a/common/ASC.Api.Core/Core/ApiContext.cs +++ b/common/ASC.Api.Core/Core/ApiContext.cs @@ -41,8 +41,8 @@ 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); } } + 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 9a17b26acb4..714b9bb9cd8 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -283,7 +283,7 @@ public class WhiteLabelHelper { 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 86509365cba..32dacc35bf4 100644 --- a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs @@ -17,7 +17,6 @@ public enum Provider 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 a77ab7943f2..275913a1175 100644 --- a/common/ASC.Core.Common/EF/Context/ConfigureDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/ConfigureDbContext.cs @@ -39,7 +39,7 @@ public void Configure(T context) 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 @@ public void Configure(string name, MultiRegionalDbContext<T> context) 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 @@ public void Configure(string name, MultiRegionalDbContext<T> context) 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 0e36f0d3ffb..0a28a3cdc88 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -547,8 +547,8 @@ protected virtual int StoreExpressionVals(int pos, string s, int type) 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 @@ protected virtual int CheckNext(int pos, string s, int val, int type) 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 @@ protected virtual int CheckNext(int pos, string s, int val, int type) 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 @@ protected virtual int CheckNext(int pos, string s, int val, int type) 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 @@ protected virtual ValueSet GetValue(int v, string s, int i) 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 @@ protected virtual int GetLastDayOfMonth(int monthNum, int year) 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 558fd6a2826..433a28cbe48 100644 --- a/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs +++ b/common/ASC.Core.Common/Notify/Signalr/SignalrServiceClient.cs @@ -113,7 +113,7 @@ public class SignalrServiceClient 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 ad573ae653f..278bf02b2a9 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 77999e0c0c6..c18650fadc7 100644 --- a/common/ASC.Core.Common/Users/UserFormatter.cs +++ b/common/ASC.Core.Common/Users/UserFormatter.cs @@ -135,7 +135,7 @@ public static DisplayUserNameFormat GetUserDisplayDefaultOrder() 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 1bf2817cb77..36d25e62c4a 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 4a17d0e1ee6..ea6fad274a0 100644 --- a/common/ASC.Data.Reassigns/QueueWorker.cs +++ b/common/ASC.Data.Reassigns/QueueWorker.cs @@ -52,7 +52,7 @@ public class QueueWorker<T> where T : DistributedTaskProgress 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 @@ public void Terminate(int tenantId, Guid userId) 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 01ee58cb18c..b7f6eadcbc0 100644 --- a/products/ASC.Files/Core/Core/Entries/EditHistory.cs +++ b/products/ASC.Files/Core/Core/Entries/EditHistory.cs @@ -79,9 +79,9 @@ public List<EditHistoryChanges> Changes 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 @@ public List<EditHistoryChanges> Changes set { throw new NotImplementedException(); } } - public DateTime ModifiedOn; + public DateTime ModifiedOn { get; set; } [JsonPropertyName("created")] public string ModifiedOnString @@ -126,8 +126,6 @@ public string ModifiedOnString 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 1370b91d3e3..8cd55011614 100644 --- a/products/ASC.Files/Core/Core/Entries/FileEntry.cs +++ b/products/ASC.Files/Core/Core/Entries/FileEntry.cs @@ -110,7 +110,7 @@ public bool ProviderEntry 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 c9363e89423..352d94bffba 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 @@ public class SharePointProviderInfo : IProviderInfo 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 f2a0fb6577f..d3d6786b1d8 100644 --- a/products/ASC.Files/Core/Helpers/Global.cs +++ b/products/ASC.Files/Core/Helpers/Global.cs @@ -135,7 +135,7 @@ public Global( #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 2aa61b54508..3dd17d89640 100644 --- a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs +++ b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs @@ -141,7 +141,7 @@ public static string Serialize(Configuration<T> configuration) [Transient] public class DocumentConfig<T> { - public string SharedLinkKey; + private string _sharedLinkKey; public DocumentConfig(DocumentServiceConnector documentServiceConnector, PathProvider pathProvider, InfoConfig<T> infoConfig) { @@ -185,7 +185,7 @@ public string Url 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 @@ public class InfoConfig<T> 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 @@ public EditorConfiguration( } } - public bool ModeWrite = false; + public bool ModeWrite { get; set; } = false; private Configuration<T> _configuration; @@ -672,8 +672,8 @@ internal void SetConfiguration(Configuration<T> configuration) 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 @@ public GobackConfig Goback { 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 c5e26c8de92..1e9841d6ee3 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -98,8 +98,8 @@ public class TrackerData [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 0eb5785345f..3b3efb88c33 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 @@ public string Name 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 9c7dbc11b75..3895e565327 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -44,14 +44,14 @@ public class MailMergeTask : IDisposable { 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 422e979f5d9..1b5e8d33577 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -616,7 +616,7 @@ public class FileLink [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 42c38ee8751..f9aef8e83f2 100644 --- a/web/ASC.Web.Core/Subscriptions/SubscriptionType.cs +++ b/web/ASC.Web.Core/Subscriptions/SubscriptionType.cs @@ -47,9 +47,9 @@ public class SubscriptionType 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 6619757da59..3bcaa956040 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -233,10 +233,10 @@ public UserPhotoManager( 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 @@ public string GetSizedPhotoUrl(Guid userId, int width, int height) } - 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/105] 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 2e3fe2c5f2b..c84035be2ac 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 @@ public AscRandom(int seed) } } } - inext = 0; - inextp = 21; + _inext = 0; + _inextp = 21; } public override int Next(int maxValue) @@ -96,8 +96,8 @@ public override void NextBytes(byte[] buffer) 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 @@ private int InternalSample() 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 c18650fadc7..0936dfb3cbe 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 @@ public string GetUserName(UserInfo userInfo) 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 3decb776786..c9a6edf1e6c 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 @@ public override void PublishChanges(DistributedTask task) 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 @@ public override FileOperationType OperationType public FileDownloadOperation(IServiceProvider serviceProvider, FileDownloadOperationData<T> fileDownloadOperationData) : base(serviceProvider, fileDownloadOperationData) { - files = fileDownloadOperationData.FilesDownload; + _files = fileDownloadOperationData.FilesDownload; headers = fileDownloadOperationData.Headers; } @@ -179,9 +179,9 @@ protected override void Do(IServiceScope scope) { 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 @@ protected override void Do(IServiceScope scope) throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound); } - ReplaceLongPath(entriesPathId); + ReplaceLongPath(_entriesPathId); - Total = entriesPathId.Count; + Total = _entriesPathId.Count; TaskInfo.PublishChanges(); } @@ -205,7 +205,7 @@ private ItemNameValueCollection<T> ExecPathFromFile(IServiceScope scope, File<T> 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 @@ private ItemNameValueCollection<T> GetFilesInFolders(IServiceScope scope, IEnume 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 @@ internal void CompressToZip(Stream stream, IServiceScope scope) { 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 @@ internal void CompressToZip(Stream stream, IServiceScope scope) 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/105] 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 4b3bf08b289..29f1cba800b 100644 --- a/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs +++ b/common/ASC.Api.Core/Auth/ConfirmAuthHandler.cs @@ -112,7 +112,7 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync() } } - 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 56f8e4eab5a..15bbd01e038 100644 --- a/common/ASC.Common/Logging/Log.cs +++ b/common/ASC.Common/Logging/Log.cs @@ -875,7 +875,7 @@ public override T Get(string name) } } - 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 @@ public static void RegisterLog(DIHelper services) } } - 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 e3270509298..f325f1951ae 100644 --- a/common/ASC.Common/Security/Authorizing/Constants.cs +++ b/common/ASC.Common/Security/Authorizing/Constants.cs @@ -28,7 +28,7 @@ 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 f404b663706..c25cdc2eac9 100644 --- a/common/ASC.Common/Security/Cryptography/Hasher.cs +++ b/common/ASC.Common/Security/Cryptography/Hasher.cs @@ -30,7 +30,7 @@ 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 25481d3cb81..f68576bb394 100644 --- a/common/ASC.Common/Utils/JsonWebToken.cs +++ b/common/ASC.Common/Utils/JsonWebToken.cs @@ -37,7 +37,7 @@ 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 fecb88be69d..b6e532c002b 100644 --- a/common/ASC.Common/Utils/VelocityFormatter.cs +++ b/common/ASC.Common/Utils/VelocityFormatter.cs @@ -58,7 +58,7 @@ public override bool IsSourceModified(NVelocity.Runtime.Resource.Resource resour } } - 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 dc08c41c324..da4916e11fd 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 98bfcedb064..852ebdd2464 100644 --- a/common/ASC.Core.Common/Configuration/Constants.cs +++ b/common/ASC.Core.Common/Configuration/Constants.cs @@ -32,7 +32,7 @@ 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 c9d5f1f75a7..68abd257e2d 100644 --- a/common/ASC.Core.Common/Context/WorkContext.cs +++ b/common/ASC.Core.Common/Context/WorkContext.cs @@ -171,7 +171,7 @@ private static void NotifyEngine_AfterTransferRequest(NotifyEngine sender, Notif } } - 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 2ba94163cd0..bf756542cb0 100644 --- a/common/ASC.Core.Common/Notify/Senders/AWSSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/AWSSender.cs @@ -249,7 +249,7 @@ public void Deconstruct(out TenantManager tenantManager, out CoreConfiguration c } } - 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 1adf0f70af6..6cc3a236c06 100644 --- a/common/ASC.Core.Common/Notify/Senders/JabberSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/JabberSender.cs @@ -78,7 +78,7 @@ public NoticeSendResult Send(NotifyMessage m) } } - 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 7091946bad4..aab41d246fa 100644 --- a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs @@ -334,7 +334,7 @@ public void Deconstruct(out TenantManager tenantManager, out CoreConfiguration c } } - 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 2f71b74967b..8cd772396bb 100644 --- a/common/ASC.Core.Common/Security/Crypto.cs +++ b/common/ASC.Core.Common/Security/Crypto.cs @@ -33,7 +33,7 @@ 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 a1314dd7543..1775abd2925 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 dabab637f13..bb54190e515 100644 --- a/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs @@ -238,7 +238,7 @@ out AuthManager authManager } } - 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 634a54d7d38..07c919bbbda 100644 --- a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs +++ b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs @@ -881,7 +881,7 @@ public void Deconstruct(out TenantManager tenantManager, } } - public class BackupWorkerExtension + public static class BackupWorkerExtension { public static void Register(DIHelper services) { @@ -890,7 +890,7 @@ public static void Register(DIHelper services) } } - 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 ea6fad274a0..638510b2eb5 100644 --- a/common/ASC.Data.Reassigns/QueueWorker.cs +++ b/common/ASC.Data.Reassigns/QueueWorker.cs @@ -37,7 +37,7 @@ 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 6a40b23afc4..54db156b61b 100644 --- a/common/ASC.Data.Reassigns/ReassignProgressItem.cs +++ b/common/ASC.Data.Reassigns/ReassignProgressItem.cs @@ -273,7 +273,7 @@ public void Deconstruct(out TenantManager tenantManager, } } - 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 c533a93760a..b3978d6a1f2 100644 --- a/common/ASC.Data.Storage/Configuration/StorageSettings.cs +++ b/common/ASC.Data.Storage/Configuration/StorageSettings.cs @@ -249,7 +249,7 @@ public void Deconstruct(out StorageSettingsHelper storageSettingsHelper, out Set } } - 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 6ec20d9cbd1..a0acdb09979 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 57649e96151..c933dc371fb 100644 --- a/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs +++ b/common/ASC.Data.Storage/Encryption/EncryptionOperation.cs @@ -378,7 +378,7 @@ public void Deconstruct(out ILog log, out EncryptionSettingsHelper encryptionSet } } - 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 3c7c079591e..618cd178f3c 100644 --- a/common/ASC.Data.Storage/Encryption/EncryptionWorker.cs +++ b/common/ASC.Data.Storage/Encryption/EncryptionWorker.cs @@ -95,7 +95,7 @@ public EncryptionOperation CreateOperation(EncryptionSettingsProto encryptionSet } } - 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 cfb0a16193f..40a45f11512 100644 --- a/common/ASC.Data.Storage/StorageFactory.cs +++ b/common/ASC.Data.Storage/StorageFactory.cs @@ -259,7 +259,7 @@ private IDataStore GetDataStore(string tenant, string module, DataStoreConsumer } } - 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 1f49776515f..36e2fe49a16 100644 --- a/common/ASC.Data.Storage/TenantPath.cs +++ b/common/ASC.Data.Storage/TenantPath.cs @@ -29,7 +29,7 @@ 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 7fec130992a..a945ed3166f 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 1c9f6024a9b..6d7d828e38d 100644 --- a/common/ASC.FederatedLogin/Helpers/HashHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/HashHelper.cs @@ -28,7 +28,7 @@ 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 17bdc13f3fd..5e610c6d23c 100644 --- a/common/ASC.FederatedLogin/Helpers/JsCallbackHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/JsCallbackHelper.cs @@ -29,7 +29,7 @@ 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 87585021621..1ee9a7d6eab 100644 --- a/common/ASC.FederatedLogin/Helpers/RequestHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/RequestHelper.cs @@ -32,7 +32,7 @@ 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 43932ad3f64..8011ad223ae 100644 --- a/common/ASC.FederatedLogin/Helpers/XrdsHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/XrdsHelper.cs @@ -30,7 +30,7 @@ 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 95f3c2e24c1..d00ae65afac 100644 --- a/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/BaseLoginProvider.cs @@ -163,7 +163,7 @@ protected virtual OAuth20Token Auth(HttpContext context, string scopes, out bool 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 acce11684ec..595cdaf3584 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 11d9b1c5298..eecbac306e0 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 ec60b04bd0c..1436632d11e 100644 --- a/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs +++ b/common/ASC.MessagingSystem/DbSender/MessagesRepository.cs @@ -276,7 +276,7 @@ public class Messages : MessagesContext 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 56a2237a97f..361992aeea8 100644 --- a/common/ASC.Textile/Blocks/BlockAttributesParser.cs +++ b/common/ASC.Textile/Blocks/BlockAttributesParser.cs @@ -17,7 +17,7 @@ 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 89dc5eca1c2..6a0c0fa422a 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 6f0a9170fef..a311eef4394 100644 --- a/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/CrmActionMapper.cs @@ -32,7 +32,7 @@ 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 0189838e043..9e46f41daa3 100644 --- a/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/DocumentsActionMapper.cs @@ -31,7 +31,7 @@ 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 0ad37f1fd24..bffafbc2a4a 100644 --- a/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/LoginActionMapper.cs @@ -32,7 +32,7 @@ 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 572e0644a18..f0bf259b4bf 100644 --- a/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/OthersActionMapper.cs @@ -32,7 +32,7 @@ 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 a67feacb0d5..5aa563afeb9 100644 --- a/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/PeopleActionMapper.cs @@ -32,7 +32,7 @@ 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 ac3de67f0f6..00135f8c7da 100644 --- a/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/ProjectsActionMapper.cs @@ -31,7 +31,7 @@ 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 74904ef51ff..8298a4b2f31 100644 --- a/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/SettingsActionMapper.cs @@ -31,7 +31,7 @@ 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 3933ee33423..c3d92d87322 100644 --- a/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs +++ b/common/services/ASC.ClearEvents/ClearEventsServiceLauncher.cs @@ -131,7 +131,7 @@ public class Messages : MessagesContext 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 2214cf7600c..0514c12027e 100644 --- a/common/services/ASC.ClearEvents/Program.cs +++ b/common/services/ASC.ClearEvents/Program.cs @@ -44,7 +44,7 @@ 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 a6e548bb9eb..6c85492eed5 100644 --- a/common/services/ASC.Data.Backup/BackupCleanerService.cs +++ b/common/services/ASC.Data.Backup/BackupCleanerService.cs @@ -182,7 +182,7 @@ private void DeleteExpiredBackups() } } - 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 b26a3033f51..c5d88c85a49 100644 --- a/common/services/ASC.Data.Backup/BackupSchedulerService.cs +++ b/common/services/ASC.Data.Backup/BackupSchedulerService.cs @@ -177,7 +177,7 @@ private void ScheduleBackupTasks() } } - 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 ef4dcd44ebe..bb8fc3cc9b8 100644 --- a/common/services/ASC.Data.Backup/Program.cs +++ b/common/services/ASC.Data.Backup/Program.cs @@ -15,7 +15,7 @@ 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 b8e35eac30a..6576a8f32c2 100644 --- a/common/services/ASC.ElasticSearch/Service/Launcher.cs +++ b/common/services/ASC.ElasticSearch/Service/Launcher.cs @@ -211,7 +211,7 @@ public void Deconstruct(out FactoryIndexer factoryIndexer, out Service.Service s } } - 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 214e73c7372..ba619f2c9e8 100644 --- a/common/services/ASC.ElasticSearch/Service/Service.cs +++ b/common/services/ASC.ElasticSearch/Service/Service.cs @@ -120,7 +120,7 @@ public void Deconstruct(out TenantManager tenantManager, out SettingsManager set } } - 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 738fedcc572..c38b72f6a31 100644 --- a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs +++ b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs @@ -337,7 +337,7 @@ public void Deconstruct(out BaseCommonLinkUtility baseCommonLinkUtility, } } - 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 17f92e59aae..b726ca53259 100644 --- a/common/services/ASC.Notify/DbWorker.cs +++ b/common/services/ASC.Notify/DbWorker.cs @@ -224,7 +224,7 @@ public void SetState(int id, MailSendingState result) } } - 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 7507390e165..970d37f2962 100644 --- a/common/services/ASC.Notify/NotifyService.cs +++ b/common/services/ASC.Notify/NotifyService.cs @@ -142,7 +142,7 @@ public void Deconstruct(out TenantManager tenantManager, out TenantWhiteLabelSet } } - 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 9f6a50c95b6..ae8e6ad1d7e 100644 --- a/common/services/ASC.Notify/Program.cs +++ b/common/services/ASC.Notify/Program.cs @@ -20,7 +20,7 @@ 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 2d7ab1da66a..82bf7514328 100644 --- a/common/services/ASC.Studio.Notify/Program.cs +++ b/common/services/ASC.Studio.Notify/Program.cs @@ -21,7 +21,7 @@ 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 cc2b79f536d..2345f62ceae 100644 --- a/common/services/ASC.TelegramService/Program.cs +++ b/common/services/ASC.TelegramService/Program.cs @@ -39,7 +39,7 @@ 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 cae084da9d2..9035834a2d1 100644 --- a/common/services/ASC.TelegramService/TelegramHandler.cs +++ b/common/services/ASC.TelegramService/TelegramHandler.cs @@ -185,7 +185,7 @@ private string UserKey(string userId, int tenantId) } } - 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 0f022e809a3..c46a10ac12f 100644 --- a/common/services/ASC.TelegramService/TelegramLauncher.cs +++ b/common/services/ASC.TelegramService/TelegramLauncher.cs @@ -100,7 +100,7 @@ public void Deconstruct(out TenantManager tenantManager, out TelegramHandler han } } - 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 f3a8c32cce5..c60a537ac1c 100644 --- a/common/services/ASC.UrlShortener.Svc/Program.cs +++ b/common/services/ASC.UrlShortener.Svc/Program.cs @@ -44,7 +44,7 @@ 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 1fdd02c81a4..13679ca1aa1 100644 --- a/common/services/ASC.Webhooks.Service/Program.cs +++ b/common/services/ASC.Webhooks.Service/Program.cs @@ -19,7 +19,7 @@ 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 d239835e94d..2ea5562740e 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 @@ public ISecurityDao<T> GetSecurityDao<T>() } } - 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 bf8820cadee..d215112583c 100644 --- a/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs +++ b/products/ASC.Files/Core/Core/Search/FactoryIndexerFile.cs @@ -196,7 +196,7 @@ public class FileTenant 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 0c2d8d54d39..8aee027f259 100644 --- a/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs +++ b/products/ASC.Files/Core/Core/Search/FactoryIndexerFolder.cs @@ -174,7 +174,7 @@ class FolderTenant 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 897ef9e01ee..99ec198360d 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 @@ public ISecurityDao<string> GetSecurityDao(string id) 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 b04414464ca..8ffc3b05fd5 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/CrossDao.cs @@ -196,7 +196,7 @@ public Folder<TTo> PerformCrossDaoFolderCopy<TFrom, TTo> } } - 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 937bb13f2c6..529a392475a 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 @@ public ISecurityDao<string> GetSecurityDao(string id) } } - 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 6eebee80676..f3f9ab73b58 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 @@ public ISecurityDao<string> GetSecurityDao(string id) } } - 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 fce1658a43f..fefce56444a 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 @@ internal void CacheResetChilds(int id, string parentDriveId, bool? childFolder = } } - 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 f5d1510da5d..57d36beb93f 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 @@ public ISecurityDao<string> GetSecurityDao(string id) } } - 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 475e4724275..bc3c5e4562a 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 @@ internal void CacheReset(int id, string onedriveId = null) } } } - 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 43b626445ab..a3900ab6c23 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs @@ -593,7 +593,7 @@ private string DecryptToken(string token) } } - 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 618b3bfb603..4159c99fb13 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 @@ public override string ConvertId(string id) } } - 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 7caba01af85..b9ab818ed13 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 @@ public ISecurityDao<string> GetSecurityDao(string id) } } - 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 e2c13b3938e..3cb2a3b6a1c 100644 --- a/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs +++ b/products/ASC.Files/Core/Services/NotifyService/NotifyClient.cs @@ -258,7 +258,7 @@ public void Deconstruct(out NotifySource notifySource, } } - 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 a537332643f..3242aac74d6 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 @@ public static (Dictionary<int, string>, Dictionary<string, string>) GetIds(Dicti } } - 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 fec6bb4e06b..2d9df9b6a86 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/IThirdPartyApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/IThirdPartyApp.cs @@ -46,7 +46,7 @@ public interface IThirdPartyApp 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 9823b5f0561..d382ca98891 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -927,7 +927,7 @@ internal class ConvertFileOperationResult : FileOperationResult public string ServerRootPath { get; set; } } - public class FileConverterQueueExtension + public static class FileConverterQueueExtension { public static void Register(DIHelper services) { @@ -935,7 +935,7 @@ public static void Register(DIHelper services) } } - 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 c73370ba482..78fd5938f9f 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -798,7 +798,7 @@ public AsyncTaskData(TenantManager tenantManager, AuthContext authContext) : bas 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 302baa18db0..e0f1d0df481 100644 --- a/products/ASC.Files/Server/Program.cs +++ b/products/ASC.Files/Server/Program.cs @@ -15,7 +15,7 @@ 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 e4c4d7e2618..ab5a266afb2 100644 --- a/products/ASC.Files/Service/Program.cs +++ b/products/ASC.Files/Service/Program.cs @@ -22,7 +22,7 @@ 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 663b7888534..433d68e4c0f 100644 --- a/products/ASC.Files/Service/Thumbnail/Worker.cs +++ b/products/ASC.Files/Service/Thumbnail/Worker.cs @@ -106,7 +106,7 @@ private void Procedure(object _) } } - 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 12409ef8afe..234c25f7dfb 100644 --- a/products/ASC.People/Server/Program.cs +++ b/products/ASC.People/Server/Program.cs @@ -15,7 +15,7 @@ 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 f79fc93f873..c081b2a6a64 100644 --- a/web/ASC.Web.Api/Program.cs +++ b/web/ASC.Web.Api/Program.cs @@ -15,7 +15,7 @@ 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 073bfa5d9fe..05df7623f85 100644 --- a/web/ASC.Web.Core/CommonPhotoManager.cs +++ b/web/ASC.Web.Core/CommonPhotoManager.cs @@ -36,7 +36,7 @@ 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 3ed1a568aa6..c19fd9e50a4 100644 --- a/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs +++ b/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs @@ -28,7 +28,7 @@ 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 87264845522..2a381adb074 100644 --- a/web/ASC.Web.Core/Notify/NotifyConfiguration.cs +++ b/web/ASC.Web.Core/Notify/NotifyConfiguration.cs @@ -455,7 +455,7 @@ public void Deconstruct(out TenantManager tenantManager, } } - 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 5d82611ae7e..023b30a1595 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -1167,7 +1167,7 @@ public void Deconstruct(out TenantManager tenantManager, } } - 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 058685ac9d6..9bc5de9f291 100644 --- a/web/ASC.Web.Core/Notify/Tags.cs +++ b/web/ASC.Web.Core/Notify/Tags.cs @@ -82,7 +82,7 @@ public static class Tags 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 50e9146beeb..5aeeb830705 100644 --- a/web/ASC.Web.Core/SecutiryConstants.cs +++ b/web/ASC.Web.Core/SecutiryConstants.cs @@ -28,7 +28,7 @@ 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 3bcaa956040..8bf97a22945 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -1025,7 +1025,7 @@ public static void Deconstruct(this Size size, out int w, out int h) } } - 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 d58dbc6f7d4..bd21457672b 100644 --- a/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoThumbnailManager.cs @@ -35,7 +35,7 @@ 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 5261aa70ecd..e0f94d0fe83 100644 --- a/web/ASC.Web.HealthChecks.UI/Program.cs +++ b/web/ASC.Web.HealthChecks.UI/Program.cs @@ -7,7 +7,7 @@ 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 fb8a125ffb8..d821a0dc7ff 100644 --- a/web/ASC.Web.Studio/Program.cs +++ b/web/ASC.Web.Studio/Program.cs @@ -15,7 +15,7 @@ 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/105] 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 a3f7e74fa99..3d0ff495d54 100644 --- a/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs +++ b/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs @@ -73,7 +73,7 @@ public List<BackupRecord> GetExpiredBackupRecords() 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 716707a2990..34266668336 100644 --- a/common/ASC.Textile/Blocks/GlyphBlockModifier.cs +++ b/common/ASC.Textile/Blocks/GlyphBlockModifier.cs @@ -75,7 +75,7 @@ public override string ModifyLine(string line) } // 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 e60dd91b58f..93dbb961895 100644 --- a/common/ASC.Textile/States/TableFormatterState.cs +++ b/common/ASC.Textile/States/TableFormatterState.cs @@ -58,7 +58,7 @@ public override bool ShouldExit(string input) @"(\.\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 3e760291e4b..e91fcb4a02b 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 @@ public File<int> GetFile(int parentId, string title) { 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 2d5b62d7757..5f427f99339 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -2315,7 +2315,7 @@ private void StartEncryption(bool notifyUsers) 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/105] 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 3fc3814246d..f51f9aca6bb 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -161,13 +161,21 @@ public IDictionary<string, Tuple<Uri, Uri>> GetPaymentUrls(string portalId, stri 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 9aecec13d9a..50e9817d2f0 100644 --- a/common/ASC.Core.Common/Caching/CachedAzService.cs +++ b/common/ASC.Core.Common/Caching/CachedAzService.cs @@ -100,8 +100,9 @@ public IEnumerable<AzRecord> GetAces(int tenant, DateTime from) 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 fbe6d7bc154..e8b4b6a7465 100644 --- a/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs +++ b/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs @@ -201,7 +201,8 @@ private SubsciptionsStore GetSubsciptionsStore(int tenant, string sourceId, stri { 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 8981515906f..b9dbc6553ff 100644 --- a/common/ASC.Core.Common/Caching/CachedTenantService.cs +++ b/common/ASC.Core.Common/Caching/CachedTenantService.cs @@ -73,8 +73,9 @@ internal TenantStore GetTenantStore() { 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 dc54200caef..153c890ffe1 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -214,8 +214,9 @@ public string GetKey(int tenant) // 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 714b9bb9cd8..0ef86e4d586 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -257,7 +257,8 @@ private Dictionary<string, string> GetResources() 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 @@ public class WhiteLabelHelper { 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 d83a3c85d7f..7dd6fdaebcd 100644 --- a/common/ASC.Core.Common/Data/DbSettingsManager.cs +++ b/common/ASC.Core.Common/Data/DbSettingsManager.cs @@ -148,13 +148,21 @@ public DbSettingsManager( 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 54598f6ef4b..ad2caf1a046 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -176,7 +176,7 @@ IQueryable<TenantUserSecurity> query() => TenantsQuery() }) .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 @@ public Tenant SaveTenant(CoreSettings coreSettings, Tenant t) .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 @@ public Tenant SaveTenant(CoreSettings coreSettings, Tenant t) 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 @@ public void RemoveTenant(int id, bool auto = false) 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 4624d5528c3..5caa0046ad3 100644 --- a/common/ASC.Core.Common/Notify/Cron/TreeSet.cs +++ b/common/ASC.Core.Common/Notify/Cron/TreeSet.cs @@ -139,8 +139,8 @@ public static TreeSet UnmodifiableTreeSet(ICollection collection) 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 050127ab148..f5ddd47fe4e 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -392,8 +392,8 @@ private List<object[]> GetDataWithPrimary(string t, List<string> columns, string 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 88b01e94b53..45794e2c743 100644 --- a/common/ASC.FederatedLogin/AccountLinker.cs +++ b/common/ASC.FederatedLogin/AccountLinker.cs @@ -65,7 +65,8 @@ public List<LoginProfile> GetFromCache(string obj, Func<string, List<LoginProfil 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 aa4d5483d1e..3f459bf4dfb 100644 --- a/common/ASC.IPSecurity/IPRestrictionsService.cs +++ b/common/ASC.IPSecurity/IPRestrictionsService.cs @@ -77,7 +77,8 @@ public IEnumerable<IPRestriction> Get(int tenant) 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 dda9889f255..52996a77ad2 100644 --- a/common/ASC.IPSecurity/IPSecurity.cs +++ b/common/ASC.IPSecurity/IPSecurity.cs @@ -94,7 +94,9 @@ public bool Verify() 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 5841592e67a..82c61b09dfc 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -529,8 +529,9 @@ private Func<ScriptDescriptor, IScript> GetScriptUpdateByQuery(T data, params Ex 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 @@ private Func<ScriptDescriptor, IScript> GetScriptForUpdate(T data, UpdateAction 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 8232d5e40e5..be4c017f4c6 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 @@ public class AbstractDao 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 b7f6eadcbc0..50791a410de 100644 --- a/products/ASC.Files/Core/Core/Entries/EditHistory.cs +++ b/products/ASC.Files/Core/Core/Entries/EditHistory.cs @@ -147,11 +147,11 @@ public string Name { 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 627b4ed8165..c7cf70574c2 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 @@ public List<File<string>> GetFilesFiltered(IEnumerable<string> fileIds, FilterTy 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 @@ public List<File<string>> GetFiles(string parentId, OrderBy orderBy, FilterType 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 540e57aaa96..901a2fde36e 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 @@ public List<File<string>> GetFilesFiltered(IEnumerable<string> fileIds, FilterTy 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 @@ public List<File<string>> GetFiles(string parentId, OrderBy orderBy, FilterType 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 ffaf005bb4b..08a92a8074b 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 @@ public List<File<string>> GetFilesFiltered(IEnumerable<string> fileIds, FilterTy 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 @@ public List<File<string>> GetFiles(string parentId, OrderBy orderBy, FilterType 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 60f36ce492f..3c9cd22b845 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 @@ public List<File<string>> GetFilesFiltered(IEnumerable<string> fileIds, FilterTy 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 @@ public List<File<string>> GetFiles(string parentId, OrderBy orderBy, FilterType 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 a3900ab6c23..8bc41e0058b 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/ProviderAccountDao.cs @@ -81,7 +81,14 @@ public enum ProviderTypes 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 b08a6482fbc..2c37a93abcb 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 @@ private List<IDaoSelector> Selectors } 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 86c11d40586..ff159ff5a97 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 @@ public List<File<string>> GetFilesFiltered(IEnumerable<string> fileIds, FilterTy 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 @@ public List<File<string>> GetFiles(string parentId, OrderBy orderBy, FilterType 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 9b0e6829bcf..b9783258ef4 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 @@ public List<File<string>> GetFilesFiltered(IEnumerable<string> fileIds, FilterTy 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 @@ public List<File<string>> GetFiles(string parentId, OrderBy orderBy, FilterType 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 04829daa84f..6ec7cff64d0 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceConnector.cs @@ -335,9 +335,9 @@ public string ReplaceCommunityAdress(string url) 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 9d3baf7539a..a7664ccc0f3 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs @@ -251,10 +251,10 @@ public File<T> GetParams<T>(File<T> file, bool lastVersion, FileShare linkRight, { 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 acddd669a5c..ee8a8f0e9e1 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -752,8 +752,10 @@ public IEnumerable<FileEntry<T>> FilterEntries<T>(IEnumerable<FileEntry<T>> entr { 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 f70a34b5485..618e5c23052 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -1175,8 +1175,8 @@ public object SendUserPasswordFromForm([FromForm] MemberModel memberModel) 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 1d289aa8bec..e06196ee795 100644 --- a/web/ASC.Web.Core/Mobile/MobileDetector.cs +++ b/web/ASC.Web.Core/Mobile/MobileDetector.cs @@ -78,7 +78,8 @@ public bool IsRequestMatchesMobile() } 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 fd27730e5ca..af3e3d9e9d8 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -83,9 +83,9 @@ public bool SendMessage(string number, string message) 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 b102438855e..50b287e1f18 100644 --- a/web/ASC.Web.Core/Utility/TenantExtra.cs +++ b/web/ASC.Web.Core/Utility/TenantExtra.cs @@ -207,9 +207,9 @@ public bool UpdatedWithoutLicense { 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 @@ public void DemandControlPanelPermission() 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 9c47739209d..bc143a935a8 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -84,7 +84,8 @@ public Dictionary<string, bool> GetOrInsert(int tenantId) 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/105] 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 3f980fb9948..3b2e59f9fa5 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 @@ internal static string FormatErrorMessage(ISubject subject, IAction[] actions, I 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 @@ internal static string FormatErrorMessage(ISubject subject, IAction[] actions, I 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 0a28a3cdc88..066ce000a59 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -1004,10 +1004,11 @@ protected virtual TreeSet GetSet(int type) 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 @@ protected virtual ValueSet GetValue(int v, string s, int i) { 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 af4a0a5cd9b..fe6aae0e9ed 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -294,6 +294,7 @@ private async Task InternalRunMysqlFile(Stream stream, string delimiter) while ((commandText = await reader.ReadLineAsync()) != null) { + var sb = new StringBuilder(commandText); while (!commandText.EndsWith(delimiter)) { var newline = await reader.ReadLineAsync(); @@ -301,9 +302,9 @@ private async Task InternalRunMysqlFile(Stream stream, string delimiter) { 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 3a2f26c493c..5ea7a7547e2 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 @@ public class JabberStyler : IPatternStyler 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 34266668336..24a9f2e4086 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 @@ public override string ModifyLine(string line) { @"\b ?[([](C|c)[])]", "©" } // copyright }; - var output = ""; + var sb = new StringBuilder(); if (!Regex.IsMatch(line, "<.*>")) { @@ -48,13 +49,14 @@ public override string ModifyLine(string line) { 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 @@ public override string ModifyLine(string line) //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 3b1c79f5892..75de7291002 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 @@ private List<FileEntry<TTo>> MoveOrCopyFolders<TTo>(IServiceScope scope, List<T> 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 @@ private List<FileEntry<TTo>> MoveOrCopyFolders<TTo>(IServiceScope scope, List<T> if (ProcessedFolder(folderId)) { - Result += string.Format("folder_{0}{1}", newFolder.ID, SPLIT_CHAR); + sb.Append($"folder_{newFolder.ID}{SPLIT_CHAR}"); } } @@ -263,7 +265,7 @@ private List<FileEntry<TTo>> MoveOrCopyFolders<TTo>(IServiceScope scope, List<T> 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 @@ private List<FileEntry<TTo>> MoveOrCopyFolders<TTo>(IServiceScope scope, List<T> 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 @@ private List<FileEntry<TTo>> MoveOrCopyFolders<TTo>(IServiceScope scope, List<T> if (ProcessedFolder(folderId)) { - Result += string.Format("folder_{0}{1}", newFolderId, SPLIT_CHAR); + sb.Append($"folder_{newFolderId}{SPLIT_CHAR}"); } } } @@ -353,10 +355,11 @@ private List<FileEntry<TTo>> MoveOrCopyFolders<TTo>(IServiceScope scope, List<T> 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 @@ private List<FileEntry<TTo>> MoveOrCopyFiles<TTo>(IServiceScope scope, List<T> f 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 @@ private List<FileEntry<TTo>> MoveOrCopyFiles<TTo>(IServiceScope scope, List<T> f 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 @@ private List<FileEntry<TTo>> MoveOrCopyFiles<TTo>(IServiceScope scope, List<T> f if (ProcessedFile(fileId)) { - Result += string.Format("file_{0}{1}", newFileId, SPLIT_CHAR); + sb.Append($"file_{newFileId}{SPLIT_CHAR}"); } } } @@ -535,7 +539,7 @@ private List<FileEntry<TTo>> MoveOrCopyFiles<TTo>(IServiceScope scope, List<T> f 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 @@ private List<FileEntry<TTo>> MoveOrCopyFiles<TTo>(IServiceScope scope, List<T> f { 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 @@ private List<FileEntry<TTo>> MoveOrCopyFiles<TTo>(IServiceScope scope, List<T> f if (ProcessedFile(fileId)) { - Result += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR); + sb.Append($"file_{newFile.ID}{SPLIT_CHAR}"); } } } @@ -589,7 +593,7 @@ private List<FileEntry<TTo>> MoveOrCopyFiles<TTo>(IServiceScope scope, List<T> f } 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 032e7cb6f7a..d30b2f968a9 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -299,12 +299,12 @@ internal static string GeneratePassword(int minLength, int maxLength, string noi { 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/105] 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 c7d83ae786c..247b08dcf83 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 @@ public override void FormatLine(string input) { // 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/105] 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 27f17952cf7..48404e7fdc1 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -109,7 +109,7 @@ public virtual void ConfigureServices(IServiceCollection services) 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 2416310efa9..c82834bb99d 100644 --- a/common/ASC.Core.Common/Data/DbUserService.cs +++ b/common/ASC.Core.Common/Data/DbUserService.cs @@ -703,8 +703,6 @@ private IQueryable<User> GetUserQueryForFilter( 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 7a488a6838d..e8d11ae0664 100644 --- a/common/ASC.Core.Common/MultiRegionHostedSolution.cs +++ b/common/ASC.Core.Common/MultiRegionHostedSolution.cs @@ -204,11 +204,10 @@ private HostedSolution GetRegionService(string region) 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 aab41d246fa..3d9cfa5504a 100644 --- a/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs +++ b/common/ASC.Core.Common/Notify/Senders/SmtpSender.cs @@ -277,9 +277,6 @@ protected string GetHtmlView(string body) 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 bb54190e515..bce7596186d 100644 --- a/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/NotifyHelper.cs @@ -112,7 +112,6 @@ public void SendAboutRestoreCompleted(Tenant tenant, bool notifyAllUsers) 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 07c919bbbda..6d6a618577c 100644 --- a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs +++ b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs @@ -405,7 +405,6 @@ protected override void DoJob() 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 95ad6c19c36..16d9e1db71b 100644 --- a/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs @@ -369,16 +369,6 @@ private IEnumerable<BackupFileInfo> GetFilesToProcess(IDataReadOperator dataRead 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 54db156b61b..4606febd22a 100644 --- a/common/ASC.Data.Reassigns/ReassignProgressItem.cs +++ b/common/ASC.Data.Reassigns/ReassignProgressItem.cs @@ -102,7 +102,6 @@ protected override void DoJob() 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 1bb12dafdf6..f035389f529 100644 --- a/common/ASC.Data.Reassigns/RemoveProgressItem.cs +++ b/common/ASC.Data.Reassigns/RemoveProgressItem.cs @@ -98,7 +98,6 @@ protected override void DoJob() 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 915c3659c4e..1e50085105b 100644 --- a/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs +++ b/common/ASC.Data.Storage/GoogleCloud/GoogleCloudStorage.cs @@ -626,9 +626,6 @@ public override Uri Copy(string srcdomain, string srcpath, string newdomain, str { 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 @@ public override void CopyDirectory(string srcdomain, string srcdir, string newdo using var storage = GetStorage(); - - var options = new ListObjectsOptions(); - var objects = storage.ListObjects(_bucket, srckey); foreach (var obj in objects) @@ -672,7 +666,6 @@ public override string SavePrivate(string domain, string path, System.IO.Stream { using var storage = GetStorage(); - var objectKey = MakePath(domain, path); var buffered = TempStream.GetBuffered(stream); var uploadObjectOptions = new UploadObjectOptions @@ -775,7 +768,6 @@ public override string UploadChunk(string domain, { 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 52996a77ad2..0153b979490 100644 --- a/common/ASC.IPSecurity/IPSecurity.cs +++ b/common/ASC.IPSecurity/IPSecurity.cs @@ -79,7 +79,6 @@ public 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 361992aeea8..288fa0998a3 100644 --- a/common/ASC.Textile/Blocks/BlockAttributesParser.cs +++ b/common/ASC.Textile/Blocks/BlockAttributesParser.cs @@ -45,7 +45,6 @@ static public string ParseBlockAttributes(string input, string element) 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 0514c12027e..a3b6860901e 100644 --- a/common/services/ASC.ClearEvents/Program.cs +++ b/common/services/ASC.ClearEvents/Program.cs @@ -66,8 +66,8 @@ public static IHostBuilder CreateHostBuilder(string[] args) => { 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 82c61b09dfc..7973707461f 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -446,14 +446,6 @@ IPromise<IAnalyzers> analyzers(AnalyzersDescriptor b) 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 38b7c21285c..fbeec7eb1ae 100644 --- a/common/services/ASC.ElasticSearch/Engine/Client.cs +++ b/common/services/ASC.ElasticSearch/Engine/Client.cs @@ -104,8 +104,6 @@ public ElasticClient Instance { 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 e91fcb4a02b..b650ad93a51 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 @@ private void DeleteFile(int fileId, bool deleteFolder) 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 88f8bb0308f..09ded4768a9 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -256,7 +256,6 @@ public DataWrapper<T> GetFolderItems(T parentId, int from, int count, FilterType 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 a8ea44b03e0..ed3d602c655 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 @@ public void Open(OAuth20Token token) 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 0e94297ab2f..d5807a398af 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 @@ public void Open(OAuth20Token token) 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 072cb6a981a..0a0f113ee25 100644 --- a/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs +++ b/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs @@ -115,12 +115,12 @@ public IEnumerable<Folder<int>> SearchFolders(string text) 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 44cabcb9aef..e4b8a3d8174 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs @@ -301,7 +301,6 @@ public ReportState Status(ReportOrigin origin, IHttpContextAccessor httpContextA 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 39ba1eba9dd..8ee058f56bb 100644 --- a/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs +++ b/products/ASC.Files/Core/ThirdPartyApp/GoogleDriveApp.cs @@ -332,7 +332,6 @@ public void SaveFile(string fileId, string fileType, string downloadUrl, Stream } 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 ee8a8f0e9e1..a04f5bab046 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -352,8 +352,6 @@ public IEnumerable<FileEntry> GetEntries<T>(Folder<T> parent, int from, int coun { 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 @@ public IEnumerable<FileEntry> GetEntries<T>(Folder<T> parent, int from, int coun } 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 @@ IEnumerable<FileEntry> GetRecentByIds<T>(IEnumerable<T> fileIds, FilterType filt 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 78fd5938f9f..86738e3c014 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -518,8 +518,6 @@ public List<FileEntry> MarkedItems<T>(Folder<T> folder) 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 3895e565327..a75e6c8de39 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -100,16 +100,6 @@ public string Run(MailMergeTask mailMergeTask, IHttpClientFactory clientFactory) 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 @@ private string AttachToMail(MailMergeTask mailMergeTask, IHttpClientFactory clie 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 dfde169ca71..bbcec0bd949 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -598,8 +598,6 @@ public bool RemoveSecurityInfo(List<T> fileIds, List<T> folderIds) 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 e678767dae1..df85dedbefb 100644 --- a/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs +++ b/web/ASC.Web.Api/Models/Smtp/SmtpOperation.cs @@ -221,9 +221,6 @@ public void RunJob(DistributedTask distributedTask, CancellationToken cancellati 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 023b30a1595..d3a70374183 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -73,7 +73,6 @@ public void SendSaasLetters(string senderName, DateTime scheduleDate) 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 a9c2b84ba85..3082af2943b 100644 --- a/web/ASC.Web.Core/Notify/TagValues.cs +++ b/web/ASC.Web.Core/Notify/TagValues.cs @@ -70,8 +70,8 @@ string action() 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 ca670c2867f..6465c80bdc7 100644 --- a/web/ASC.Web.Core/Sms/SmsManager.cs +++ b/web/ASC.Web.Core/Sms/SmsManager.cs @@ -140,7 +140,7 @@ public void ValidateSmsCode(UserInfo user, string code) 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 5c049aca8b5..474b4a4f45d 100644 --- a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs +++ b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs @@ -327,7 +327,6 @@ public void SetLogo(TenantWhiteLabelSettings tenantWhiteLabelSettings, WhiteLabe 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 @@ private static void ResizeLogo(string fileName, byte[] data, long maxFileSize, S 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/105] 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 ead6ec0a20e..c000ddf7379 100644 --- a/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs +++ b/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs @@ -35,7 +35,6 @@ public class SenderChannel : ISenderChannel { private readonly ISink firstSink; private readonly ISink senderSink; - private readonly Context context; public string SenderName @@ -47,12 +46,13 @@ public string SenderName 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 764080ab7ca..56d45d8b6e9 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 b3978d6a1f2..5a1992cfc4f 100644 --- a/common/ASC.Data.Storage/Configuration/StorageSettings.cs +++ b/common/ASC.Data.Storage/Configuration/StorageSettings.cs @@ -174,7 +174,6 @@ public StorageSettingsHelper( public bool Save<T>(BaseStorageSettings<T> baseStorageSettings) where T : class, ISettings, new() { ClearDataStoreCache(); - dataStoreConsumer = null; return SettingsManager.Save(baseStorageSettings); } @@ -195,16 +194,15 @@ internal void ClearDataStoreCache() 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 a5cad6e13e0..7e189d8bf59 100644 --- a/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs +++ b/common/services/ASC.UrlShortener.Svc/UrlShortenerService.cs @@ -50,7 +50,6 @@ public class UrlShortenerService : IServiceController private readonly IHostEnvironment hostEnvironment; private readonly ConfigurationExtension configurationExtension; - private ProcessStartInfo processStartInfo; private Process process; @@ -74,7 +73,7 @@ public void Start() { 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/105] 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 60fdd42fbf2..563d4a889ec 100644 --- a/common/ASC.Core.Common/Data/DbSubscriptionService.cs +++ b/common/ASC.Core.Common/Data/DbSubscriptionService.cs @@ -136,7 +136,7 @@ public bool IsUnsubscribe(int tenant, string sourceId, string actionId, string r } 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 32dacc35bf4..8509b4e5659 100644 --- a/common/ASC.Core.Common/EF/Context/BaseDbContext.cs +++ b/common/ASC.Core.Common/EF/Context/BaseDbContext.cs @@ -65,7 +65,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { 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 b8cb130cd86..29b040578ae 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -261,7 +261,7 @@ private NotifyResult SendNotify(NotifyRequest request, IServiceScope serviceScop } 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 e8499f95c0d..97abdc3d1bc 100644 --- a/common/ASC.Data.Storage/CrossModuleTransferUtility.cs +++ b/common/ASC.Data.Storage/CrossModuleTransferUtility.cs @@ -90,7 +90,6 @@ public void CopyFile(string srcDomain, string srcPath, string destDomain, string 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 8c3b0eb24b6..9d9a026cccd 100644 --- a/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs +++ b/common/ASC.Data.Storage/RackspaceCloud/RackspaceCloudStorage.cs @@ -288,10 +288,6 @@ public Uri Save(string domain, string path, Stream stream, string contentType, ? 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 7973707461f..0d832015d46 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -526,7 +526,6 @@ private Func<ScriptDescriptor, IScript> GetScriptUpdateByQuery(T data, params Ex while (!string.IsNullOrEmpty(name)) { sourceExprText = "." + name + sourceExprText; - expression = member.Expression; } if (isList) @@ -581,7 +580,6 @@ private Func<ScriptDescriptor, IScript> GetScriptForUpdate(T data, UpdateAction 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 3d16cfe71a3..bd01d3db477 100644 --- a/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/FactoryIndexer.cs @@ -230,7 +230,7 @@ public void Index(List<T> data, bool immediately = true, int retry = 0) Thread.Sleep(60000); if (retry < 5) { - Index(data, immediately, retry++); + Index(data, immediately, retry + 1); return; } @@ -259,7 +259,7 @@ public void Index(List<T> data, bool immediately = true, int retry = 0) Thread.Sleep(60000); if (retry < 5) { - Index(data, immediately, retry++); + Index(data, immediately, retry + 1); return; } @@ -304,7 +304,7 @@ private async Task InternalIndexAsync(List<T> data, bool immediately, int retry) await Task.Delay(60000); if (retry < 5) { - await IndexAsync(data, immediately, retry++); + await IndexAsync(data, immediately, retry + 1); return; } @@ -333,7 +333,7 @@ private async Task InternalIndexAsync(List<T> data, bool immediately, int retry) 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/105] 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 fba49e19d6b..a9e233dba34 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -96,7 +96,7 @@ public string GetPath(HttpContext httpContext, IOptionsMonitor<ILog> options, st 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/105] 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 b51f7e44166..7627303edf1 100644 --- a/web/ASC.Web.Api/Controllers/PortalController.cs +++ b/web/ASC.Web.Api/Controllers/PortalController.cs @@ -208,7 +208,7 @@ public object GetFullAbsolutePath(string virtualPath) [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/105] 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 0d832015d46..febed6aed57 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -258,7 +258,6 @@ internal async Task IndexAsync(List<T> data, bool immediately = true) { wwd.Document.Data = null; wwd.Document = null; - wwd = null; GC.Collect(); } continue; @@ -288,7 +287,6 @@ internal async Task IndexAsync(List<T> data, bool immediately = true) 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 867ec54e2fb..16e425a4c91 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -272,18 +272,13 @@ private async Task InternalBulkDownloadFile(HttpContext context, IDataStore stor { 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 0a0f113ee25..b14d6a41cda 100644 --- a/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs +++ b/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs @@ -119,7 +119,7 @@ public IEnumerable<Folder<int>> SearchFolders(string text) //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 a04f5bab046..d794bc81249 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -350,7 +350,7 @@ public IEnumerable<FileEntry> GetEntries<T>(Folder<T> parent, int from, int coun 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 5f427f99339..c6aeefaf99c 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -3011,7 +3011,7 @@ private void CheckCache(string basekey) 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 d3a70374183..372deb48f1f 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -72,7 +72,7 @@ public void SendSaasLetters(string senderName, DateTime scheduleDate) Log.Info("Start SendSaasTariffLetters"); - var activeTenants = new List<Tenant>(); + List<Tenant> activeTenants; using (var scope = ServiceProvider.CreateScope()) { @@ -871,7 +871,7 @@ public void SendOpensourceLetters(string senderName, DateTime scheduleDate) 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 0d892d4398c..11d094284c0 100644 --- a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs +++ b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs @@ -174,7 +174,7 @@ public Result ValidateKey(string phone, string key) 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 1ec6a08ee10..fe357f2875c 100644 --- a/web/ASC.Web.Core/Tfa/TfaManager.cs +++ b/web/ASC.Web.Core/Tfa/TfaManager.cs @@ -155,7 +155,7 @@ public bool ValidateAuthCode(UserInfo user, string code, bool checkBackup = true } } - 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 @@ public IEnumerable<BackupCode> GenerateBackupCodes() 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/105] 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 10f8cb5538e..3995ba28962 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 b0d2a2b1787..8961e34aa53 100644 --- a/common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs +++ b/common/ASC.Core.Common/Notify/Jabber/JabberServiceClientWcf.cs @@ -32,7 +32,7 @@ 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 8cd55011614..9a681671e57 100644 --- a/products/ASC.Files/Core/Core/Entries/FileEntry.cs +++ b/products/ASC.Files/Core/Core/Entries/FileEntry.cs @@ -127,7 +127,7 @@ public object Clone() } [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/105] 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 7e83a7d8346..daeddcdd3e4 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -251,7 +251,7 @@ 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 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 fd00bd4e162..ef76304537c 100644 --- a/common/ASC.Data.Storage/ChunkedUploader/CommonChunkedUploadSession.cs +++ b/common/ASC.Data.Storage/ChunkedUploader/CommonChunkedUploadSession.cs @@ -111,7 +111,7 @@ public void TransformItems() { 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 2278b550405..c177c363ae1 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -712,8 +712,8 @@ public List<FileEntry> GetSharesForMe(FilterType filterType, bool subjectGroup, 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 @@ public List<FileEntry> GetPrivacyForMe(FilterType filterType, bool subjectGroup, 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 86738e3c014..1dd1c569b46 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -528,7 +528,7 @@ public List<FileEntry> MarkedItems<T>(Folder<T> folder) 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 @@ public List<FileEntry> MarkedItems<T>(Folder<T> folder) .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 372deb48f1f..3cf016e4ca7 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -472,7 +472,7 @@ public void SendEnterpriseLetters(string senderName, DateTime scheduleDate) 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 8bf97a22945..ace0e0c302d 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -83,7 +83,7 @@ public override bool Equals(object obj) { 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/105] 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 2931de38e15..a1740505bf6 100644 --- a/common/ASC.Common/Caching/KafkaCache.cs +++ b/common/ASC.Common/Caching/KafkaCache.cs @@ -159,7 +159,7 @@ void action() 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 c84035be2ac..e50ea7fe2c2 100644 --- a/common/ASC.Common/Security/AscRandom.cs +++ b/common/ASC.Common/Security/AscRandom.cs @@ -51,7 +51,7 @@ public AscRandom(int seed) 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 63510288ce0..5ecccafd33b 100644 --- a/common/ASC.Common/Utils/HttpRequestExtensions.cs +++ b/common/ASC.Common/Utils/HttpRequestExtensions.cs @@ -186,7 +186,7 @@ private static Uri ParseRewriterUrl(string s) } 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 @@ private static Uri ParseRewriterUrl(string s) { 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 e3a36da22c3..b0db7e137d5 100644 --- a/common/ASC.Common/Utils/Wildcard.cs +++ b/common/ASC.Common/Utils/Wildcard.cs @@ -98,7 +98,7 @@ public static bool IsMatch(string pattern, string input, bool ignoreCase) 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 12dcf9a9666..07c096202ba 100644 --- a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs +++ b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs @@ -59,7 +59,7 @@ public PaymentManager(TenantManager tenantManager, ITariffService tariffService, 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 066ce000a59..ea1e8fe9c9d 100644 --- a/common/ASC.Core.Common/Notify/Cron/CronExpression.cs +++ b/common/ASC.Core.Common/Notify/Cron/CronExpression.cs @@ -420,13 +420,13 @@ protected virtual int StoreExpressionVals(int pos, string s, int type) 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 @@ protected virtual int CheckNext(int pos, string s, int val, int type) 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 @@ protected virtual int GetDayOfWeekNumber(string s) } 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 @@ protected virtual int GetDayOfWeekNumber(string s) if (st != null && st.Count != 0) { t = min; - min = ((int)st.First()); + min = (int)st.First(); } else { @@ -1249,7 +1249,7 @@ protected virtual int GetDayOfWeekNumber(string s) 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 @@ protected virtual int GetDayOfWeekNumber(string s) } else { - day = ((int)daysOfMonth.First()); + day = (int)daysOfMonth.First(); mon++; } if (day != t || mon != tmon) @@ -1295,9 +1295,9 @@ protected virtual int GetDayOfWeekNumber(string s) { 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 @@ protected virtual int GetDayOfWeekNumber(string s) } 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 @@ protected virtual int GetDayOfWeekNumber(string s) 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 @@ protected virtual int GetDayOfWeekNumber(string s) 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 @@ protected virtual int GetDayOfWeekNumber(string s) } 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 e57bbbd7ee8..77b11a7b070 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -38,7 +38,7 @@ public class RecipientProviderImpl : IRecipientProvider 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 b89b13757f3..72d094e6f9d 100644 --- a/common/ASC.Core.Common/Security/Authorizing/RoleProvider.cs +++ b/common/ASC.Core.Common/Security/Authorizing/RoleProvider.cs @@ -43,7 +43,7 @@ class RoleProvider : IRoleProvider { //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 e2ce90f933b..d738cdf29d4 100644 --- a/common/ASC.Core.Common/Tenants/TenantCookieSettings.cs +++ b/common/ASC.Core.Common/Tenants/TenantCookieSettings.cs @@ -91,7 +91,7 @@ public TenantCookieSettings GetForTenant(int tenantId) 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 @@ public TenantCookieSettings GetForUser(int tenantId, Guid userId) 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 8aca730396c..64abdee234b 100644 --- a/common/ASC.Data.Backup.Core/Core/DbHelper.cs +++ b/common/ASC.Data.Backup.Core/Core/DbHelper.cs @@ -117,7 +117,7 @@ public List<string> GetTables() 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 6d6a618577c..2b03e887680 100644 --- a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs +++ b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs @@ -559,14 +559,14 @@ protected override void DoJob() 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 f5ddd47fe4e..a952f1b6094 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -605,7 +605,7 @@ private void DoBackupModule(IDataWriteOperator writer, IModuleSpecifics module) 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 2888a72d7b4..46bcbbbaf26 100644 --- a/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/DeletePortalTask.cs @@ -75,7 +75,7 @@ private void DoDeleteModule(IModuleSpecifics module) 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 @@ private void DoDeleteStorage() 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 7ff38c2187e..1665c36e3ff 100644 --- a/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs @@ -230,7 +230,7 @@ private void SaveTenant(DbFactory dbFactory, string alias, TenantStatus status, $"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 af7ce40e5d7..f0e003ee0c1 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -151,12 +151,12 @@ public override Uri GetInternalUri(string domain, string path, TimeSpan expire, 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 @@ public override bool IsDirectory(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; return response.S3Objects.Count > 0; } @@ -965,7 +965,7 @@ public override void DeleteDirectory(string domain, string path) 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 @@ private IEnumerable<S3Object> GetS3ObjectsByPath(string domain, string path) { 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 a9e233dba34..40f97243bbd 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -96,7 +96,7 @@ public string GetPath(HttpContext httpContext, IOptionsMonitor<ILog> options, st 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 a945ed3166f..68a297f566e 100644 --- a/common/ASC.Data.Storage/Wildcard.cs +++ b/common/ASC.Data.Storage/Wildcard.cs @@ -90,7 +90,7 @@ public static bool IsMatch(string pattern, string input, bool caseInsensitive) } // 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 6d7d828e38d..d4cf589bc3f 100644 --- a/common/ASC.FederatedLogin/Helpers/HashHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/HashHelper.cs @@ -34,7 +34,7 @@ public static int CombineHashCodes(int hash1, int hash2) { 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 9f4b8d006c5..6be75592bb8 100644 --- a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs @@ -88,8 +88,8 @@ public OAuth20TokenHelper(IHttpContextAccessor httpContextAccessor, ConsumerFact 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 8052978b4fc..c98dbc92959 100644 --- a/common/ASC.IPSecurity/IPAddressRange.cs +++ b/common/ASC.IPSecurity/IPAddressRange.cs @@ -66,8 +66,8 @@ public bool IsInRange(IPAddress address) 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 288fa0998a3..e0b5e11abf5 100644 --- a/common/ASC.Textile/Blocks/BlockAttributesParser.cs +++ b/common/ASC.Textile/Blocks/BlockAttributesParser.cs @@ -52,7 +52,7 @@ static public string ParseBlockAttributes(string input, string element) } if (input.Length == 0) - return (style.Length > 0 ? " style=\"" + style + "\"" : ""); + return style.Length > 0 ? " style=\"" + style + "\"" : ""; Match m; @@ -133,14 +133,14 @@ static public string ParseBlockAttributes(string input, string element) - 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 72b8b5510e3..b6c660f46ce 100644 --- a/common/ASC.Textile/States/ListFormatterState.cs +++ b/common/ASC.Textile/States/ListFormatterState.cs @@ -86,7 +86,7 @@ public sealed override void FormatLine(string input) 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 2a494b36e0a..b1a0a849052 100644 --- a/common/ASC.Textile/States/SimpleBlockFormatterState.cs +++ b/common/ASC.Textile/States/SimpleBlockFormatterState.cs @@ -35,9 +35,9 @@ public override string Consume(string input, Match m) 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 93dbb961895..ca6aafed003 100644 --- a/common/ASC.Textile/States/TableFormatterState.cs +++ b/common/ASC.Textile/States/TableFormatterState.cs @@ -58,7 +58,7 @@ public override bool ShouldExit(string input) @"(\.\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 8b0c33fdbc5..74dfb147ab3 100644 --- a/common/services/ASC.ElasticSearch/Core/Selector.cs +++ b/common/services/ASC.ElasticSearch/Core/Selector.cs @@ -207,7 +207,7 @@ public Selector<T> MatchAll(string value) { 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 f3808eff58f..140afdde8c1 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 @@ public Folder<int> ToFolder(DbFolderQuery r) 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 09ded4768a9..1aef4898eb3 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -317,8 +317,8 @@ public DataWrapper<T> GetFolderItems(T parentId, int from, int count, FilterType || 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 c177c363ae1..647d2117187 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -712,8 +712,8 @@ public List<FileEntry> GetSharesForMe(FilterType filterType, bool subjectGroup, 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 @@ public List<FileEntry> GetPrivacyForMe(FilterType filterType, bool subjectGroup, 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 1cd4f28b609..a23d86a359f 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 @@ public string MakeOneDrivePath(Item onedriveItem) { 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 352d94bffba..bcdb7d73234 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 @@ private File GetFile(object id) { 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 @@ private Folder GetFolder(object id) { 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 a2cb4e3b167..340c8aea65f 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 @@ protected IEnumerable<ICloudFileSystemEntry> GetFolderFiles(ICloudDirectoryEntry 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 b9783258ef4..965f1c33232 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 @@ public File<string> SaveFile(File<string> file, Stream fileStream) 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 96877abb9b1..b30b9339f5d 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 @@ public string SaveFolder(Folder<string> folder) 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 1e9841d6ee3..4070b97190c 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceTracker.cs @@ -565,7 +565,7 @@ private TrackResponse ProcessMailMerge<T>(T fileId, TrackerData fileData) { 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 d794bc81249..ed90fd22be1 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -772,7 +772,7 @@ public IEnumerable<FileEntry> SortEntries<T>(IEnumerable<FileEntry> entries, Ord { 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 1dd1c569b46..56f45af9dd7 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -549,8 +549,8 @@ public List<FileEntry> MarkedItems<T>(Folder<T> folder) .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 ba65129f43e..fa34b85c612 100644 --- a/products/ASC.Files/Core/Utils/FileSharing.cs +++ b/products/ASC.Files/Core/Utils/FileSharing.cs @@ -299,7 +299,7 @@ public List<AceWrapper> GetSharedInfo<T>(FileEntry<T> entry) 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 a4c3dc0d875..0e066dcdf44 100644 --- a/products/ASC.Files/Core/Utils/FileTracker.cs +++ b/products/ASC.Files/Core/Utils/FileTracker.cs @@ -66,7 +66,7 @@ public bool ProlongEditing<T>(T fileId, Guid tabId, Guid userId, bool editingAlo 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 bbcec0bd949..04dbcb3d3d3 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -248,7 +248,7 @@ public object CreateUploadSession(T folderId, string fileName, long fileSize, st 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 0ce47f95d08..2de3ef40fc7 100644 --- a/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs +++ b/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs @@ -109,11 +109,11 @@ group by t.tenant !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 c6aeefaf99c..1906780259a 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -1168,7 +1168,7 @@ private void SaveWhiteLabelSettingsFromFilesForTenant(TenantWhiteLabelSettings s 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 @@ public object UploadLicense([FromForm] UploadLicenseModel model) 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 e99749ff905..b1d4bdd894a 100644 --- a/web/ASC.Web.Core/Calendars/RecurrenceRule.cs +++ b/web/ASC.Web.Core/Calendars/RecurrenceRule.cs @@ -120,7 +120,7 @@ public DayOfWeek DayOfWeek { get { - return ((Id ?? "").ToLower()) switch + return (Id ?? "").ToLower() switch { "su" => DayOfWeek.Sunday, "mo" => DayOfWeek.Monday, @@ -256,7 +256,7 @@ public List<DateTime> GetDates(DateTime utcStartDate, TimeZoneInfo eventTimeZone { 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 @@ public List<DateTime> GetDates(DateTime utcStartDate, TimeZoneInfo eventTimeZone 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 @@ public List<DateTime> GetDates(DateTime utcStartDate, TimeZoneInfo eventTimeZone 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 @@ public List<DateTime> GetDates(DateTime utcStartDate, TimeZoneInfo eventTimeZone } 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 @@ public List<DateTime> GetDates(DateTime utcStartDate, TimeZoneInfo eventTimeZone 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 @@ public List<DateTime> GetDates(DateTime utcStartDate, TimeZoneInfo eventTimeZone 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 @@ public List<DateTime> GetDates(DateTime utcStartDate, TimeZoneInfo eventTimeZone } } 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 @@ public List<DateTime> GetDates(DateTime utcStartDate, TimeZoneInfo eventTimeZone 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 @@ public string ToString(bool iCal) public static Frequency ParseFrequency(string frequency) { - return (frequency.ToLower()) switch + return frequency.ToLower() switch { "monthly" => Frequency.Monthly, @@ -963,7 +963,7 @@ public static RecurrenceRule Parse(string serializedString) 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 05df7623f85..bedb1f67e4e 100644 --- a/web/ASC.Web.Core/CommonPhotoManager.cs +++ b/web/ASC.Web.Core/CommonPhotoManager.cs @@ -53,7 +53,7 @@ public static Image DoThumbnail(Image image, Size size, bool crop, bool transpar 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 c19fd9e50a4..a574a8b5dc9 100644 --- a/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs +++ b/web/ASC.Web.Core/Helpers/GrammaticalHelper.cs @@ -38,7 +38,7 @@ public static string ChooseNumeralCase(int number, string nominative, string gen 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 c83aa94c5e6..8a87666a1be 100644 --- a/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs +++ b/web/ASC.Web.Core/Helpers/ResourceEnumConverter.cs @@ -106,7 +106,7 @@ private bool IsSingleBitValue(ulong value) { 0 => false, 1 => true, - _ => ((value & (value - 1)) == 0), + _ => (value & (value - 1)) == 0, }; } @@ -216,7 +216,7 @@ public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext { if (value is string @string) { - var result = (_isFlagEnum) ? + var result = _isFlagEnum ? GetFlagValue(culture, @string) : GetValue(culture, @string); if (result == null) { @@ -242,7 +242,7 @@ public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext co { 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 6039ff24a66..d828bee1c5b 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyService.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyService.cs @@ -144,7 +144,7 @@ public void SendRequestTariff(bool license, string fname, string lname, string t 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 3cf016e4ca7..0c371cf36f1 100644 --- a/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs +++ b/web/ASC.Web.Core/Notify/StudioPeriodicNotify.cs @@ -502,7 +502,7 @@ public void SendEnterpriseLetters(string senderName, DateTime scheduleDate) 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 fe357f2875c..c09ac5f33bb 100644 --- a/web/ASC.Web.Core/Tfa/TfaManager.cs +++ b/web/ASC.Web.Core/Tfa/TfaManager.cs @@ -190,7 +190,7 @@ public IEnumerable<BackupCode> GenerateBackupCodes() 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 ace0e0c302d..9f8c81f9554 100644 --- a/web/ASC.Web.Core/Users/UserPhotoManager.cs +++ b/web/ASC.Web.Core/Users/UserPhotoManager.cs @@ -834,7 +834,7 @@ public string SaveThumbnail(Guid userID, Image img, IImageFormat format) 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 474b4a4f45d..5f778ad637f 100644 --- a/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs +++ b/web/ASC.Web.Core/WhiteLabel/TenantWhiteLabelSettings.cs @@ -347,7 +347,7 @@ public void SetLogo(TenantWhiteLabelSettings tenantWhiteLabelSettings, Dictionar 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/105] 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 6a0c0fa422a..34dfea0f2d8 100644 --- a/common/ASC.Textile/Globals.cs +++ b/common/ASC.Textile/Globals.cs @@ -44,44 +44,29 @@ static class Globals #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 @@ static Globals() ["<>"] = "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/105] 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 690367553b1..e3252aacc14 100644 --- a/common/ASC.Core.Common/EF/Context/DbContextManager.cs +++ b/common/ASC.Core.Common/EF/Context/DbContextManager.cs @@ -88,7 +88,7 @@ public MultiRegionalDbContextManager(IOptionsFactory<MultiRegionalDbContext<T>> 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 1aef4898eb3..be27708c0cf 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -1214,7 +1214,7 @@ public List<FileEntry> GetThirdPartyFolder(int folderType = 0) 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 @@ public object DeleteThirdParty(string providerId) 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 b14d6a41cda..7ff59c49aa9 100644 --- a/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs +++ b/products/ASC.Files/Core/HttpHandlers/SearchHandler.cs @@ -143,7 +143,7 @@ public SearchResultItem[] Search(string text) 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 @@ public SearchResultItem[] Search(string text) 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 @@ public SearchResultItem[] Search(string text) 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 ed90fd22be1..50ca9904fa7 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -589,7 +589,7 @@ public IEnumerable<Folder<string>> GetThirpartyFolders<T>(Folder<T> parent, stri 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 @@ public IEnumerable<FileEntry> SortEntries<T>(IEnumerable<FileEntry> entries, Ord 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/105] 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 e3252aacc14..690367553b1 100644 --- a/common/ASC.Core.Common/EF/Context/DbContextManager.cs +++ b/common/ASC.Core.Common/EF/Context/DbContextManager.cs @@ -88,7 +88,7 @@ public MultiRegionalDbContextManager(IOptionsFactory<MultiRegionalDbContext<T>> 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/105] 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 b0db7e137d5..a08b686e7ce 100644 --- a/common/ASC.Common/Utils/Wildcard.cs +++ b/common/ASC.Common/Utils/Wildcard.cs @@ -51,8 +51,8 @@ public static bool IsMatch(string pattern, string input, bool ignoreCase) { 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 68a297f566e..235c47a8b54 100644 --- a/common/ASC.Data.Storage/Wildcard.cs +++ b/common/ASC.Data.Storage/Wildcard.cs @@ -38,8 +38,8 @@ public static bool IsMatch(string pattern, string input, bool caseInsensitive) 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/105] 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 1801ead8322..2454e50c28f 100644 --- a/common/ASC.Common/Threading/DistributedTaskQueue.cs +++ b/common/ASC.Common/Threading/DistributedTaskQueue.cs @@ -232,7 +232,7 @@ public T GetTask<T>(string id) where T : DistributedTask 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 @@ public DistributedTask GetTask(string id) { 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 495fc732bb0..8ef62e58ef1 100644 --- a/common/ASC.Core.Common/BaseCommonLinkUtility.cs +++ b/common/ASC.Core.Common/BaseCommonLinkUtility.cs @@ -185,7 +185,7 @@ public string GetFullAbsolutePath(string virtualPath) 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 ad2caf1a046..5d8a0f25a2e 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -478,16 +478,15 @@ private void ValidateDomain(string domain, int tenantId, bool validateCharacters } // 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 29b040578ae..5687bb78802 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -255,7 +255,7 @@ private NotifyResult SendNotify(NotifyRequest request, IServiceScope serviceScop } 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 61283bf6374..8705c8d8b0d 100644 --- a/common/ASC.Core.Common/Security/Authorizing/AzManager.cs +++ b/common/ASC.Core.Common/Security/Authorizing/AzManager.cs @@ -76,7 +76,7 @@ internal AzManagerAcl GetAzManagerAcl(ISubject subject, IAction action, ISecurit 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 6bce910864c..bdc6f4d4f84 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -427,7 +427,7 @@ public override void DeleteDirectory(string domain, string path) 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/105] 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 c10998e4027..d18cc4adbdd 100644 --- a/common/ASC.Api.Core/Routing/FormatRoute.cs +++ b/common/ASC.Api.Core/Routing/FormatRoute.cs @@ -10,7 +10,7 @@ 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) + 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 cf8e2b0c4fb..9aa3f064753 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 dbb8dcee3ff..f07571420a9 100644 --- a/common/ASC.Common/DIHelper.cs +++ b/common/ASC.Common/DIHelper.cs @@ -97,14 +97,14 @@ public abstract class DIAttribute : Attribute 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 5687bb78802..df3c0c651bc 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -575,7 +575,7 @@ private void PrepareRequestFillTags(NotifyRequest request, IServiceScope service } - 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 76917bcb217..89258ede8f6 100644 --- a/common/ASC.Core.Common/Notify/NotifySource.cs +++ b/common/ASC.Core.Common/Notify/NotifySource.cs @@ -67,7 +67,7 @@ public string ID 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 @@ public NotifySource(string id, UserManager userManager, IRecipientProvider recip 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 40a0d196a69..98a291822ec 100644 --- a/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs +++ b/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs @@ -45,16 +45,16 @@ protected Regex RegEx } - 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 2b03e887680..6ea1eb38d93 100644 --- a/common/ASC.Data.Backup.Core/Service/BackupWorker.cs +++ b/common/ASC.Data.Backup.Core/Service/BackupWorker.cs @@ -334,7 +334,7 @@ public int TenantId 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 06066c8b1c1..8cb6a321a93 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 @@ public virtual string ConnectionStringName 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 b0c8f49873d..2b1ab923977 100644 --- a/common/ASC.Data.Storage/BaseStorage.cs +++ b/common/ASC.Data.Storage/BaseStorage.cs @@ -55,8 +55,8 @@ public abstract class BaseStorage : IDataStore 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 985c506815f..d77e9993f80 100644 --- a/common/ASC.Textile/Blocks/PhraseBlockModifier.cs +++ b/common/ASC.Textile/Blocks/PhraseBlockModifier.cs @@ -61,7 +61,7 @@ protected string PhraseModifierFormat(string input, string modifier, string tag) 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 c51cdb3f7cd..b65085b0950 100644 --- a/common/ASC.Textile/FormatterState.cs +++ b/common/ASC.Textile/FormatterState.cs @@ -36,7 +36,7 @@ public abstract class FormatterState /// 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 b6c660f46ce..fbeaef8518a 100644 --- a/common/ASC.Textile/States/ListFormatterState.cs +++ b/common/ASC.Textile/States/ListFormatterState.cs @@ -36,7 +36,7 @@ protected int NestingDepth 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 80dcd7049a8..ed70d20b3fd 100644 --- a/common/services/ASC.AuditTrail/AuditEventsRepository.cs +++ b/common/services/ASC.AuditTrail/AuditEventsRepository.cs @@ -69,7 +69,7 @@ public IEnumerable<AuditEvent> Get(int tenant, DateTime from, DateTime to) 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 a364647bfba..edfccf89f0d 100644 --- a/common/services/ASC.AuditTrail/LoginEventsRepository.cs +++ b/common/services/ASC.AuditTrail/LoginEventsRepository.cs @@ -61,7 +61,7 @@ public LoginEventsRepository(UserFormatter userFormatter, DbContextManager<Audit 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 c676c283ee8..84964b39c13 100644 --- a/common/services/ASC.Feed.Aggregator/Modules/FeedModule.cs +++ b/common/services/ASC.Feed.Aggregator/Modules/FeedModule.cs @@ -49,7 +49,7 @@ protected int Tenant 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 5e4f66b4ca9..387a2e1a2f5 100644 --- a/common/services/ASC.TelegramService/Core/Core.cs +++ b/common/services/ASC.TelegramService/Core/Core.cs @@ -186,7 +186,7 @@ protected ParamParser(Type type) 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 9a681671e57..67d9016b8db 100644 --- a/products/ASC.Files/Core/Core/Entries/FileEntry.cs +++ b/products/ASC.Files/Core/Core/Entries/FileEntry.cs @@ -46,7 +46,7 @@ protected FileEntry() } - 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 647d2117187..0822201e1b0 100644 --- a/products/ASC.Files/Core/Core/Security/FileSecurity.cs +++ b/products/ASC.Files/Core/Core/Security/FileSecurity.cs @@ -942,7 +942,7 @@ public List<Guid> GetUserSubjects(Guid userId) 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 59d16f94b4d..be2793b2e06 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 @@ internal abstract class BoxDaoBase : ThirdPartyProviderDao<BoxProviderInfo> { 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 6f0bb681691..07bc5d50171 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 @@ internal abstract class DropboxDaoBase : ThirdPartyProviderDao<DropboxProviderIn { 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 16e833a95d0..566c03555f2 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 @@ internal abstract class GoogleDriveDaoBase : ThirdPartyProviderDao<GoogleDrivePr { 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 fe1f4973c0f..40f14f0aa73 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/IThirdPartyProviderDao.cs @@ -229,7 +229,7 @@ internal abstract class ThirdPartyProviderDao<T> : ThirdPartyProviderDao, IDispo 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 a23d86a359f..399540137f6 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 @@ internal abstract class OneDriveDaoBase : ThirdPartyProviderDao<OneDriveProvider { 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 340c8aea65f..a6a4f51077e 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 @@ internal abstract class SharpBoxDaoBase : ThirdPartyProviderDao<SharpBoxProvider { 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 982333dbba3..12243c63e96 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 @@ public abstract class FileOperation : DistributedTask 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 fed61d05880..942991c97c4 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 17a4a895ffb..dca66493706 100644 --- a/web/ASC.Web.Core/Calendars/BaseEvent.cs +++ b/web/ASC.Web.Core/Calendars/BaseEvent.cs @@ -33,7 +33,7 @@ public abstract class BaseEvent : IEvent, ICloneable { 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 6dce6fff94a..e2f81514cb0 100644 --- a/web/ASC.Web.Core/Calendars/BaseTodo.cs +++ b/web/ASC.Web.Core/Calendars/BaseTodo.cs @@ -33,7 +33,7 @@ public abstract class BaseTodo : ITodo, ICloneable { 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/105] 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 9fd70561609..27cd20b1a79 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -56,7 +56,7 @@ public class CouponManager 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 402cdab7573..3b4c0173f33 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/105] 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 daeddcdd3e4..a481eec9063 100644 --- a/common/ASC.Api.Core/Core/ApiDateTime.cs +++ b/common/ASC.Api.Core/Core/ApiDateTime.cs @@ -88,7 +88,7 @@ public static ApiDateTime Parse(string data, TenantManager tenantManager, TimeZo 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 c27b05eee19..655a7c13a63 100644 --- a/common/ASC.Common/Data/StreamExtension.cs +++ b/common/ASC.Common/Data/StreamExtension.cs @@ -36,8 +36,8 @@ 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; diff --git a/common/ASC.Common/Data/TempStream.cs b/common/ASC.Common/Data/TempStream.cs index 0b6ee909112..196af2f604d 100644 --- a/common/ASC.Common/Data/TempStream.cs +++ b/common/ASC.Common/Data/TempStream.cs @@ -32,7 +32,7 @@ public TempStream(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 diff --git a/common/ASC.Core.Common/Billing/BillingClient.cs b/common/ASC.Core.Common/Billing/BillingClient.cs index f51f9aca6bb..f4f4d229e62 100644 --- a/common/ASC.Core.Common/Billing/BillingClient.cs +++ b/common/ASC.Core.Common/Billing/BillingClient.cs @@ -186,7 +186,7 @@ public IDictionary<string, Dictionary<string, decimal>> GetProductPriceInfo(para { 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 bcb2518b1c4..859128a9818 100644 --- a/common/ASC.Core.Common/Billing/License/LicenseReader.cs +++ b/common/ASC.Core.Common/Billing/License/LicenseReader.cs @@ -153,7 +153,7 @@ public DateTime SaveLicenseTemp(Stream licenseStream) 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 aad10a1f67b..4e07ccdcad0 100644 --- a/common/ASC.Core.Common/Billing/TariffService.cs +++ b/common/ASC.Core.Common/Billing/TariffService.cs @@ -279,7 +279,7 @@ public void SetTariff(int tenantId, Tariff tariff) { if (tariff == null) { - throw new ArgumentNullException("tariff"); + throw new ArgumentNullException(nameof(tariff)); } var q = QuotaService.GetTenantQuota(tariff.QuotaId); @@ -432,7 +432,7 @@ public IDictionary<string, Dictionary<string, decimal>> GetProductPriceInfo(para { 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 50e9817d2f0..2150ebcb76e 100644 --- a/common/ASC.Core.Common/Caching/CachedAzService.cs +++ b/common/ASC.Core.Common/Caching/CachedAzService.cs @@ -87,7 +87,7 @@ class CachedAzService : IAzService 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 7a490d5c548..f8ff5be3884 100644 --- a/common/ASC.Core.Common/Caching/CachedQuotaService.cs +++ b/common/ASC.Core.Common/Caching/CachedQuotaService.cs @@ -127,7 +127,7 @@ public CachedQuotaService() 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 e8b4b6a7465..9d3448b0a9d 100644 --- a/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs +++ b/common/ASC.Core.Common/Caching/CachedSubscriptionService.cs @@ -114,7 +114,7 @@ class CachedSubscriptionService : ISubscriptionService 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 b9dbc6553ff..9ff75ae5e4c 100644 --- a/common/ASC.Core.Common/Caching/CachedTenantService.cs +++ b/common/ASC.Core.Common/Caching/CachedTenantService.cs @@ -205,7 +205,7 @@ public CachedTenantService() 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 4dda7d23546..35dc77a9a3f 100644 --- a/common/ASC.Core.Common/Caching/CachedUserService.cs +++ b/common/ASC.Core.Common/Caching/CachedUserService.cs @@ -207,7 +207,7 @@ public CachedUserService( 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 7348d06ef1d..08c1641427c 100644 --- a/common/ASC.Core.Common/Configuration/SmtpSettings.cs +++ b/common/ASC.Core.Common/Configuration/SmtpSettings.cs @@ -83,17 +83,17 @@ public SmtpSettings(string host, int port, string senderAddress, string senderDi { 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 @@ public void SetCredentials(string userName, string password, string domain) { 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 153c890ffe1..d3f4eb1e7fd 100644 --- a/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs +++ b/common/ASC.Core.Common/Context/Impl/CoreConfiguration.cs @@ -179,7 +179,7 @@ public void SaveSetting(string key, string value, int tenant = Tenant.DEFAULT_TE { if (string.IsNullOrEmpty(key)) { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); } byte[] bytes = null; if (value != null) @@ -193,7 +193,7 @@ public string GetSetting(string key, int tenant = Tenant.DEFAULT_TENANT) { 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 07c096202ba..d8837644ea2 100644 --- a/common/ASC.Core.Common/Context/Impl/PaymentManager.cs +++ b/common/ASC.Core.Common/Context/Impl/PaymentManager.cs @@ -104,7 +104,7 @@ public void ActivateKey(string key) { 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 5f7315fc568..9b7c6a1c305 100644 --- a/common/ASC.Core.Common/Context/Impl/TenantManager.cs +++ b/common/ASC.Core.Common/Context/Impl/TenantManager.cs @@ -194,7 +194,7 @@ public Tenant GetTenant(string domain) 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 b602aed346d..218702e095f 100644 --- a/common/ASC.Core.Common/Context/SecurityContext.cs +++ b/common/ASC.Core.Common/Context/SecurityContext.cs @@ -113,8 +113,8 @@ IOptionsMonitor<ILog> options 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 0ef86e4d586..d44c3375f99 100644 --- a/common/ASC.Core.Common/Core/DBResourceManager.cs +++ b/common/ASC.Core.Common/Core/DBResourceManager.cs @@ -174,11 +174,11 @@ public DBResourceSet( { 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 0c271f2242d..1711343f18b 100644 --- a/common/ASC.Core.Common/Data/DbQuotaService.cs +++ b/common/ASC.Core.Common/Data/DbQuotaService.cs @@ -115,7 +115,7 @@ public TenantQuota GetTenantQuota(int id) 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 @@ public void RemoveTenantQuota(int id) 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 7dd6fdaebcd..78561ab5a9f 100644 --- a/common/ASC.Core.Common/Data/DbSettingsManager.cs +++ b/common/ASC.Core.Common/Data/DbSettingsManager.cs @@ -185,7 +185,7 @@ public void ClearCache<T>(int tenantId) where T : class, ISettings 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 563d4a889ec..5c15dc0d1cf 100644 --- a/common/ASC.Core.Common/Data/DbSubscriptionService.cs +++ b/common/ASC.Core.Common/Data/DbSubscriptionService.cs @@ -69,8 +69,8 @@ public DbSubscriptionService(DbContextManager<UserDbContext> dbContextManager) 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 @@ public string[] GetRecipients(int tenant, string sourceId, string actionId, stri 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 @@ public IEnumerable<SubscriptionRecord> GetSubscriptions(int tenant, string sourc 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 @@ public SubscriptionRecord GetSubscription(int tenant, string sourceId, string ac 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 @@ public bool IsUnsubscribe(int tenant, string sourceId, string actionId, string r 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 @@ public string[] GetSubscriptions(int tenant, string sourceId, string actionId, s 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 @@ public void RemoveSubscriptions(int tenant, string sourceId, string actionId) 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 @@ public void RemoveSubscriptions(int tenant, string sourceId, string actionId, st 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 @@ public IEnumerable<SubscriptionMethod> GetSubscriptionMethods(int tenant, string 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 @@ public void SetSubscriptionMethod(SubscriptionMethod m) 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 5d8a0f25a2e..7b0ba0de8ed 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -158,7 +158,7 @@ public IEnumerable<Tenant> GetTenants(DateTime from, bool active = true) 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 @@ public Tenant GetTenant(int id) 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 c82834bb99d..f3250557fdd 100644 --- a/common/ASC.Core.Common/Data/DbUserService.cs +++ b/common/ASC.Core.Common/Data/DbUserService.cs @@ -239,7 +239,7 @@ public UserInfo GetUserByUserName(int tenant, string userName) 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 @@ public Group SaveGroup(int tenant, Group group) 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 8494e71c410..7764765c15a 100644 --- a/common/ASC.Core.Common/Encryption/EncryptionSettings.cs +++ b/common/ASC.Core.Common/Encryption/EncryptionSettings.cs @@ -131,12 +131,12 @@ public string GeneratePassword(int length, int numberOfNonAlphanumericCharacters 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 c000ddf7379..92f8b1eda9b 100644 --- a/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs +++ b/common/ASC.Core.Common/Notify/Channels/SenderChannel.cs @@ -46,19 +46,19 @@ public string SenderName 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 7ae665ae8c7..07b0b2088ad 100644 --- a/common/ASC.Core.Common/Notify/DirectSubscriptionProvider.cs +++ b/common/ASC.Core.Common/Notify/DirectSubscriptionProvider.cs @@ -41,32 +41,32 @@ class DirectSubscriptionProvider : ISubscriptionProvider 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 @@ public IRecipient[] GetRecipients(INotifyAction action, string objectID) 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 3b99a635fc7..abcca2d244a 100644 --- a/common/ASC.Core.Common/Notify/EmailSenderSink.cs +++ b/common/ASC.Core.Common/Notify/EmailSenderSink.cs @@ -49,7 +49,7 @@ public class EmailSenderSink : Sink 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 b9686b7a9b9..6f5d6a8d81a 100644 --- a/common/ASC.Core.Common/Notify/Engine/DispatchEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/DispatchEngine.cs @@ -47,7 +47,7 @@ public DispatchEngine(Context context, IConfiguration configuration, IOptionsMon { 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 a514d10fb82..89f7136fdcf 100644 --- a/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs +++ b/common/ASC.Core.Common/Notify/Engine/InterceptorStorage.cs @@ -54,8 +54,8 @@ private Dictionary<string, ISendInterceptor> CallInterceptors 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 @@ public void Add(ISendInterceptor interceptor) 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 @@ public ISendInterceptor Get(string name) 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 df3c0c651bc..3c13771148a 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyEngine.cs @@ -76,7 +76,7 @@ public class NotifyEngine : INotifyEngine 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 @@ public virtual void QueueRequest(NotifyRequest request, IServiceScope serviceSco 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 @@ internal void RegisterSendMethod(Action<DateTime> method, string cron) 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 @@ private void SendGroupNotify(NotifyRequest request, List<SendResponse> responces 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 @@ private List<SendResponse> SendDirectNotify(NotifyRequest request, IServiceScope 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 @@ private SendResponse SendDirectNotify(NotifyRequest request, ISenderChannel chan 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 1e34ce40cf0..b1e4151d1b5 100644 --- a/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs +++ b/common/ASC.Core.Common/Notify/Engine/NotifyRequest.cs @@ -75,9 +75,9 @@ public NotifyRequest(INotifySource notifySource, INotifyAction action, string ob 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 @@ internal IPattern GetSenderPattern(string senderName) 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 25d6104f208..e6b56d66014 100644 --- a/common/ASC.Core.Common/Notify/Engine/SendInterceptorSkeleton.cs +++ b/common/ASC.Core.Common/Notify/Engine/SendInterceptorSkeleton.cs @@ -44,8 +44,8 @@ public class SendInterceptorSkeleton : ISendInterceptor 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 868d9edd4ae..d491898849f 100644 --- a/common/ASC.Core.Common/Notify/JabberSenderSink.cs +++ b/common/ASC.Core.Common/Notify/JabberSenderSink.cs @@ -44,7 +44,7 @@ class JabberSenderSink : Sink 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 c3b86fa4018..a764d5400f0 100644 --- a/common/ASC.Core.Common/Notify/Messages/NoticeMessage.cs +++ b/common/ASC.Core.Common/Notify/Messages/NoticeMessage.cs @@ -48,25 +48,25 @@ public NoticeMessage() 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 @@ public ITagValue[] Arguments 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 ec0a449c6c6..dfd96793b0e 100644 --- a/common/ASC.Core.Common/Notify/Model/NotifyAction.cs +++ b/common/ASC.Core.Common/Notify/Model/NotifyAction.cs @@ -43,7 +43,7 @@ public NotifyAction(string id) 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 25492b93774..34de37863a6 100644 --- a/common/ASC.Core.Common/Notify/Model/NotifyClientImpl.cs +++ b/common/ASC.Core.Common/Notify/Model/NotifyClientImpl.cs @@ -43,9 +43,9 @@ class NotifyClientImpl : INotifyClient 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 @@ public void RemoveInterceptor(string name) 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 @@ private void SendAsync(NotifyRequest request) 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 89258ede8f6..61484884464 100644 --- a/common/ASC.Core.Common/Notify/NotifySource.cs +++ b/common/ASC.Core.Common/Notify/NotifySource.cs @@ -69,7 +69,7 @@ public string ID 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 3c2605273c4..01398d5e441 100644 --- a/common/ASC.Core.Common/Notify/Patterns/Pattern.cs +++ b/common/ASC.Core.Common/Notify/Patterns/Pattern.cs @@ -52,8 +52,8 @@ public Pattern(string id, string subject, string body, string contentType) { 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 98a291822ec..d9959ba492b 100644 --- a/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs +++ b/common/ASC.Core.Common/Notify/Patterns/PatternFormatter.cs @@ -65,7 +65,7 @@ protected PatternFormatter(string tagSearchRegExp, bool formatMessage) 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 @@ public string[] GetTags(IPattern pattern) 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 77ec54dee7f..b1575905a16 100644 --- a/common/ASC.Core.Common/Notify/Patterns/TagValue.cs +++ b/common/ASC.Core.Common/Notify/Patterns/TagValue.cs @@ -46,7 +46,7 @@ public object Value 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 77b11a7b070..cc76fa8520a 100644 --- a/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs +++ b/common/ASC.Core.Common/Notify/RecipientProviderImpl.cs @@ -54,7 +54,7 @@ public virtual IRecipient GetRecipient(string id) 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 @@ public virtual IRecipient[] GetGroupEntries(IRecipientsGroup group) 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 @@ public virtual IRecipientsGroup[] GetGroups(IRecipient recipient) 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 922fe8a09ef..bd1fe259392 100644 --- a/common/ASC.Core.Common/Notify/Sinks/DispatchSink.cs +++ b/common/ASC.Core.Common/Notify/Sinks/DispatchSink.cs @@ -38,7 +38,7 @@ class DispatchSink : Sink 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 b7ac18be60d..1f8aa3b8865 100644 --- a/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs +++ b/common/ASC.Core.Common/Notify/Telegram/TelegramSenderSink.cs @@ -43,7 +43,7 @@ class TelegramSenderSink : Sink 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 01351c226d8..779aacfb72b 100644 --- a/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs +++ b/common/ASC.Core.Common/Notify/TopSubscriptionProvider.cs @@ -41,8 +41,8 @@ public class TopSubscriptionProvider : ISubscriptionProvider 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 @@ public TopSubscriptionProvider(IRecipientProvider recipientProvider, ISubscripti 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 @@ public virtual string[] GetSubscriptionMethod(INotifyAction action, IRecipient r 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 @@ public virtual IRecipient[] GetRecipients(INotifyAction action, string objectID) 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 @@ public virtual bool IsUnsubscribe(IDirectRecipient recipient, INotifyAction acti 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 @@ public virtual void UnSubscribe(INotifyAction action, IRecipient recipient) 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 @@ public virtual object GetSubscriptionRecord(INotifyAction action, IRecipient rec 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 8705c8d8b0d..4036462b189 100644 --- a/common/ASC.Core.Common/Security/Authorizing/AzManager.cs +++ b/common/ASC.Core.Common/Security/Authorizing/AzManager.cs @@ -43,8 +43,8 @@ internal AzManager() 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 @@ public bool CheckPermission(ISubject subject, IAction action, ISecurityObjectId 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 878e65d4b8b..7ffc4a84104 100644 --- a/common/ASC.Core.Common/Security/Authorizing/PermissionProvider.cs +++ b/common/ASC.Core.Common/Security/Authorizing/PermissionProvider.cs @@ -44,8 +44,8 @@ public PermissionProvider(AuthorizationManager authorizationManager) 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 4d7cc57b1f5..6fe753fc002 100644 --- a/common/ASC.Core.Common/Security/Authorizing/PermissionResolver.cs +++ b/common/ASC.Core.Common/Security/Authorizing/PermissionResolver.cs @@ -45,7 +45,7 @@ class PermissionResolver : IPermissionResolver 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 36da33b5455..820fbe17e5f 100644 --- a/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs +++ b/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs @@ -85,7 +85,7 @@ public string GetEmailKey(string email) 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 @@ public string GetEmailKey(int tenantId, string email) 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 @@ public ValidationResult ValidateEmailKey(string email, string key, TimeSpan vali 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 0936dfb3cbe..394f3f8f9b1 100644 --- a/common/ASC.Core.Common/Users/UserFormatter.cs +++ b/common/ASC.Core.Common/Users/UserFormatter.cs @@ -51,7 +51,7 @@ public UserFormatter(IConfiguration configuration) 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 e4ce1689632..32c1be95af7 100644 --- a/common/ASC.Data.Backup.Core/ActionInvoker.cs +++ b/common/ASC.Data.Backup.Core/ActionInvoker.cs @@ -52,7 +52,7 @@ public static void Try( 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 23e6934fc41..6fc7aec1ddf 100644 --- a/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs +++ b/common/ASC.Data.Backup.Core/Extensions/EnumerableExtensions.cs @@ -56,13 +56,13 @@ public static IEnumerable<TreeNode<TEntry>> ToTree<TEntry, TKey>(this IEnumerabl 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 @@ public static IEnumerable<TreeNode<TEntry>> ToTree<TEntry, TKey>(this IEnumerabl 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 a952f1b6094..5a0f1b8b584 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -78,7 +78,7 @@ public BackupPortalTask(DbFactory dbFactory, DbContextManager<BackupsContext> db 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 fe6aae0e9ed..41c67c55119 100644 --- a/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs +++ b/common/ASC.Data.Backup.Core/Tasks/PortalTaskBase.cs @@ -167,7 +167,7 @@ protected void SetStepsCount(int value) { if (value <= 0) { - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException(nameof(value)); } stepsCount = value; Logger.Debug("Steps: " + stepsCount); @@ -191,7 +191,7 @@ protected void SetCurrentStepProgress(int value) { if (value < 0 || value > 100) { - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException(nameof(value)); } if (value == 100) { @@ -207,7 +207,7 @@ protected void SetProgress(int value) { 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 06f36cbb434..22ff8414535 100644 --- a/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/RestoreDbModuleTask.cs @@ -54,9 +54,9 @@ internal class RestoreDbModuleTask : PortalTaskBase 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 16d9e1db71b..5dc5985a30b 100644 --- a/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs @@ -84,7 +84,7 @@ public RestorePortalTask( 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 1665c36e3ff..632af50158f 100644 --- a/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/TransferPortalTask.cs @@ -83,7 +83,7 @@ public TransferPortalTask( 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 2b1ab923977..b25f4fac77f 100644 --- a/common/ASC.Data.Storage/BaseStorage.cs +++ b/common/ASC.Data.Storage/BaseStorage.cs @@ -104,7 +104,7 @@ public Uri GetPreSignedUri(string domain, string path, TimeSpan expire, IEnumera { 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 97abdc3d1bc..3bc35eb1de8 100644 --- a/common/ASC.Data.Storage/CrossModuleTransferUtility.cs +++ b/common/ASC.Data.Storage/CrossModuleTransferUtility.cs @@ -57,18 +57,18 @@ public CrossModuleTransferUtility( 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 bdc6f4d4f84..1fe967da004 100644 --- a/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs +++ b/common/ASC.Data.Storage/DiscStorage/DiscDataStore.cs @@ -98,7 +98,7 @@ public string GetPhysicalPath(string domain, string path) { if (path == null) { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } var pathMap = GetPath(domain); @@ -118,7 +118,7 @@ public override Stream GetReadStream(string domain, string path) 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 @@ public override Task<Stream> GetReadStreamAsync(string domain, string path, int 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 @@ public override Uri Save(string domain, string path, Stream stream) 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 @@ public override bool IsSupportChunking 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 @@ public override void Delete(string domain, string path) 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 @@ public override void DeleteFiles(string domain, List<string> paths) 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 @@ public override void DeleteFiles(string domain, string folderPath, string patter 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 @@ public override void MoveDirectory(string srcdomain, string srcdir, string newdo 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 @@ public override Uri Move(string srcdomain, string srcpath, string newdomain, str 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 @@ public override bool IsDirectory(string domain, string path) 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 @@ public override string SavePrivate(string domain, string path, Stream stream, Da 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 @@ public override string GetPostParams(string domain, string directoryPath, long m 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 @@ public override string[] ListDirectoriesRelative(string domain, string path, boo 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 @@ public override string[] ListFilesRelative(string domain, string path, string pa 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 @@ public override long GetUsedQuota(string domain) 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 @@ public Stream GetWriteStream(string domain, string path) 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 @@ private static void ValidatePath(string target) 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 @@ public void Encrypt(string domain, string path) 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 b8892a79dae..afc368009e0 100644 --- a/common/ASC.Data.Storage/Extensions.cs +++ b/common/ASC.Data.Storage/Extensions.cs @@ -46,8 +46,8 @@ public static Stream IronReadStream(this IDataStore store, TempStream tempStream 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 7d29302a6d8..720d5bbc50d 100644 --- a/common/ASC.Data.Storage/ProgressStream.cs +++ b/common/ASC.Data.Storage/ProgressStream.cs @@ -36,7 +36,7 @@ public class ProgressStream : Stream 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 f0e003ee0c1..abe306b95ab 100644 --- a/common/ASC.Data.Storage/S3/S3Storage.cs +++ b/common/ASC.Data.Storage/S3/S3Storage.cs @@ -1262,7 +1262,7 @@ private class ResponseStreamWrapper : Stream 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 36e2fe49a16..0f604fda123 100644 --- a/common/ASC.Data.Storage/TenantPath.cs +++ b/common/ASC.Data.Storage/TenantPath.cs @@ -35,7 +35,7 @@ public static string CreatePath(string tenant) { 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 40f97243bbd..0752ac206e1 100644 --- a/common/ASC.Data.Storage/WebPath.cs +++ b/common/ASC.Data.Storage/WebPath.cs @@ -82,7 +82,7 @@ public string GetPath(HttpContext httpContext, IOptionsMonitor<ILog> options, st { 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 @@ public string GetPath(string relativePath) { 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 6be75592bb8..5ed17df780b 100644 --- a/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/OAuth20TokenHelper.cs @@ -103,7 +103,7 @@ public OAuth20TokenHelper(IHttpContextAccessor httpContextAccessor, ConsumerFact 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 @@ public OAuth20TokenHelper(IHttpContextAccessor httpContextAccessor, ConsumerFact 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 1ee9a7d6eab..be5240a8593 100644 --- a/common/ASC.FederatedLogin/Helpers/RequestHelper.cs +++ b/common/ASC.FederatedLogin/Helpers/RequestHelper.cs @@ -38,7 +38,7 @@ public static class RequestHelper 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 21549f20903..42fe66347dd 100644 --- a/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs +++ b/common/ASC.FederatedLogin/LoginProviders/DocuSignLoginProvider.cs @@ -88,7 +88,7 @@ private string AuthHeader 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 85ddffe722c..3d1deb91ee5 100644 --- a/common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs +++ b/common/ASC.FederatedLogin/LoginProviders/ProviderManager.cs @@ -79,7 +79,7 @@ public LoginProfile Process(string providerType, HttpContext context, IDictionar 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 cfb901392a8..2a38655e774 100644 --- a/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs +++ b/common/ASC.FederatedLogin/MultiRegionAccountLinker.cs @@ -48,7 +48,7 @@ private string GetDatabaseId(string hostedRegion) 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 bbed67d0df4..af7b337aee0 100644 --- a/common/ASC.FederatedLogin/Profile/LoginProfile.cs +++ b/common/ASC.FederatedLogin/Profile/LoginProfile.cs @@ -233,7 +233,7 @@ public LoginProfile GetMinimalProfile() 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 @@ public static bool HasProfile(HttpContext context) 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 @@ internal static LoginProfile CreateFromSerializedString(Signature signature, Ins 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 @@ internal LoginProfile(Signature signature, InstanceCrypto instanceCrypto) 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 d2ee57c9305..533e698b571 100644 --- a/common/ASC.VoipService/Twilio/TwilioProvider.cs +++ b/common/ASC.VoipService/Twilio/TwilioProvider.cs @@ -60,8 +60,8 @@ public class TwilioProvider : IVoipProvider 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 febed6aed57..904047c81fe 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -611,7 +611,7 @@ private void UpdateByAction(UpdateAction action, IList newValue, string key, Dic } 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 b650ad93a51..10af00d5f3b 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 @@ public File<int> SaveFile(File<int> file, Stream fileStream, bool checkQuota = t { if (file == null) { - throw new ArgumentNullException("file"); + throw new ArgumentNullException(nameof(file)); } var maxChunkedUploadSize = SetupInfo.MaxChunkedUploadSize(TenantExtra, TenantStatisticProvider); @@ -514,7 +514,7 @@ public File<int> SaveFile(File<int> file, Stream fileStream, bool checkQuota = t 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 @@ public Task<bool> IsExistOnStorageAsync(File<int> file) 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 @@ public IEnumerable<int> GetTenantsWithFeeds(DateTime fromTime) 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 140afdde8c1..2f99f6ae1cf 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 @@ public int SaveFolder(Folder<int> folder) 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 @@ public int MoveFolder(int folderId, int toFolderId, CancellationToken? cancellat 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 @@ private IEnumerable<Folder<int>> Search(string text) 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 @@ public IEnumerable<int> GetFolderIDs(string module, string bunch, IEnumerable<st 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 8766c941a12..05ffb3813fe 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 @@ public IEnumerable<Tag> GetTags(T entryID, FileEntryType entryType, TagType tagT 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 @@ public IEnumerable<Tag> GetTags(string[] names, TagType tagType) 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 3cf65ce08e1..70aefb7bf8c 100644 --- a/products/ASC.Files/Core/Core/Entries/EncryptionKeyPair.cs +++ b/products/ASC.Files/Core/Core/Entries/EncryptionKeyPair.cs @@ -72,8 +72,8 @@ public EncryptionKeyPairHelper( 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 70658a8de84..8ce27d11e93 100644 --- a/products/ASC.Files/Core/Core/FilesIntegration.cs +++ b/products/ASC.Files/Core/Core/FilesIntegration.cs @@ -55,7 +55,7 @@ public T RegisterBunch<T>(string module, string bunch, string data) 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 c7cf70574c2..0db8e96994f 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 @@ public Stream GetFileStream(File<string> file, long offset) 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 @@ public bool IsSupportedPreSignedUri(File<string> file) 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 99ee0e9a967..bd13e5738d0 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 @@ public List<Folder<string>> GetParentFolders(string folderId) 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 ed3d602c655..66a1959fbe5 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 @@ public List<BoxItem> GetItems(string folderId, int limit = 500) 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 901a2fde36e..43f8440ffe7 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 @@ public Stream GetFileStream(File<string> file, long offset) 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 @@ public bool IsSupportedPreSignedUri(File<string> file) 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 d7751a8ad96..5d793c7846f 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 @@ public List<Folder<string>> GetParentFolders(string folderId) 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 08a92a8074b..8f68abf428a 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 @@ public Stream GetFileStream(File<string> file, long offset) 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 @@ public bool IsSupportedPreSignedUri(File<string> file) 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 28b26accd36..e784006a19c 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 @@ public List<Folder<string>> GetParentFolders(string folderId) 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 8930f5d4c91..d95b3d25ee1 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 @@ public List<DriveFile> GetEntries(string folderId, bool? folders = null) 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 @@ public DriveFile FileConstructor(string title = null, string mimeType = null, st 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 @@ public ResumableUploadSession CreateResumableSession(DriveFile driveFile, long c 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 3c9cd22b845..29a2b63bd0a 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 @@ public Stream GetFileStream(File<string> file, long offset) 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 @@ public bool IsSupportedPreSignedUri(File<string> file) 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 7a0bfda7f47..ff81daa7282 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 @@ public List<Folder<string>> GetParentFolders(string folderId) 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 fd901dca45e..37658b87b92 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 @@ public List<Item> GetItems(string folderId, int limit = 500) 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 @@ private IItemRequestBuilder GetItemRequest(string itemId) 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 @@ public ResumableUploadSession CreateResumableSession(Item onedriveFile, long con 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 7bb179e8b5e..64202e8a5fa 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 @@ public override Stream GetFileStream(File<string> file) /// <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 @@ public Stream GetFileStream(File<string> file, long offset) 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 @@ public bool IsSupportedPreSignedUri(File<string> file) 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 @@ public Uri GetPreSignedUri(File<string> file, TimeSpan expires) 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 @@ public File<string> SaveFile(File<string> file, Stream fileStream) 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 @@ private IFileDao<string> GetFileDao(File<string> file) 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 4a3b3a38b77..9ed97f90941 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 @@ public List<Folder<string>> GetParentFolders(string folderId) 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 f0653fec6c1..2e825eb568c 100644 --- a/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs +++ b/products/ASC.Files/Core/Core/Thirdparty/RegexDaoSelectorBase.cs @@ -130,7 +130,7 @@ private T1 GetDao<T1>(string id) where T1 : ThirdPartyProviderDao<T> 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 ff159ff5a97..4c960d0d8f3 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 @@ public Stream GetFileStream(File<string> file, long offset) { 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 @@ public bool IsSupportedPreSignedUri(File<string> file) 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 965f1c33232..7050e138658 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 @@ public Stream GetFileStream(File<string> file, long offset) 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 @@ public override Stream GetFileStream(File<string> file) 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 @@ public string FileRename(File<string> file, string newTitle) 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 75e9d3c9917..a54f8ca4667 100644 --- a/products/ASC.Files/Core/Helpers/DocuSignHelper.cs +++ b/products/ASC.Files/Core/Helpers/DocuSignHelper.cs @@ -99,7 +99,7 @@ public void DeleteToken(Guid? userId = null) 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 @@ public bool ValidateToken(OAuth20Token token) 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 @@ public string SendDocuSign<T>(T fileId, DocuSignData docuSignData, IDictionary<s 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 @@ private DocuSignAccount GetDocuSignAccount(OAuth20Token token) 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 @@ private string CreateEnvelope(string accountId, Document document, DocuSignData 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 9ea4dbaf0ac..4d1559b9712 100644 --- a/products/ASC.Files/Core/Helpers/PathProvider.cs +++ b/products/ASC.Files/Core/Helpers/PathProvider.cs @@ -107,7 +107,7 @@ public string GetFileControlPath(string fileName) 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 @@ public string GetFolderUrlById<T>(T folderId) 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 @@ public string GetFileStreamUrl<T>(File<T> file, string doc = null, bool lastVers 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 @@ public string GetFileChangesUrl<T>(File<T> file, string doc = null) 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 b0908e05ff6..21e1881891e 100644 --- a/products/ASC.Files/Core/Helpers/WordpressHelper.cs +++ b/products/ASC.Files/Core/Helpers/WordpressHelper.cs @@ -61,7 +61,7 @@ public OAuth20Token GetToken() 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 @@ public OAuth20Token SaveTokenFromCode(string code) 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 034c2111188..136f0046667 100644 --- a/products/ASC.Files/Core/HttpHandlers/ChunkedUploaderHandler.cs +++ b/products/ASC.Files/Core/HttpHandlers/ChunkedUploaderHandler.cs @@ -385,7 +385,7 @@ private IFormFile File 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 a69b74d3188..0d1c715a449 100644 --- a/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs +++ b/products/ASC.Files/Core/Services/FFmpegService/FFmpeg.cs @@ -123,8 +123,8 @@ private ProcessStartInfo PrepareFFmpeg(string inputFormat) 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 50ca9904fa7..7ad6c458bd2 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -332,7 +332,7 @@ public IEnumerable<FileEntry> GetEntries<T>(Folder<T> parent, int from, int coun { 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 @@ public void TrackEditing<T>(T fileId, Guid tabId, Guid userId, string doc, bool 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 d382ca98891..323d25ada4e 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -697,7 +697,7 @@ public FileOperationResult ExecSync<T>(File<T> file, string doc) 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 56f45af9dd7..696b110726b 100644 --- a/products/ASC.Files/Core/Utils/FileMarker.cs +++ b/products/ASC.Files/Core/Utils/FileMarker.cs @@ -513,7 +513,7 @@ public int GetRootFoldersIdMarkedAsNew<T>(T rootId) 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 04dbcb3d3d3..f9778a3f272 100644 --- a/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs +++ b/products/ASC.Files/Server/Helpers/FilesControllerHelper.cs @@ -281,7 +281,7 @@ public object CreateUploadSession(T folderId, string fileName, long fileSize, st 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 @@ private FileWrapper<T> CreateFile(T folderId, string title, string content, stri 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 1906780259a..686e08ad7ce 100644 --- a/web/ASC.Web.Api/Controllers/SettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SettingsController.cs @@ -2743,7 +2743,7 @@ public bool SaveMailWhiteLabelSettingsFromForm([FromForm] MailWhiteLabelSettings 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 1476025ca0d..980c88b456e 100644 --- a/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs +++ b/web/ASC.Web.Api/Controllers/SmtpSettingsController.cs @@ -100,7 +100,7 @@ private SmtpSettingsWrapper SaveSmtpSettings(SmtpSettingsWrapper smtpSettings) //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 1b5e8d33577..c12d2574893 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -114,8 +114,8 @@ public static int GetConvertedUri( 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 @@ public static string DocbuilderRequest( 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 @@ public static string DocbuilderRequest( 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 @@ public enum ErrorCode /// <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 64bebf52ec0..db8693d74c0 100644 --- a/web/ASC.Web.Core/Mobile/CachedMobileAppInstallRegistrator.cs +++ b/web/ASC.Web.Core/Mobile/CachedMobileAppInstallRegistrator.cs @@ -49,7 +49,7 @@ public CachedMobileAppInstallRegistrator(MobileAppInstallRegistrator registrator { 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 d828bee1c5b..be375daafcc 100644 --- a/web/ASC.Web.Core/Notify/StudioNotifyService.cs +++ b/web/ASC.Web.Core/Notify/StudioNotifyService.cs @@ -125,22 +125,22 @@ public void SendMsgToAdminFromNotAuthUser(string email, string message) 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 11d094284c0..bb0f3c0f840 100644 --- a/web/ASC.Web.Core/Sms/SmsKeyStorage.cs +++ b/web/ASC.Web.Core/Sms/SmsKeyStorage.cs @@ -108,7 +108,7 @@ public bool GenerateKey(string phone, out string key) { 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 e903983ab90..3f6a3adde9b 100644 --- a/web/ASC.Web.Core/Sms/SmsSender.cs +++ b/web/ASC.Web.Core/Sms/SmsSender.cs @@ -62,11 +62,11 @@ public bool SendSMS(string number, string message) { 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 d30b2f968a9..ba9c0fee412 100644 --- a/web/ASC.Web.Core/Users/UserManagerWrapper.cs +++ b/web/ASC.Web.Core/Users/UserManagerWrapper.cs @@ -98,7 +98,7 @@ private bool TestUniqueUserName(string uniqueName) 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 @@ public bool CheckUniqueEmail(Guid userId, string email) 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 @@ public bool CheckPasswordRegex(PasswordSettings passwordSettings, string passwor 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 bc143a935a8..3dce5b757d0 100644 --- a/web/ASC.Web.Core/WebItemSecurity.cs +++ b/web/ASC.Web.Core/WebItemSecurity.cs @@ -399,7 +399,7 @@ public static WebItemSecurityObject Create(string id, WebItemManager webItemMana { 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/105] 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 48404e7fdc1..a85e1a99eac 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -64,6 +64,7 @@ public virtual void ConfigureServices(IServiceCollection services) 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/105] 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 64b87e03865..cb034a96338 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 @@ public class DocumentServiceLicense 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 @@ private CommandResponse GetDocumentServiceLicense() null, null, null, - FileUtility.SignatureSecret); + FileUtility.SignatureSecret, + ClientFactory + ); Cache.Insert(cacheKey, commandResponse, DateTime.UtcNow.Add(CACHE_EXPIRATION)); } 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 102/105] 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 bd2fb5c2342..be3045ec18a 100644 --- a/products/ASC.Files/Core/Core/FileStorageService.cs +++ b/products/ASC.Files/Core/Core/FileStorageService.cs @@ -436,7 +436,7 @@ public Folder<T> FolderRename(T folderId, string title) 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 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 103/105] Analyzers: fix --- common/ASC.Common/Utils/HtmlUtil.cs | 2 +- .../ASC.Core.Common/Data/DbTenantService.cs | 5 ++-- .../Tasks/BackupPortalTask.cs | 10 +++---- .../Tasks/RestorePortalTask.cs | 18 ++++++++++--- .../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, 138 insertions(+), 103 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 ff90d5e5bb1..3837d983d48 100644 --- a/common/ASC.Common/Utils/HtmlUtil.cs +++ b/common/ASC.Common/Utils/HtmlUtil.cs @@ -104,7 +104,7 @@ public static string SearchTextHighlight(string searchText, string htmlText, boo 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 a4ded10215d..f87e802febb 100644 --- a/common/ASC.Core.Common/Data/DbTenantService.cs +++ b/common/ASC.Core.Common/Data/DbTenantService.cs @@ -228,7 +228,8 @@ IQueryable<TenantUserSecurity> query() => TenantsQuery() .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 @@ public Tenant GetTenant(int id) 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 5a0f1b8b584..046e82f3fa6 100644 --- a/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/BackupPortalTask.cs @@ -320,7 +320,7 @@ private void DumpTableData(string t, string dir, int count) { 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 @@ private List<object[]> GetDataWithPrimary(string t, List<string> columns, string 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 @@ private void SaveToFile(string path, string t, IReadOnlyCollection<string> colum 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 5dc5985a30b..ffcafd28553 100644 --- a/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs +++ b/common/ASC.Data.Backup.Core/Tasks/RestorePortalTask.cs @@ -368,9 +368,21 @@ private IEnumerable<BackupFileInfo> GetFilesToProcess(IDataReadOperator dataRead private void SetTenantActive(int tenantId) { - using var connection = DbFactory.OpenConnection(); - - connection.CreateCommand().WithTimeout(120).ExecuteNonQuery(); + 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); + + 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 4606febd22a..ccd69d86658 100644 --- a/common/ASC.Data.Reassigns/ReassignProgressItem.cs +++ b/common/ASC.Data.Reassigns/ReassignProgressItem.cs @@ -102,6 +102,7 @@ protected override void DoJob() 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 f035389f529..f71393935e8 100644 --- a/common/ASC.Data.Reassigns/RemoveProgressItem.cs +++ b/common/ASC.Data.Reassigns/RemoveProgressItem.cs @@ -97,7 +97,8 @@ protected override void DoJob() 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 45794e2c743..4cee0290022 100644 --- a/common/ASC.FederatedLogin/AccountLinker.cs +++ b/common/ASC.FederatedLogin/AccountLinker.cs @@ -169,8 +169,9 @@ private List<LoginProfile> GetLinkedProfilesFromDB(string obj) //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 9a9d1c41297..134c1cc2cd2 100644 --- a/common/ASC.Feed/Data/FeedAggregateDataProvider.cs +++ b/common/ASC.Feed/Data/FeedAggregateDataProvider.cs @@ -244,7 +244,7 @@ private List<FeedResultItem> GetFeedsInternal(FeedApiFilter filter) 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 bd28563a05e..0f091116b13 100644 --- a/common/ASC.Textile/States/HeaderFormatterState.cs +++ b/common/ASC.Textile/States/HeaderFormatterState.cs @@ -32,7 +32,7 @@ public override void Enter() { for (var i = 0; i < HeaderLevel; i++) { - Formatter.Output.Write("<br {0}/>"); + Formatter.Output.Write($"<br {FormattedStylesAndAlignment("br")}/>"); } } @@ -77,7 +77,7 @@ public HeaderFormatterState(TextileFormatter f) 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 650430d80a3..bb025abcaa5 100644 --- a/common/ASC.VoipService/Dao/VoipDao.cs +++ b/common/ASC.VoipService/Dao/VoipDao.cs @@ -93,7 +93,8 @@ public virtual IEnumerable<VoipPhone> GetAllNumbers() { 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 @@ public virtual IEnumerable<VoipPhone> GetNumbers(params string[] ids) 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 @@ public IEnumerable<VoipCall> GetCalls(VoipCallFilter filter) 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 @@ public IEnumerable<VoipCall> GetMissedCalls(Guid agent, long count = 0, DateTime .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 fae7e9e9367..5aa604c97e8 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 f05963afcc0..00000000000 --- 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 f0afbbb24bc..039a3c54e42 100644 --- a/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs +++ b/common/services/ASC.AuditTrail/Mappers/AuditActionMapper.cs @@ -71,7 +71,7 @@ public string GetActionText(AuditEvent evt) { 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 @@ public string GetActionText(LoginEvent evt) { 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 78fcaeaabd1..b07b2e50e2b 100644 --- a/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs +++ b/common/services/ASC.ElasticSearch/Engine/BaseIndexer.cs @@ -444,6 +444,14 @@ IPromise<IAnalyzers> analyzers(AnalyzersDescriptor b) 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 @@ private Func<ScriptDescriptor, IScript> GetScriptUpdateByQuery(T data, params Ex 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 @@ private Func<ScriptDescriptor, IScript> GetScriptForUpdate(T data, UpdateAction 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 d9dfda15455..325417599ec 100644 --- a/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs +++ b/common/services/ASC.Feed.Aggregator/Service/FeedAggregatorService.cs @@ -200,9 +200,9 @@ private void AggregateFeeds(object interval) { 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 d292ed87021..1eb8f76e883 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 @@ private void DeleteFile(int fileId, bool deleteFolder) .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 @@ private void DeleteFile(int fileId, bool deleteFolder) tx.Commit(); - foreach(var folderId in fromFolders) + foreach (var folderId in fromFolders) { RecalculateFilesCount(folderId); } @@ -770,7 +773,7 @@ public int MoveFile(int fileId, int toFolderId) 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 d5cb793cf7a..c3f0b963b69 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 @@ public IEnumerable<Tag> GetNewTags(Guid subject, Folder<T> parentFolder, bool de 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 ac399991172..1798d62fd58 100644 --- a/products/ASC.Files/Core/Core/Entries/EditHistory.cs +++ b/products/ASC.Files/Core/Core/Entries/EditHistory.cs @@ -168,11 +168,11 @@ public string Name { 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 db899371b39..7564bfb8842 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 @@ public class FileHelper 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 9dbe4c48c74..618161336af 100644 --- a/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs +++ b/products/ASC.Files/Core/HttpHandlers/FileHandler.ashx.cs @@ -271,14 +271,19 @@ private Task BulkDownloadFile(HttpContext context) 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 e4b8a3d8174..f7c2bc687d2 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocbuilderReportsUtility.cs @@ -189,7 +189,7 @@ public void GenerateReport(DistributedTask task, CancellationToken cancellationT 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 a7664ccc0f3..9d3baf7539a 100644 --- a/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs +++ b/products/ASC.Files/Core/Services/DocumentService/DocumentServiceHelper.cs @@ -251,10 +251,10 @@ public File<T> GetParams<T>(File<T> file, bool lastVersion, FileShare linkRight, { 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 c9a6edf1e6c..e4f74fe9a5f 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.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 @@ public override void RunJob(DistributedTask distributedTask, CancellationToken c { string archiveExtension; - using(var zip = scope.ServiceProvider.GetService<CompressToArchive>()) + using (var zip = scope.ServiceProvider.GetService<CompressToArchive>()) { archiveExtension = zip.ArchiveExtension; } @@ -233,7 +232,7 @@ private ItemNameValueCollection<T> GetEntriesPathId(IServiceScope scope) { var folders = FilesSecurity.FilterRead(FolderDao.GetFolders(Files)); - foreach(var folder in folders) + foreach (var folder in folders) { fileMarker.RemoveMarkAsNew(folder); } @@ -276,8 +275,8 @@ private ItemNameValueCollection<T> GetFilesInFolders(IServiceScope scope, IEnume entriesPathId.Add(filesInFolder); } return entriesPathId; - } - + } + internal void CompressToZip(Stream stream, IServiceScope scope) { if (_entriesPathId == null) return; @@ -330,7 +329,7 @@ internal void CompressToZip(Stream stream, IServiceScope scope) 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 5692ceba25f..8728933fa62 100644 --- a/products/ASC.Files/Core/Utils/FileConverter.cs +++ b/products/ASC.Files/Core/Utils/FileConverter.cs @@ -172,7 +172,8 @@ private void CheckConvertFilesStatus(object _) 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 1f0d7bc9c44..88e78d3dae7 100644 --- a/products/ASC.Files/Core/Utils/MailMergeTask.cs +++ b/products/ASC.Files/Core/Utils/MailMergeTask.cs @@ -99,7 +99,16 @@ public string Run(MailMergeTask mailMergeTask, IHttpClientFactory clientFactory) } 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 @@ private string AttachToMail(MailMergeTask mailMergeTask, IHttpClientFactory clie } 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 618e5c23052..e5513ebbff1 100644 --- a/products/ASC.People/Server/Controllers/PeopleController.cs +++ b/products/ASC.People/Server/Controllers/PeopleController.cs @@ -895,14 +895,26 @@ public EmployeeWraperFull DeleteProfile() [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 @@ private EmployeeWraperFull SetMemberContacts(string userid, UpdateMemberModel me 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 6465c80bdc7..b1f5874c254 100644 --- a/web/ASC.Web.Core/Sms/SmsManager.cs +++ b/web/ASC.Web.Core/Sms/SmsManager.cs @@ -140,7 +140,7 @@ public void ValidateSmsCode(UserInfo user, string code) 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 2b1e6fe867c..993931efcce 100644 --- a/web/ASC.Web.Core/Sms/SmsProvider.cs +++ b/web/ASC.Web.Core/Sms/SmsProvider.cs @@ -84,9 +84,9 @@ public bool SendMessage(string number, string message) 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 50b287e1f18..b102438855e 100644 --- a/web/ASC.Web.Core/Utility/TenantExtra.cs +++ b/web/ASC.Web.Core/Utility/TenantExtra.cs @@ -207,9 +207,9 @@ public bool UpdatedWithoutLicense { 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 @@ public void DemandControlPanelPermission() 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 fd15c79ec06..9cb9ca2f43a 100644 --- a/web/ASC.Web.Core/WebItemManager.cs +++ b/web/ASC.Web.Core/WebItemManager.cs @@ -261,8 +261,11 @@ public List<IWebItem> GetSubItems(Guid parentItemID) 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 104/105] 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 1eb8f76e883..96730f23dba 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 @@ public File<int> SaveFile(File<int> file, Stream fileStream, bool checkQuota = t 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 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 105/105] 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 | 197 +++++++++--------- .../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, 104 insertions(+), 149 deletions(-) diff --git a/common/ASC.Api.Core/Core/BaseStartup.cs b/common/ASC.Api.Core/Core/BaseStartup.cs index 05ceda2c3d8..e2f50f1c1f2 100644 --- a/common/ASC.Api.Core/Core/BaseStartup.cs +++ b/common/ASC.Api.Core/Core/BaseStartup.cs @@ -23,7 +23,6 @@ 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 e78b469ee0f..92a461f2e7a 100644 --- a/common/ASC.Common/Caching/AscCache.cs +++ b/common/ASC.Common/Caching/AscCache.cs @@ -30,8 +30,6 @@ 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 a7adf92428e..2b268f8bd11 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 27cd20b1a79..f83815f3b33 100644 --- a/common/ASC.Core.Common/Billing/CouponManager.cs +++ b/common/ASC.Core.Common/Billing/CouponManager.cs @@ -28,7 +28,6 @@ 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 859128a9818..8f8df79c714 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 7b7fc291dac..cba8c9fe174 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 8961e34aa53..5767129aad9 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 da2395908b0..d9315cac805 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 64abdee234b..af0f64580ed 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.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 83647816c84..dd735303c9c 100644 --- a/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs +++ b/common/ASC.Data.Backup.Core/Storage/BackupRepository.cs @@ -30,7 +30,6 @@ 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 c52d3835457..9f3b0b9d0c1 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 bc8c334827b..45e32aa25b3 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.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 fbe9944c0ba..38ed2fc4315 100644 --- a/common/services/ASC.TelegramService/Startup.cs +++ b/common/services/ASC.TelegramService/Startup.cs @@ -30,9 +30,6 @@ 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 be3045ec18a..79d57f77b52 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.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 cccc309a715..32f1fbaa4a2 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 02d8606e3bc..2cb3ce33790 100644 --- a/products/ASC.Files/Core/Services/DocumentService/Configuration.cs +++ b/products/ASC.Files/Core/Services/DocumentService/Configuration.cs @@ -681,7 +681,7 @@ internal void SetConfiguration(Configuration<T> configuration) Logo.SetConfiguration(_configuration); } - private string _gobackUrl; + //private string _gobackUrl; public bool IsRetina { get; set; } = false; @@ -726,13 +726,13 @@ public GobackConfig Goback { 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 2dc17ce56b8..4c4ff246211 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.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 05b05f562fa..7b3b69b09f2 100644 --- a/products/ASC.Files/Core/Utils/EntryManager.cs +++ b/products/ASC.Files/Core/Utils/EntryManager.cs @@ -28,10 +28,8 @@ 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 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 @@ public class EntryManager 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 @@ public EntryManager( FilesIntegration filesIntegration, FileMarker fileMarker, FileUtility fileUtility, - Global global, GlobalStore globalStore, CoreBaseSettings coreBaseSettings, FilesSettingsHelper filesSettingsHelper, @@ -307,7 +301,6 @@ public EntryManager( FilesIntegration = filesIntegration; FileMarker = fileMarker; FileUtility = fileUtility; - Global = global; GlobalStore = globalStore; CoreBaseSettings = coreBaseSettings; FilesSettingsHelper = filesSettingsHelper; @@ -347,99 +340,99 @@ public IEnumerable<FileEntry> GetEntries<T>(Folder<T> parent, int from, int coun //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; - - 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); - - responseApi = JObject.Parse(""); //Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET")))); - - var responseData = responseApi["response"]; - - 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>()); - - 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()); - - 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)); - } - } - - 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); - - folders.RemoveAll(folder => rootKeys.Contains(folder.ID)); - - 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; - }); - - 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)); - } - } - - CalculateTotal(); + //const string responseBody = null;// apiServer.GetApiResponse(apiUrl, "GET"); + //if (responseBody != null) + //{ + // JObject responseApi; + + // 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); + + // responseApi = JObject.Parse(""); //Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET")))); + + // var responseData = responseApi["response"]; + + // 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>()); + + // 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()); + + // 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)); + // } + // } + + // 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); + + // folders.RemoveAll(folder => rootKeys.Contains(folder.ID)); + + // 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; + // }); + + // 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)); + // } + //} + + //CalculateTotal(); } else if (parent.FolderType == FolderType.SHARE) { @@ -595,11 +588,11 @@ public IEnumerable<Folder<string>> GetThirpartyFolders<T>(Folder<T> parent, stri 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 5efc0905eb6..52bd9db9adc 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 57bd7c9b163..e6b321652a3 100644 --- a/products/ASC.Files/Server/Startup.cs +++ b/products/ASC.Files/Server/Startup.cs @@ -13,9 +13,6 @@ 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 48ef826a499..4d901c9782e 100644 --- a/products/ASC.Files/Service/Thumbnail/Builder.cs +++ b/products/ASC.Files/Service/Thumbnail/Builder.cs @@ -19,7 +19,6 @@ 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 @@ internal class BuilderQueue<T> { 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 f8330ef99f9..46a6f62cc7d 100644 --- a/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs +++ b/products/ASC.Files/Service/Thumbnail/FileDataProvider.cs @@ -23,7 +23,6 @@ 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 31d8e6196b9..77b01317d77 100644 --- a/products/ASC.People/Server/Startup.cs +++ b/products/ASC.People/Server/Startup.cs @@ -7,12 +7,9 @@ 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 506ad7912be..aa24156847c 100644 --- a/web/ASC.Web.Core/Files/DocumentService.cs +++ b/web/ASC.Web.Core/Files/DocumentService.cs @@ -41,7 +41,6 @@ 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 de0cce7a79c..4f62fb6ce22 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 e0f94d0fe83..4f643d32f44 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 a2c2023ceeb..887a0392374 100644 --- a/web/ASC.Web.Studio/Startup.cs +++ b/web/ASC.Web.Studio/Startup.cs @@ -12,9 +12,6 @@ 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