Merge branch 'feature/virtual-rooms-1.2' of github.com:ONLYOFFICE/AppServer into feature/virtual-rooms-1.2

This commit is contained in:
Vlada Gazizova 2022-02-09 10:32:41 +03:00
commit 85a8c7b75b
506 changed files with 4778 additions and 4760 deletions

View File

@ -53,7 +53,7 @@ namespace ASC.Api.Core.Auth
{ {
return SecurityContext.IsAuthenticated return SecurityContext.IsAuthenticated
? Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name))) ? 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; EmailValidationKeyProvider.ValidationResult checkKeyResult;
@ -105,14 +105,14 @@ namespace ASC.Api.Core.Auth
var result = checkKeyResult switch var result = checkKeyResult switch
{ {
EmailValidationKeyProvider.ValidationResult.Ok => AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)), 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); return Task.FromResult(result);
} }
} }
public class ConfirmAuthHandlerExtension public static class ConfirmAuthHandlerExtension
{ {
public static void Register(DIHelper services) public static void Register(DIHelper services)
{ {

View File

@ -50,7 +50,7 @@ namespace ASC.Api.Core.Auth
return Task.FromResult( return Task.FromResult(
result ? result ?
AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)) : AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), Scheme.Name)) :
AuthenticateResult.Fail(new AuthenticationException(HttpStatusCode.Unauthorized.ToString())) AuthenticateResult.Fail(new AuthenticationException(nameof(HttpStatusCode.Unauthorized)))
); );
} }
} }

View File

@ -41,8 +41,8 @@ namespace ASC.Api.Core
{ {
private static int MaxCount = 1000; private static int MaxCount = 1000;
public IHttpContextAccessor HttpContextAccessor { get; set; } public IHttpContextAccessor HttpContextAccessor { get; set; }
public Tenant tenant; private Tenant _tenant;
public Tenant Tenant { get { return tenant ??= TenantManager.GetCurrentTenant(HttpContextAccessor?.HttpContext); } } public Tenant Tenant { get { return _tenant ??= TenantManager.GetCurrentTenant(HttpContextAccessor?.HttpContext); } }
public ApiContext(IHttpContextAccessor httpContextAccessor, SecurityContext securityContext, TenantManager tenantManager) public ApiContext(IHttpContextAccessor httpContextAccessor, SecurityContext securityContext, TenantManager tenantManager)
{ {

View File

@ -37,7 +37,7 @@ using ASC.Core;
namespace ASC.Api.Core namespace ASC.Api.Core
{ {
[TypeConverter(typeof(ApiDateTimeTypeConverter))] [TypeConverter(typeof(ApiDateTimeTypeConverter))]
public class ApiDateTime : IComparable<ApiDateTime>, IComparable public sealed class ApiDateTime : IComparable<ApiDateTime>, IComparable
{ {
internal static readonly string[] Formats = new[] internal static readonly string[] Formats = new[]
{ {
@ -88,7 +88,7 @@ namespace ASC.Api.Core
public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tenantManager, TimeZoneConverter timeZoneConverter) public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tenantManager, TimeZoneConverter timeZoneConverter)
{ {
if (string.IsNullOrEmpty(data)) throw new ArgumentNullException("data"); if (string.IsNullOrEmpty(data)) throw new ArgumentNullException(nameof(data));
if (data.Length < 7) throw new ArgumentException("invalid date time format"); if (data.Length < 7) throw new ArgumentException("invalid date time format");
@ -97,7 +97,7 @@ namespace ASC.Api.Core
{ {
//Parse time //Parse time
var tzOffset = TimeSpan.Zero; 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); return new ApiDateTime(dateTime, tzOffset);
} }
@ -251,7 +251,7 @@ namespace ASC.Api.Core
{ {
if (obj is null) return false; if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(ApiDateTime)) return false; if (!(obj is ApiDateTime)) return false;
return Equals((ApiDateTime)obj); return Equals((ApiDateTime)obj);
} }

View File

@ -23,7 +23,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Mvc.Authorization;
@ -68,6 +67,7 @@ namespace ASC.Api.Core
services.AddCustomHealthCheck(Configuration); services.AddCustomHealthCheck(Configuration);
services.AddHttpContextAccessor(); services.AddHttpContextAccessor();
services.AddMemoryCache(); services.AddMemoryCache();
services.AddHttpClient();
if (AddAndUseSession) if (AddAndUseSession)
services.AddSession(); services.AddSession();
@ -131,7 +131,7 @@ namespace ASC.Api.Core
DIHelper.RegisterProducts(Configuration, HostEnvironment.ContentRootPath); DIHelper.RegisterProducts(Configuration, HostEnvironment.ContentRootPath);
} }
var builder = services.AddMvcCore(config => services.AddMvcCore(config =>
{ {
config.Conventions.Add(new ControllerNameAttributeConvention()); config.Conventions.Add(new ControllerNameAttributeConvention());

View File

@ -24,7 +24,7 @@ namespace ASC.Api.Core.Core
var connectionString = configurationExtension.GetConnectionStrings("default"); 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, hcBuilder.AddMySql(connectionString.ConnectionString,
name: "mysqldb", name: "mysqldb",
@ -32,7 +32,7 @@ namespace ASC.Api.Core.Core
); );
} }
if (String.Compare(connectionString.ProviderName, "Npgsql") == 0) if (string.Equals(connectionString.ProviderName, "Npgsql"))
{ {
hcBuilder.AddNpgSql(connectionString.ConnectionString, hcBuilder.AddNpgSql(connectionString.ConnectionString,
name: "postgredb", name: "postgredb",

View File

@ -103,16 +103,16 @@ namespace ASC.Api.Core.Middleware
if (!string.IsNullOrEmpty(url)) if (!string.IsNullOrEmpty(url))
{ {
var module = url.Split('/')[0]; 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; return default;
} }

View File

@ -34,7 +34,7 @@ namespace ASC.Api.Core.Middleware
if (tenant == null) if (tenant == null)
{ {
context.Result = new StatusCodeResult((int)HttpStatusCode.NotFound); context.Result = new StatusCodeResult((int)HttpStatusCode.NotFound);
log.WarnFormat("Tenant {0} not found", tenant.TenantId); log.WarnFormat("Current tenant not found");
return; return;
} }

View File

@ -262,7 +262,7 @@ namespace ASC.Web.Api.Models
{ {
var listAdminModules = userInfo.GetListAdminModules(WebItemSecurity); var listAdminModules = userInfo.GetListAdminModules(WebItemSecurity);
if (listAdminModules.Any()) if (listAdminModules.Count > 0)
result.ListAdminModules = listAdminModules; result.ListAdminModules = listAdminModules;
} }
@ -283,7 +283,7 @@ namespace ASC.Web.Api.Models
} }
} }
if (contacts.Any()) if (contacts.Count > 0)
{ {
employeeWraperFull.Contacts = contacts; employeeWraperFull.Contacts = contacts;
} }

View File

@ -10,7 +10,7 @@ namespace ASC.Web.Api.Routing
public bool Check { get; set; } public bool Check { get; set; }
public bool DisableFormat { 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}" : "")}") : base(new List<string>() { method }, $"[controller]{(template != null ? $"/{template}" : "")}")
{ {
Check = check; Check = check;

View File

@ -30,8 +30,6 @@ using System.Linq;
using System.Runtime.Caching; using System.Runtime.Caching;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Google.Protobuf;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
namespace ASC.Common.Caching namespace ASC.Common.Caching
@ -55,7 +53,7 @@ namespace ASC.Common.Caching
public static void OnClearCache() 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) foreach (var k in keys)
{ {
@ -114,7 +112,7 @@ namespace ASC.Common.Caching
public void Remove(Regex pattern) public void Remove(Regex pattern)
{ {
var copy = MemoryCacheKeys.ToDictionary(p => p.Key, p => p.Value); var copy = MemoryCacheKeys.ToDictionary(p => p.Key, p => p.Value);
var keys = copy.Select(p => p.Key).Where(k => pattern.IsMatch(k)).ToArray(); var keys = copy.Select(p => p.Key).Where(k => pattern.IsMatch(k));
foreach (var key in keys) foreach (var key in keys)
{ {

View File

@ -89,7 +89,7 @@ namespace ASC.Collections
protected string BuildKey(string key, string rootkey) 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); protected abstract object GetObjectFromCache(string fullKey);
@ -106,7 +106,7 @@ namespace ASC.Collections
protected virtual bool FitsCondition(object cached) 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) public virtual T Get(string rootkey, string key, Func<T> defaults)

View File

@ -29,7 +29,7 @@ namespace ASC.Collections
{ {
public sealed class HttpRequestDictionary<T> : CachedDictionaryBase<T> public sealed class HttpRequestDictionary<T> : CachedDictionaryBase<T>
{ {
private class CachedItem private sealed class CachedItem
{ {
internal T Value { get; set; } internal T Value { get; set; }

View File

@ -97,14 +97,14 @@ namespace ASC.Common
public Type Service { get; } public Type Service { get; }
public Type Additional { get; set; } public Type Additional { get; set; }
public DIAttribute() { } protected DIAttribute() { }
public DIAttribute(Type service) protected DIAttribute(Type service)
{ {
Service = service; Service = service;
} }
public DIAttribute(Type service, Type implementation) protected DIAttribute(Type service, Type implementation)
{ {
Implementation = implementation; Implementation = implementation;
Service = service; Service = service;
@ -233,7 +233,7 @@ namespace ASC.Common
} }
else else
{ {
Type c = null; Type c;
var a1 = a.GetGenericTypeDefinition(); var a1 = a.GetGenericTypeDefinition();
var b = a.GetGenericArguments().FirstOrDefault(); var b = a.GetGenericArguments().FirstOrDefault();
@ -297,7 +297,7 @@ namespace ASC.Common
} }
else else
{ {
Type c = null; Type c;
var a1 = a.GetGenericTypeDefinition(); var a1 = a.GetGenericTypeDefinition();
var b = a.GetGenericArguments().FirstOrDefault(); var b = a.GetGenericArguments().FirstOrDefault();

View File

@ -27,22 +27,26 @@
using System; using System;
using System.IO; using System.IO;
public static class StreamExtension
{
public const int BufferSize = 2048; //NOTE: set to 2048 to fit in minimum tcp window
public static void StreamCopyTo(this Stream srcStream, Stream dstStream, int length)
{
if (srcStream == null) throw new ArgumentNullException("srcStream");
if (dstStream == null) throw new ArgumentNullException("dstStream");
var buffer = new byte[BufferSize]; namespace ASC.Common.Data
int totalRead = 0; {
int readed; public static class StreamExtension
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); if (srcStream == null) throw new ArgumentNullException(nameof(srcStream));
totalRead += readed; if (dstStream == null) throw new ArgumentNullException(nameof(dstStream));
}
} var buffer = new byte[BufferSize];
} int totalRead = 0;
int readed;
while ((readed = srcStream.Read(buffer, 0, length - totalRead > BufferSize ? BufferSize : length - totalRead)) > 0 && totalRead < length)
{
dstStream.Write(buffer, 0, readed);
totalRead += readed;
}
}
}
}

View File

@ -32,7 +32,7 @@ namespace ASC.Common
public Stream GetBuffered(Stream srcStream) 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) if (!srcStream.CanSeek || srcStream.CanTimeout)
{ {
//Buffer it //Buffer it

View File

@ -120,7 +120,7 @@ namespace ASC.Common.DependencyInjection
void LoadAssembly(string type) void LoadAssembly(string type)
{ {
var dll = type.Substring(type.IndexOf(",") + 1).Trim(); var dll = type.Substring(type.IndexOf(',') + 1).Trim();
var path = GetFullPath(dll); var path = GetFullPath(dll);
if (!string.IsNullOrEmpty(path)) if (!string.IsNullOrEmpty(path))

View File

@ -875,7 +875,7 @@ namespace ASC.Common.Logging
} }
} }
public class LoggerExtension<T> where T : class, ILog, new() public static class LoggerExtension<T> where T : class, ILog, new()
{ {
public static void RegisterLog(DIHelper services) public static void RegisterLog(DIHelper services)
{ {
@ -883,11 +883,11 @@ namespace ASC.Common.Logging
} }
} }
public class LogNLogExtension : LoggerExtension<LogNLog> public static class LogNLogExtension
{ {
public static void Register(DIHelper services) public static void Register(DIHelper services)
{ {
RegisterLog(services); LoggerExtension<LogNLog>.RegisterLog(services);
} }
} }
} }

View File

@ -53,10 +53,8 @@ namespace ASC.Common.Logging
const string key = "cleanPeriod"; 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)) if (variable != null && !string.IsNullOrEmpty(variable.Text))
{ {
int.TryParse(variable.Text, out value); int.TryParse(variable.Text, out value);
@ -111,7 +109,7 @@ namespace ASC.Common.Logging
{ {
Exception = err, Exception = err,
Level = LogLevel.Error, 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" LoggerName = "SelfCleaningTarget"
}); });
} }

View File

@ -49,7 +49,7 @@ namespace ASC.Common.Logging
var args = Environment.CommandLine.Split(' '); var args = Environment.CommandLine.Split(' ');
for (var i = 0; i < args.Length - 1; i++) 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]; result = args[i + 1];
} }

View File

@ -44,8 +44,7 @@ namespace ASC.Common.Mapping
var types = assembly.GetExportedTypes() var types = assembly.GetExportedTypes()
.Where(t => t.GetInterfaces().Any(i => .Where(t => t.GetInterfaces().Any(i =>
i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>))) i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>)));
.ToList();
foreach (var type in types) foreach (var type in types)
{ {

View File

@ -30,8 +30,8 @@ namespace ASC.Common.Security
{ {
public class AscRandom : Random public class AscRandom : Random
{ {
private int inext; private int _inext;
private int inextp; private int _inextp;
private const int MBIG = int.MaxValue; private const int MBIG = int.MaxValue;
private const int MSEED = 161803398; private const int MSEED = 161803398;
private const int MZ = 0; private const int MZ = 0;
@ -51,7 +51,7 @@ namespace ASC.Common.Security
var num3 = 1; var num3 = 1;
for (var i = 1; i < seeds.Length - 1; i++) for (var i = 1; i < seeds.Length - 1; i++)
{ {
var index = (21 * i) % (seeds.Length - 1); var index = 21 * i % (seeds.Length - 1);
seeds[index] = num3; seeds[index] = num3;
num3 = num2 - num3; num3 = num2 - num3;
if (num3 < 0) if (num3 < 0)
@ -71,8 +71,8 @@ namespace ASC.Common.Security
} }
} }
} }
inext = 0; _inext = 0;
inextp = 21; _inextp = 21;
} }
public override int Next(int maxValue) public override int Next(int maxValue)
@ -96,8 +96,8 @@ namespace ASC.Common.Security
private int InternalSample() private int InternalSample()
{ {
var inext = this.inext; var inext = this._inext;
var inextp = this.inextp; var inextp = this._inextp;
if (++inext >= seeds.Length - 1) if (++inext >= seeds.Length - 1)
{ {
inext = 1; inext = 1;
@ -116,8 +116,8 @@ namespace ASC.Common.Security
num += int.MaxValue; num += int.MaxValue;
} }
seeds[inext] = num; seeds[inext] = num;
this.inext = inext; this._inext = inext;
this.inextp = inextp; this._inextp = inextp;
return num; return num;
} }
} }

View File

@ -28,6 +28,7 @@
using System; using System;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Text;
#endregion #endregion
@ -95,30 +96,27 @@ namespace ASC.Common.Security.Authorizing
if (denyActions == null || denyActions.Length == 0) throw new ArgumentNullException(nameof(denyActions)); if (denyActions == null || denyActions.Length == 0) throw new ArgumentNullException(nameof(denyActions));
if (actions.Length != denySubjects.Length || actions.Length != denyActions.Length) if (actions.Length != denySubjects.Length || actions.Length != denyActions.Length)
throw new ArgumentException(); throw new ArgumentException();
var reasons = "";
var sb = new StringBuilder();
for (var i = 0; i < actions.Length; i++) for (var i = 0; i < actions.Length; i++)
{ {
var reason = ""; var action = actions[i];
if (denySubjects[i] != null && denyActions[i] != null) var denyAction = denyActions[i];
reason = string.Format("{0}:{1} access denied {2}.", var denySubject = denySubjects[i];
actions[i].Name,
(denySubjects[i] is IRole ? "role:" : "") + denySubjects[i].Name, string reason;
denyActions[i].Name if (denySubject != null && denyAction != null)
); reason = $"{action.Name}:{(denySubject is IRole ? "role:" : "") + denySubject.Name} access denied {denyAction.Name}.";
else else
reason = string.Format("{0}: access denied.", actions[i].Name); reason = $"{action.Name}: access denied.";
if (i != actions.Length - 1) if (i != actions.Length - 1)
reason += ", "; reason += ", ";
reasons += reason; sb.Append(reason);
} }
var reasons = sb.ToString();
var sactions = ""; var sactions = "";
Array.ForEach(actions, action => { sactions += action.ToString() + ", "; }); Array.ForEach(actions, action => { sactions += action.ToString() + ", "; });
var message = string.Format( var message = $"\"{(subject is IRole ? "role:" : "") + subject.Name}\" access denied \"{sactions}\". Cause: {reasons}.";
"\"{0}\" access denied \"{1}\". Cause: {2}.",
(subject is IRole ? "role:" : "") + subject.Name,
sactions,
reasons
);
return message; return message;
} }
} }

View File

@ -28,7 +28,7 @@ using System;
namespace ASC.Common.Security.Authorizing 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"); public static readonly Role Admin = new Role(new Guid("cd84e66b-b803-40fc-99f9-b2969a54a1de"), "Admin");

View File

@ -75,7 +75,7 @@ namespace ASC.Common.Security.Authorizing
public override string ToString() public override string ToString()
{ {
return string.Format("Role: {0}", Name); return $"Role: {Name}";
} }
} }
} }

View File

@ -30,7 +30,7 @@ using System.Text;
namespace ASC.Security.Cryptography namespace ASC.Security.Cryptography
{ {
public sealed class Hasher public static class Hasher
{ {
private const HashAlg DefaultAlg = HashAlg.SHA256; private const HashAlg DefaultAlg = HashAlg.SHA256;

View File

@ -55,7 +55,7 @@ namespace ASC.Common.Threading
} }
protected set protected set
{ {
DistributedTaskCache.Id = value?.ToString() ?? ""; DistributedTaskCache.Id = value ?? "";
} }
} }

View File

@ -135,7 +135,7 @@ namespace ASC.Common.Threading
public class DistributedTaskQueue public class DistributedTaskQueue
{ {
public static readonly int InstanceId; public static readonly int InstanceId = Process.GetCurrentProcess().Id;
private string key; private string key;
private TaskScheduler Scheduler { get; set; } = TaskScheduler.Default; private TaskScheduler Scheduler { get; set; } = TaskScheduler.Default;
@ -157,12 +157,6 @@ namespace ASC.Common.Threading
public DistributedTaskCacheNotify DistributedTaskCacheNotify { get; set; } public DistributedTaskCacheNotify DistributedTaskCacheNotify { get; set; }
static DistributedTaskQueue()
{
InstanceId = Process.GetCurrentProcess().Id;
}
public void QueueTask(DistributedTaskProgress taskProgress) public void QueueTask(DistributedTaskProgress taskProgress)
{ {
QueueTask((a, b) => taskProgress.RunJob(), taskProgress); QueueTask((a, b) => taskProgress.RunJob(), taskProgress);
@ -238,7 +232,7 @@ namespace ASC.Common.Threading
using var scope = ServiceProvider.CreateScope(); using var scope = ServiceProvider.CreateScope();
var task = scope.ServiceProvider.GetService<T>(); var task = scope.ServiceProvider.GetService<T>();
task.DistributedTaskCache = cache; task.DistributedTaskCache = cache;
if (task != null && task.Publication == null) if (task.Publication == null)
{ {
task.Publication = GetPublication(); task.Publication = GetPublication();
} }
@ -255,7 +249,7 @@ namespace ASC.Common.Threading
{ {
var task = new DistributedTask(); var task = new DistributedTask();
task.DistributedTaskCache = cache; task.DistributedTaskCache = cache;
if (task != null && task.Publication == null) if (task.Publication == null)
{ {
task.Publication = GetPublication(); task.Publication = GetPublication();
} }

View File

@ -101,7 +101,7 @@ namespace ASC.Common.Utils
var dnsMessage = GetDnsMessage(domainName); var dnsMessage = GetDnsMessage(domainName);
return dnsMessage.AnswerRecords.Any(); return dnsMessage.AnswerRecords.Count != 0;
} }
/// <summary> /// <summary>

View File

@ -102,9 +102,9 @@ namespace ASC.Common.Utils
{ {
if (string.IsNullOrEmpty(searchText) || string.IsNullOrEmpty(htmlText)) return htmlText; 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); 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) + "'>" + m.Value + "</span>");
} }
} }
} }

View File

@ -186,7 +186,7 @@ namespace System.Web
} }
const StringComparison cmp = StringComparison.OrdinalIgnoreCase; 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); s = Uri.UriSchemeHttp + s.Substring(1);
} }
@ -194,7 +194,7 @@ namespace System.Web
{ {
s = Uri.UriSchemeHttp + s.Substring(3); 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); s = Uri.UriSchemeHttps + s.Substring(1);
} }

View File

@ -37,7 +37,7 @@ using Formatting = Newtonsoft.Json.Formatting;
namespace ASC.Web.Core.Files namespace ASC.Web.Core.Files
{ {
public class JsonWebToken public static class JsonWebToken
{ {
public static string Encode(object payload, string key) public static string Encode(object payload, string key)
{ {

View File

@ -66,7 +66,7 @@ namespace ASC.Common.Utils
private static string ToSmtpAddress(string address, string displayName) private static string ToSmtpAddress(string address, string displayName)
{ {
return string.Format("\"{0}\" <{1}>", displayName, address); return $"\"{displayName}\" <{address}>";
} }
} }
} }

View File

@ -24,7 +24,7 @@
*/ */
using System; using System.Security.Cryptography;
using System.Text; using System.Text;
namespace ASC.Common.Utils namespace ASC.Common.Utils
@ -35,10 +35,9 @@ namespace ASC.Common.Utils
{ {
const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var res = new StringBuilder(); var res = new StringBuilder();
var rnd = new Random();
while (0 < length--) while (0 < length--)
{ {
res.Append(valid[rnd.Next(valid.Length)]); res.Append(valid[RandomNumberGenerator.GetInt32(valid.Length)]);
} }
return res.ToString(); return res.ToString();
} }

View File

@ -122,7 +122,7 @@ namespace ASC.Common.Utils
if (mapZone != null) if (mapZone != null)
return mapZone.WindowsTimeZoneId; return mapZone.WindowsTimeZoneId;
Log.Error(string.Format("OlsonTimeZone {0} not found", olsonTimeZoneId)); Log.Error("OlsonTimeZone " + olsonTimeZoneId + " not found");
return defaultIfNoMatch ? "UTC" : null; return defaultIfNoMatch ? "UTC" : null;
} }
@ -139,7 +139,7 @@ namespace ASC.Common.Utils
if (mapZone != null) if (mapZone != null)
return mapZone.OlsonTimeZoneId; return mapZone.OlsonTimeZoneId;
Log.Error(string.Format("WindowsTimeZone {0} not found", windowsTimeZoneId)); Log.Error("WindowsTimeZone " + windowsTimeZoneId + " not found");
return defaultIfNoMatch ? "Etc/GMT" : null; return defaultIfNoMatch ? "Etc/GMT" : null;
} }

View File

@ -58,7 +58,7 @@ namespace ASC.Common.Utils
} }
} }
public class VelocityFormatter public static class VelocityFormatter
{ {
private static bool initialized; private static bool initialized;
private static readonly ConcurrentDictionary<string, Template> patterns = new ConcurrentDictionary<string, Template>(); private static readonly ConcurrentDictionary<string, Template> patterns = new ConcurrentDictionary<string, Template>();

View File

@ -51,8 +51,8 @@ namespace ASC.Common.Utils
{ {
var offsetInput = 0; var offsetInput = 0;
var isAsterix = false; var isAsterix = false;
int i; int i = 0;
for (i = 0; i < pattern.Length;) while (i < pattern.Length)
{ {
switch (pattern[i]) switch (pattern[i])
{ {
@ -98,7 +98,7 @@ namespace ASC.Common.Utils
while (i < pattern.Length && pattern[i] == '*') while (i < pattern.Length && pattern[i] == '*')
++i; ++i;
return (offsetInput == input.Length); return offsetInput == input.Length;
} }
} }
} }

View File

@ -857,7 +857,7 @@ namespace ASC.Common.Web
foreach (DictionaryEntry entry in extensionToMimeMappingTable) foreach (DictionaryEntry entry in extensionToMimeMappingTable)
{ {
var mime = (string)entry.Value; 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.ContainsKey(mime)) continue;
if (mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key; if (mimeSynonyms[mime].Contains(mimeMapping.ToLowerInvariant())) return (string)entry.Key;
} }

View File

@ -2,7 +2,7 @@
namespace ASC.Common.Web namespace ASC.Common.Web
{ {
public class VirtualPathUtility public static class VirtualPathUtility
{ {
public static string ToAbsolute(string virtualPath) public static string ToAbsolute(string virtualPath)
{ {

View File

@ -56,6 +56,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="MailKit" Version="3.1.1" /> <PackageReference Include="MailKit" Version="3.1.1" />
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.3" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.3" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" /> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" />
<PackageReference Include="Telegram.Bot" Version="15.7.1" /> <PackageReference Include="Telegram.Bot" Version="15.7.1" />

View File

@ -90,6 +90,9 @@ namespace ASC.Core.Common
if (HttpContextAccessor?.HttpContext?.Request != null) if (HttpContextAccessor?.HttpContext?.Request != null)
{ {
var u = HttpContextAccessor?.HttpContext.Request.GetUrlRewriter(); var u = HttpContextAccessor?.HttpContext.Request.GetUrlRewriter();
if (u == null) throw new ArgumentNullException("u");
uriBuilder = new UriBuilder(u.Scheme, LOCALHOST, u.Port); uriBuilder = new UriBuilder(u.Scheme, LOCALHOST, u.Port);
} }
_serverRoot = uriBuilder; _serverRoot = uriBuilder;
@ -125,6 +128,9 @@ namespace ASC.Core.Common
if (HttpContextAccessor?.HttpContext?.Request != null) if (HttpContextAccessor?.HttpContext?.Request != null)
{ {
var u = HttpContextAccessor?.HttpContext?.Request.GetUrlRewriter(); var u = HttpContextAccessor?.HttpContext?.Request.GetUrlRewriter();
if (u == null) throw new ArgumentNullException("u");
result = new UriBuilder(u.Scheme, u.Host, u.Port); result = new UriBuilder(u.Scheme, u.Host, u.Port);
if (CoreBaseSettings.Standalone && !result.Uri.IsLoopback) if (CoreBaseSettings.Standalone && !result.Uri.IsLoopback)
@ -179,7 +185,7 @@ namespace ASC.Core.Common
virtualPath.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) virtualPath.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
return virtualPath; return virtualPath;
if (string.IsNullOrEmpty(virtualPath) || virtualPath.StartsWith("/")) if (virtualPath.StartsWith('/'))
{ {
return ServerRootPath + virtualPath; return ServerRootPath + virtualPath;
} }
@ -193,7 +199,7 @@ namespace ASC.Core.Common
return VirtualPathUtility.ToAbsolute(virtualPath); return VirtualPathUtility.ToAbsolute(virtualPath);
} }
if (string.IsNullOrEmpty(virtualPath) || virtualPath.StartsWith("/")) if (string.IsNullOrEmpty(virtualPath) || virtualPath.StartsWith('/'))
{ {
return virtualPath; return virtualPath;
} }
@ -211,7 +217,7 @@ namespace ASC.Core.Common
if (string.IsNullOrEmpty(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 else
{ {

View File

@ -53,6 +53,8 @@ namespace ASC.Core.Billing
private const int AvangatePaymentSystemId = 1; private const int AvangatePaymentSystemId = 1;
static readonly HttpClient HttpClient = new HttpClient();
public BillingClient(IConfiguration configuration) public BillingClient(IConfiguration configuration)
: this(false, configuration) : this(false, configuration)
@ -159,13 +161,21 @@ namespace ASC.Core.Billing
string url; string url;
var paymentUrl = (Uri)null; var paymentUrl = (Uri)null;
var upgradeUrl = (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); urls[p] = Tuple.Create(paymentUrl, upgradeUrl);
} }
@ -176,7 +186,7 @@ namespace ASC.Core.Billing
{ {
if (productIds == null) if (productIds == null)
{ {
throw new ArgumentNullException("productIds"); throw new ArgumentNullException(nameof(productIds));
} }
var parameters = productIds.Select(pid => Tuple.Create("ProductId", pid)).ToList(); var parameters = productIds.Select(pid => Tuple.Create("ProductId", pid)).ToList();
@ -185,15 +195,13 @@ namespace ASC.Core.Billing
var result = Request("GetProductsPrices", null, parameters.ToArray()); var result = Request("GetProductsPrices", null, parameters.ToArray());
var prices = JsonSerializer.Deserialize<Dictionary<int, Dictionary<string, Dictionary<string, decimal>>>>(result); 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 => 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>() }; return new { ProductId = productId, Prices = new Dictionary<string, decimal>() };
}) })
@ -210,7 +218,7 @@ namespace ASC.Core.Billing
{ {
var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss"); var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
var hash = WebEncoders.Base64UrlEncode(hasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("\n", now, pkey)))); 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;
} }
} }
@ -226,8 +234,7 @@ namespace ASC.Core.Billing
request.Headers.Add("Authorization", CreateAuthToken(_billingKey, _billingSecret)); 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>>(); var data = new Dictionary<string, List<string>>();
if (!string.IsNullOrEmpty(portalId)) if (!string.IsNullOrEmpty(portalId))
@ -250,7 +257,7 @@ namespace ASC.Core.Billing
request.Content = new StringContent(body, Encoding.UTF8, "application/json"); request.Content = new StringContent(body, Encoding.UTF8, "application/json");
string result; string result;
using (var response = httpClient.Send(request)) using (var response = HttpClient.Send(request))
using (var stream = response.Content.ReadAsStream()) using (var stream = response.Content.ReadAsStream())
{ {
if (stream == null) if (stream == null)
@ -272,7 +279,7 @@ namespace ASC.Core.Billing
return result; 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 => p.Item1 + ": " + p.Item2);
var info = new { Method = method, PortalId = portalId, Params = string.Join(", ", @params) }; var info = new { Method = method, PortalId = portalId, Params = string.Join(", ", @params) };
if (result.Contains("{\"Message\":\"error: cannot find ")) if (result.Contains("{\"Message\":\"error: cannot find "))
{ {

View File

@ -28,7 +28,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Configuration; using System.Configuration;
using System.Linq; using System.Linq;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
@ -47,7 +46,8 @@ namespace ASC.Core.Common.Billing
[Singletone] [Singletone]
public class CouponManager 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 IEnumerable<string> Groups { get; set; }
private readonly int Percent; private readonly int Percent;
private readonly int Schedule; private readonly int Schedule;
@ -55,13 +55,15 @@ namespace ASC.Core.Common.Billing
private readonly byte[] Secret; private readonly byte[] Secret;
private readonly Uri BaseAddress; private readonly Uri BaseAddress;
private readonly string ApiVersion; private readonly string ApiVersion;
private readonly SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1); private readonly SemaphoreSlim SemaphoreSlim;
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); SemaphoreSlim = new SemaphoreSlim(1, 1);
Log = option.CurrentValue; Log = option.CurrentValue;
ClientFactory = clientFactory;
try try
{ {
@ -98,7 +100,7 @@ namespace ASC.Core.Common.Billing
{ {
using var httpClient = PrepaireClient(); using var httpClient = PrepaireClient();
using var content = new StringContent(await Promotion.GeneratePromotion(Log, this, tenantManager, Percent, Schedule), Encoding.Default, "application/json"); 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) if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase); throw new Exception(response.ReasonPhrase);
@ -112,24 +114,28 @@ namespace ASC.Core.Common.Billing
Log.Error(ex.Message, ex); Log.Error(ex.Message, ex);
throw; throw;
} }
}
internal Task<IEnumerable<AvangateProduct>> GetProducts()
{
if (Products != null) return Task.FromResult(Products);
return InternalGetProducts();
} }
internal async Task<IEnumerable<AvangateProduct>> GetProducts() private async Task<IEnumerable<AvangateProduct>> InternalGetProducts()
{ {
if (Products != null) return Products;
await SemaphoreSlim.WaitAsync(); await SemaphoreSlim.WaitAsync();
if (Products != null) if (Products != null)
{ {
SemaphoreSlim.Release(); SemaphoreSlim.Release();
return Products; return Products;
} }
try try
{ {
using var httpClient = PrepaireClient(); 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) if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase); throw new Exception(response.ReasonPhrase);
@ -153,9 +159,12 @@ namespace ASC.Core.Common.Billing
private HttpClient PrepaireClient() private HttpClient PrepaireClient()
{ {
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; const string applicationJson = "application/json";
const string applicationJson = "application/json";
using var httpClient = new HttpClient { BaseAddress = BaseAddress, Timeout = TimeSpan.FromMinutes(3) }; var httpClient = ClientFactory.CreateClient();
httpClient.BaseAddress = BaseAddress;
httpClient.Timeout = TimeSpan.FromMinutes(3);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", applicationJson); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", applicationJson);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", applicationJson); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", applicationJson);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("X-Avangate-Authentication", CreateAuthHeader()); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("X-Avangate-Authentication", CreateAuthHeader());
@ -176,9 +185,9 @@ namespace ASC.Core.Common.Billing
} }
var stringBuilder = new StringBuilder(); var stringBuilder = new StringBuilder();
stringBuilder.AppendFormat("code='{0}' ", VendorCode); stringBuilder.Append($"code='{VendorCode}' ");
stringBuilder.AppendFormat("date='{0}' ", date); stringBuilder.Append($"date='{date}' ");
stringBuilder.AppendFormat("hash='{0}'", sBuilder); stringBuilder.Append($"hash='{sBuilder}'");
return stringBuilder.ToString(); return stringBuilder.ToString();
} }
} }

View File

@ -26,7 +26,6 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq;
using ASC.Common; using ASC.Common;
using ASC.Common.Logging; using ASC.Common.Logging;
@ -153,7 +152,7 @@ namespace ASC.Core.Billing
private static void SaveLicense(Stream licenseStream, string path) 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) if (licenseStream.CanSeek)
{ {
@ -189,7 +188,7 @@ namespace ASC.Core.Billing
{ {
license.PortalCount = TenantManager.GetTenantQuota(Tenant.DEFAULT_TENANT).CountPortals; license.PortalCount = TenantManager.GetTenantQuota(Tenant.DEFAULT_TENANT).CountPortals;
} }
var activePortals = TenantManager.GetTenants().Count(); var activePortals = TenantManager.GetTenants().Count;
if (activePortals > 1 && license.PortalCount < activePortals) if (activePortals > 1 && license.PortalCount < activePortals)
{ {
throw new LicensePortalException("License portal count", license.OriginalLicense); throw new LicensePortalException("License portal count", license.OriginalLicense);

View File

@ -239,7 +239,7 @@ namespace ASC.Core.Billing
var quota = QuotaService.GetTenantQuotas().SingleOrDefault(q => q.AvangateId == lastPayment.ProductId); var quota = QuotaService.GetTenantQuotas().SingleOrDefault(q => q.AvangateId == lastPayment.ProductId);
if (quota == null) 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(); var asynctariff = Tariff.CreateDefault();
@ -279,7 +279,7 @@ namespace ASC.Core.Billing
{ {
if (tariff == null) if (tariff == null)
{ {
throw new ArgumentNullException("tariff"); throw new ArgumentNullException(nameof(tariff));
} }
var q = QuotaService.GetTenantQuota(tariff.QuotaId); var q = QuotaService.GetTenantQuota(tariff.QuotaId);
@ -362,7 +362,7 @@ namespace ASC.Core.Billing
var key = tenant.HasValue var key = tenant.HasValue
? GetBillingUrlCacheKey(tenant.Value) ? GetBillingUrlCacheKey(tenant.Value)
: string.Format("notenant{0}", !string.IsNullOrEmpty(affiliateId) ? "_" + affiliateId : ""); : string.Format($"notenant{(!string.IsNullOrEmpty(affiliateId) ? "_" + affiliateId : "")}");
key += quota.Visible ? "" : "0"; key += quota.Visible ? "" : "0";
if (!(Cache.Get<Dictionary<string, Tuple<Uri, Uri>>>(key) is IDictionary<string, Tuple<Uri, Uri>> urls)) if (!(Cache.Get<Dictionary<string, Tuple<Uri, Uri>>>(key) is IDictionary<string, Tuple<Uri, Uri>> urls))
{ {
@ -432,7 +432,7 @@ namespace ASC.Core.Billing
{ {
if (productIds == null) if (productIds == null)
{ {
throw new ArgumentNullException("productIds"); throw new ArgumentNullException(nameof(productIds));
} }
try try
{ {
@ -503,10 +503,10 @@ namespace ASC.Core.Billing
using var tx = CoreDbContext.Database.BeginTransaction(); using var tx = CoreDbContext.Database.BeginTransaction();
// last record is not the same // last record is not the same
var count = CoreDbContext.Tariffs var any = CoreDbContext.Tariffs
.Count(r => r.Tenant == tenant && r.Tariff == tariffInfo.QuotaId && r.Stamp == tariffInfo.DueDate && r.Quantity == tariffInfo.Quantity); .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 var efTariff = new DbTariff
{ {

View File

@ -68,9 +68,9 @@ namespace ASC.Core.Caching
if (r == null) return; if (r == null) return;
var id = r.ObjectId ?? string.Empty; 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);
} }
} }

View File

@ -87,7 +87,7 @@ namespace ASC.Core.Caching
public CachedAzService(DbAzService service, AzServiceCache azServiceCache) public CachedAzService(DbAzService service, AzServiceCache azServiceCache)
{ {
this.service = service ?? throw new ArgumentNullException("service"); this.service = service ?? throw new ArgumentNullException(nameof(service));
Cache = azServiceCache.Cache; Cache = azServiceCache.Cache;
cacheNotify = azServiceCache.CacheNotify; cacheNotify = azServiceCache.CacheNotify;
CacheExpiration = TimeSpan.FromMinutes(10); CacheExpiration = TimeSpan.FromMinutes(10);
@ -100,8 +100,9 @@ namespace ASC.Core.Caching
var aces = Cache.Get<AzRecordStore>(key); var aces = Cache.Get<AzRecordStore>(key);
if (aces == null) if (aces == null)
{ {
var records = service.GetAces(tenant, default); var records = service.GetAces(tenant, default);
Cache.Insert(key, aces = new AzRecordStore(records), DateTime.UtcNow.Add(CacheExpiration)); aces = new AzRecordStore(records);
Cache.Insert(key, aces, DateTime.UtcNow.Add(CacheExpiration));
} }
return aces; return aces;
} }

View File

@ -127,7 +127,7 @@ namespace ASC.Core.Caching
public CachedQuotaService(DbQuotaService service, QuotaServiceCache quotaServiceCache) : this() public CachedQuotaService(DbQuotaService service, QuotaServiceCache quotaServiceCache) : this()
{ {
Service = service ?? throw new ArgumentNullException("service"); Service = service ?? throw new ArgumentNullException(nameof(service));
QuotaServiceCache = quotaServiceCache; QuotaServiceCache = quotaServiceCache;
Cache = quotaServiceCache.Cache; Cache = quotaServiceCache.Cache;
CacheNotify = quotaServiceCache.CacheNotify; CacheNotify = quotaServiceCache.CacheNotify;

View File

@ -114,7 +114,7 @@ namespace ASC.Core.Caching
public CachedSubscriptionService(DbSubscriptionService service, SubscriptionServiceCache subscriptionServiceCache) public CachedSubscriptionService(DbSubscriptionService service, SubscriptionServiceCache subscriptionServiceCache)
{ {
this.service = service ?? throw new ArgumentNullException("service"); this.service = service ?? throw new ArgumentNullException(nameof(service));
cache = subscriptionServiceCache.Cache; cache = subscriptionServiceCache.Cache;
notifyRecord = subscriptionServiceCache.NotifyRecord; notifyRecord = subscriptionServiceCache.NotifyRecord;
notifyMethod = subscriptionServiceCache.NotifyMethod; notifyMethod = subscriptionServiceCache.NotifyMethod;
@ -201,7 +201,8 @@ namespace ASC.Core.Caching
{ {
var records = service.GetSubscriptions(tenant, sourceId, actionId); var records = service.GetSubscriptions(tenant, sourceId, actionId);
var methods = service.GetSubscriptionMethods(tenant, sourceId, actionId, null); 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; return store;
} }

View File

@ -73,8 +73,9 @@ namespace ASC.Core.Caching
{ {
var store = Cache.Get<TenantStore>(KEY); var store = Cache.Get<TenantStore>(KEY);
if (store == null) 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; return store;
} }
@ -204,7 +205,7 @@ namespace ASC.Core.Caching
public CachedTenantService(DbTenantService service, TenantServiceCache tenantServiceCache, ICache cache) : this() public CachedTenantService(DbTenantService service, TenantServiceCache tenantServiceCache, ICache cache) : this()
{ {
this.cache = cache; this.cache = cache;
Service = service ?? throw new ArgumentNullException("service"); Service = service ?? throw new ArgumentNullException(nameof(service));
TenantServiceCache = tenantServiceCache; TenantServiceCache = tenantServiceCache;
CacheNotifyItem = tenantServiceCache.CacheNotifyItem; CacheNotifyItem = tenantServiceCache.CacheNotifyItem;
CacheNotifySettings = tenantServiceCache.CacheNotifySettings; CacheNotifySettings = tenantServiceCache.CacheNotifySettings;
@ -298,8 +299,9 @@ namespace ASC.Core.Caching
var data = cache.Get<byte[]>(cacheKey); var data = cache.Get<byte[]>(cacheKey);
if (data == null) if (data == null)
{ {
data = Service.GetTenantSettings(tenant, key); data = Service.GetTenantSettings(tenant, key);
cache.Insert(cacheKey, data ?? new byte[0], DateTime.UtcNow + SettingsExpiration);
cache.Insert(cacheKey, data ?? Array.Empty<byte>(), DateTime.UtcNow + SettingsExpiration);
} }
return data == null ? null : data.Length == 0 ? null : data; return data == null ? null : data.Length == 0 ? null : data;
} }

View File

@ -207,7 +207,7 @@ namespace ASC.Core.Caching
UserServiceCache userServiceCache UserServiceCache userServiceCache
) : this() ) : this()
{ {
Service = service ?? throw new ArgumentNullException("service"); Service = service ?? throw new ArgumentNullException(nameof(service));
CoreBaseSettings = coreBaseSettings; CoreBaseSettings = coreBaseSettings;
UserServiceCache = userServiceCache; UserServiceCache = userServiceCache;
Cache = userServiceCache.Cache; Cache = userServiceCache.Cache;
@ -322,7 +322,7 @@ namespace ASC.Core.Caching
group = Service.GetGroup(tenant, id); group = Service.GetGroup(tenant, id);
if (group != null) Cache.Insert(key, group, CacheExpiration); if (group != null) Cache.Insert(key, group, CacheExpiration);
}; }
return group; return group;
} }

View File

@ -54,13 +54,13 @@ namespace ASC.Core.Configuration
{ {
using var scope = ServiceProvider.CreateScope(); using var scope = ServiceProvider.CreateScope();
var scopeClass = scope.ServiceProvider.GetService<AmiPublicDnsSyncServiceScope>(); var scopeClass = scope.ServiceProvider.GetService<AmiPublicDnsSyncServiceScope>();
var (tenantManager, coreBaseSettings) = scopeClass; var (tenantManager, coreBaseSettings, clientFactory) = scopeClass;
if (coreBaseSettings.Standalone) if (coreBaseSettings.Standalone)
{ {
var tenants = tenantManager.GetTenants(false).Where(t => MappedDomainNotSettedByUser(t.MappedDomain)); var tenants = tenantManager.GetTenants(false).Where(t => MappedDomainNotSettedByUser(t.MappedDomain));
if (tenants.Any()) if (tenants.Any())
{ {
var dnsname = GetAmiPublicDnsName(); var dnsname = GetAmiPublicDnsName(clientFactory);
foreach (var tenant in tenants.Where(t => !string.IsNullOrEmpty(dnsname) && t.MappedDomain != dnsname)) foreach (var tenant in tenants.Where(t => !string.IsNullOrEmpty(dnsname) && t.MappedDomain != dnsname))
{ {
tenant.MappedDomain = dnsname; tenant.MappedDomain = dnsname;
@ -75,7 +75,7 @@ namespace ASC.Core.Configuration
return string.IsNullOrEmpty(domain) || Regex.IsMatch(domain, "^ec2.+\\.compute\\.amazonaws\\.com$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); 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 try
{ {
@ -83,7 +83,7 @@ namespace ASC.Core.Configuration
request.RequestUri = new Uri("http://169.254.169.254/latest/meta-data/public-hostname"); request.RequestUri = new Uri("http://169.254.169.254/latest/meta-data/public-hostname");
request.Method = HttpMethod.Get; request.Method = HttpMethod.Get;
using var httpClient = new HttpClient(); var httpClient = clientFactory.CreateClient();
httpClient.Timeout = TimeSpan.FromMilliseconds(5000); httpClient.Timeout = TimeSpan.FromMilliseconds(5000);
using var responce = httpClient.Send(request); using var responce = httpClient.Send(request);
@ -106,16 +106,18 @@ namespace ASC.Core.Configuration
{ {
private TenantManager TenantManager { get; } private TenantManager TenantManager { get; }
private CoreBaseSettings CoreBaseSettings { 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; TenantManager = tenantManager;
CoreBaseSettings = coreBaseSettings; 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);
} }
} }
} }

View File

@ -32,7 +32,7 @@ using ASC.Common.Security.Authorizing;
namespace ASC.Core.Configuration namespace ASC.Core.Configuration
{ {
public sealed class Constants public static class Constants
{ {
public static readonly string NotifyEMailSenderSysName = "email.sender"; public static readonly string NotifyEMailSenderSysName = "email.sender";

View File

@ -50,13 +50,13 @@ namespace ASC.Core.Common.Configuration
protected readonly Dictionary<string, string> Props; protected readonly Dictionary<string, string> Props;
public IEnumerable<string> ManagedKeys 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; protected readonly Dictionary<string, string> Additional;
public virtual IEnumerable<string> AdditionalKeys 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; } } public ICollection<string> Keys { get { return AllProps.Keys; } }
@ -88,7 +88,7 @@ namespace ASC.Core.Common.Configuration
public bool IsSet 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() static Consumer()
@ -152,7 +152,7 @@ namespace ASC.Core.Common.Configuration
Props = props ?? new Dictionary<string, string>(); Props = props ?? new Dictionary<string, string>();
Additional = additional ?? 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)); CanSet = props.All(r => string.IsNullOrEmpty(r.Value));
} }
@ -245,10 +245,7 @@ namespace ASC.Core.Common.Configuration
if (string.IsNullOrEmpty(value)) if (string.IsNullOrEmpty(value))
{ {
if (AllProps.ContainsKey(name)) AllProps.TryGetValue(name, out value);
{
value = AllProps[name];
}
} }
return value; return value;
@ -339,7 +336,7 @@ namespace ASC.Core.Common.Configuration
public override IEnumerable<string> AdditionalKeys 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) protected override string GetSettingsKey(string name)
@ -354,9 +351,9 @@ namespace ASC.Core.Common.Configuration
HandlerType = Type.GetType(additional[HandlerTypeKey]); HandlerType = Type.GetType(additional[HandlerTypeKey]);
if (additional.ContainsKey(CdnKey)) if (additional.TryGetValue(CdnKey, out var value))
{ {
Cdn = GetCdn(additional[CdnKey]); Cdn = GetCdn(value);
} }
} }

View File

@ -54,7 +54,7 @@ namespace ASC.Core.Configuration
public bool IsDefaultSettings { get; internal set; } public bool IsDefaultSettings { get; internal set; }
public static SmtpSettings Empty = new SmtpSettings(); public static readonly SmtpSettings Empty = new SmtpSettings();
private SmtpSettings() private SmtpSettings()
{ {
@ -83,17 +83,17 @@ namespace ASC.Core.Configuration
{ {
if (string.IsNullOrEmpty(host)) if (string.IsNullOrEmpty(host))
{ {
throw new ArgumentException("Empty smtp host.", "host"); throw new ArgumentException("Empty smtp host.", nameof(host));
} }
if (string.IsNullOrEmpty(senderAddress)) if (string.IsNullOrEmpty(senderAddress))
{ {
throw new ArgumentException("Empty sender address.", "senderAddress"); throw new ArgumentException("Empty sender address.", nameof(senderAddress));
} }
Host = host; Host = host;
Port = port; Port = port;
SenderAddress = senderAddress; SenderAddress = senderAddress;
SenderDisplayName = senderDisplayName ?? throw new ArgumentNullException("senderDisplayName"); SenderDisplayName = senderDisplayName ?? throw new ArgumentNullException(nameof(senderDisplayName));
} }
public void SetCredentials(string userName, string password) public void SetCredentials(string userName, string password)
@ -105,11 +105,11 @@ namespace ASC.Core.Configuration
{ {
if (string.IsNullOrEmpty(userName)) if (string.IsNullOrEmpty(userName))
{ {
throw new ArgumentException("Empty user name.", "userName"); throw new ArgumentException("Empty user name.", nameof(userName));
} }
if (string.IsNullOrEmpty(password)) if (string.IsNullOrEmpty(password))
{ {
throw new ArgumentException("Empty password.", "password"); throw new ArgumentException("Empty password.", nameof(password));
} }
CredentialsUserName = userName; CredentialsUserName = userName;
CredentialsUserPassword = password; CredentialsUserPassword = password;

View File

@ -100,7 +100,7 @@ namespace ASC.Core
public void RemoveAllAces(ISecurityObjectId id) 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); RemoveAce(r);
} }

View File

@ -43,15 +43,27 @@ namespace ASC.Core
[Singletone] [Singletone]
public class CoreBaseSettings public class CoreBaseSettings
{ {
private bool? standalone; private bool? standalone;
private string basedomain;
private bool? personal; private bool? personal;
private bool? customMode; private bool? customMode;
private IConfiguration Configuration { get; } private IConfiguration Configuration { get; }
public CoreBaseSettings(IConfiguration configuration) public CoreBaseSettings(IConfiguration configuration)
{ {
Configuration = configuration; Configuration = configuration;
}
public string Basedomain
{
get
{
if (basedomain == null)
{
basedomain = Configuration["core:base-domain"] ?? string.Empty;
}
return basedomain;
}
} }
public bool Standalone public bool Standalone
@ -64,13 +76,13 @@ namespace ASC.Core
get get
{ {
//TODO:if (CustomMode && HttpContext.Current != null && HttpContext.Current.Request.SailfishApp()) return true; //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 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)); }
} }
} }
@ -108,31 +120,24 @@ namespace ASC.Core
[Scope(typeof(ConfigureCoreSettings))] [Scope(typeof(ConfigureCoreSettings))]
public class CoreSettings public class CoreSettings
{ {
private string basedomain;
public string BaseDomain public string BaseDomain
{ {
get get
{ {
if (basedomain == null)
{
basedomain = Configuration["core:base-domain"] ?? string.Empty;
}
string result; 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 else
{ {
result = basedomain; result = CoreBaseSettings.Basedomain;
} }
return result; return result;
} }
set set
{ {
if (CoreBaseSettings.Standalone || string.IsNullOrEmpty(basedomain)) if (CoreBaseSettings.Standalone || string.IsNullOrEmpty(CoreBaseSettings.Basedomain))
{ {
SaveSetting("BaseDomain", value); SaveSetting("BaseDomain", value);
} }
@ -162,7 +167,7 @@ namespace ASC.Core
{ {
var baseHost = BaseDomain; var baseHost = BaseDomain;
if (string.IsNullOrEmpty(hostedRegion) || string.IsNullOrEmpty(baseHost) || !baseHost.Contains(".")) if (string.IsNullOrEmpty(hostedRegion) || string.IsNullOrEmpty(baseHost) || baseHost.IndexOf('.') < 0)
{ {
return baseHost; return baseHost;
} }
@ -174,7 +179,7 @@ namespace ASC.Core
{ {
if (string.IsNullOrEmpty(key)) if (string.IsNullOrEmpty(key))
{ {
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
} }
byte[] bytes = null; byte[] bytes = null;
if (value != null) if (value != null)
@ -188,7 +193,7 @@ namespace ASC.Core
{ {
if (string.IsNullOrEmpty(key)) if (string.IsNullOrEmpty(key))
{ {
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
} }
var bytes = TenantService.GetTenantSettings(tenant, key); var bytes = TenantService.GetTenantSettings(tenant, key);
@ -209,8 +214,9 @@ namespace ASC.Core
// thread safe // thread safe
key = GetSetting("PortalId"); key = GetSetting("PortalId");
if (string.IsNullOrEmpty(key)) if (string.IsNullOrEmpty(key))
{ {
SaveSetting("PortalId", key = Guid.NewGuid().ToString()); key = Guid.NewGuid().ToString();
SaveSetting("PortalId", key);
} }
} }
} }

View File

@ -50,15 +50,17 @@ namespace ASC.Core
private readonly string partnerKey; private readonly string partnerKey;
private TenantManager TenantManager { get; } 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; TenantManager = tenantManager;
this.tariffService = tariffService; this.tariffService = tariffService;
Configuration = configuration; Configuration = configuration;
partnerUrl = (Configuration["core:payment:partners"] ?? "https://partners.onlyoffice.com/api").TrimEnd('/'); partnerUrl = (Configuration["core:payment:partners"] ?? "https://partners.onlyoffice.com/api").TrimEnd('/');
partnerKey = (Configuration["core:machinekey"] ?? "C5C1F4E85A3A43F5B3202C24D97351DF"); partnerKey = Configuration["core:machinekey"] ?? "C5C1F4E85A3A43F5B3202C24D97351DF";
ClientFactory = clientFactory;
} }
@ -102,7 +104,7 @@ namespace ASC.Core
{ {
if (string.IsNullOrEmpty(key)) if (string.IsNullOrEmpty(key))
{ {
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
} }
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
@ -112,7 +114,7 @@ namespace ASC.Core
request.Headers.Add("Authorization", GetPartnerAuthHeader(actionUrl)); request.Headers.Add("Authorization", GetPartnerAuthHeader(actionUrl));
request.RequestUri = new Uri(partnerUrl + actionUrl); request.RequestUri = new Uri(partnerUrl + actionUrl);
using var httpClient = new HttpClient(); var httpClient = ClientFactory.CreateClient();
using var response = httpClient.Send(request); using var response = httpClient.Send(request);
@ -133,7 +135,7 @@ namespace ASC.Core
var now = DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture); 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 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))); var hash = WebEncoders.Base64UrlEncode(hasher.ComputeHash(Encoding.UTF8.GetBytes(data)));
return string.Format("ASC :{0}:{1}", now, hash); return $"ASC :{now}:{hash}";
} }
} }

View File

@ -42,19 +42,13 @@ namespace ASC.Core
private TenantManager TenantManager { get; } private TenantManager TenantManager { get; }
private ICache Cache { get; set; } private ICache Cache { get; set; }
public static readonly object CacheLocker; public static readonly object CacheLocker = new object();
public static readonly List<Guid> Groups; public static readonly List<Guid> Groups = Groups = new List<Guid>
static SubscriptionManager()
{
CacheLocker = new object();
Groups = new List<Guid>
{ {
Constants.Admin.ID, Constants.Admin.ID,
Constants.Everyone.ID, Constants.Everyone.ID,
Constants.User.ID Constants.User.ID
}; };
}
public SubscriptionManager(ISubscriptionService service, TenantManager tenantManager, ICache cache) public SubscriptionManager(ISubscriptionService service, TenantManager tenantManager, ICache cache)
{ {
@ -123,7 +117,7 @@ namespace ASC.Core
m = methods.FirstOrDefault(); 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) public string[] GetRecipients(string sourceID, string actionID, string objectID)

View File

@ -198,7 +198,7 @@ namespace ASC.Core
public Tenant SetTenantVersion(Tenant tenant, int version) 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) if (tenant.Version != version)
{ {
tenant.Version = version; tenant.Version = version;

View File

@ -175,13 +175,13 @@ namespace ASC.Core
public UserInfo GetUserBySid(string sid) public UserInfo GetUserBySid(string sid)
{ {
return GetUsersInternal() 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) public UserInfo GetSsoUserByNameId(string nameId)
{ {
return GetUsersInternal() 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) public bool IsUserNameExists(string username)
{ {
@ -239,7 +239,7 @@ namespace ASC.Core
public UserInfo[] Search(string text, EmployeeStatus status, Guid groupId) 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); var words = text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (words.Length == 0) return new UserInfo[0]; if (words.Length == 0) return new UserInfo[0];

View File

@ -113,8 +113,8 @@ namespace ASC.Core
public string AuthenticateMe(string login, string passwordHash) public string AuthenticateMe(string login, string passwordHash)
{ {
if (login == null) throw new ArgumentNullException("login"); if (login == null) throw new ArgumentNullException(nameof(login));
if (passwordHash == null) throw new ArgumentNullException("passwordHash"); if (passwordHash == null) throw new ArgumentNullException(nameof(passwordHash));
var tenantid = TenantManager.GetCurrentTenant().TenantId; var tenantid = TenantManager.GetCurrentTenant().TenantId;
var u = UserManager.GetUsersByPasswordHash(tenantid, login, passwordHash); var u = UserManager.GetUsersByPasswordHash(tenantid, login, passwordHash);
@ -134,6 +134,9 @@ namespace ASC.Core
if (HttpContextAccessor?.HttpContext != null) if (HttpContextAccessor?.HttpContext != null)
{ {
var request = HttpContextAccessor?.HttpContext.Request; var request = HttpContextAccessor?.HttpContext.Request;
if (request == null) throw new ArgumentNullException("request");
ipFrom = "from " + (request.Headers["X-Forwarded-For"].ToString() ?? request.GetUserHostAddress()); ipFrom = "from " + (request.Headers["X-Forwarded-For"].ToString() ?? request.GetUserHostAddress());
address = "for " + request.GetUrlRewriter(); address = "for " + request.GetUrlRewriter();
} }
@ -189,6 +192,9 @@ namespace ASC.Core
if (HttpContextAccessor?.HttpContext != null) if (HttpContextAccessor?.HttpContext != null)
{ {
var request = HttpContextAccessor?.HttpContext.Request; var request = HttpContextAccessor?.HttpContext.Request;
if (request == null) throw new ArgumentNullException("request");
address = "for " + request.GetUrlRewriter(); address = "for " + request.GetUrlRewriter();
ipFrom = "from " + (request.Headers["X-Forwarded-For"].ToString() ?? request.GetUserHostAddress()); ipFrom = "from " + (request.Headers["X-Forwarded-For"].ToString() ?? request.GetUserHostAddress());
} }

View File

@ -171,7 +171,7 @@ namespace ASC.Core
} }
} }
public class WorkContextExtension public static class WorkContextExtension
{ {
public static void Register(DIHelper dIHelper) public static void Register(DIHelper dIHelper)
{ {

View File

@ -50,7 +50,7 @@ namespace TMResourceData
{ {
public class DBResourceManager : ResourceManager 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>(); private readonly ConcurrentDictionary<string, ResourceSet> resourceSets = new ConcurrentDictionary<string, ResourceSet>();
public DBResourceManager(string filename, Assembly assembly) public DBResourceManager(string filename, Assembly assembly)
@ -125,7 +125,7 @@ namespace TMResourceData
private static bool Accept(Assembly a) private static bool Accept(Assembly a)
{ {
var n = a.GetName().Name; 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;
} }
@ -174,11 +174,11 @@ namespace TMResourceData
{ {
if (culture == null) if (culture == null)
{ {
throw new ArgumentNullException("culture"); throw new ArgumentNullException(nameof(culture));
} }
if (string.IsNullOrEmpty(filename)) if (string.IsNullOrEmpty(filename))
{ {
throw new ArgumentNullException("filename"); throw new ArgumentNullException(nameof(filename));
} }
DbContext = dbContext; DbContext = dbContext;
@ -248,7 +248,7 @@ namespace TMResourceData
private Dictionary<string, string> GetResources() 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)) if (!(cache.Get(key) is Dictionary<string, string> dic))
{ {
lock (locker) lock (locker)
@ -257,7 +257,8 @@ namespace TMResourceData
if (dic == null) if (dic == null)
{ {
var policy = cacheTimeout == TimeSpan.Zero ? null : new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.Add(cacheTimeout) }; var policy = cacheTimeout == TimeSpan.Zero ? null : new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.Add(cacheTimeout) };
cache.Set(key, dic = LoadResourceSet(filename, culture), policy); dic = LoadResourceSet(filename, culture);
cache.Set(key, dic, policy);
} }
} }
} }
@ -283,7 +284,7 @@ namespace TMResourceData
{ {
private readonly ILog log; private readonly ILog log;
private readonly ConcurrentDictionary<int, string> whiteLabelDictionary; private readonly ConcurrentDictionary<int, string> whiteLabelDictionary;
public string DefaultLogoText; public string DefaultLogoText { get; set; }
private IConfiguration Configuration { get; } private IConfiguration Configuration { get; }
@ -341,7 +342,7 @@ namespace TMResourceData
{ {
var newTextReplacement = newText; 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); newTextReplacement = HttpUtility.HtmlEncode(newTextReplacement);
} }

View File

@ -27,7 +27,6 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using ASC.Common.Caching;
using ASC.Core.Caching; using ASC.Core.Caching;
namespace ASC.Core namespace ASC.Core

View File

@ -112,7 +112,7 @@ namespace ASC.Core.Users
public override string ToString() public override string ToString()
{ {
return string.Format("{0} {1}", FirstName, LastName).Trim(); return $"{FirstName} {LastName}".Trim();
} }
public override int GetHashCode() public override int GetHashCode()
@ -138,7 +138,7 @@ namespace ASC.Core.Users
string[] IDirectRecipient.Addresses 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 public bool CheckActivation
@ -168,7 +168,7 @@ namespace ASC.Core.Users
var sBuilder = new StringBuilder(); var sBuilder = new StringBuilder();
foreach (var contact in ContactsList) foreach (var contact in ContactsList)
{ {
sBuilder.AppendFormat("{0}|", contact); sBuilder.Append($"{contact}|");
} }
return sBuilder.ToString(); return sBuilder.ToString();
} }

View File

@ -75,9 +75,8 @@ namespace ASC.Core.Data
foreach (var a in tenantAces) foreach (var a in tenantAces)
{ {
var key = string.Concat(a.Tenant.ToString(), a.SubjectId.ToString(), a.ActionId.ToString(), a.ObjectId); 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); commonAces.Remove(key);
if (common.Reaction == a.Reaction) if (common.Reaction == a.Reaction)
{ {
@ -126,15 +125,13 @@ namespace ASC.Core.Data
private bool ExistEscapeRecord(AzRecord r) private bool ExistEscapeRecord(AzRecord r)
{ {
var count = UserDbContext.Acl return UserDbContext.Acl
.Where(a => a.Tenant == Tenant.DEFAULT_TENANT) .Where(a => a.Tenant == Tenant.DEFAULT_TENANT)
.Where(a => a.Subject == r.SubjectId) .Where(a => a.Subject == r.SubjectId)
.Where(a => a.Action == r.ActionId) .Where(a => a.Action == r.ActionId)
.Where(a => a.Object == (r.ObjectId ?? string.Empty)) .Where(a => a.Object == (r.ObjectId ?? string.Empty))
.Where(a => a.AceType == r.Reaction) .Where(a => a.AceType == r.Reaction)
.Count(); .Any();
return count != 0;
} }
private void DeleteRecord(AzRecord r) private void DeleteRecord(AzRecord r)

View File

@ -115,7 +115,7 @@ namespace ASC.Core.Data
public TenantQuota SaveTenantQuota(TenantQuota quota) public TenantQuota SaveTenantQuota(TenantQuota quota)
{ {
if (quota == null) throw new ArgumentNullException("quota"); if (quota == null) throw new ArgumentNullException(nameof(quota));
var dbQuota = new DbQuota var dbQuota = new DbQuota
{ {
@ -155,7 +155,7 @@ namespace ASC.Core.Data
public void SetTenantQuotaRow(TenantQuotaRow row, bool exchange) 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(); using var tx = CoreDbContext.Database.BeginTransaction();

View File

@ -148,13 +148,21 @@ namespace ASC.Core.Data
private int tenantID; private int tenantID;
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;
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 public bool SaveSettings<T>(T settings, int tenantId) where T : ISettings
@ -177,7 +185,7 @@ namespace ASC.Core.Data
public bool SaveSettingsFor<T>(T settings, int tenantId, Guid userId) where T : 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 try
{ {
var key = settings.ID.ToString() + tenantId + userId; var key = settings.ID.ToString() + tenantId + userId;

View File

@ -69,8 +69,8 @@ namespace ASC.Core.Data
public string[] GetRecipients(int tenant, string sourceId, string actionId, string objectId) public string[] GetRecipients(int tenant, string sourceId, string actionId, string objectId)
{ {
if (sourceId == null) throw new ArgumentNullException("sourceId"); if (sourceId == null) throw new ArgumentNullException(nameof(sourceId));
if (actionId == null) throw new ArgumentNullException("actionId"); if (actionId == null) throw new ArgumentNullException(nameof(actionId));
var q = GetQuery(tenant, sourceId, actionId) var q = GetQuery(tenant, sourceId, actionId)
.Where(r => r.Object == (objectId ?? string.Empty)) .Where(r => r.Object == (objectId ?? string.Empty))
@ -83,8 +83,8 @@ namespace ASC.Core.Data
public IEnumerable<SubscriptionRecord> GetSubscriptions(int tenant, string sourceId, string actionId) public IEnumerable<SubscriptionRecord> GetSubscriptions(int tenant, string sourceId, string actionId)
{ {
if (sourceId == null) throw new ArgumentNullException("sourceId"); if (sourceId == null) throw new ArgumentNullException(nameof(sourceId));
if (actionId == null) throw new ArgumentNullException("actionId"); if (actionId == null) throw new ArgumentNullException(nameof(actionId));
var q = GetQuery(tenant, sourceId, actionId); var q = GetQuery(tenant, sourceId, actionId);
return GetSubscriptions(q, tenant); return GetSubscriptions(q, tenant);
@ -108,7 +108,7 @@ namespace ASC.Core.Data
public SubscriptionRecord GetSubscription(int tenant, string sourceId, string actionId, string recipientId, string objectId) 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) var q = GetQuery(tenant, sourceId, actionId)
.Where(r => r.Recipient == recipientId) .Where(r => r.Recipient == recipientId)
@ -119,9 +119,9 @@ namespace ASC.Core.Data
public bool IsUnsubscribe(int tenant, string sourceId, string actionId, string recipientId, string objectId) public bool IsUnsubscribe(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));
if (sourceId == null) throw new ArgumentNullException("sourceId"); if (sourceId == null) throw new ArgumentNullException(nameof(sourceId));
if (actionId == null) throw new ArgumentNullException("actionId"); if (actionId == null) throw new ArgumentNullException(nameof(actionId));
var q = UserDbContext.Subscriptions var q = UserDbContext.Subscriptions
.Where(r => r.Source == sourceId && .Where(r => r.Source == sourceId &&
@ -136,7 +136,7 @@ namespace ASC.Core.Data
} }
else else
{ {
q = q = q.Where(r => r.Object == string.Empty);; q = q.Where(r => r.Object == string.Empty);
} }
return q.Any(); return q.Any();
@ -144,9 +144,9 @@ namespace ASC.Core.Data
public string[] GetSubscriptions(int tenant, string sourceId, string actionId, string recipientId, bool checkSubscribe) public string[] GetSubscriptions(int tenant, string sourceId, string actionId, string recipientId, bool checkSubscribe)
{ {
if (recipientId == null) throw new ArgumentNullException("recipientId"); if (recipientId == null) throw new ArgumentNullException(nameof(recipientId));
if (sourceId == null) throw new ArgumentNullException("sourceId"); if (sourceId == null) throw new ArgumentNullException(nameof(sourceId));
if (actionId == null) throw new ArgumentNullException("actionId"); if (actionId == null) throw new ArgumentNullException(nameof(actionId));
var q = GetQuery(tenant, sourceId, actionId) var q = GetQuery(tenant, sourceId, actionId)
.Where(r=> r.Recipient == recipientId) .Where(r=> r.Recipient == recipientId)
@ -163,7 +163,7 @@ namespace ASC.Core.Data
public void SaveSubscription(SubscriptionRecord 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 var subs = new Subscription
{ {
@ -186,8 +186,8 @@ namespace ASC.Core.Data
public void RemoveSubscriptions(int tenant, string sourceId, string actionId, string objectId) public void RemoveSubscriptions(int tenant, string sourceId, string actionId, string objectId)
{ {
if (sourceId == null) throw new ArgumentNullException("sourceId"); if (sourceId == null) throw new ArgumentNullException(nameof(sourceId));
if (actionId == null) throw new ArgumentNullException("actionId"); if (actionId == null) throw new ArgumentNullException(nameof(actionId));
using var tr = UserDbContext.Database.BeginTransaction(); using var tr = UserDbContext.Database.BeginTransaction();
var q = UserDbContext.Subscriptions var q = UserDbContext.Subscriptions
@ -195,7 +195,7 @@ namespace ASC.Core.Data
.Where(r => r.Source == sourceId) .Where(r => r.Source == sourceId)
.Where(r => r.Action == actionId); .Where(r => r.Action == actionId);
if (objectId != string.Empty) if (objectId.Length != 0)
{ {
q = q.Where(r => r.Object == (objectId ?? string.Empty)); q = q.Where(r => r.Object == (objectId ?? string.Empty));
} }
@ -213,8 +213,8 @@ namespace ASC.Core.Data
public IEnumerable<SubscriptionMethod> GetSubscriptionMethods(int tenant, string sourceId, string actionId, string recipientId) public IEnumerable<SubscriptionMethod> GetSubscriptionMethods(int tenant, string sourceId, string actionId, string recipientId)
{ {
if (sourceId == null) throw new ArgumentNullException("sourceId"); if (sourceId == null) throw new ArgumentNullException(nameof(sourceId));
if (actionId == null) throw new ArgumentNullException("actionId"); if (actionId == null) throw new ArgumentNullException(nameof(actionId));
var q = UserDbContext.SubscriptionMethods var q = UserDbContext.SubscriptionMethods
.Where(r => r.Tenant == -1 || r.Tenant == tenant) .Where(r => r.Tenant == -1 || r.Tenant == tenant)
@ -258,7 +258,7 @@ namespace ASC.Core.Data
public void SetSubscriptionMethod(SubscriptionMethod m) 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(); using var tr = UserDbContext.Database.BeginTransaction();
@ -297,8 +297,8 @@ namespace ASC.Core.Data
private IQueryable<Subscription> GetQuery(int tenant, string sourceId, string actionId) private IQueryable<Subscription> GetQuery(int tenant, string sourceId, string actionId)
{ {
if (sourceId == null) throw new ArgumentNullException("sourceId"); if (sourceId == null) throw new ArgumentNullException(nameof(sourceId));
if (actionId == null) throw new ArgumentNullException("actionId"); if (actionId == null) throw new ArgumentNullException(nameof(actionId));
return return
UserDbContext.Subscriptions UserDbContext.Subscriptions

View File

@ -1,31 +1,31 @@
/* /*
* *
* (c) Copyright Ascensio System Limited 2010-2018 * (c) Copyright Ascensio System Limited 2010-2018
* *
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU * This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html). * General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that * In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights. * Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
* *
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR * THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html * FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
* *
* You can contact Ascensio System SIA by email at sales@onlyoffice.com * You can contact Ascensio System SIA by email at sales@onlyoffice.com
* *
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display * The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3. * Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
* *
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains * Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic * relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE" * form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute. * in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks. * Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
* *
*/ */
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Text; using System.Text;
@ -34,17 +34,17 @@ using ASC.Common;
using ASC.Core.Common.EF; using ASC.Core.Common.EF;
using ASC.Core.Common.EF.Context; using ASC.Core.Common.EF.Context;
using ASC.Core.Common.EF.Model; using ASC.Core.Common.EF.Model;
using ASC.Core.Tenants; using ASC.Core.Tenants;
using ASC.Core.Users; using ASC.Core.Users;
using ASC.Security.Cryptography; using ASC.Security.Cryptography;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace ASC.Core.Data namespace ASC.Core.Data
{ {
[Scope] [Scope]
public class ConfigureDbTenantService : IConfigureNamedOptions<DbTenantService> public class ConfigureDbTenantService : IConfigureNamedOptions<DbTenantService>
{ {
private TenantDomainValidator TenantDomainValidator { get; } private TenantDomainValidator TenantDomainValidator { get; }
private DbContextManager<TenantDbContext> DbContextManager { get; } private DbContextManager<TenantDbContext> DbContextManager { get; }
@ -71,8 +71,8 @@ namespace ASC.Core.Data
} }
[Scope] [Scope]
public class DbTenantService : ITenantService public class DbTenantService : ITenantService
{ {
private List<string> forbiddenDomains; private List<string> forbiddenDomains;
internal TenantDomainValidator TenantDomainValidator { get; set; } internal TenantDomainValidator TenantDomainValidator { get; set; }
@ -84,7 +84,7 @@ namespace ASC.Core.Data
private static Expression<Func<DbTenant, Tenant>> FromDbTenantToTenant { get; set; } private static Expression<Func<DbTenant, Tenant>> FromDbTenantToTenant { get; set; }
private static Expression<Func<TenantUserSecurity, Tenant>> FromTenantUserToTenant { get; set; } private static Expression<Func<TenantUserSecurity, Tenant>> FromTenantUserToTenant { get; set; }
static DbTenantService() static DbTenantService()
{ {
FromDbTenantToTenant = r => new Tenant FromDbTenantToTenant = r => new Tenant
{ {
@ -131,15 +131,15 @@ namespace ASC.Core.Data
LazyUserDbContext = new Lazy<UserDbContext>(() => DbContextManager.Value); LazyUserDbContext = new Lazy<UserDbContext>(() => DbContextManager.Value);
TenantDomainValidator = tenantDomainValidator; TenantDomainValidator = tenantDomainValidator;
MachinePseudoKeys = machinePseudoKeys; MachinePseudoKeys = machinePseudoKeys;
} }
public void ValidateDomain(string domain) public void ValidateDomain(string domain)
{ {
using var tr = TenantDbContext.Database.BeginTransaction(); using var tr = TenantDbContext.Database.BeginTransaction();
ValidateDomain(domain, Tenant.DEFAULT_TENANT, true); ValidateDomain(domain, Tenant.DEFAULT_TENANT, true);
} }
public IEnumerable<Tenant> GetTenants(DateTime from, bool active = true) public IEnumerable<Tenant> GetTenants(DateTime from, bool active = true)
{ {
var q = TenantsQuery(); var q = TenantsQuery();
@ -152,8 +152,8 @@ namespace ASC.Core.Data
{ {
q = q.Where(r => r.LastModified >= from); q = q.Where(r => r.LastModified >= from);
} }
return q.Select(FromDbTenantToTenant).ToList(); return q.Select(FromDbTenantToTenant).ToList();
} }
public IEnumerable<Tenant> GetTenants(List<int> ids) public IEnumerable<Tenant> GetTenants(List<int> ids)
@ -162,10 +162,10 @@ namespace ASC.Core.Data
return q.Where(r => ids.Contains(r.Id) && r.Status == TenantStatus.Active).Select(FromDbTenantToTenant).ToList(); return q.Where(r => ids.Contains(r.Id) && r.Status == TenantStatus.Active).Select(FromDbTenantToTenant).ToList();
} }
public IEnumerable<Tenant> GetTenants(string login, string passwordHash) 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() IQueryable<TenantUserSecurity> query() => TenantsQuery()
.Where(r => r.Status == TenantStatus.Active) .Where(r => r.Status == TenantStatus.Active)
@ -183,7 +183,7 @@ namespace ASC.Core.Data
}) })
.Where(r => r.User.Status == EmployeeStatus.Active) .Where(r => r.User.Status == EmployeeStatus.Active)
.Where(r => r.DbTenant.Status == TenantStatus.Active) .Where(r => r.DbTenant.Status == TenantStatus.Active)
.Where(r => r.User.Removed == false); .Where(r => !r.User.Removed);
if (passwordHash == null) if (passwordHash == null)
{ {
@ -238,70 +238,71 @@ namespace ASC.Core.Data
//new password //new password
result = result.Concat(q.Select(FromTenantUserToTenant)).ToList(); result = result.Concat(q.Select(FromTenantUserToTenant)).ToList();
result.Distinct();
return result; return result.Distinct();
} }
} }
public Tenant GetTenant(int id) public Tenant GetTenant(int id)
{ {
return TenantsQuery() return TenantsQuery()
.Where(r => r.Id == id) .Where(r => r.Id == id)
.Select(FromDbTenantToTenant) .Select(FromDbTenantToTenant)
.SingleOrDefault(); .SingleOrDefault();
} }
public Tenant GetTenant(string domain) 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(); domain = domain.ToLowerInvariant();
return TenantsQuery() return TenantsQuery()
.Where(r => r.Alias == domain || r.MappedDomain == domain) .Where(r => r.Alias == domain || r.MappedDomain == domain)
.OrderBy(a => a.Status == TenantStatus.Restoring ? TenantStatus.Active : a.Status) .OrderBy(a => a.Status == TenantStatus.Restoring ? TenantStatus.Active : a.Status)
.ThenByDescending(a => a.Status == TenantStatus.Restoring ? 0 : a.Id) .ThenByDescending(a => a.Status == TenantStatus.Restoring ? 0 : a.Id)
.Select(FromDbTenantToTenant) .Select(FromDbTenantToTenant)
.FirstOrDefault(); .FirstOrDefault();
} }
public Tenant GetTenantForStandaloneWithoutAlias(string ip) public Tenant GetTenantForStandaloneWithoutAlias(string ip)
{ {
return TenantsQuery() return TenantsQuery()
.OrderBy(a => a.Status) .OrderBy(a => a.Status)
.ThenByDescending(a => a.Id) .ThenByDescending(a => a.Id)
.Select(FromDbTenantToTenant) .Select(FromDbTenantToTenant)
.FirstOrDefault(); .FirstOrDefault();
} }
public Tenant SaveTenant(CoreSettings coreSettings, Tenant t) public Tenant SaveTenant(CoreSettings coreSettings, Tenant t)
{ {
if (t == null) throw new ArgumentNullException("tenant"); if (t == null) throw new ArgumentNullException("tenant");
using var tx = TenantDbContext.Database.BeginTransaction(); using var tx = TenantDbContext.Database.BeginTransaction();
if (!string.IsNullOrEmpty(t.MappedDomain)) if (!string.IsNullOrEmpty(t.MappedDomain))
{ {
var baseUrl = coreSettings.GetBaseDomain(t.HostedRegion); var baseUrl = coreSettings.GetBaseDomain(t.HostedRegion);
if (baseUrl != null && t.MappedDomain.EndsWith("." + baseUrl, StringComparison.InvariantCultureIgnoreCase)) if (baseUrl != null && t.MappedDomain.EndsWith("." + baseUrl, StringComparison.InvariantCultureIgnoreCase))
{ {
ValidateDomain(t.MappedDomain.Substring(0, t.MappedDomain.Length - baseUrl.Length - 1), t.TenantId, false); ValidateDomain(t.MappedDomain.Substring(0, t.MappedDomain.Length - baseUrl.Length - 1), t.TenantId, false);
} }
else else
{ {
ValidateDomain(t.MappedDomain, t.TenantId, false); ValidateDomain(t.MappedDomain, t.TenantId, false);
} }
} }
if (t.TenantId == Tenant.DEFAULT_TENANT) if (t.TenantId == Tenant.DEFAULT_TENANT)
{ {
t.Version = TenantDbContext.TenantVersion t.Version = TenantDbContext.TenantVersion
.Where(r => r.DefaultVersion == 1 || r.Id == 0) .Where(r => r.DefaultVersion == 1 || r.Id == 0)
.OrderByDescending(r => r.Id) .OrderByDescending(r => r.Id)
.Select(r => r.Id) .Select(r => r.Id)
.FirstOrDefault(); .FirstOrDefault();
t.LastModified = DateTime.UtcNow;
var tenant = new DbTenant var tenant = new DbTenant
{ {
@ -320,7 +321,7 @@ namespace ASC.Core.Data
Status = t.Status, Status = t.Status,
StatusChanged = t.StatusChangeDate, StatusChanged = t.StatusChangeDate,
PaymentId = t.PaymentId, PaymentId = t.PaymentId,
LastModified = t.LastModified = DateTime.UtcNow, LastModified = t.LastModified,
Industry = t.Industry, Industry = t.Industry,
Spam = t.Spam, Spam = t.Spam,
Calls = t.Calls Calls = t.Calls
@ -328,9 +329,9 @@ namespace ASC.Core.Data
tenant = TenantDbContext.Tenants.Add(tenant).Entity; tenant = TenantDbContext.Tenants.Add(tenant).Entity;
TenantDbContext.SaveChanges(); TenantDbContext.SaveChanges();
t.TenantId = tenant.Id; t.TenantId = tenant.Id;
} }
else else
{ {
var tenant = TenantDbContext.Tenants var tenant = TenantDbContext.Tenants
.Where(r => r.Id == t.TenantId) .Where(r => r.Id == t.TenantId)
@ -356,10 +357,10 @@ namespace ASC.Core.Data
tenant.Spam = t.Spam; tenant.Spam = t.Spam;
tenant.Calls = t.Calls; tenant.Calls = t.Calls;
} }
TenantDbContext.SaveChanges(); TenantDbContext.SaveChanges();
} }
if (string.IsNullOrEmpty(t.PartnerId) && string.IsNullOrEmpty(t.AffiliateId) && string.IsNullOrEmpty(t.Campaign)) if (string.IsNullOrEmpty(t.PartnerId) && string.IsNullOrEmpty(t.AffiliateId) && string.IsNullOrEmpty(t.Campaign))
{ {
var p = TenantDbContext.TenantPartner var p = TenantDbContext.TenantPartner
.Where(r => r.TenantId == t.TenantId) .Where(r => r.TenantId == t.TenantId)
@ -368,9 +369,9 @@ namespace ASC.Core.Data
if (p != null) if (p != null)
{ {
TenantDbContext.TenantPartner.Remove(p); TenantDbContext.TenantPartner.Remove(p);
} }
} }
else else
{ {
var tenantPartner = new DbTenantPartner var tenantPartner = new DbTenantPartner
{ {
@ -380,18 +381,18 @@ namespace ASC.Core.Data
Campaign = t.Campaign Campaign = t.Campaign
}; };
TenantDbContext.TenantPartner.Add(tenantPartner); TenantDbContext.TenantPartner.Add(tenantPartner);
} }
tx.Commit(); tx.Commit();
//CalculateTenantDomain(t); //CalculateTenantDomain(t);
return t; return t;
} }
public void RemoveTenant(int id, bool auto = false) public void RemoveTenant(int id, bool auto = false)
{ {
var postfix = auto ? "_auto_deleted" : "_deleted"; var postfix = auto ? "_auto_deleted" : "_deleted";
using var tx = TenantDbContext.Database.BeginTransaction(); using var tx = TenantDbContext.Database.BeginTransaction();
@ -416,28 +417,28 @@ namespace ASC.Core.Data
TenantDbContext.SaveChanges(); TenantDbContext.SaveChanges();
tx.Commit(); tx.Commit();
} }
public IEnumerable<TenantVersion> GetTenantVersions() public IEnumerable<TenantVersion> GetTenantVersions()
{ {
return TenantDbContext.TenantVersion return TenantDbContext.TenantVersion
.Where(r => r.Visible == true) .Where(r => r.Visible)
.Select(r => new TenantVersion(r.Id, r.Version)) .Select(r => new TenantVersion(r.Id, r.Version))
.ToList(); .ToList();
} }
public byte[] GetTenantSettings(int tenant, string key) public byte[] GetTenantSettings(int tenant, string key)
{ {
return TenantDbContext.CoreSettings return TenantDbContext.CoreSettings
.Where(r => r.Tenant == tenant) .Where(r => r.Tenant == tenant)
.Where(r => r.Id == key) .Where(r => r.Id == key)
.Select(r => r.Value) .Select(r => r.Value)
.FirstOrDefault(); .FirstOrDefault();
} }
public void SetTenantSettings(int tenant, string key, byte[] data) public void SetTenantSettings(int tenant, string key, byte[] data)
{ {
using var tx = TenantDbContext.Database.BeginTransaction(); using var tx = TenantDbContext.Database.BeginTransaction();
@ -465,73 +466,72 @@ namespace ASC.Core.Data
TenantDbContext.AddOrUpdate(r => r.CoreSettings, settings); TenantDbContext.AddOrUpdate(r => r.CoreSettings, settings);
} }
TenantDbContext.SaveChanges(); TenantDbContext.SaveChanges();
tx.Commit(); tx.Commit();
} }
private IQueryable<DbTenant> TenantsQuery() private IQueryable<DbTenant> TenantsQuery()
{ {
return TenantDbContext.Tenants; return TenantDbContext.Tenants;
} }
private void ValidateDomain(string domain, int tenantId, bool validateCharacters) private void ValidateDomain(string domain, int tenantId, bool validateCharacters)
{ {
// size // size
TenantDomainValidator.ValidateDomainLength(domain); TenantDomainValidator.ValidateDomainLength(domain);
// characters // characters
if (validateCharacters) if (validateCharacters)
{ {
TenantDomainValidator.ValidateDomainCharacters(domain); TenantDomainValidator.ValidateDomainCharacters(domain);
} }
// forbidden or exists // forbidden or exists
var exists = false; var exists = false;
domain = domain.ToLowerInvariant();
if (!exists) domain = domain.ToLowerInvariant();
{ if (forbiddenDomains == null)
if (forbiddenDomains == null) {
{ forbiddenDomains = TenantDbContext.TenantForbiden.Select(r => r.Address).ToList();
forbiddenDomains = TenantDbContext.TenantForbiden.Select(r => r.Address).ToList(); }
} exists = tenantId != 0 && forbiddenDomains.Contains(domain);
exists = tenantId != 0 && forbiddenDomains.Contains(domain);
} if (!exists)
if (!exists) {
{ exists = TenantDbContext.Tenants.Where(r => r.Alias == domain && r.Id != tenantId).Any();
exists = 0 < TenantDbContext.Tenants.Where(r => r.Alias == domain && r.Id != tenantId).Count(); }
} if (!exists)
if (!exists) {
{ exists = TenantDbContext.Tenants
exists = 0 < TenantDbContext.Tenants
.Where(r => r.MappedDomain == domain && r.Id != tenantId && !(r.Status == TenantStatus.RemovePending || r.Status == TenantStatus.Restoring)) .Where(r => r.MappedDomain == domain && r.Id != tenantId && !(r.Status == TenantStatus.RemovePending || r.Status == TenantStatus.Restoring))
.Count(); .Any();
} }
if (exists) if (exists)
{ {
// cut number suffix // cut number suffix
while (true) while (true)
{ {
if (6 < domain.Length && char.IsNumber(domain, domain.Length - 1)) if (6 < domain.Length && char.IsNumber(domain, domain.Length - 1))
{ {
domain = domain[0..^1]; domain = domain[0..^1];
} }
else else
{ {
break; break;
} }
} }
var existsTenants = TenantDbContext.TenantForbiden.Where(r => r.Address.StartsWith(domain)).Select(r => r.Address) var existsTenants = TenantDbContext.TenantForbiden.Where(r => r.Address.StartsWith(domain)).Select(r => r.Address)
.Union(TenantDbContext.Tenants.Where(r => r.Alias.StartsWith(domain) && r.Id != tenantId).Select(r => r.Alias)) .Union(TenantDbContext.Tenants.Where(r => r.Alias.StartsWith(domain) && r.Id != tenantId).Select(r => r.Alias))
.Union(TenantDbContext.Tenants.Where(r => r.MappedDomain.StartsWith(domain) && r.Id != tenantId && r.Status != TenantStatus.RemovePending).Select(r => r.MappedDomain)); .Union(TenantDbContext.Tenants.Where(r => r.MappedDomain.StartsWith(domain) && r.Id != tenantId && r.Status != TenantStatus.RemovePending).Select(r => r.MappedDomain));
throw new TenantAlreadyExistsException("Address busy.", existsTenants); throw new TenantAlreadyExistsException("Address busy.", existsTenants);
} }
} }
protected string GetPasswordHash(Guid userId, string password) protected string GetPasswordHash(Guid userId, string password)
{ {
return Hasher.Base64Hash(password + userId + Encoding.UTF8.GetString(MachinePseudoKeys.GetMachineConstant()), HashAlg.SHA512); return Hasher.Base64Hash(password + userId + Encoding.UTF8.GetString(MachinePseudoKeys.GetMachineConstant()), HashAlg.SHA512);
} }
} }
public class TenantUserSecurity public class TenantUserSecurity
@ -539,5 +539,5 @@ namespace ASC.Core.Data
public DbTenant DbTenant { get; set; } public DbTenant DbTenant { get; set; }
public User User { get; set; } public User User { get; set; }
public UserSecurity UserSecurity { get; set; } public UserSecurity UserSecurity { get; set; }
} }
} }

View File

@ -239,7 +239,7 @@ namespace ASC.Core.Data
public UserInfo GetUserByPasswordHash(int tenant, string login, string passwordHash) 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)) if (Guid.TryParse(login, out var userId))
{ {
@ -373,7 +373,7 @@ namespace ASC.Core.Data
.Select(r => r.Photo) .Select(r => r.Photo)
.FirstOrDefault(); .FirstOrDefault();
return photo ?? new byte[0]; return photo ?? Array.Empty<byte>();
} }
public IEnumerable<UserInfo> GetUsers(int tenant) public IEnumerable<UserInfo> GetUsers(int tenant)
@ -556,7 +556,7 @@ namespace ASC.Core.Data
public UserInfo SaveUser(int tenant, UserInfo user) 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 (string.IsNullOrEmpty(user.UserName)) throw new ArgumentOutOfRangeException("Empty username.");
if (user.ID == default) user.ID = Guid.NewGuid(); if (user.ID == default) user.ID = Guid.NewGuid();
@ -709,17 +709,15 @@ namespace ASC.Core.Data
q = q.Where(r => !r.Removed); q = q.Where(r => !r.Removed);
if (includeGroups != null && includeGroups.Any()) if (includeGroups != null && includeGroups.Count > 0)
{ {
Expression or = Expression.Empty();
foreach (var ig in includeGroups) 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))); q = q.Where(r => r.Groups.Any(a => !a.Removed && a.Tenant == r.Tenant && a.UserId == r.Id && ig.Any(r => r == a.GroupId)));
} }
} }
if (excludeGroups != null && excludeGroups.Any()) if (excludeGroups != null && excludeGroups.Count > 0)
{ {
foreach (var eg in excludeGroups) foreach (var eg in excludeGroups)
{ {

View File

@ -17,7 +17,6 @@ namespace ASC.Core.Common.EF
public class BaseDbContext : DbContext public class BaseDbContext : DbContext
{ {
public string baseName;
public BaseDbContext() { } public BaseDbContext() { }
public BaseDbContext(DbContextOptions options) : base(options) public BaseDbContext(DbContextOptions options) : base(options)
{ {
@ -29,7 +28,7 @@ namespace ASC.Core.Common.EF
public ConnectionStringSettings ConnectionStringSettings { get; set; } public ConnectionStringSettings ConnectionStringSettings { get; set; }
protected internal Provider Provider { 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 protected virtual Dictionary<Provider, Func<BaseDbContext>> ProviderContext
{ {
get { return null; } get { return null; }
@ -66,7 +65,7 @@ namespace ASC.Core.Common.EF
{ {
if (!string.IsNullOrEmpty(MigrateAssembly)) if (!string.IsNullOrEmpty(MigrateAssembly))
{ {
r = r.MigrationsAssembly(MigrateAssembly); r.MigrationsAssembly(MigrateAssembly);
} }
}); });
break; break;
@ -133,10 +132,16 @@ namespace ASC.Core.Common.EF
} }
} }
} }
public async ValueTask DisposeAsync()
{
if (Context == null) return;
public ValueTask DisposeAsync()
{
if (Context == null) return ValueTask.CompletedTask;
return InternalDisposeAsync();
}
private async ValueTask InternalDisposeAsync()
{
foreach (var c in Context) foreach (var c in Context)
{ {
if (c != null) if (c != null)

View File

@ -39,7 +39,7 @@ namespace ASC.Core.Common.EF
public class ConfigureMultiRegionalDbContext<T> : IConfigureNamedOptions<MultiRegionalDbContext<T>> where T : BaseDbContext, new() 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 ConfigurationExtension Configuration { get; }
private DbContextManager<T> DbContext { get; } private DbContextManager<T> DbContext { get; }
@ -57,7 +57,7 @@ namespace ASC.Core.Common.EF
foreach (var c in Configuration.GetConnectionStrings().Where(r => foreach (var c in Configuration.GetConnectionStrings().Where(r =>
r.Name.Equals(name, cmp) || r.Name.StartsWith(name + ".", cmp) || 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)); context.Context.Add(DbContext.Get(c.Name));
@ -66,7 +66,7 @@ namespace ASC.Core.Common.EF
public void Configure(MultiRegionalDbContext<T> context) public void Configure(MultiRegionalDbContext<T> context)
{ {
Configure(baseName, context); Configure(_baseName, context);
} }
} }
} }

View File

@ -31,7 +31,7 @@ namespace ASC.Core.Common.EF
private static PropertyInfo GetPropertyInfo(Type objType, string name) private static PropertyInfo GetPropertyInfo(Type objType, string name)
{ {
var properties = objType.GetProperties(); 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) if (matchedProperty == null)
throw new ArgumentException("name"); throw new ArgumentException("name");

View File

@ -131,19 +131,18 @@ namespace ASC.Core.Encryption
if (length < 1 || length > 128) 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) 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 array = new byte[length];
var array2 = new char[length]; var array2 = new char[length];
var num = 0; var num = 0;
array = RandomNumberGenerator.GetBytes(length); var array = RandomNumberGenerator.GetBytes(length);
for (var i = 0; i < length; i++) for (var i = 0; i < length; i++)
{ {
@ -172,16 +171,15 @@ namespace ASC.Core.Encryption
if (num < numberOfNonAlphanumericCharacters) if (num < numberOfNonAlphanumericCharacters)
{ {
var random = new Random();
for (var j = 0; j < numberOfNonAlphanumericCharacters - num; j++) for (var j = 0; j < numberOfNonAlphanumericCharacters - num; j++)
{ {
int num3; int num3;
do do
{ {
num3 = random.Next(0, length); num3 = RandomNumberGenerator.GetInt32(0, length);
} }
while (!char.IsLetterOrDigit(array2[num3])); while (!char.IsLetterOrDigit(array2[num3]));
array2[num3] = punctuations[random.Next(0, punctuations.Length)]; array2[num3] = punctuations[RandomNumberGenerator.GetInt32(0, punctuations.Length)];
} }
} }

View File

@ -107,7 +107,7 @@ namespace ASC.Core
error = exception; error = exception;
} }
} }
if (!result.Any() && error != null) if (result.Count == 0 && error != null)
{ {
throw error; throw error;
} }
@ -204,11 +204,10 @@ namespace ASC.Core
private void Initialize() private void Initialize()
{ {
var connectionStrings = ConfigurationExtension.GetConnectionStrings(); var connectionStrings = ConfigurationExtension.GetConnectionStrings();
var dbConnectionStrings = ConfigurationExtension.GetConnectionStrings(dbid);
if (Convert.ToBoolean(Configuraion["core.multi-hosted.config-only"] ?? "false")) 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 + ".")) if (cs.Name.StartsWith(dbid + "."))
{ {

View File

@ -35,7 +35,6 @@ namespace ASC.Notify.Channels
{ {
private readonly ISink firstSink; private readonly ISink firstSink;
private readonly ISink senderSink; private readonly ISink senderSink;
private readonly Context context;
public string SenderName public string SenderName
@ -47,18 +46,19 @@ namespace ASC.Notify.Channels
public SenderChannel(Context context, string senderName, ISink decorateSink, ISink senderSink) public SenderChannel(Context context, string senderName, ISink decorateSink, ISink senderSink)
{ {
this.context = context ?? throw new ArgumentNullException("context"); this.SenderName = senderName ?? throw new ArgumentNullException(nameof(senderName));
this.SenderName = senderName ?? throw new ArgumentNullException("senderName");
this.firstSink = decorateSink; 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);
context = context ?? throw new ArgumentNullException(nameof(context));
var dispatcherSink = new DispatchSink(SenderName, context.DispatchEngine);
this.firstSink = AddSink(firstSink, dispatcherSink); this.firstSink = AddSink(firstSink, dispatcherSink);
} }
public void SendAsync(INoticeMessage message) public void SendAsync(INoticeMessage message)
{ {
if (message == null) throw new ArgumentNullException("message"); if (message == null) throw new ArgumentNullException(nameof(message));
firstSink.ProcessMessageAsync(message); firstSink.ProcessMessageAsync(message);
} }

View File

@ -131,7 +131,7 @@ namespace ASC.Notify
var pattern = source.GetPatternProvider().GetPattern(a, s); var pattern = source.GetPatternProvider().GetPattern(a, s);
if (pattern == null) 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) catch (Exception error)

View File

@ -277,13 +277,13 @@ namespace ASC.Notify.Cron
break; 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( throw new FormatException(
"Support for specifying 'L' and 'LW' with other days of the month is not implemented"); "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( throw new FormatException(
"Support for specifying 'L' with other days of the week is not implemented"); "Support for specifying 'L' with other days of the week is not implemented");
@ -350,8 +350,7 @@ namespace ASC.Notify.Cron
sval = GetMonthNumber(sub) + 1; sval = GetMonthNumber(sub) + 1;
if (sval <= 0) if (sval <= 0)
{ {
throw new FormatException(string.Format(CultureInfo.InvariantCulture, throw new FormatException($"Invalid Month value: '{sub}'");
"Invalid Month value: '{0}'", sub));
} }
if (s.Length > i + 3) if (s.Length > i + 3)
{ {
@ -363,8 +362,7 @@ namespace ASC.Notify.Cron
eval = GetMonthNumber(sub) + 1; eval = GetMonthNumber(sub) + 1;
if (eval <= 0) if (eval <= 0)
{ {
throw new FormatException( throw new FormatException($"Invalid Month value: '{sub}'");
string.Format(CultureInfo.InvariantCulture, "Invalid Month value: '{0}'", sub));
} }
} }
} }
@ -374,8 +372,7 @@ namespace ASC.Notify.Cron
sval = GetDayOfWeekNumber(sub); sval = GetDayOfWeekNumber(sub);
if (sval < 0) if (sval < 0)
{ {
throw new FormatException(string.Format(CultureInfo.InvariantCulture, throw new FormatException($"Invalid Day-of-Week value: '{sub}'");
"Invalid Day-of-Week value: '{0}'", sub));
} }
if (s.Length > i + 3) if (s.Length > i + 3)
{ {
@ -387,8 +384,7 @@ namespace ASC.Notify.Cron
eval = GetDayOfWeekNumber(sub); eval = GetDayOfWeekNumber(sub);
if (eval < 0) if (eval < 0)
{ {
throw new FormatException( throw new FormatException($"Invalid Day-of-Week value: '{sub}'");
string.Format(CultureInfo.InvariantCulture, "Invalid Day-of-Week value: '{0}'", sub));
} }
} }
else if (c == '#') else if (c == '#')
@ -417,21 +413,20 @@ namespace ASC.Notify.Cron
} }
else else
{ {
throw new FormatException( throw new FormatException($"Illegal characters for this position: '{sub}'");
string.Format(CultureInfo.InvariantCulture, "Illegal characters for this position: '{0}'", sub));
} }
if (eval != -1) if (eval != -1)
{ {
incr = 1; incr = 1;
} }
AddToSet(sval, eval, incr, type); AddToSet(sval, eval, incr, type);
return (i + 3); return i + 3;
} }
if (c == '?') if (c == '?')
{ {
i++; i++;
if ((i + 1) < s.Length if ((i + 1) < s.Length
&& (s[i] != ' ' && s[i + 1] != '\t')) && s[i] != ' ' && s[i + 1] != '\t')
{ {
throw new FormatException("Illegal character after '?': " throw new FormatException("Illegal character after '?': "
+ s[i]); + s[i]);
@ -552,8 +547,8 @@ namespace ASC.Notify.Cron
if (c >= '0' && c <= '9') if (c >= '0' && c <= '9')
{ {
var vs = GetValue(val, s, i); var vs = GetValue(val, s, i);
val = vs.theValue; val = vs.TheValue;
i = vs.pos; i = vs.Pos;
} }
i = CheckNext(i, s, val, type); i = CheckNext(i, s, val, type);
return i; return i;
@ -670,11 +665,11 @@ namespace ASC.Notify.Cron
if (c >= '0' && c <= '9') if (c >= '0' && c <= '9')
{ {
var vs = GetValue(v, s, i); var vs = GetValue(v, s, i);
var v1 = vs.theValue; var v1 = vs.TheValue;
end = v1; end = v1;
i = vs.pos; i = vs.Pos;
} }
if (i < s.Length && ((s[i]) == '/')) if (i < s.Length && (s[i] == '/'))
{ {
i++; i++;
c = s[i]; c = s[i];
@ -689,9 +684,9 @@ namespace ASC.Notify.Cron
if (c >= '0' && c <= '9') if (c >= '0' && c <= '9')
{ {
var vs = GetValue(v2, s, i); var vs = GetValue(v2, s, i);
var v3 = vs.theValue; var v3 = vs.TheValue;
AddToSet(val, end, v3, type); AddToSet(val, end, v3, type);
i = vs.pos; i = vs.Pos;
return i; return i;
} }
else else
@ -721,9 +716,9 @@ namespace ASC.Notify.Cron
if (c >= '0' && c <= '9') if (c >= '0' && c <= '9')
{ {
var vs = GetValue(v2, s, i); var vs = GetValue(v2, s, i);
var v3 = vs.theValue; var v3 = vs.TheValue;
AddToSet(val, end, v3, type); AddToSet(val, end, v3, type);
i = vs.pos; i = vs.Pos;
return i; return i;
} }
else else
@ -742,43 +737,43 @@ namespace ASC.Notify.Cron
var buf = new StringBuilder(); var buf = new StringBuilder();
buf.Append("seconds: "); buf.Append("seconds: ");
buf.Append(GetExpressionSetSummary(seconds)); buf.Append(GetExpressionSetSummary(seconds));
buf.Append("\n"); buf.Append('\n');
buf.Append("minutes: "); buf.Append("minutes: ");
buf.Append(GetExpressionSetSummary(minutes)); buf.Append(GetExpressionSetSummary(minutes));
buf.Append("\n"); buf.Append('\n');
buf.Append("hours: "); buf.Append("hours: ");
buf.Append(GetExpressionSetSummary(hours)); buf.Append(GetExpressionSetSummary(hours));
buf.Append("\n"); buf.Append('\n');
buf.Append("daysOfMonth: "); buf.Append("daysOfMonth: ");
buf.Append(GetExpressionSetSummary(daysOfMonth)); buf.Append(GetExpressionSetSummary(daysOfMonth));
buf.Append("\n"); buf.Append('\n');
buf.Append("months: "); buf.Append("months: ");
buf.Append(GetExpressionSetSummary(months)); buf.Append(GetExpressionSetSummary(months));
buf.Append("\n"); buf.Append('\n');
buf.Append("daysOfWeek: "); buf.Append("daysOfWeek: ");
buf.Append(GetExpressionSetSummary(daysOfWeek)); buf.Append(GetExpressionSetSummary(daysOfWeek));
buf.Append("\n"); buf.Append('\n');
buf.Append("lastdayOfWeek: "); buf.Append("lastdayOfWeek: ");
buf.Append(lastdayOfWeek); buf.Append(lastdayOfWeek);
buf.Append("\n"); buf.Append('\n');
buf.Append("nearestWeekday: "); buf.Append("nearestWeekday: ");
buf.Append(nearestWeekday); buf.Append(nearestWeekday);
buf.Append("\n"); buf.Append('\n');
buf.Append("NthDayOfWeek: "); buf.Append("NthDayOfWeek: ");
buf.Append(nthdayOfWeek); buf.Append(nthdayOfWeek);
buf.Append("\n"); buf.Append('\n');
buf.Append("lastdayOfMonth: "); buf.Append("lastdayOfMonth: ");
buf.Append(lastdayOfMonth); buf.Append(lastdayOfMonth);
buf.Append("\n"); buf.Append('\n');
buf.Append("calendardayOfWeek: "); buf.Append("calendardayOfWeek: ");
buf.Append(calendardayOfWeek); buf.Append(calendardayOfWeek);
buf.Append("\n"); buf.Append('\n');
buf.Append("calendardayOfMonth: "); buf.Append("calendardayOfMonth: ");
buf.Append(calendardayOfMonth); buf.Append(calendardayOfMonth);
buf.Append("\n"); buf.Append('\n');
buf.Append("years: "); buf.Append("years: ");
buf.Append(GetExpressionSetSummary(years)); buf.Append(GetExpressionSetSummary(years));
buf.Append("\n"); buf.Append('\n');
return buf.ToString(); return buf.ToString();
} }
@ -799,7 +794,7 @@ namespace ASC.Notify.Cron
var val = iVal.ToString(CultureInfo.InvariantCulture); var val = iVal.ToString(CultureInfo.InvariantCulture);
if (!first) if (!first)
{ {
buf.Append(","); buf.Append(',');
} }
buf.Append(val); buf.Append(val);
first = false; first = false;
@ -811,7 +806,7 @@ namespace ASC.Notify.Cron
{ {
for (; i < s.Length && (s[i] == ' ' || s[i] == '\t'); i++) for (; i < s.Length && (s[i] == ' ' || s[i] == '\t'); i++)
{ {
;
} }
return i; return i;
} }
@ -820,7 +815,7 @@ namespace ASC.Notify.Cron
{ {
for (; i < s.Length && (s[i] != ' ' || s[i] != '\t'); i++) for (; i < s.Length && (s[i] != ' ' || s[i] != '\t'); i++)
{ {
;
} }
return i; return i;
} }
@ -1009,10 +1004,11 @@ namespace ASC.Notify.Cron
protected virtual ValueSet GetValue(int v, string s, int i) protected virtual ValueSet GetValue(int v, string s, int i)
{ {
var c = s[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') while (c >= '0' && c <= '9')
{ {
s1 += c; sb.Append(c);
i++; i++;
if (i >= s.Length) if (i >= s.Length)
{ {
@ -1023,13 +1019,13 @@ namespace ASC.Notify.Cron
var val = new ValueSet(); var val = new ValueSet();
if (i < s.Length) if (i < s.Length)
{ {
val.pos = i; val.Pos = i;
} }
else else
{ {
val.pos = i + 1; val.Pos = i + 1;
} }
val.theValue = Convert.ToInt32(s1, CultureInfo.InvariantCulture); val.TheValue = Convert.ToInt32(sb.ToString(), CultureInfo.InvariantCulture);
return val; return val;
} }
@ -1121,7 +1117,7 @@ namespace ASC.Notify.Cron
} }
else else
{ {
sec = ((int)seconds.First()); sec = (int)seconds.First();
d = d.AddMinutes(1); d = d.AddMinutes(1);
} }
d = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, sec, d.Millisecond); d = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, sec, d.Millisecond);
@ -1133,7 +1129,7 @@ namespace ASC.Notify.Cron
if (st != null && st.Count != 0) if (st != null && st.Count != 0)
{ {
t = min; t = min;
min = ((int)st.First()); min = (int)st.First();
} }
else else
{ {
@ -1253,7 +1249,7 @@ namespace ASC.Notify.Cron
tcal = new DateTime(tcal.Year, mon, day, hr, min, sec); tcal = new DateTime(tcal.Year, mon, day, hr, min, sec);
if (tcal.ToUniversalTime() < afterTimeUtc) if (tcal.ToUniversalTime() < afterTimeUtc)
{ {
day = ((int)daysOfMonth.First()); day = (int)daysOfMonth.First();
mon++; mon++;
} }
} }
@ -1271,7 +1267,7 @@ namespace ASC.Notify.Cron
} }
else else
{ {
day = ((int)daysOfMonth.First()); day = (int)daysOfMonth.First();
mon++; mon++;
} }
if (day != t || mon != tmon) if (day != t || mon != tmon)
@ -1299,9 +1295,9 @@ namespace ASC.Notify.Cron
{ {
if (lastdayOfWeek) 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; var daysToAdd = 0;
if (cDow < dow) if (cDow < dow)
{ {
@ -1342,9 +1338,9 @@ namespace ASC.Notify.Cron
} }
else if (nthdayOfWeek != 0) 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; var daysToAdd = 0;
if (cDow < dow) if (cDow < dow)
{ {
@ -1393,12 +1389,12 @@ namespace ASC.Notify.Cron
else else
{ {
var cDow = ((int)d.DayOfWeek) + 1; var cDow = ((int)d.DayOfWeek) + 1;
var dow = ((int)daysOfWeek.First()); var dow = (int)daysOfWeek.First();
st = daysOfWeek.TailSet(cDow); st = daysOfWeek.TailSet(cDow);
if (st != null && st.Count > 0) if (st != null && st.Count > 0)
{ {
dow = ((int)st.First()); dow = (int)st.First();
} }
var daysToAdd = 0; var daysToAdd = 0;
if (cDow < dow) if (cDow < dow)
@ -1448,15 +1444,15 @@ namespace ASC.Notify.Cron
return null; return null;
} }
st = months.TailSet((mon)); st = months.TailSet(mon);
if (st != null && st.Count != 0) if (st != null && st.Count != 0)
{ {
t = mon; t = mon;
mon = ((int)st.First()); mon = (int)st.First();
} }
else else
{ {
mon = ((int)months.First()); mon = (int)months.First();
year++; year++;
} }
if (mon != t) if (mon != t)
@ -1466,11 +1462,11 @@ namespace ASC.Notify.Cron
} }
d = new DateTime(d.Year, mon, d.Day, d.Hour, d.Minute, d.Second); d = new DateTime(d.Year, mon, d.Day, d.Hour, d.Minute, d.Second);
year = d.Year; year = d.Year;
st = years.TailSet((year)); st = years.TailSet(year);
if (st != null && st.Count != 0) if (st != null && st.Count != 0)
{ {
t = year; t = year;
year = ((int)st.First()); year = (int)st.First();
} }
else else
{ {
@ -1531,7 +1527,7 @@ namespace ASC.Notify.Cron
public class ValueSet public class ValueSet
{ {
public int pos; public int Pos { get; set; }
public int theValue; public int TheValue { get; set; }
} }
} }

View File

@ -37,7 +37,7 @@ namespace ASC.Notify.Cron
#endregion #endregion
public interface ISet : ICollection, IList public interface ISet : IList
{ {
#region Methods #region Methods

View File

@ -139,8 +139,8 @@ namespace ASC.Notify.Cron
private bool AddWithoutSorting(object obj) private bool AddWithoutSorting(object obj)
{ {
bool inserted; bool inserted = Contains(obj);
if (!(inserted = Contains(obj))) if (!inserted)
{ {
base.Add(obj); base.Add(obj);
} }

View File

@ -41,32 +41,32 @@ namespace ASC.Core.Notify
public DirectSubscriptionProvider(string sourceID, SubscriptionManager subscriptionManager, IRecipientProvider recipientProvider) 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.sourceID = sourceID;
this.subscriptionManager = subscriptionManager ?? throw new ArgumentNullException("subscriptionManager"); this.subscriptionManager = subscriptionManager ?? throw new ArgumentNullException(nameof(subscriptionManager));
this.recipientProvider = recipientProvider ?? throw new ArgumentNullException("recipientProvider"); this.recipientProvider = recipientProvider ?? throw new ArgumentNullException(nameof(recipientProvider));
} }
public object GetSubscriptionRecord(INotifyAction action, IRecipient recipient, string objectID) public object GetSubscriptionRecord(INotifyAction action, IRecipient recipient, string objectID)
{ {
if (action == null) throw new ArgumentNullException("action"); if (action == null) throw new ArgumentNullException(nameof(action));
if (recipient == null) throw new ArgumentNullException("recipient"); if (recipient == null) throw new ArgumentNullException(nameof(recipient));
return subscriptionManager.GetSubscriptionRecord(sourceID, action.ID, recipient.ID, objectID); return subscriptionManager.GetSubscriptionRecord(sourceID, action.ID, recipient.ID, objectID);
} }
public string[] GetSubscriptions(INotifyAction action, IRecipient recipient, bool checkSubscribe = true) public string[] GetSubscriptions(INotifyAction action, IRecipient recipient, bool checkSubscribe = true)
{ {
if (action == null) throw new ArgumentNullException("action"); if (action == null) throw new ArgumentNullException(nameof(action));
if (recipient == null) throw new ArgumentNullException("recipient"); if (recipient == null) throw new ArgumentNullException(nameof(recipient));
return subscriptionManager.GetSubscriptions(sourceID, action.ID, recipient.ID, checkSubscribe); return subscriptionManager.GetSubscriptions(sourceID, action.ID, recipient.ID, checkSubscribe);
} }
public IRecipient[] GetRecipients(INotifyAction action, string objectID) 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) return subscriptionManager.GetRecipients(sourceID, action.ID, objectID)
.Select(r => recipientProvider.GetRecipient(r)) .Select(r => recipientProvider.GetRecipient(r))
@ -76,53 +76,53 @@ namespace ASC.Core.Notify
public string[] GetSubscriptionMethod(INotifyAction action, IRecipient recipient) public string[] GetSubscriptionMethod(INotifyAction action, IRecipient recipient)
{ {
if (action == null) throw new ArgumentNullException("action"); if (action == null) throw new ArgumentNullException(nameof(action));
if (recipient == null) throw new ArgumentNullException("recipient"); if (recipient == null) throw new ArgumentNullException(nameof(recipient));
return subscriptionManager.GetSubscriptionMethod(sourceID, action.ID, recipient.ID); return subscriptionManager.GetSubscriptionMethod(sourceID, action.ID, recipient.ID);
} }
public void UpdateSubscriptionMethod(INotifyAction action, IRecipient recipient, params string[] senderNames) public void UpdateSubscriptionMethod(INotifyAction action, IRecipient recipient, params string[] senderNames)
{ {
if (action == null) throw new ArgumentNullException("action"); if (action == null) throw new ArgumentNullException(nameof(action));
if (recipient == null) throw new ArgumentNullException("recipient"); if (recipient == null) throw new ArgumentNullException(nameof(recipient));
subscriptionManager.UpdateSubscriptionMethod(sourceID, action.ID, recipient.ID, senderNames); subscriptionManager.UpdateSubscriptionMethod(sourceID, action.ID, recipient.ID, senderNames);
} }
public bool IsUnsubscribe(IDirectRecipient recipient, INotifyAction action, string objectID) public bool IsUnsubscribe(IDirectRecipient recipient, INotifyAction action, string objectID)
{ {
if (recipient == null) throw new ArgumentNullException("recipient"); if (recipient == null) throw new ArgumentNullException(nameof(recipient));
if (action == null) throw new ArgumentNullException("action"); if (action == null) throw new ArgumentNullException(nameof(action));
return subscriptionManager.IsUnsubscribe(sourceID, recipient.ID, action.ID, objectID); return subscriptionManager.IsUnsubscribe(sourceID, recipient.ID, action.ID, objectID);
} }
public void Subscribe(INotifyAction action, string objectID, IRecipient recipient) public void Subscribe(INotifyAction action, string objectID, IRecipient recipient)
{ {
if (action == null) throw new ArgumentNullException("action"); if (action == null) throw new ArgumentNullException(nameof(action));
if (recipient == null) throw new ArgumentNullException("recipient"); if (recipient == null) throw new ArgumentNullException(nameof(recipient));
subscriptionManager.Subscribe(sourceID, action.ID, objectID, recipient.ID); subscriptionManager.Subscribe(sourceID, action.ID, objectID, recipient.ID);
} }
public void UnSubscribe(INotifyAction action, string objectID, IRecipient recipient) public void UnSubscribe(INotifyAction action, string objectID, IRecipient recipient)
{ {
if (action == null) throw new ArgumentNullException("action"); if (action == null) throw new ArgumentNullException(nameof(action));
if (recipient == null) throw new ArgumentNullException("recipient"); if (recipient == null) throw new ArgumentNullException(nameof(recipient));
subscriptionManager.Unsubscribe(sourceID, action.ID, objectID, recipient.ID); subscriptionManager.Unsubscribe(sourceID, action.ID, objectID, recipient.ID);
} }
public void UnSubscribe(INotifyAction action) 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); subscriptionManager.UnsubscribeAll(sourceID, action.ID);
} }
public void UnSubscribe(INotifyAction action, string objectID) 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); subscriptionManager.UnsubscribeAll(sourceID, action.ID, objectID);
} }

View File

@ -49,7 +49,7 @@ namespace ASC.Core.Notify
public EmailSenderSink(INotifySender sender, IServiceProvider serviceProvider, IOptionsMonitor<ILog> options) 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; ServiceProvider = serviceProvider;
Log = options.Get("ASC.Notify"); Log = options.Get("ASC.Notify");
} }

View File

@ -47,7 +47,7 @@ namespace ASC.Notify.Engine
{ {
log = options.Get("ASC.Notify"); log = options.Get("ASC.Notify");
logMessages = options.Get("ASC.Notify.Messages"); 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); logOnly = "log".Equals(configuration["core:notify:postman"], StringComparison.InvariantCultureIgnoreCase);
log.DebugFormat("LogOnly: {0}", logOnly); log.DebugFormat("LogOnly: {0}", logOnly);
} }

View File

@ -54,8 +54,8 @@ namespace ASC.Notify.Engine
public void Add(ISendInterceptor interceptor) public void Add(ISendInterceptor interceptor)
{ {
if (interceptor == null) throw new ArgumentNullException("interceptor"); if (interceptor == null) throw new ArgumentNullException(nameof(interceptor));
if (string.IsNullOrEmpty(interceptor.Name)) throw new ArgumentException("empty name property", "interceptor"); if (string.IsNullOrEmpty(interceptor.Name)) throw new ArgumentException("empty name property", nameof(interceptor));
switch (interceptor.Lifetime) switch (interceptor.Lifetime)
{ {
@ -72,7 +72,7 @@ namespace ASC.Notify.Engine
public ISendInterceptor Get(string name) 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); var result = GetInternal(name, CallInterceptors);
if (result == null) result = GetInternal(name, globalInterceptors); if (result == null) result = GetInternal(name, globalInterceptors);
return result; return result;
@ -80,7 +80,7 @@ namespace ASC.Notify.Engine
public void Remove(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, CallInterceptors);
RemoveInternal(name, globalInterceptors); RemoveInternal(name, globalInterceptors);
@ -119,7 +119,7 @@ namespace ASC.Notify.Engine
private ISendInterceptor GetInternal(string name, Dictionary<string, ISendInterceptor> storage) private ISendInterceptor GetInternal(string name, Dictionary<string, ISendInterceptor> storage)
{ {
ISendInterceptor interceptor = null; ISendInterceptor interceptor;
lock (syncRoot) lock (syncRoot)
{ {
storage.TryGetValue(name, out interceptor); storage.TryGetValue(name, out interceptor);

View File

@ -76,7 +76,7 @@ namespace ASC.Notify.Engine
public NotifyEngine(Context context, IServiceProvider serviceProvider) 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"); log = serviceProvider.GetService<IOptionsMonitor<ILog>>().Get("ASC.Notify");
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
notifyScheduler = new Thread(NotifyScheduler) { IsBackground = true, Name = "NotifyScheduler" }; notifyScheduler = new Thread(NotifyScheduler) { IsBackground = true, Name = "NotifyScheduler" };
@ -102,8 +102,8 @@ namespace ASC.Notify.Engine
internal void RegisterSendMethod(Action<DateTime> method, string cron) internal void RegisterSendMethod(Action<DateTime> method, string cron)
{ {
if (method == null) throw new ArgumentNullException("method"); if (method == null) throw new ArgumentNullException(nameof(method));
if (string.IsNullOrEmpty(cron)) throw new ArgumentNullException("cron"); if (string.IsNullOrEmpty(cron)) throw new ArgumentNullException(nameof(cron));
var w = new SendMethodWrapper(method, cron, log); var w = new SendMethodWrapper(method, cron, log);
lock (sendMethods) lock (sendMethods)
@ -121,7 +121,7 @@ namespace ASC.Notify.Engine
internal void UnregisterSendMethod(Action<DateTime> method) internal void UnregisterSendMethod(Action<DateTime> method)
{ {
if (method == null) throw new ArgumentNullException("method"); if (method == null) throw new ArgumentNullException(nameof(method));
lock (sendMethods) lock (sendMethods)
{ {
@ -205,7 +205,7 @@ namespace ASC.Notify.Engine
NotifyRequest request = null; NotifyRequest request = null;
lock (requests) lock (requests)
{ {
if (requests.Any()) if (requests.Count > 0)
{ {
request = requests.Dequeue(); request = requests.Dequeue();
} }
@ -254,14 +254,14 @@ namespace ASC.Notify.Engine
sendResponces.AddRange(SendGroupNotify(request, serviceScope)); sendResponces.AddRange(SendGroupNotify(request, serviceScope));
} }
NotifyResult result = null; NotifyResult result;
if (sendResponces == null || sendResponces.Count == 0) if (sendResponces.Count == 0)
{ {
result = new NotifyResult(SendResult.OK, sendResponces); result = new NotifyResult(SendResult.OK, sendResponces);
} }
else 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); log.Debug(result);
return result; return result;
@ -346,7 +346,7 @@ namespace ASC.Notify.Engine
private List<SendResponse> SendDirectNotify(NotifyRequest request, IServiceScope serviceScope) 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 responses = new List<SendResponse>();
var response = CheckPreventInterceptors(request, InterceptorPlace.DirectSend, serviceScope, null); var response = CheckPreventInterceptors(request, InterceptorPlace.DirectSend, serviceScope, null);
@ -386,7 +386,7 @@ namespace ASC.Notify.Engine
} }
else 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); responses.Add(response);
} }
@ -401,7 +401,7 @@ namespace ASC.Notify.Engine
private SendResponse SendDirectNotify(NotifyRequest request, ISenderChannel channel, IServiceScope serviceScope) 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; request.CurrentSender = channel.SenderName;
@ -419,13 +419,13 @@ namespace ASC.Notify.Engine
private SendResponse CreateNoticeMessageFromNotifyRequest(NotifyRequest request, string sender, IServiceScope serviceScope, out NoticeMessage noticeMessage) 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 recipientProvider = request.GetRecipientsProvider(serviceScope);
var recipient = request.Recipient as IDirectRecipient; var recipient = request.Recipient as IDirectRecipient;
var addresses = recipient.Addresses; var addresses = recipient.Addresses;
if (addresses == null || !addresses.Any()) if (addresses == null || addresses.Length == 0)
{ {
addresses = recipientProvider.GetRecipientAddresses(request.Recipient as IDirectRecipient, sender); addresses = recipientProvider.GetRecipientAddresses(request.Recipient as IDirectRecipient, sender);
recipient = new DirectRecipient(request.Recipient.ID, request.Recipient.Name, addresses); recipient = new DirectRecipient(request.Recipient.ID, request.Recipient.Name, addresses);
@ -507,7 +507,7 @@ namespace ASC.Notify.Engine
var subscriptionProvider = request.GetSubscriptionProvider(serviceScope); var subscriptionProvider = request.GetSubscriptionProvider(serviceScope);
var senderNames = new List<string>(); 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)); senderNames.AddRange(request.Arguments.OfType<AdditionalSenderTag>().Select(tag => (string)tag.Value));
request.SenderNames = senderNames.ToArray(); request.SenderNames = senderNames.ToArray();
@ -535,7 +535,7 @@ namespace ASC.Notify.Engine
pattern = apProvider.GetPattern(request.NotifyAction, senderName); 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.");
} }
} }
} }
@ -554,12 +554,12 @@ namespace ASC.Notify.Engine
{ {
throw new NotifyException(string.Format("For pattern \"{0}\" formatter not instanced.", pattern), exc); throw new NotifyException(string.Format("For pattern \"{0}\" formatter not instanced.", pattern), exc);
} }
var tags = new string[0]; var tags = Array.Empty<string>();
try try
{ {
if (formatter != null) if (formatter != null)
{ {
tags = formatter.GetTags(pattern) ?? new string[0]; tags = formatter.GetTags(pattern) ?? Array.Empty<string>();
} }
} }
catch (Exception exc) catch (Exception exc)
@ -575,7 +575,7 @@ namespace ASC.Notify.Engine
} }
private class SendMethodWrapper private sealed class SendMethodWrapper
{ {
private readonly object locker = new object(); private readonly object locker = new object();
private readonly CronExpression cronExpression; private readonly CronExpression cronExpression;

View File

@ -75,9 +75,9 @@ namespace ASC.Notify.Engine
RequaredTags = new List<string>(); RequaredTags = new List<string>();
Interceptors = new List<ISendInterceptor>(); Interceptors = new List<ISendInterceptor>();
NotifySource = notifySource ?? throw new ArgumentNullException("notifySource"); NotifySource = notifySource ?? throw new ArgumentNullException(nameof(notifySource));
Recipient = recipient ?? throw new ArgumentNullException("recipient"); Recipient = recipient ?? throw new ArgumentNullException(nameof(recipient));
NotifyAction = action ?? throw new ArgumentNullException("action"); NotifyAction = action ?? throw new ArgumentNullException(nameof(action));
ObjectID = objectID; ObjectID = objectID;
IsNeedCheckSubscriptions = true; IsNeedCheckSubscriptions = true;
@ -118,14 +118,14 @@ namespace ASC.Notify.Engine
var index = Array.IndexOf(SenderNames, senderName); var index = Array.IndexOf(SenderNames, senderName);
if (index < 0) 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]; return Patterns[index];
} }
internal NotifyRequest Split(IRecipient recipient) 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) var newRequest = new NotifyRequest(NotifySource, NotifyAction, ObjectID, recipient)
{ {
SenderNames = SenderNames, SenderNames = SenderNames,

View File

@ -44,8 +44,8 @@ namespace ASC.Notify.Engine
public SendInterceptorSkeleton(string name, InterceptorPlace preventPlace, InterceptorLifetime lifetime, Func<NotifyRequest, InterceptorPlace, IServiceScope, bool> sendInterceptor) 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 (string.IsNullOrEmpty(name)) throw new ArgumentException("Empty name.", nameof(name));
if (sendInterceptor == null) throw new ArgumentNullException("sendInterceptor"); if (sendInterceptor == null) throw new ArgumentNullException(nameof(sendInterceptor));
method = sendInterceptor; method = sendInterceptor;
Name = name; Name = name;

View File

@ -94,7 +94,7 @@ namespace ASC.Core.Notify.Jabber
public int GetNewMessagesCount() public int GetNewMessagesCount()
{ {
var result = 0; const int result = 0;
if (IsServiceProbablyNotAvailable()) return result; if (IsServiceProbablyNotAvailable()) return result;
using (var service = GetService()) using (var service = GetService())

View File

@ -24,7 +24,6 @@
*/ */
using System;
using System.Collections.Generic; using System.Collections.Generic;
using ASC.Common.Module; using ASC.Common.Module;
@ -32,7 +31,7 @@ using ASC.Core.Common.Notify.Jabber;
namespace ASC.Core.Notify.Jabber namespace ASC.Core.Notify.Jabber
{ {
public class JabberServiceClientWcf : BaseWcfClient<IJabberService>, IJabberService, IDisposable public class JabberServiceClientWcf : BaseWcfClient<IJabberService>, IJabberService
{ {
public JabberServiceClientWcf() public JabberServiceClientWcf()
{ {

View File

@ -44,7 +44,7 @@ namespace ASC.Core.Notify
public JabberSenderSink(INotifySender sender, IServiceProvider serviceProvider) public JabberSenderSink(INotifySender sender, IServiceProvider serviceProvider)
{ {
this.sender = sender ?? throw new ArgumentNullException("sender"); this.sender = sender ?? throw new ArgumentNullException(nameof(sender));
ServiceProvider = serviceProvider; ServiceProvider = serviceProvider;
} }

View File

@ -48,25 +48,25 @@ namespace ASC.Notify.Messages
public NoticeMessage(IDirectRecipient recipient, INotifyAction action, string objectID) public NoticeMessage(IDirectRecipient recipient, INotifyAction action, string objectID)
{ {
Recipient = recipient ?? throw new ArgumentNullException("recipient"); Recipient = recipient ?? throw new ArgumentNullException(nameof(recipient));
Action = action; Action = action;
ObjectID = objectID; ObjectID = objectID;
} }
public NoticeMessage(IDirectRecipient recipient, INotifyAction action, string objectID, IPattern pattern) 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; Action = action;
Pattern = pattern ?? throw new ArgumentNullException("pattern"); Pattern = pattern ?? throw new ArgumentNullException(nameof(pattern));
ObjectID = objectID; ObjectID = objectID;
ContentType = pattern.ContentType; ContentType = pattern.ContentType;
} }
public NoticeMessage(IDirectRecipient recipient, string subject, string body, string 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; Subject = subject;
Body = body ?? throw new ArgumentNullException("body"); Body = body ?? throw new ArgumentNullException(nameof(body));
ContentType = contentType; ContentType = contentType;
} }
@ -89,7 +89,7 @@ namespace ASC.Notify.Messages
public void AddArgument(params ITagValue[] tagValues) public void AddArgument(params ITagValue[] tagValues)
{ {
if (tagValues == null) throw new ArgumentNullException("tagValues"); if (tagValues == null) throw new ArgumentNullException(nameof(tagValues));
Array.ForEach(tagValues, Array.ForEach(tagValues,
tagValue => tagValue =>
{ {

View File

@ -69,7 +69,7 @@ namespace ASC.Notify.Model
if (subscriptionRecord != null) if (subscriptionRecord != null)
{ {
var properties = subscriptionRecord.GetType().GetProperties(); var properties = subscriptionRecord.GetType().GetProperties();
if (properties.Any()) if (properties.Length > 0)
{ {
var property = properties.Single(p => p.Name == "Subscribed"); var property = properties.Single(p => p.Name == "Subscribed");
if (property != null) if (property != null)

View File

@ -43,7 +43,7 @@ namespace ASC.Notify.Model
public NotifyAction(string id, string name) public NotifyAction(string id, string name)
{ {
ID = id ?? throw new ArgumentNullException("id"); ID = id ?? throw new ArgumentNullException(nameof(id));
Name = name; Name = name;
} }
@ -69,7 +69,7 @@ namespace ASC.Notify.Model
public override string ToString() public override string ToString()
{ {
return string.Format("action: {0}", ID); return $"action: {ID}";
} }
} }
} }

View File

@ -43,9 +43,9 @@ namespace ASC.Notify.Model
public NotifyClientImpl(Context context, INotifySource notifySource, IServiceScope serviceScope) 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; 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) public void SendNoticeToAsync(INotifyAction action, IRecipient[] recipients, string[] senderNames, params ITagValue[] args)
@ -108,7 +108,7 @@ namespace ASC.Notify.Model
public void SendNoticeToAsync(INotifyAction action, string objectID, IRecipient[] recipients, string[] senderNames, bool checkSubsciption, params ITagValue[] args) 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"); BeginSingleRecipientEvent("__syspreventduplicateinterceptor");
@ -127,8 +127,8 @@ namespace ASC.Notify.Model
private NotifyRequest CreateRequest(INotifyAction action, string objectID, IRecipient recipient, ITagValue[] args, string[] senders, bool checkSubsciption) private NotifyRequest CreateRequest(INotifyAction action, string objectID, IRecipient recipient, ITagValue[] args, string[] senders, bool checkSubsciption)
{ {
if (action == null) throw new ArgumentNullException("action"); if (action == null) throw new ArgumentNullException(nameof(action));
if (recipient == null) throw new ArgumentNullException("recipient"); if (recipient == null) throw new ArgumentNullException(nameof(recipient));
var request = new NotifyRequest(notifySource, action, objectID, recipient) var request = new NotifyRequest(notifySource, action, objectID, recipient)
{ {

View File

@ -67,9 +67,9 @@ namespace ASC.Core.Notify
private UserManager UserManager { get; } private UserManager UserManager { get; }
private SubscriptionManager SubscriptionManager { 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"); if (string.IsNullOrEmpty(id)) throw new ArgumentNullException(nameof(id));
ID = id; ID = id;
UserManager = userManager; UserManager = userManager;
@ -77,7 +77,7 @@ namespace ASC.Core.Notify
SubscriptionManager = subscriptionManager; 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) : this(id.ToString(), userManager, recipientsProvider, subscriptionManager)
{ {
} }
@ -132,12 +132,12 @@ namespace ASC.Core.Notify
{ {
var subscriptionProvider = new DirectSubscriptionProvider(ID, SubscriptionManager, RecipientsProvider); var subscriptionProvider = new DirectSubscriptionProvider(ID, SubscriptionManager, RecipientsProvider);
return new TopSubscriptionProvider(RecipientsProvider, subscriptionProvider, WorkContext.DefaultClientSenders) ?? 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() 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.");
} }
} }
} }

View File

@ -71,7 +71,7 @@ namespace ASC.Notify.Patterns
base.AfterFormat(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; if (!(e.OriginalValue is string originalString)) return;
var lines = originalString.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var lines = originalString.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
@ -79,9 +79,9 @@ namespace ASC.Notify.Patterns
e.NewValue = string.Empty; e.NewValue = string.Empty;
for (var i = 0; i < lines.Length - 1; i++) 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}";
} }
} }
} }

View File

@ -52,8 +52,8 @@ namespace ASC.Notify.Patterns
{ {
if (string.IsNullOrEmpty(id)) throw new ArgumentException("id"); if (string.IsNullOrEmpty(id)) throw new ArgumentException("id");
ID = id; ID = id;
Subject = subject ?? throw new ArgumentNullException("subject"); Subject = subject ?? throw new ArgumentNullException(nameof(subject));
Body = body ?? throw new ArgumentNullException("body"); Body = body ?? throw new ArgumentNullException(nameof(body));
ContentType = string.IsNullOrEmpty(contentType) ? HTMLContentType : contentType; ContentType = string.IsNullOrEmpty(contentType) ? HTMLContentType : contentType;
} }

View File

@ -45,16 +45,16 @@ namespace ASC.Notify.Patterns
} }
public PatternFormatter() protected PatternFormatter()
{ {
} }
public PatternFormatter(string tagSearchRegExp) protected PatternFormatter(string tagSearchRegExp)
: this(tagSearchRegExp, false) : this(tagSearchRegExp, false)
{ {
} }
internal PatternFormatter(string tagSearchRegExp, bool formatMessage) protected PatternFormatter(string tagSearchRegExp, bool formatMessage)
{ {
if (string.IsNullOrEmpty(tagSearchRegExp)) throw new ArgumentException("tagSearchRegExp"); if (string.IsNullOrEmpty(tagSearchRegExp)) throw new ArgumentException("tagSearchRegExp");
@ -65,7 +65,7 @@ namespace ASC.Notify.Patterns
public string[] GetTags(IPattern pattern) 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)); var findedTags = new List<string>(SearchTags(pattern.Body));
Array.ForEach(SearchTags(pattern.Subject), tag => { if (!findedTags.Contains(tag)) findedTags.Add(tag); }); Array.ForEach(SearchTags(pattern.Subject), tag => { if (!findedTags.Contains(tag)) findedTags.Add(tag); });
@ -74,9 +74,9 @@ namespace ASC.Notify.Patterns
public void FormatMessage(INoticeMessage message, ITagValue[] tagsValues) 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 (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); BeforeFormat(message, tagsValues);
@ -98,7 +98,7 @@ namespace ASC.Notify.Patterns
protected virtual string[] SearchTags(string text) 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 maches = RegEx.Matches(text);
var findedTags = new List<string>(maches.Count); var findedTags = new List<string>(maches.Count);

Some files were not shown because too many files have changed in this diff Show More