Merge branch 'feature/backend-refactor' into feature/files-mapping

This commit is contained in:
Maksim Chegulov 2022-03-10 12:19:18 +03:00
commit 26066ccb7f
286 changed files with 7845 additions and 8539 deletions

View File

@ -29,34 +29,30 @@ dotnet_style_qualification_for_method = false:silent
dotnet_style_qualification_for_property = false:silent
# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true:warning
dotnet_style_predefined_type_for_member_access = true:warning
dotnet_style_predefined_type_for_locals_parameters_members = true:silent
dotnet_style_predefined_type_for_member_access = true:silent
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
dotnet_style_parentheses_in_other_operators = always_for_clarity:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
# Modifier preferences
dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
# Expression-level preferences
dotnet_style_coalesce_expression = true:warning
dotnet_style_collection_initializer = true:warning
dotnet_style_explicit_tuple_names = true:warning
dotnet_style_null_propagation = true:warning
dotnet_style_object_initializer = true:warning
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true:warning
dotnet_style_prefer_compound_assignment = true:warning
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_return = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning
dotnet_style_prefer_inferred_tuple_names = true:warning
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
dotnet_style_prefer_simplified_boolean_expressions = true:warning
dotnet_style_prefer_simplified_interpolation = true:suggestion
# Field preferences
dotnet_style_readonly_field = true:warning
@ -64,6 +60,13 @@ dotnet_style_readonly_field = true:warning
# Parameter preferences
dotnet_code_quality_unused_parameters = all:warning
# Suppression preferences
dotnet_remove_unnecessary_suppression_exclusions = none
# New line preferences
dotnet_style_allow_multiple_blank_lines_experimental = false
dotnet_style_allow_statement_immediately_after_block_experimental = false
#### C# Coding Conventions ####
# var preferences
@ -72,44 +75,48 @@ csharp_style_var_for_built_in_types = true:warning
csharp_style_var_when_type_is_apparent = true:warning
# Expression-bodied members
csharp_style_expression_bodied_accessors = when_on_single_line:suggestion
csharp_style_expression_bodied_methods = false:silent
csharp_style_expression_bodied_constructors = false:silent
csharp_style_expression_bodied_indexers = when_on_single_line:suggestion
csharp_style_expression_bodied_lambdas = when_on_single_line:suggestion
csharp_style_expression_bodied_local_functions = when_on_single_line:suggestion
csharp_style_expression_bodied_methods = false:suggestion
csharp_style_expression_bodied_operators = false:silent
csharp_style_expression_bodied_properties = when_on_single_line:suggestion
csharp_style_expression_bodied_properties = true:silent
csharp_style_expression_bodied_indexers = true:silent
csharp_style_expression_bodied_accessors = true:silent
# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check = true:warning
csharp_style_pattern_matching_over_is_with_cast_check = true:warning
csharp_style_prefer_switch_expression = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
# Null-checking preferences
csharp_style_conditional_delegate_call = true:warning
csharp_style_conditional_delegate_call = true:suggestion
# Modifier preferences
csharp_prefer_static_local_function = true:suggestion
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion
# Code-block preferences
csharp_prefer_braces = true:silent
csharp_prefer_simple_using_statement = true:suggestion
csharp_prefer_braces = true:warning
csharp_prefer_simple_using_statement = false:silent
csharp_style_namespace_declarations = file_scoped:warning
# Expression-level preferences
csharp_prefer_simple_default_expression = true:warning
csharp_style_deconstructed_variable_declaration = true:warning
csharp_style_inlined_variable_declaration = true:warning
csharp_style_pattern_local_over_anonymous_function = true:warning
csharp_style_prefer_index_operator = true:warning
csharp_style_prefer_range_operator = true:warning
csharp_style_throw_expression = true:warning
csharp_prefer_simple_default_expression = false:silent
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = false:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_pattern_local_over_anonymous_function = true:suggestion
csharp_style_prefer_index_operator = false:suggestion
csharp_style_prefer_null_check_over_type_check = true:suggestion
csharp_style_prefer_range_operator = false:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_unused_value_assignment_preference = discard_variable:suggestion
csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion
# 'using' directive preferences
csharp_using_directive_placement = outside_namespace:silent
csharp_using_directive_placement = outside_namespace:warning
# New line preferences
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false:silent
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false:silent
csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent
#### C# Formatting Rules ####
@ -126,7 +133,7 @@ csharp_new_line_between_query_expression_clauses = true
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = false
csharp_indent_case_contents_when_block = true
csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true
@ -162,32 +169,32 @@ csharp_preserve_single_line_statements = true
# Naming rules
dotnet_naming_rule.private_or_internal_field_should_be_begin_with_underscore.severity = warning
dotnet_naming_rule.private_or_internal_field_should_be_begin_with_underscore.symbols = private_or_internal_field
dotnet_naming_rule.private_or_internal_field_should_be_begin_with_underscore.style = begin_with_underscore
dotnet_naming_rule.interface_should_be_begins_with_i.severity = warning
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity = warning
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = warning
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.private_or_internal_field.applicable_kinds = field
dotnet_naming_symbols.private_or_internal_field.applicable_accessibilities = internal, private, private_protected
dotnet_naming_symbols.private_or_internal_field.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Naming styles
dotnet_naming_style.pascal_case.required_prefix =
@ -200,5 +207,58 @@ dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
# Default severity for analyzer diagnostics with category 'Style'
dotnet_analyzer_diagnostic.category-Style.severity = silent
dotnet_naming_style.begin_with_underscore.required_prefix = _
dotnet_naming_style.begin_with_underscore.required_suffix =
dotnet_naming_style.begin_with_underscore.word_separator =
dotnet_naming_style.begin_with_underscore.capitalization = camel_case
csharp_style_expression_bodied_lambdas = true:silent
csharp_style_expression_bodied_local_functions = false:silent
csharp_style_prefer_local_over_anonymous_function = true:suggestion
csharp_style_prefer_tuple_swap = true:suggestion
csharp_prefer_static_local_function = true:suggestion
csharp_style_prefer_switch_expression = true:suggestion
csharp_style_prefer_pattern_matching = true:silent
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_extended_property_pattern = true:suggestion
dotnet_diagnostic.CA1001.severity = warning
dotnet_diagnostic.CA1805.severity = warning
dotnet_diagnostic.CA1841.severity = warning
[*.{cs,vb}]
dotnet_style_operator_placement_when_wrapping = beginning_of_line
tab_width = 4
indent_size = 4
end_of_line = crlf
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_return = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
dotnet_style_namespace_match_folder = true:suggestion
dotnet_style_readonly_field = true:warning
dotnet_style_predefined_type_for_locals_parameters_members = true:silent
dotnet_style_predefined_type_for_member_access = true:silent
dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
dotnet_style_allow_multiple_blank_lines_experimental = false:silent
dotnet_style_allow_statement_immediately_after_block_experimental = false:silent
dotnet_code_quality_unused_parameters = all:warning
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_operators = always_for_clarity:silent
dotnet_style_qualification_for_field = false:silent
dotnet_style_qualification_for_property = false:silent
dotnet_style_qualification_for_method = false:silent
dotnet_style_qualification_for_event = false:silent
dotnet_diagnostic.CA1715.severity = warning
dotnet_diagnostic.CA1716.severity = silent
dotnet_diagnostic.CA5397.severity = warning

View File

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ProduceReferenceAssembly>false</ProduceReferenceAssembly>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

View File

@ -85,18 +85,18 @@ public sealed class ApiDateTime : IComparable<ApiDateTime>, IComparable
public static ApiDateTime Parse(string data, TimeZoneInfo tz, TenantManager tenantManager, TimeZoneConverter timeZoneConverter)
{
if (string.IsNullOrEmpty(data)) throw new ArgumentNullException(nameof(data));
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(data);
var offsetPart = data.Substring(data.Length - 6, 6);
if (DateTime.TryParseExact(data, Formats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var dateTime))
{
//Parse time
var tzOffset = TimeSpan.Zero;
if (offsetPart.Contains(':') && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset))
if (offsetPart.Contains(':') && TimeSpan.TryParse(offsetPart.TrimStart('+'), out tzOffset))
{
return new ApiDateTime(dateTime, tzOffset);
}
if (!data.EndsWith("Z", true, CultureInfo.InvariantCulture))
{
if (tz == null)
@ -139,7 +139,7 @@ public sealed class ApiDateTime : IComparable<ApiDateTime>, IComparable
if (value.Kind == DateTimeKind.Unspecified)
{
value = new DateTime(value.Ticks, DateTimeKind.Utc); //Assume it's utc
}
}
if (value.Kind == DateTimeKind.Utc)
{
@ -166,8 +166,8 @@ public sealed class ApiDateTime : IComparable<ApiDateTime>, IComparable
private string ToRoundTripString(DateTime date, TimeSpan offset)
{
var dateString = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff", CultureInfo.InvariantCulture);
var offsetString = offset.Ticks == 0
? "Z" : ((offset < TimeSpan.Zero)
var offsetString = offset.Ticks == 0
? "Z" : ((offset < TimeSpan.Zero)
? "-" : "+") + offset.ToString("hh\\:mm", CultureInfo.InvariantCulture);
return dateString + offsetString;
@ -277,9 +277,9 @@ public sealed class ApiDateTime : IComparable<ApiDateTime>, IComparable
public override bool Equals(object obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
if (!(obj is ApiDateTime)) return false;
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
if (!(obj is ApiDateTime)) return false;
return Equals((ApiDateTime)obj);
}
@ -369,7 +369,7 @@ public class ApiDateTimeConverter : System.Text.Json.Serialization.JsonConverter
}
else
{
if (DateTime.TryParseExact(reader.GetString(), ApiDateTime.Formats,
if (DateTime.TryParseExact(reader.GetString(), ApiDateTime.Formats,
CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var dateTime))
{
return new ApiDateTime(dateTime, TimeSpan.Zero);
@ -377,7 +377,7 @@ public class ApiDateTimeConverter : System.Text.Json.Serialization.JsonConverter
else
{
return new ApiDateTime();
}
}
}
}

View File

@ -1,11 +1,9 @@
global using System;
global using System.Collections.Generic;
global using System.ComponentModel;
global using System.Globalization;
global using System.Linq;
global using System.ComponentModel;
global using System.Globalization;
global using System.Linq.Expressions;
global using System.Net;
global using System.Net.Http;
global using System.Reflection;
global using System.Runtime.Serialization;
global using System.Security;
@ -14,8 +12,7 @@ global using System.Security.Claims;
global using System.Text.Encodings.Web;
global using System.Text.Json;
global using System.Text.Json.Serialization;
global using System.Threading;
global using System.Threading.Tasks;
global using System.Web;
global using System.Xml.Linq;

View File

@ -1,116 +1,115 @@
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
namespace ASC.Web.Api.Models;
public class EmployeeWraper
{
public Guid Id { get; set; }
public string DisplayName { get; set; }
public string Title { get; set; }
public string AvatarSmall { get; set; }
public string ProfileUrl { get; set; }
public static EmployeeWraper GetSample()
{
return new EmployeeWraper
{
Id = Guid.Empty,
DisplayName = "Mike Zanyatski",
Title = "Manager",
AvatarSmall = "url to small avatar",
};
}
}
[Scope]
public class EmployeeWraperHelper
{
protected UserPhotoManager UserPhotoManager { get; }
protected UserManager UserManager { get; }
private readonly ApiContext _httpContext;
private readonly DisplayUserSettingsHelper _displayUserSettingsHelper;
private readonly CommonLinkUtility _commonLinkUtility;
public EmployeeWraperHelper(
ApiContext httpContext,
DisplayUserSettingsHelper displayUserSettingsHelper,
UserPhotoManager userPhotoManager,
CommonLinkUtility commonLinkUtility,
UserManager userManager)
{
UserPhotoManager = userPhotoManager;
UserManager = userManager;
_httpContext = httpContext;
_displayUserSettingsHelper = displayUserSettingsHelper;
_commonLinkUtility = commonLinkUtility;
}
public EmployeeWraper Get(UserInfo userInfo)
{
return Init(new EmployeeWraper(), userInfo);
}
public EmployeeWraper Get(Guid userId)
{
try
{
return Get(UserManager.GetUsers(userId));
}
catch (Exception)
{
return Get(Constants.LostUser);
}
}
protected EmployeeWraper Init(EmployeeWraper result, UserInfo userInfo)
{
result.Id = userInfo.Id;
result.DisplayName = _displayUserSettingsHelper.GetFullUserName(userInfo);
if (!string.IsNullOrEmpty(userInfo.Title))
{
result.Title = userInfo.Title;
}
var userInfoLM = userInfo.LastModified.GetHashCode();
if (_httpContext.Check("avatarSmall"))
{
result.AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.Id, out var isdef)
+ (isdef ? "" : $"?_={userInfoLM}");
}
if (result.Id != Guid.Empty)
{
var profileUrl = _commonLinkUtility.GetUserProfile(userInfo, false);
result.ProfileUrl = _commonLinkUtility.GetFullAbsolutePath(profileUrl);
}
return result;
}
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
namespace ASC.Web.Api.Models;
public class EmployeeDto
{
public Guid Id { get; set; }
public string DisplayName { get; set; }
public string Title { get; set; }
public string AvatarSmall { get; set; }
public string ProfileUrl { get; set; }
public static EmployeeDto GetSample()
{
return new EmployeeDto
{
Id = Guid.Empty,
DisplayName = "Mike Zanyatski",
Title = "Manager",
AvatarSmall = "url to small avatar",
};
}
}
[Scope]
public class EmployeeDtoHelper
{
protected readonly UserPhotoManager UserPhotoManager;
protected readonly UserManager UserManager;
private readonly ApiContext _httpContext;
private readonly DisplayUserSettingsHelper _displayUserSettingsHelper;
private readonly CommonLinkUtility _commonLinkUtility;
public EmployeeDtoHelper(
ApiContext httpContext,
DisplayUserSettingsHelper displayUserSettingsHelper,
UserPhotoManager userPhotoManager,
CommonLinkUtility commonLinkUtility,
UserManager userManager)
{
UserPhotoManager = userPhotoManager;
UserManager = userManager;
_httpContext = httpContext;
_displayUserSettingsHelper = displayUserSettingsHelper;
_commonLinkUtility = commonLinkUtility;
}
public EmployeeDto Get(UserInfo userInfo)
{
return Init(new EmployeeDto(), userInfo);
}
public EmployeeDto Get(Guid userId)
{
try
{
return Get(UserManager.GetUsers(userId));
}
catch (Exception)
{
return Get(Constants.LostUser);
}
}
protected EmployeeDto Init(EmployeeDto result, UserInfo userInfo)
{
result.Id = userInfo.Id;
result.DisplayName = _displayUserSettingsHelper.GetFullUserName(userInfo);
if (!string.IsNullOrEmpty(userInfo.Title))
{
result.Title = userInfo.Title;
}
var userInfoLM = userInfo.LastModified.GetHashCode();
if (_httpContext.Check("avatarSmall"))
{
result.AvatarSmall = UserPhotoManager.GetSmallPhotoURL(userInfo.Id, out var isdef)
+ (isdef ? "" : $"?_={userInfoLM}");
}
if (result.Id != Guid.Empty)
{
var profileUrl = _commonLinkUtility.GetUserProfile(userInfo, false);
result.ProfileUrl = _commonLinkUtility.GetFullAbsolutePath(profileUrl);
}
return result;
}
}

View File

@ -1,257 +1,257 @@
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
namespace ASC.Web.Api.Models;
public class EmployeeWraperFull : EmployeeWraper
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public List<Contact> Contacts { get; set; }
public ApiDateTime Birthday { get; set; }
public string Sex { get; set; }
public EmployeeStatus Status { get; set; }
public EmployeeActivationStatus ActivationStatus { get; set; }
public ApiDateTime Terminated { get; set; }
public string Department { get; set; }
public ApiDateTime WorkFrom { get; set; }
public List<GroupWrapperSummary> Groups { get; set; }
public string Location { get; set; }
public string Notes { get; set; }
public string AvatarMax { get; set; }
public string AvatarMedium { get; set; }
public string Avatar { get; set; }
public bool IsAdmin { get; set; }
public bool IsLDAP { get; set; }
public List<string> ListAdminModules { get; set; }
public bool IsOwner { get; set; }
public bool IsVisitor { get; set; }
public string CultureName { get; set; }
public string MobilePhone { get; set; }
public MobilePhoneActivationStatus MobilePhoneActivationStatus { get; set; }
public bool IsSSO { get; set; }
public new static EmployeeWraperFull GetSample()
{
return new EmployeeWraperFull
{
Avatar = "url to big avatar",
AvatarSmall = "url to small avatar",
AvatarMax = "url to max avatar",
Contacts = new List<Contact> { Contact.GetSample() },
Email = "my@gmail.com",
FirstName = "Mike",
Id = Guid.Empty,
IsAdmin = false,
ListAdminModules = new List<string> { "projects", "crm" },
UserName = "Mike.Zanyatski",
LastName = "Zanyatski",
Title = "Manager",
Groups = new List<GroupWrapperSummary> { GroupWrapperSummary.GetSample() },
AvatarMedium = "url to medium avatar",
Birthday = ApiDateTime.GetSample(),
Department = "Marketing",
Location = "Palo Alto",
Notes = "Notes to worker",
Sex = "male",
Status = EmployeeStatus.Active,
WorkFrom = ApiDateTime.GetSample(),
Terminated = ApiDateTime.GetSample(),
CultureName = "en-EN",
IsLDAP = false,
IsSSO = false
};
}
}
[Scope]
public class EmployeeWraperFullHelper : EmployeeWraperHelper
{
private readonly ApiContext _context;
private readonly WebItemSecurity _webItemSecurity;
private readonly ApiDateTimeHelper _apiDateTimeHelper;
public EmployeeWraperFullHelper(
ApiContext context,
UserManager userManager,
UserPhotoManager userPhotoManager,
WebItemSecurity webItemSecurity,
CommonLinkUtility commonLinkUtility,
DisplayUserSettingsHelper displayUserSettingsHelper,
ApiDateTimeHelper apiDateTimeHelper)
: base(context, displayUserSettingsHelper, userPhotoManager, commonLinkUtility, userManager)
{
_context = context;
_webItemSecurity = webItemSecurity;
_apiDateTimeHelper = apiDateTimeHelper;
}
public static Expression<Func<User, UserInfo>> GetExpression(ApiContext apiContext)
{
if (apiContext?.Fields == null)
{
return null;
}
var newExpr = Expression.New(typeof(UserInfo));
//i => new UserInfo { ID = i.id }
var parameter = Expression.Parameter(typeof(User), "i");
var bindExprs = new List<MemberAssignment>();
if (apiContext.Check("Id"))
{
bindExprs.Add(Expression.Bind(typeof(UserInfo).GetProperty("ID"),
Expression.Property(parameter, typeof(User).GetProperty("Id"))));
}
var body = Expression.MemberInit(newExpr, bindExprs);
var lambda = Expression.Lambda<Func<User, UserInfo>>(body, parameter);
return lambda;
}
public EmployeeWraperFull GetFull(UserInfo userInfo)
{
var result = new EmployeeWraperFull
{
UserName = userInfo.UserName,
FirstName = userInfo.FirstName,
LastName = userInfo.LastName,
Birthday = _apiDateTimeHelper.Get(userInfo.BirthDate),
Status = userInfo.Status,
ActivationStatus = userInfo.ActivationStatus & ~EmployeeActivationStatus.AutoGenerated,
Terminated = _apiDateTimeHelper.Get(userInfo.TerminatedDate),
WorkFrom = _apiDateTimeHelper.Get(userInfo.WorkFromDate),
Email = userInfo.Email,
IsVisitor = userInfo.IsVisitor(UserManager),
IsAdmin = userInfo.IsAdmin(UserManager),
IsOwner = userInfo.IsOwner(_context.Tenant),
IsLDAP = userInfo.IsLDAP(),
IsSSO = userInfo.IsSSO()
};
Init(result, userInfo);
if (userInfo.Sex.HasValue)
{
result.Sex = userInfo.Sex.Value ? "male" : "female";
}
if (!string.IsNullOrEmpty(userInfo.Location))
{
result.Location = userInfo.Location;
}
if (!string.IsNullOrEmpty(userInfo.Notes))
{
result.Notes = userInfo.Notes;
}
if (!string.IsNullOrEmpty(userInfo.MobilePhone))
{
result.MobilePhone = userInfo.MobilePhone;
}
result.MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus;
if (!string.IsNullOrEmpty(userInfo.CultureName))
{
result.CultureName = userInfo.CultureName;
}
FillConacts(result, userInfo);
if (_context.Check("groups") || _context.Check("department"))
{
var groups = UserManager.GetUserGroups(userInfo.Id)
.Select(x => new GroupWrapperSummary(x, UserManager))
.ToList();
if (groups.Count > 0)
{
result.Groups = groups;
result.Department = string.Join(", ", result.Groups.Select(d => d.Name.HtmlEncode()));
}
else
{
result.Department = "";
}
}
var userInfoLM = userInfo.LastModified.GetHashCode();
if (_context.Check("avatarMax"))
{
result.AvatarMax = UserPhotoManager.GetMaxPhotoURL(userInfo.Id, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
}
if (_context.Check("avatarMedium"))
{
result.AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.Id, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
}
if (_context.Check("avatar"))
{
result.Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.Id, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
}
if (_context.Check("listAdminModules"))
{
var listAdminModules = userInfo.GetListAdminModules(_webItemSecurity);
if (listAdminModules.Count > 0)
{
result.ListAdminModules = listAdminModules;
}
}
return result;
}
private void FillConacts(EmployeeWraperFull employeeWraperFull, UserInfo userInfo)
{
if (userInfo.ContactsList == null)
{
return;
}
var contacts = new List<Contact>();
for (var i = 0; i < userInfo.ContactsList.Count; i += 2)
{
if (i + 1 < userInfo.ContactsList.Count)
{
contacts.Add(new Contact(userInfo.ContactsList[i], userInfo.ContactsList[i + 1]));
}
}
if (contacts.Count > 0)
{
employeeWraperFull.Contacts = contacts;
}
}
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
namespace ASC.Web.Api.Models;
public class EmployeeFullDto : EmployeeDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public List<Contact> Contacts { get; set; }
public ApiDateTime Birthday { get; set; }
public string Sex { get; set; }
public EmployeeStatus Status { get; set; }
public EmployeeActivationStatus ActivationStatus { get; set; }
public ApiDateTime Terminated { get; set; }
public string Department { get; set; }
public ApiDateTime WorkFrom { get; set; }
public List<GroupSummaryDto> Groups { get; set; }
public string Location { get; set; }
public string Notes { get; set; }
public string AvatarMax { get; set; }
public string AvatarMedium { get; set; }
public string Avatar { get; set; }
public bool IsAdmin { get; set; }
public bool IsLDAP { get; set; }
public List<string> ListAdminModules { get; set; }
public bool IsOwner { get; set; }
public bool IsVisitor { get; set; }
public string CultureName { get; set; }
public string MobilePhone { get; set; }
public MobilePhoneActivationStatus MobilePhoneActivationStatus { get; set; }
public bool IsSSO { get; set; }
public new static EmployeeFullDto GetSample()
{
return new EmployeeFullDto
{
Avatar = "url to big avatar",
AvatarSmall = "url to small avatar",
AvatarMax = "url to max avatar",
Contacts = new List<Contact> { Contact.GetSample() },
Email = "my@gmail.com",
FirstName = "Mike",
Id = Guid.Empty,
IsAdmin = false,
ListAdminModules = new List<string> { "projects", "crm" },
UserName = "Mike.Zanyatski",
LastName = "Zanyatski",
Title = "Manager",
Groups = new List<GroupSummaryDto> { GroupSummaryDto.GetSample() },
AvatarMedium = "url to medium avatar",
Birthday = ApiDateTime.GetSample(),
Department = "Marketing",
Location = "Palo Alto",
Notes = "Notes to worker",
Sex = "male",
Status = EmployeeStatus.Active,
WorkFrom = ApiDateTime.GetSample(),
Terminated = ApiDateTime.GetSample(),
CultureName = "en-EN",
IsLDAP = false,
IsSSO = false
};
}
}
[Scope]
public class EmployeeFullDtoHelper : EmployeeDtoHelper
{
private readonly ApiContext _context;
private readonly WebItemSecurity _webItemSecurity;
private readonly ApiDateTimeHelper _apiDateTimeHelper;
public EmployeeFullDtoHelper(
ApiContext context,
UserManager userManager,
UserPhotoManager userPhotoManager,
WebItemSecurity webItemSecurity,
CommonLinkUtility commonLinkUtility,
DisplayUserSettingsHelper displayUserSettingsHelper,
ApiDateTimeHelper apiDateTimeHelper)
: base(context, displayUserSettingsHelper, userPhotoManager, commonLinkUtility, userManager)
{
_context = context;
_webItemSecurity = webItemSecurity;
_apiDateTimeHelper = apiDateTimeHelper;
}
public static Expression<Func<User, UserInfo>> GetExpression(ApiContext apiContext)
{
if (apiContext?.Fields == null)
{
return null;
}
var newExpr = Expression.New(typeof(UserInfo));
//i => new UserInfo { ID = i.id }
var parameter = Expression.Parameter(typeof(User), "i");
var bindExprs = new List<MemberAssignment>();
if (apiContext.Check("Id"))
{
bindExprs.Add(Expression.Bind(typeof(UserInfo).GetProperty("ID"),
Expression.Property(parameter, typeof(User).GetProperty("Id"))));
}
var body = Expression.MemberInit(newExpr, bindExprs);
var lambda = Expression.Lambda<Func<User, UserInfo>>(body, parameter);
return lambda;
}
public EmployeeFullDto GetFull(UserInfo userInfo)
{
var result = new EmployeeFullDto
{
UserName = userInfo.UserName,
FirstName = userInfo.FirstName,
LastName = userInfo.LastName,
Birthday = _apiDateTimeHelper.Get(userInfo.BirthDate),
Status = userInfo.Status,
ActivationStatus = userInfo.ActivationStatus & ~EmployeeActivationStatus.AutoGenerated,
Terminated = _apiDateTimeHelper.Get(userInfo.TerminatedDate),
WorkFrom = _apiDateTimeHelper.Get(userInfo.WorkFromDate),
Email = userInfo.Email,
IsVisitor = userInfo.IsVisitor(UserManager),
IsAdmin = userInfo.IsAdmin(UserManager),
IsOwner = userInfo.IsOwner(_context.Tenant),
IsLDAP = userInfo.IsLDAP(),
IsSSO = userInfo.IsSSO()
};
Init(result, userInfo);
if (userInfo.Sex.HasValue)
{
result.Sex = userInfo.Sex.Value ? "male" : "female";
}
if (!string.IsNullOrEmpty(userInfo.Location))
{
result.Location = userInfo.Location;
}
if (!string.IsNullOrEmpty(userInfo.Notes))
{
result.Notes = userInfo.Notes;
}
if (!string.IsNullOrEmpty(userInfo.MobilePhone))
{
result.MobilePhone = userInfo.MobilePhone;
}
result.MobilePhoneActivationStatus = userInfo.MobilePhoneActivationStatus;
if (!string.IsNullOrEmpty(userInfo.CultureName))
{
result.CultureName = userInfo.CultureName;
}
FillConacts(result, userInfo);
if (_context.Check("groups") || _context.Check("department"))
{
var groups = UserManager.GetUserGroups(userInfo.Id)
.Select(x => new GroupSummaryDto(x, UserManager))
.ToList();
if (groups.Count > 0)
{
result.Groups = groups;
result.Department = string.Join(", ", result.Groups.Select(d => d.Name.HtmlEncode()));
}
else
{
result.Department = "";
}
}
var userInfoLM = userInfo.LastModified.GetHashCode();
if (_context.Check("avatarMax"))
{
result.AvatarMax = UserPhotoManager.GetMaxPhotoURL(userInfo.Id, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
}
if (_context.Check("avatarMedium"))
{
result.AvatarMedium = UserPhotoManager.GetMediumPhotoURL(userInfo.Id, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
}
if (_context.Check("avatar"))
{
result.Avatar = UserPhotoManager.GetBigPhotoURL(userInfo.Id, out var isdef) + (isdef ? "" : $"?_={userInfoLM}");
}
if (_context.Check("listAdminModules"))
{
var listAdminModules = userInfo.GetListAdminModules(_webItemSecurity);
if (listAdminModules.Count > 0)
{
result.ListAdminModules = listAdminModules;
}
}
return result;
}
private void FillConacts(EmployeeFullDto employeeWraperFull, UserInfo userInfo)
{
if (userInfo.ContactsList == null)
{
return;
}
var contacts = new List<Contact>();
for (var i = 0; i < userInfo.ContactsList.Count; i += 2)
{
if (i + 1 < userInfo.ContactsList.Count)
{
contacts.Add(new Contact(userInfo.ContactsList[i], userInfo.ContactsList[i + 1]));
}
}
if (contacts.Count > 0)
{
employeeWraperFull.Contacts = contacts;
}
}
}

View File

@ -1,54 +1,54 @@
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
using GroupInfo = ASC.Core.Users.GroupInfo;
namespace ASC.Web.Api.Models;
public class GroupWrapperSummary
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Manager { get; set; }
protected GroupWrapperSummary() { }
public GroupWrapperSummary(GroupInfo group, UserManager userManager)
{
Id = group.ID;
Name = group.Name;
Manager = userManager.GetUsers(userManager.GetDepartmentManager(group.ID)).UserName;
}
public static GroupWrapperSummary GetSample()
{
return new GroupWrapperSummary
{
Id = Guid.Empty,
Manager = "Jake.Zazhitski",
Name = "Group Name"
};
}
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
using GroupInfo = ASC.Core.Users.GroupInfo;
namespace ASC.Web.Api.Models;
public class GroupSummaryDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Manager { get; set; }
protected GroupSummaryDto() { }
public GroupSummaryDto(GroupInfo group, UserManager userManager)
{
Id = group.ID;
Name = group.Name;
Manager = userManager.GetUsers(userManager.GetDepartmentManager(group.ID)).UserName;
}
public static GroupSummaryDto GetSample()
{
return new GroupSummaryDto
{
Id = Guid.Empty,
Manager = "Jake.Zazhitski",
Name = "Group Name"
};
}
}

View File

@ -12,6 +12,7 @@
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<WarningsAsErrors></WarningsAsErrors>
<NoWarn>$(NoWarn);NU1605</NoWarn>
<ImplicitUsings>enable</ImplicitUsings>
<ProduceReferenceAssembly>false</ProduceReferenceAssembly>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">

View File

@ -0,0 +1,12 @@
namespace System;
public static class ArgumentNullOrEmptyException
{
public static void ThrowIfNullOrEmpty(string argument, [CallerArgumentExpression("argument")] string? paramName = null)
{
if (string.IsNullOrEmpty(argument))
{
throw new ArgumentNullException(paramName);
}
}
}

View File

@ -31,8 +31,8 @@ public static class StreamExtension
public static void StreamCopyTo(this Stream srcStream, Stream dstStream, int length)
{
if (srcStream == null) throw new ArgumentNullException(nameof(srcStream));
if (dstStream == null) throw new ArgumentNullException(nameof(dstStream));
ArgumentNullException.ThrowIfNull(srcStream);
ArgumentNullException.ThrowIfNull(dstStream);
var buffer = new byte[BufferSize];
int totalRead = 0;

View File

@ -28,7 +28,7 @@ public class TempStream
public Stream GetBuffered(Stream srcStream)
{
if (srcStream == null) throw new ArgumentNullException(nameof(srcStream));
ArgumentNullException.ThrowIfNull(srcStream);
if (!srcStream.CanSeek || srcStream.CanTimeout)
{
//Buffer it

View File

@ -1,32 +1,27 @@
global using System;
global using System.Collections;
global using System.Collections;
global using System.Collections.Concurrent;
global using System.Collections.Generic;
global using System.Configuration;
global using System.Diagnostics;
global using System.Globalization;
global using System.IO;
global using System.Linq;
global using System.Net;
global using System.Net.Mail;
global using System.Reflection;
global using System.Runtime.Caching;
global using System.Runtime.CompilerServices;
global using System.Runtime.Loader;
global using System.Runtime.Serialization;
global using System.Security.Cryptography;
global using System.Security.Principal;
global using System.ServiceModel;
global using System.Text;
global using System.Text.RegularExpressions;
global using System.Threading;
global using System.Threading.Tasks;
global using System.Web;
global using System.Xml.Linq;
global using System.Xml.XPath;
global using System.ServiceModel;
global using System.Runtime.Serialization;
global using ARSoft.Tools.Net;
global using ARSoft.Tools.Net.Dns;
global using ASC.Common;
global using ASC.Common.Caching;
global using ASC.Common.DependencyInjection;
@ -35,26 +30,26 @@ global using ASC.Common.Security;
global using ASC.Common.Security.Authorizing;
global using ASC.Common.Utils;
global using ASC.Security.Cryptography;
global using Autofac;
global using Autofac.Configuration;
global using AutoMapper;
global using Confluent.Kafka;
global using Confluent.Kafka.Admin;
global using Google.Protobuf;
global using JWT;
global using JWT.Algorithms;
global using JWT.Serializers;
global using log4net.Appender;
global using log4net.Config;
global using log4net.Core;
global using log4net.Util;
global using Microsoft.AspNetCore.Cryptography.KeyDerivation;
global using Microsoft.AspNetCore.Http;
global using Microsoft.AspNetCore.Http.Extensions;
@ -70,16 +65,16 @@ global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Options;
global using Microsoft.Net.Http.Headers;
global using Newtonsoft.Json;
global using Newtonsoft.Json.Serialization;
global using NLog;
global using NLog.Common;
global using NLog.Targets;
global using NVelocity;
global using NVelocity.App;
global using NVelocity.Runtime.Resource.Loader;
global using StackExchange.Redis.Extensions.Core.Abstractions;

View File

@ -88,10 +88,7 @@ public class AscRandom : Random
public override void NextBytes(byte[] buffer)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
ArgumentNullException.ThrowIfNull(buffer);
for (var i = 0; i < buffer.Length; i++)
{

View File

@ -43,9 +43,11 @@ public class AuthorizingException : Exception
if (actions == null || actions.Length == 0)
{
throw new ArgumentNullException(nameof(actions));
}
}
ArgumentNullException.ThrowIfNull(subject);
Subject = subject ?? throw new ArgumentNullException(nameof(subject));
Subject = subject;
Actions = actions;
var sactions = "";
@ -80,10 +82,8 @@ public class AuthorizingException : Exception
internal static string FormatErrorMessage(ISubject subject, IAction[] actions, ISubject[] denySubjects,
IAction[] denyActions)
{
if (subject == null)
{
throw new ArgumentNullException(nameof(subject));
}
ArgumentNullException.ThrowIfNull(subject);
if (actions == null || actions.Length == 0)
{
throw new ArgumentNullException(nameof(actions));

View File

@ -35,9 +35,10 @@ public class AzObjectSecurityProviderHelper
private ISecurityObjectProvider _currSecObjProvider;
public AzObjectSecurityProviderHelper(ISecurityObjectId objectId, ISecurityObjectProvider secObjProvider)
{
{
ArgumentNullException.ThrowIfNull(objectId);
_currObjIdAsProvider = false;
CurrentObjectId = objectId ?? throw new ArgumentNullException(nameof(objectId));
CurrentObjectId = objectId;
_currSecObjProvider = secObjProvider;
if (_currSecObjProvider == null && CurrentObjectId is ISecurityObjectProvider securityObjectProvider)

View File

@ -45,11 +45,9 @@ public sealed class Role : IRole
if (id == Guid.Empty)
{
throw new ArgumentException(nameof(id));
}
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(name);
ID = id;
Name = name;

View File

@ -106,40 +106,28 @@ public static class Hasher
private static byte[] S2B(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
ArgumentNullException.ThrowIfNull(str);
return Encoding.UTF8.GetBytes(str);
}
private static string B2S(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
ArgumentNullException.ThrowIfNull(data);
return Encoding.UTF8.GetString(data);
}
private static byte[] S642B(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
ArgumentNullException.ThrowIfNull(str);
return Convert.FromBase64String(str);
}
private static string B2S64(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
ArgumentNullException.ThrowIfNull(data);
return Convert.ToBase64String(data);
}

View File

@ -34,8 +34,10 @@ public class SecurityObjectId : ISecurityObjectId
public SecurityObjectId(object id, Type objType)
{
ArgumentNullException.ThrowIfNull(objType);
SecurityId = id;
ObjectType = objType ?? throw new ArgumentNullException(nameof(objType));
ObjectType = objType;
}
public override int GetHashCode()

View File

@ -45,10 +45,7 @@ public class DnsLookup
/// <returns>list of MxRecord</returns>
public List<MxRecord> GetDomainMxRecords(string domainName)
{
if (string.IsNullOrEmpty(domainName))
{
throw new ArgumentNullException(nameof(domainName));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(domainName);
var mxRecords = DnsResolve<MxRecord>(domainName, RecordType.Mx);
@ -65,15 +62,8 @@ public class DnsLookup
/// <returns>true if exists and vice versa</returns>
public bool IsDomainMxRecordExists(string domainName, string mxRecord)
{
if (string.IsNullOrEmpty(domainName))
{
throw new ArgumentNullException(nameof(domainName));
}
if (string.IsNullOrEmpty(mxRecord))
{
throw new ArgumentNullException(nameof(mxRecord));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(domainName);
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(mxRecord);
var mxDomain = DomainName.Parse(mxRecord);
@ -93,14 +83,11 @@ public class DnsLookup
/// <returns>true if any DNS record exists and vice versa</returns>
public bool IsDomainExists(string domainName)
{
if (string.IsNullOrEmpty(domainName))
{
throw new ArgumentNullException(nameof(domainName));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(domainName);
var dnsMessage = GetDnsMessage(domainName);
return dnsMessage.AnswerRecords.Count != 0;
return dnsMessage.AnswerRecords.Count != 0;
}
/// <summary>
@ -112,10 +99,7 @@ public class DnsLookup
/// <returns>list of ARecord</returns>
public List<ARecord> GetDomainARecords(string domainName)
{
if (string.IsNullOrEmpty(domainName))
{
throw new ArgumentNullException(nameof(domainName));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(domainName);
var aRecords = DnsResolve<ARecord>(domainName, RecordType.A);
@ -131,10 +115,7 @@ public class DnsLookup
/// <returns>list of IPAddress</returns>
public List<IPAddress> GetDomainIPs(string domainName)
{
if (string.IsNullOrEmpty(domainName))
{
throw new ArgumentNullException(nameof(domainName));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(domainName);
var addresses = _sDnsResolver.ResolveHost(domainName);
@ -150,10 +131,7 @@ public class DnsLookup
/// <returns>list of TxtRecord</returns>
public List<TxtRecord> GetDomainTxtRecords(string domainName)
{
if (string.IsNullOrEmpty(domainName))
{
throw new ArgumentNullException(nameof(domainName));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(domainName);
var txtRecords = DnsResolve<TxtRecord>(domainName, RecordType.Txt);
@ -206,14 +184,9 @@ public class DnsLookup
/// <returns>true if exists and vice versa</returns>
public bool IsDomainPtrRecordExists(IPAddress ipAddress, string domainName)
{
if (string.IsNullOrEmpty(domainName))
{
throw new ArgumentNullException(nameof(domainName));
}
if (ipAddress == null)
{
throw new ArgumentNullException(nameof(ipAddress));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(domainName);
ArgumentNullException.ThrowIfNull(ipAddress);
var domain = DomainName.Parse(domainName);
@ -238,10 +211,7 @@ public class DnsLookup
private DnsMessage GetDnsMessage(string domainName, RecordType? type = null)
{
if (string.IsNullOrEmpty(domainName))
{
throw new ArgumentNullException(nameof(domainName));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(domainName);
var domain = DomainName.Parse(domainName);
@ -257,10 +227,7 @@ public class DnsLookup
private List<T> DnsResolve<T>(string domainName, RecordType type)
{
if (string.IsNullOrEmpty(domainName))
{
throw new ArgumentNullException(nameof(domainName));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(domainName);
var dnsMessage = GetDnsMessage(domainName, type);

View File

@ -68,8 +68,9 @@ public class DisposableHttpContext : IDisposable
private bool _isDisposed;
public DisposableHttpContext(HttpContext ctx)
{
_context = ctx ?? throw new ArgumentNullException(nameof(ctx));
{
ArgumentNullException.ThrowIfNull(ctx);
_context = ctx;
}
public void Dispose()

View File

@ -11,6 +11,7 @@
<Copyright>(c) Ascensio System SIA. All rights reserved</Copyright>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<ProduceReferenceAssembly>false</ProduceReferenceAssembly>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugType>full</DebugType>

View File

@ -78,10 +78,7 @@ public class BaseCommonLinkUtility
{
var u = HttpContextAccessor?.HttpContext.Request.GetUrlRewriter();
if (u == null)
{
throw new ArgumentNullException(nameof(u));
}
ArgumentNullException.ThrowIfNull(u);
uriBuilder = new UriBuilder(u.Scheme, LocalHost, u.Port);
}
@ -120,10 +117,7 @@ public class BaseCommonLinkUtility
{
var u = HttpContextAccessor?.HttpContext?.Request.GetUrlRewriter();
if (u == null)
{
throw new ArgumentNullException(nameof(u));
}
ArgumentNullException.ThrowIfNull(u);
result = new UriBuilder(u.Scheme, u.Host, u.Port);

View File

@ -170,10 +170,7 @@ public class BillingClient
public IDictionary<string, Dictionary<string, decimal>> GetProductPriceInfo(params string[] productIds)
{
if (productIds == null)
{
throw new ArgumentNullException(nameof(productIds));
}
ArgumentNullException.ThrowIfNull(productIds);
var parameters = productIds.Select(pid => Tuple.Create("ProductId", pid)).ToList();
parameters.Add(Tuple.Create("PaymentSystemId", AvangatePaymentSystemId.ToString()));

View File

@ -153,10 +153,7 @@ public class LicenseReader
private static void SaveLicense(Stream licenseStream, string path)
{
if (licenseStream == null)
{
throw new ArgumentNullException(nameof(licenseStream));
}
ArgumentNullException.ThrowIfNull(licenseStream);
if (licenseStream.CanSeek)
{

View File

@ -40,7 +40,7 @@ public class TariffServiceStorage
Cache.Remove(TariffService.GetTariffCacheKey(i.TenantId));
Cache.Remove(TariffService.GetBillingUrlCacheKey(i.TenantId));
Cache.Remove(TariffService.GetBillingPaymentCacheKey(i.TenantId)); // clear all payments
}, CacheNotifyAction.Remove);
}, CacheNotifyAction.Remove);
//TODO: Change code of WCF -> not supported in .NET standard/.Net Core
/*try
@ -259,10 +259,7 @@ public class TariffService : ITariffService
public void SetTariff(int tenantId, Tariff tariff)
{
if (tariff == null)
{
throw new ArgumentNullException(nameof(tariff));
}
ArgumentNullException.ThrowIfNull(tariff);
var q = QuotaService.GetTenantQuota(tariff.QuotaId);
if (q == null)
@ -423,10 +420,8 @@ public class TariffService : ITariffService
public IDictionary<string, Dictionary<string, decimal>> GetProductPriceInfo(params string[] productIds)
{
if (productIds == null)
{
throw new ArgumentNullException(nameof(productIds));
}
ArgumentNullException.ThrowIfNull(productIds);
try
{
var key = "biling-prices" + string.Join(",", productIds);

View File

@ -151,10 +151,7 @@ public class CoreSettings
public void SaveSetting(string key, string value, int tenant = Tenant.DefaultTenant)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(key);
byte[] bytes = null;
if (value != null)
@ -167,10 +164,7 @@ public class CoreSettings
public string GetSetting(string key, int tenant = Tenant.DefaultTenant)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(key);
var bytes = TenantService.GetTenantSettings(tenant, key);

View File

@ -84,10 +84,7 @@ public class PaymentManager
public void ActivateKey(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(key);
var now = DateTime.UtcNow;
var actionUrl = "/partnerapi/ActivateKey?code=" + HttpUtility.UrlEncode(key) + "&portal=" + HttpUtility.UrlEncode(_tenantManager.GetCurrentTenant().Alias);

View File

@ -185,10 +185,7 @@ public class TenantManager
public Tenant SetTenantVersion(Tenant tenant, int version)
{
if (tenant == null)
{
throw new ArgumentNullException(nameof(tenant));
}
ArgumentNullException.ThrowIfNull(tenant);
if (tenant.Version != version)
{

View File

@ -80,15 +80,8 @@ public class SecurityContext
public string AuthenticateMe(string login, string passwordHash)
{
if (login == null)
{
throw new ArgumentNullException(nameof(login));
}
if (passwordHash == null)
{
throw new ArgumentNullException(nameof(passwordHash));
}
ArgumentNullException.ThrowIfNull(login);
ArgumentNullException.ThrowIfNull(passwordHash);
var tenantid = _tenantManager.GetCurrentTenant().Id;
var u = _userManager.GetUsersByPasswordHash(tenantid, login, passwordHash);
@ -109,10 +102,7 @@ public class SecurityContext
{
var request = _httpContextAccessor?.HttpContext.Request;
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
ArgumentNullException.ThrowIfNull(request);
ipFrom = "from " + (request.Headers["X-Forwarded-For"].ToString() ?? request.GetUserHostAddress());
address = "for " + request.GetUrlRewriter();
@ -170,10 +160,7 @@ public class SecurityContext
{
var request = _httpContextAccessor?.HttpContext.Request;
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
ArgumentNullException.ThrowIfNull(request);
address = "for " + request.GetUrlRewriter();
ipFrom = "from " + (request.Headers["X-Forwarded-For"].ToString() ?? request.GetUserHostAddress());

View File

@ -145,14 +145,8 @@ public class DBResourceManager : ResourceManager
CultureInfo culture,
string filename)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException(nameof(filename));
}
ArgumentNullException.ThrowIfNull(culture);
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(filename);
_dbContext = dbContext;
_logger = option.CurrentValue;

View File

@ -23,8 +23,6 @@
*
*/
using System.Diagnostics.Metrics;
using AutoMapper.QueryableExtensions;
namespace ASC.Core.Data;
@ -81,10 +79,7 @@ class DbQuotaService : IQuotaService
public TenantQuota SaveTenantQuota(TenantQuota quota)
{
if (quota == null)
{
throw new ArgumentNullException(nameof(quota));
}
ArgumentNullException.ThrowIfNull(quota);
CoreDbContext.AddOrUpdate(r => r.Quotas, _mapper.Map<TenantQuota, DbQuota>(quota));
CoreDbContext.SaveChanges();
@ -111,10 +106,7 @@ class DbQuotaService : IQuotaService
public void SetTenantQuotaRow(TenantQuotaRow row, bool exchange)
{
if (row == null)
{
throw new ArgumentNullException(nameof(row));
}
ArgumentNullException.ThrowIfNull(row);
using var tx = CoreDbContext.Database.BeginTransaction();

View File

@ -169,10 +169,7 @@ public class DbSettingsManager
public bool SaveSettingsFor<T>(T settings, int tenantId, Guid userId) where T : ISettings
{
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
ArgumentNullException.ThrowIfNull(settings);
try
{

View File

@ -40,14 +40,8 @@ public class DbSubscriptionService : ISubscriptionService
public string[] GetRecipients(int tenant, string sourceId, string actionId, string objectId)
{
if (sourceId == null)
{
throw new ArgumentNullException(nameof(sourceId));
}
if (actionId == null)
{
throw new ArgumentNullException(nameof(actionId));
}
ArgumentNullException.ThrowIfNull(sourceId);
ArgumentNullException.ThrowIfNull(actionId);
var q = GetQuery(tenant, sourceId, actionId)
.Where(r => r.Object == (objectId ?? string.Empty))
@ -60,14 +54,8 @@ public class DbSubscriptionService : ISubscriptionService
public IEnumerable<SubscriptionRecord> GetSubscriptions(int tenant, string sourceId, string actionId)
{
if (sourceId == null)
{
throw new ArgumentNullException(nameof(sourceId));
}
if (actionId == null)
{
throw new ArgumentNullException(nameof(actionId));
}
ArgumentNullException.ThrowIfNull(sourceId);
ArgumentNullException.ThrowIfNull(actionId);
var q = GetQuery(tenant, sourceId, actionId);
@ -92,10 +80,7 @@ public class DbSubscriptionService : ISubscriptionService
public SubscriptionRecord GetSubscription(int tenant, string sourceId, string actionId, string recipientId, string objectId)
{
if (recipientId == null)
{
throw new ArgumentNullException(nameof(recipientId));
}
ArgumentNullException.ThrowIfNull(recipientId);
var q = GetQuery(tenant, sourceId, actionId)
.Where(r => r.Recipient == recipientId)
@ -106,18 +91,9 @@ public class DbSubscriptionService : ISubscriptionService
public bool IsUnsubscribe(int tenant, string sourceId, string actionId, string recipientId, string objectId)
{
if (recipientId == null)
{
throw new ArgumentNullException(nameof(recipientId));
}
if (sourceId == null)
{
throw new ArgumentNullException(nameof(sourceId));
}
if (actionId == null)
{
throw new ArgumentNullException(nameof(actionId));
}
ArgumentNullException.ThrowIfNull(recipientId);
ArgumentNullException.ThrowIfNull(sourceId);
ArgumentNullException.ThrowIfNull(actionId);
var q = UserDbContext.Subscriptions
.Where(r => r.Source == sourceId &&
@ -140,18 +116,9 @@ public class DbSubscriptionService : ISubscriptionService
public string[] GetSubscriptions(int tenant, string sourceId, string actionId, string recipientId, bool checkSubscribe)
{
if (recipientId == null)
{
throw new ArgumentNullException(nameof(recipientId));
}
if (sourceId == null)
{
throw new ArgumentNullException(nameof(sourceId));
}
if (actionId == null)
{
throw new ArgumentNullException(nameof(actionId));
}
ArgumentNullException.ThrowIfNull(recipientId);
ArgumentNullException.ThrowIfNull(sourceId);
ArgumentNullException.ThrowIfNull(actionId);
var q = GetQuery(tenant, sourceId, actionId)
.Where(r => r.Recipient == recipientId)
@ -168,10 +135,7 @@ public class DbSubscriptionService : ISubscriptionService
public void SaveSubscription(SubscriptionRecord s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
ArgumentNullException.ThrowIfNull(s);
var subs = new Subscription
{
@ -194,15 +158,8 @@ public class DbSubscriptionService : ISubscriptionService
public void RemoveSubscriptions(int tenant, string sourceId, string actionId, string objectId)
{
if (sourceId == null)
{
throw new ArgumentNullException(nameof(sourceId));
}
if (actionId == null)
{
throw new ArgumentNullException(nameof(actionId));
}
ArgumentNullException.ThrowIfNull(sourceId);
ArgumentNullException.ThrowIfNull(actionId);
using var tr = UserDbContext.Database.BeginTransaction();
var q = UserDbContext.Subscriptions
@ -228,14 +185,8 @@ public class DbSubscriptionService : ISubscriptionService
public IEnumerable<SubscriptionMethod> GetSubscriptionMethods(int tenant, string sourceId, string actionId, string recipientId)
{
if (sourceId == null)
{
throw new ArgumentNullException(nameof(sourceId));
}
if (actionId == null)
{
throw new ArgumentNullException(nameof(actionId));
}
ArgumentNullException.ThrowIfNull(sourceId);
ArgumentNullException.ThrowIfNull(actionId);
var q = UserDbContext.SubscriptionMethods
.Where(r => r.Tenant == -1 || r.Tenant == tenant)
@ -278,10 +229,7 @@ public class DbSubscriptionService : ISubscriptionService
public void SetSubscriptionMethod(SubscriptionMethod m)
{
if (m == null)
{
throw new ArgumentNullException(nameof(m));
}
ArgumentNullException.ThrowIfNull(m);
using var tr = UserDbContext.Database.BeginTransaction();
@ -320,14 +268,8 @@ public class DbSubscriptionService : ISubscriptionService
private IQueryable<Subscription> GetQuery(int tenant, string sourceId, string actionId)
{
if (sourceId == null)
{
throw new ArgumentNullException(nameof(sourceId));
}
if (actionId == null)
{
throw new ArgumentNullException(nameof(actionId));
}
ArgumentNullException.ThrowIfNull(sourceId);
ArgumentNullException.ThrowIfNull(actionId);
return
UserDbContext.Subscriptions

View File

@ -114,10 +114,7 @@ public class DbTenantService : ITenantService
public IEnumerable<Tenant> GetTenants(string login, string passwordHash)
{
if (string.IsNullOrEmpty(login))
{
throw new ArgumentNullException(nameof(login));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(login);
IQueryable<TenantUserSecurity> query() => TenantsQuery()
.Where(r => r.Status == TenantStatus.Active)
@ -205,10 +202,7 @@ public class DbTenantService : ITenantService
public Tenant GetTenant(string domain)
{
if (string.IsNullOrEmpty(domain))
{
throw new ArgumentNullException(nameof(domain));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(domain);
domain = domain.ToLowerInvariant();
@ -229,79 +223,76 @@ public class DbTenantService : ITenantService
.FirstOrDefault();
}
public Tenant SaveTenant(CoreSettings coreSettings, Tenant t)
public Tenant SaveTenant(CoreSettings coreSettings, Tenant tenant)
{
if (t == null)
{
throw new ArgumentNullException("tenant");
}
ArgumentNullException.ThrowIfNull(tenant);
using var tx = TenantDbContext.Database.BeginTransaction();
if (!string.IsNullOrEmpty(t.MappedDomain))
if (!string.IsNullOrEmpty(tenant.MappedDomain))
{
var baseUrl = coreSettings.GetBaseDomain(t.HostedRegion);
var baseUrl = coreSettings.GetBaseDomain(tenant.HostedRegion);
if (baseUrl != null && t.MappedDomain.EndsWith("." + baseUrl, StringComparison.InvariantCultureIgnoreCase))
if (baseUrl != null && tenant.MappedDomain.EndsWith("." + baseUrl, StringComparison.InvariantCultureIgnoreCase))
{
ValidateDomain(t.MappedDomain.Substring(0, t.MappedDomain.Length - baseUrl.Length - 1), t.Id, false);
ValidateDomain(tenant.MappedDomain.Substring(0, tenant.MappedDomain.Length - baseUrl.Length - 1), tenant.Id, false);
}
else
{
ValidateDomain(t.MappedDomain, t.Id, false);
ValidateDomain(tenant.MappedDomain, tenant.Id, false);
}
}
if (t.Id == Tenant.DefaultTenant)
if (tenant.Id == Tenant.DefaultTenant)
{
t.Version = TenantDbContext.TenantVersion
tenant.Version = TenantDbContext.TenantVersion
.Where(r => r.DefaultVersion == 1 || r.Id == 0)
.OrderByDescending(r => r.Id)
.Select(r => r.Id)
.FirstOrDefault();
t.LastModified = DateTime.UtcNow;
tenant.LastModified = DateTime.UtcNow;
var tenant = _mapper.Map<Tenant, DbTenant>(t);
var dbTenant = _mapper.Map<Tenant, DbTenant>(tenant);
tenant = TenantDbContext.Tenants.Add(tenant).Entity;
dbTenant = TenantDbContext.Tenants.Add(dbTenant).Entity;
TenantDbContext.SaveChanges();
t.Id = tenant.Id;
tenant.Id = dbTenant.Id;
}
else
{
var tenant = TenantDbContext.Tenants
.Where(r => r.Id == t.Id)
var dbTenant = TenantDbContext.Tenants
.Where(r => r.Id == tenant.Id)
.FirstOrDefault();
if (tenant != null)
if (dbTenant != null)
{
tenant.Alias = t.Alias.ToLowerInvariant();
tenant.MappedDomain = !string.IsNullOrEmpty(t.MappedDomain) ? t.MappedDomain.ToLowerInvariant() : null;
tenant.Version = t.Version;
tenant.VersionChanged = t.VersionChanged;
tenant.Name = t.Name ?? t.Alias;
tenant.Language = t.Language;
tenant.TimeZone = t.TimeZone;
tenant.TrustedDomainsRaw = t.GetTrustedDomains();
tenant.TrustedDomainsEnabled = t.TrustedDomainsType;
tenant.CreationDateTime = t.CreationDateTime;
tenant.Status = t.Status;
tenant.StatusChanged = t.StatusChangeDate;
tenant.PaymentId = t.PaymentId;
tenant.LastModified = t.LastModified = DateTime.UtcNow;
tenant.Industry = t.Industry;
tenant.Spam = t.Spam;
tenant.Calls = t.Calls;
dbTenant.Alias = tenant.Alias.ToLowerInvariant();
dbTenant.MappedDomain = !string.IsNullOrEmpty(tenant.MappedDomain) ? tenant.MappedDomain.ToLowerInvariant() : null;
dbTenant.Version = tenant.Version;
dbTenant.VersionChanged = tenant.VersionChanged;
dbTenant.Name = tenant.Name ?? tenant.Alias;
dbTenant.Language = tenant.Language;
dbTenant.TimeZone = tenant.TimeZone;
dbTenant.TrustedDomainsRaw = tenant.GetTrustedDomains();
dbTenant.TrustedDomainsEnabled = tenant.TrustedDomainsType;
dbTenant.CreationDateTime = tenant.CreationDateTime;
dbTenant.Status = tenant.Status;
dbTenant.StatusChanged = tenant.StatusChangeDate;
dbTenant.PaymentId = tenant.PaymentId;
dbTenant.LastModified = tenant.LastModified = DateTime.UtcNow;
dbTenant.Industry = tenant.Industry;
dbTenant.Spam = tenant.Spam;
dbTenant.Calls = tenant.Calls;
}
TenantDbContext.SaveChanges();
}
if (string.IsNullOrEmpty(t.PartnerId) && string.IsNullOrEmpty(t.AffiliateId) && string.IsNullOrEmpty(t.Campaign))
if (string.IsNullOrEmpty(tenant.PartnerId) && string.IsNullOrEmpty(tenant.AffiliateId) && string.IsNullOrEmpty(tenant.Campaign))
{
var p = TenantDbContext.TenantPartner
.Where(r => r.TenantId == t.Id)
.Where(r => r.TenantId == tenant.Id)
.FirstOrDefault();
if (p != null)
@ -313,10 +304,10 @@ public class DbTenantService : ITenantService
{
var tenantPartner = new DbTenantPartner
{
TenantId = t.Id,
PartnerId = t.PartnerId,
AffiliateId = t.AffiliateId,
Campaign = t.Campaign
TenantId = tenant.Id,
PartnerId = tenant.PartnerId,
AffiliateId = tenant.AffiliateId,
Campaign = tenant.Campaign
};
TenantDbContext.TenantPartner.Add(tenantPartner);
@ -325,7 +316,7 @@ public class DbTenantService : ITenantService
tx.Commit();
//CalculateTenantDomain(t);
return t;
return tenant;
}
public void RemoveTenant(int id, bool auto = false)

View File

@ -115,10 +115,7 @@ public class EFUserService : IUserService
public UserInfo GetUserByPasswordHash(int tenant, string login, string passwordHash)
{
if (string.IsNullOrEmpty(login))
{
throw new ArgumentNullException(nameof(login));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(login);
if (Guid.TryParse(login, out var userId))
{
@ -430,10 +427,7 @@ public class EFUserService : IUserService
public Group SaveGroup(int tenant, Group group)
{
if (group == null)
{
throw new ArgumentNullException(nameof(group));
}
ArgumentNullException.ThrowIfNull(group);
if (group.Id == default)
{
@ -452,10 +446,7 @@ public class EFUserService : IUserService
public UserInfo SaveUser(int tenant, UserInfo user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
ArgumentNullException.ThrowIfNull(user);
if (string.IsNullOrEmpty(user.UserName))
{
@ -501,29 +492,26 @@ public class EFUserService : IUserService
return user;
}
public UserGroupRef SaveUserGroupRef(int tenant, UserGroupRef r)
public UserGroupRef SaveUserGroupRef(int tenant, UserGroupRef userGroupRef)
{
if (r == null)
{
throw new ArgumentNullException("userGroupRef");
}
ArgumentNullException.ThrowIfNull(userGroupRef);
r.LastModified = DateTime.UtcNow;
r.Tenant = tenant;
userGroupRef.LastModified = DateTime.UtcNow;
userGroupRef.Tenant = tenant;
using var tr = UserDbContext.Database.BeginTransaction();
var user = GetUserQuery(tenant).FirstOrDefault(a => a.Tenant == tenant && a.Id == r.UserId);
var user = GetUserQuery(tenant).FirstOrDefault(a => a.Tenant == tenant && a.Id == userGroupRef.UserId);
if (user != null)
{
user.LastModified = r.LastModified;
UserDbContext.AddOrUpdate(r => r.UserGroups, _mapper.Map<UserGroupRef, UserGroup>(r));
user.LastModified = userGroupRef.LastModified;
UserDbContext.AddOrUpdate(r => r.UserGroups, _mapper.Map<UserGroupRef, UserGroup>(userGroupRef));
}
UserDbContext.SaveChanges();
tr.Commit();
return r;
return userGroupRef;
}
public void SetUserPasswordHash(int tenant, Guid id, string passwordHash)

View File

@ -10,9 +10,9 @@ public class DbVoipCall
public Guid AnsweredBy { get; set; }
public DateTime DialDate { get; set; }
public int DialDuration { get; set; }
public string RecordSid { get; set; }
public string RecordUrl { get; set; }
public int RecordDuration { get; set; }
public string Sid { get; set; }
public string Uri { get; set; }
public int Duration { get; set; }
public decimal RecordPrice { get; set; }
public int ContactId { get; set; }
public decimal Price { get; set; }
@ -30,6 +30,7 @@ public static class DbVoipCallExtension
return modelBuilder;
}
public static void MySqlAddDbVoipCall(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<DbVoipCall>(entity =>
@ -89,19 +90,19 @@ public static class DbVoipCallExtension
.HasColumnName("price")
.HasColumnType("decimal(10,4)");
entity.Property(e => e.RecordDuration).HasColumnName("record_duration");
entity.Property(e => e.Duration).HasColumnName("record_duration");
entity.Property(e => e.RecordPrice)
.HasColumnName("record_price")
.HasColumnType("decimal(10,4)");
entity.Property(e => e.RecordSid)
entity.Property(e => e.Sid)
.HasColumnName("record_sid")
.HasColumnType("varchar(50)")
.HasCharSet("utf8")
.UseCollation("utf8_general_ci");
entity.Property(e => e.RecordUrl)
entity.Property(e => e.Uri)
.HasColumnName("record_url")
.HasColumnType("text")
.HasCharSet("utf8")
@ -160,18 +161,18 @@ public static class DbVoipCallExtension
.HasColumnType("numeric(10,4)")
.HasDefaultValueSql("NULL");
entity.Property(e => e.RecordDuration).HasColumnName("record_duration");
entity.Property(e => e.Duration).HasColumnName("record_duration");
entity.Property(e => e.RecordPrice)
.HasColumnName("record_price")
.HasColumnType("numeric(10,4)");
entity.Property(e => e.RecordSid)
entity.Property(e => e.Sid)
.HasColumnName("record_sid")
.HasMaxLength(50)
.HasDefaultValueSql("NULL");
entity.Property(e => e.RecordUrl).HasColumnName("record_url");
entity.Property(e => e.Uri).HasColumnName("record_url");
entity.Property(e => e.Status).HasColumnName("status");

View File

@ -1,16 +1,11 @@
global using System;
global using System.Collections;
global using System.Collections;
global using System.Collections.Concurrent;
global using System.Collections.Generic;
global using System.Configuration;
global using System.Data.Common;
global using System.Diagnostics;
global using System.Globalization;
global using System.IO;
global using System.Linq;
global using System.Linq.Expressions;
global using System.Net;
global using System.Net.Http;
global using System.Reflection;
global using System.Resources;
global using System.Runtime.Caching;
@ -25,8 +20,6 @@ global using System.Text;
global using System.Text.Json;
global using System.Text.Json.Serialization;
global using System.Text.RegularExpressions;
global using System.Threading;
global using System.Threading.Tasks;
global using System.Web;
global using System.Xml;

View File

@ -143,51 +143,49 @@ public class HostedSolution
TenantService.ValidateDomain(address);
}
public void RegisterTenant(TenantRegistrationInfo ri, out Tenant tenant)
public void RegisterTenant(TenantRegistrationInfo registrationInfo, out Tenant tenant)
{
if (ri == null)
{
throw new ArgumentNullException("registrationInfo");
}
if (string.IsNullOrEmpty(ri.Address))
ArgumentNullException.ThrowIfNull(registrationInfo);
if (string.IsNullOrEmpty(registrationInfo.Address))
{
throw new Exception("Address can not be empty");
}
if (string.IsNullOrEmpty(ri.Email))
if (string.IsNullOrEmpty(registrationInfo.Email))
{
throw new Exception("Account email can not be empty");
}
if (ri.FirstName == null)
if (registrationInfo.FirstName == null)
{
throw new Exception("Account firstname can not be empty");
}
if (ri.LastName == null)
if (registrationInfo.LastName == null)
{
throw new Exception("Account lastname can not be empty");
}
if (!UserFormatter.IsValidUserName(ri.FirstName, ri.LastName))
if (!UserFormatter.IsValidUserName(registrationInfo.FirstName, registrationInfo.LastName))
{
throw new Exception("Incorrect firstname or lastname");
}
if (string.IsNullOrEmpty(ri.PasswordHash))
if (string.IsNullOrEmpty(registrationInfo.PasswordHash))
{
ri.PasswordHash = Guid.NewGuid().ToString();
registrationInfo.PasswordHash = Guid.NewGuid().ToString();
}
// create tenant
tenant = new Tenant(ri.Address.ToLowerInvariant())
tenant = new Tenant(registrationInfo.Address.ToLowerInvariant())
{
Name = ri.Name,
Language = ri.Culture.Name,
TimeZone = ri.TimeZoneInfo.Id,
HostedRegion = ri.HostedRegion,
PartnerId = ri.PartnerId,
AffiliateId = ri.AffiliateId,
Campaign = ri.Campaign,
Industry = ri.Industry,
Spam = ri.Spam,
Calls = ri.Calls
Name = registrationInfo.Name,
Language = registrationInfo.Culture.Name,
TimeZone = registrationInfo.TimeZoneInfo.Id,
HostedRegion = registrationInfo.HostedRegion,
PartnerId = registrationInfo.PartnerId,
AffiliateId = registrationInfo.AffiliateId,
Campaign = registrationInfo.Campaign,
Industry = registrationInfo.Industry,
Spam = registrationInfo.Spam,
Calls = registrationInfo.Calls
};
tenant = TenantService.SaveTenant(CoreSettings, tenant);
@ -195,24 +193,24 @@ public class HostedSolution
// create user
var user = new UserInfo
{
UserName = ri.Email.Substring(0, ri.Email.IndexOf('@')),
LastName = ri.LastName,
FirstName = ri.FirstName,
Email = ri.Email,
MobilePhone = ri.MobilePhone,
UserName = registrationInfo.Email.Substring(0, registrationInfo.Email.IndexOf('@')),
LastName = registrationInfo.LastName,
FirstName = registrationInfo.FirstName,
Email = registrationInfo.Email,
MobilePhone = registrationInfo.MobilePhone,
WorkFromDate = TenantUtil.DateTimeNow(tenant.TimeZone),
ActivationStatus = ri.ActivationStatus
ActivationStatus = registrationInfo.ActivationStatus
};
user = UserService.SaveUser(tenant.Id, user);
UserService.SetUserPasswordHash(tenant.Id, user.Id, ri.PasswordHash);
UserService.SetUserPasswordHash(tenant.Id, user.Id, registrationInfo.PasswordHash);
UserService.SaveUserGroupRef(tenant.Id, new UserGroupRef(user.Id, Constants.GroupAdmin.ID, UserGroupRefType.Contains));
// save tenant owner
tenant.OwnerId = user.Id;
tenant = TenantService.SaveTenant(CoreSettings, tenant);
SettingsManager.SaveSettings(new TenantControlPanelSettings { LimitedAccess = ri.LimitedControlPanel }, tenant.Id);
SettingsManager.SaveSettings(new TenantControlPanelSettings { LimitedAccess = registrationInfo.LimitedControlPanel }, tenant.Id);
}
public Tenant SaveTenant(Tenant tenant)

View File

@ -47,10 +47,7 @@ public class SenderChannel : ISenderChannel
public void SendAsync(INoticeMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
ArgumentNullException.ThrowIfNull(message);
_firstSink.ProcessMessageAsync(message);
}

View File

@ -34,7 +34,7 @@ class DirectSubscriptionProvider : ISubscriptionProvider
public DirectSubscriptionProvider(string sourceID, SubscriptionManager subscriptionManager, IRecipientProvider recipientProvider)
{
if (string.IsNullOrEmpty(sourceID)) throw new ArgumentNullException(nameof(sourceID));
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(sourceID);
_sourceId = sourceID;
_subscriptionManager = subscriptionManager ?? throw new ArgumentNullException(nameof(subscriptionManager));
_recipientProvider = recipientProvider ?? throw new ArgumentNullException(nameof(recipientProvider));
@ -43,40 +43,23 @@ class DirectSubscriptionProvider : ISubscriptionProvider
public object GetSubscriptionRecord(INotifyAction action, IRecipient recipient, string objectID)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
return _subscriptionManager.GetSubscriptionRecord(_sourceId, action.ID, recipient.ID, objectID);
}
public string[] GetSubscriptions(INotifyAction action, IRecipient recipient, bool checkSubscribe = true)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
return _subscriptionManager.GetSubscriptions(_sourceId, action.ID, recipient.ID, checkSubscribe);
}
public IRecipient[] GetRecipients(INotifyAction action, string objectID)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
ArgumentNullException.ThrowIfNull(action);
return _subscriptionManager.GetRecipients(_sourceId, action.ID, objectID)
.Select(r => _recipientProvider.GetRecipient(r))
@ -86,90 +69,54 @@ class DirectSubscriptionProvider : ISubscriptionProvider
public string[] GetSubscriptionMethod(INotifyAction action, IRecipient recipient)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
return _subscriptionManager.GetSubscriptionMethod(_sourceId, action.ID, recipient.ID);
}
public void UpdateSubscriptionMethod(INotifyAction action, IRecipient recipient, params string[] senderNames)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
_subscriptionManager.UpdateSubscriptionMethod(_sourceId, action.ID, recipient.ID, senderNames);
}
public bool IsUnsubscribe(IDirectRecipient recipient, INotifyAction action, string objectID)
{
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
ArgumentNullException.ThrowIfNull(recipient);
ArgumentNullException.ThrowIfNull(action);
return _subscriptionManager.IsUnsubscribe(_sourceId, recipient.ID, action.ID, objectID);
}
public void Subscribe(INotifyAction action, string objectID, IRecipient recipient)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
_subscriptionManager.Subscribe(_sourceId, action.ID, objectID, recipient.ID);
}
public void UnSubscribe(INotifyAction action, string objectID, IRecipient recipient)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
_subscriptionManager.Unsubscribe(_sourceId, action.ID, objectID, recipient.ID);
}
public void UnSubscribe(INotifyAction action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
ArgumentNullException.ThrowIfNull(action);
_subscriptionManager.UnsubscribeAll(_sourceId, action.ID);
}
public void UnSubscribe(INotifyAction action, string objectID)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
ArgumentNullException.ThrowIfNull(action);
_subscriptionManager.UnsubscribeAll(_sourceId, action.ID, objectID);
}

View File

@ -47,7 +47,7 @@ class InterceptorStorage
public void Add(ISendInterceptor interceptor)
{
if (interceptor == null) throw new ArgumentNullException(nameof(interceptor));
ArgumentNullException.ThrowIfNull(interceptor);
if (string.IsNullOrEmpty(interceptor.Name)) throw new ArgumentException("empty name property", nameof(interceptor));
switch (interceptor.Lifetime)

View File

@ -73,15 +73,8 @@ public class NotifyEngine : INotifyEngine
internal void RegisterSendMethod(Action<DateTime> method, string cron)
{
if (method == null)
{
throw new ArgumentNullException(nameof(method));
}
if (string.IsNullOrEmpty(cron))
{
throw new ArgumentNullException(nameof(cron));
}
ArgumentNullException.ThrowIfNull(method);
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(cron);
var w = new SendMethodWrapper(method, cron, _logger);
lock (_sendMethods)
@ -99,10 +92,7 @@ public class NotifyEngine : INotifyEngine
internal void UnregisterSendMethod(Action<DateTime> method)
{
if (method == null)
{
throw new ArgumentNullException(nameof(method));
}
ArgumentNullException.ThrowIfNull(method);
lock (_sendMethods)
{
@ -418,10 +408,7 @@ public class NotifyEngine : INotifyEngine
private SendResponse CreateNoticeMessageFromNotifyRequest(NotifyRequest request, string sender, IServiceScope serviceScope, out NoticeMessage noticeMessage)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
ArgumentNullException.ThrowIfNull(request);
var recipientProvider = request.GetRecipientsProvider(serviceScope);
var recipient = request.Recipient as IDirectRecipient;

View File

@ -100,10 +100,7 @@ public class NotifyRequest
internal NotifyRequest Split(IRecipient recipient)
{
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(recipient);
var newRequest = new NotifyRequest(NotifySource, NotifyAction, ObjectID, recipient)
{

View File

@ -37,12 +37,9 @@ public class SendInterceptorSkeleton : ISendInterceptor
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Empty name.", nameof(name));
}
if (sendInterceptor == null)
{
throw new ArgumentNullException(nameof(sendInterceptor));
}
}
ArgumentNullException.ThrowIfNull(sendInterceptor);
_method = sendInterceptor;
Name = name;

View File

@ -76,7 +76,8 @@ public class NoticeMessage : INoticeMessage
public void AddArgument(params ITagValue[] tagValues)
{
if (tagValues == null) throw new ArgumentNullException(nameof(tagValues));
ArgumentNullException.ThrowIfNull(tagValues);
Array.ForEach(tagValues,
tagValue =>
{

View File

@ -98,10 +98,7 @@ class NotifyClientImpl : INotifyClient
public void SendNoticeToAsync(INotifyAction action, string objectID, IRecipient[] recipients, string[] senderNames, bool checkSubsciption, params ITagValue[] args)
{
if (recipients == null)
{
throw new ArgumentNullException(nameof(recipients));
}
ArgumentNullException.ThrowIfNull(recipients);
BeginSingleRecipientEvent("__syspreventduplicateinterceptor");
@ -120,14 +117,8 @@ class NotifyClientImpl : INotifyClient
private NotifyRequest CreateRequest(INotifyAction action, string objectID, IRecipient recipient, ITagValue[] args, string[] senders, bool checkSubsciption)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
var request = new NotifyRequest(_notifySource, action, objectID, recipient)
{

View File

@ -41,10 +41,7 @@ public abstract class NotifySource : INotifySource
protected NotifySource(string id, UserManager userManager, IRecipientProvider recipientsProvider, SubscriptionManager subscriptionManager)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException(nameof(id));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(id);
Id = id;
_userManager = userManager;

View File

@ -52,11 +52,8 @@ public abstract class PatternFormatter : IPatternFormatter
}
public string[] GetTags(IPattern pattern)
{
if (pattern == null)
{
throw new ArgumentNullException(nameof(pattern));
}
{
ArgumentNullException.ThrowIfNull(pattern);
var findedTags = new List<string>(SearchTags(pattern.Body));
Array.ForEach(SearchTags(pattern.Subject), tag => { if (!findedTags.Contains(tag)) findedTags.Add(tag); });
@ -64,19 +61,10 @@ public abstract class PatternFormatter : IPatternFormatter
}
public void FormatMessage(INoticeMessage message, ITagValue[] tagsValues)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (message.Pattern == null)
{
throw new ArgumentException(nameof(message));
}
if (tagsValues == null)
{
throw new ArgumentNullException(nameof(tagsValues));
}
{
ArgumentNullException.ThrowIfNull(message);
ArgumentNullException.ThrowIfNull(message.Pattern);
ArgumentNullException.ThrowIfNull(tagsValues);
BeforeFormat(message, tagsValues);

View File

@ -33,10 +33,7 @@ public class TagValue : ITagValue
public TagValue(string tag, object value)
{
if (string.IsNullOrEmpty(tag))
{
throw new ArgumentNullException(nameof(tag));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(tag);
Tag = tag;
Value = value;

View File

@ -58,10 +58,7 @@ public class RecipientProviderImpl : IRecipientProvider
public virtual IRecipient[] GetGroupEntries(IRecipientsGroup group)
{
if (group == null)
{
throw new ArgumentNullException(nameof(group));
}
ArgumentNullException.ThrowIfNull(group);
var result = new List<IRecipient>();
if (TryParseGuid(group.ID, out var groupID))
@ -79,10 +76,7 @@ public class RecipientProviderImpl : IRecipientProvider
public virtual IRecipientsGroup[] GetGroups(IRecipient recipient)
{
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(recipient);
var result = new List<IRecipientsGroup>();
if (TryParseGuid(recipient.ID, out var recID))
@ -110,10 +104,7 @@ public class RecipientProviderImpl : IRecipientProvider
public virtual string[] GetRecipientAddresses(IDirectRecipient recipient, string senderName)
{
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(recipient);
if (TryParseGuid(recipient.ID, out var userID))
{

View File

@ -47,14 +47,8 @@ public class TopSubscriptionProvider : ISubscriptionProvider
public virtual string[] GetSubscriptionMethod(INotifyAction action, IRecipient recipient)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
var senders = _subscriptionProvider.GetSubscriptionMethod(action, recipient);
if (senders == null || senders.Length == 0)
@ -75,10 +69,7 @@ public class TopSubscriptionProvider : ISubscriptionProvider
public virtual IRecipient[] GetRecipients(INotifyAction action, string objectID)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
ArgumentNullException.ThrowIfNull(action);
var recipents = new List<IRecipient>(5);
var directRecipients = _subscriptionProvider.GetRecipients(action, objectID) ?? new IRecipient[0];
@ -89,14 +80,8 @@ public class TopSubscriptionProvider : ISubscriptionProvider
public virtual bool IsUnsubscribe(IDirectRecipient recipient, INotifyAction action, string objectID)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
return _subscriptionProvider.IsUnsubscribe(recipient, action, objectID);
}
@ -104,48 +89,30 @@ public class TopSubscriptionProvider : ISubscriptionProvider
public virtual void Subscribe(INotifyAction action, string objectID, IRecipient recipient)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
_subscriptionProvider.Subscribe(action, objectID, recipient);
}
public virtual void UnSubscribe(INotifyAction action, string objectID, IRecipient recipient)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
_subscriptionProvider.UnSubscribe(action, objectID, recipient);
}
public void UnSubscribe(INotifyAction action, string objectID)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
ArgumentNullException.ThrowIfNull(action);
_subscriptionProvider.UnSubscribe(action, objectID);
}
public void UnSubscribe(INotifyAction action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
ArgumentNullException.ThrowIfNull(action);
_subscriptionProvider.UnSubscribe(action);
}
@ -161,32 +128,17 @@ public class TopSubscriptionProvider : ISubscriptionProvider
public virtual void UpdateSubscriptionMethod(INotifyAction action, IRecipient recipient, params string[] senderNames)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
if (senderNames == null)
{
throw new ArgumentNullException(nameof(senderNames));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
ArgumentNullException.ThrowIfNull(senderNames);
_subscriptionProvider.UpdateSubscriptionMethod(action, recipient, senderNames);
}
public virtual object GetSubscriptionRecord(INotifyAction action, IRecipient recipient, string objectID)
{
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
var subscriptionRecord = _subscriptionProvider.GetSubscriptionRecord(action, recipient, objectID);
@ -212,14 +164,8 @@ public class TopSubscriptionProvider : ISubscriptionProvider
public virtual string[] GetSubscriptions(INotifyAction action, IRecipient recipient, bool checkSubscription = true)
{
if (recipient == null)
{
throw new ArgumentNullException(nameof(recipient));
}
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(recipient);
var objects = new List<string>();
var direct = _subscriptionProvider.GetSubscriptions(action, recipient, checkSubscription) ?? Array.Empty<string>();

View File

@ -44,15 +44,8 @@ public class AzManager
ISecurityObjectProvider securityObjProvider, out ISubject denySubject,
out IAction denyAction)
{
if (subject == null)
{
throw new ArgumentNullException(nameof(subject));
}
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
ArgumentNullException.ThrowIfNull(action);
ArgumentNullException.ThrowIfNull(subject);
var acl = GetAzManagerAcl(subject, action, objectId, securityObjProvider);
denySubject = acl.DenySubject;

View File

@ -35,15 +35,9 @@ class PermissionProvider : IPermissionProvider
}
public IEnumerable<Ace> GetAcl(ISubject subject, IAction action, ISecurityObjectId objectId, ISecurityObjectProvider secObjProvider)
{
if (subject == null)
{
throw new ArgumentNullException(nameof(subject));
}
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
{
ArgumentNullException.ThrowIfNull(subject);
ArgumentNullException.ThrowIfNull(action);
return _authorizationManager
.GetAcesWithInherits(subject.ID, action.ID, objectId, secObjProvider)

View File

@ -23,8 +23,6 @@
*
*/
using static ASC.Security.Cryptography.EmailValidationKeyProvider;
namespace ASC.Security.Cryptography;
[Scope]
@ -69,10 +67,7 @@ public class EmailValidationKeyProvider
public string GetEmailKey(int tenantId, string email)
{
if (string.IsNullOrEmpty(email))
{
throw new ArgumentNullException(nameof(email));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(email);
email = FormatEmail(tenantId, email);
@ -84,10 +79,7 @@ public class EmailValidationKeyProvider
private string FormatEmail(int tenantId, string email)
{
if (email == null)
{
throw new ArgumentNullException(nameof(email));
}
ArgumentNullException.ThrowIfNull(email);
try
{
@ -116,14 +108,8 @@ public class EmailValidationKeyProvider
private ValidationResult ValidateEmailKeyInternal(string email, string key, TimeSpan validInterval)
{
if (string.IsNullOrEmpty(email))
{
throw new ArgumentNullException(nameof(email));
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(email);
ArgumentNullException.ThrowIfNull(key);
email = FormatEmail(_tenantManager.GetCurrentTenant().Id, email);
var parts = key.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

View File

@ -41,10 +41,7 @@ public class UserFormatter : IComparer<UserInfo>
public string GetUserName(UserInfo userInfo, DisplayUserNameFormat format)
{
if (userInfo == null)
{
throw new ArgumentNullException(nameof(userInfo));
}
ArgumentNullException.ThrowIfNull(userInfo);
return string.Format(GetUserDisplayFormat(format), userInfo.FirstName, userInfo.LastName);
}

View File

@ -5,6 +5,7 @@
<TargetFramework>net6.0</TargetFramework>
<OutputType>Library</OutputType>
<NoWarn>NU1701</NoWarn>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>

View File

@ -46,11 +46,8 @@ public static class ActionInvoker
Action<Exception> onAttemptFailure = null,
int sleepMs = 1000,
bool isSleepExponential = true)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
{
ArgumentNullException.ThrowIfNull(action);
var countAttempts = 0;
while (countAttempts++ < maxAttempts)

View File

@ -49,15 +49,10 @@ public static class EnumerableExtensions
public static IEnumerable<TreeNode<TEntry>> ToTree<TEntry, TKey>(this IEnumerable<TEntry> elements,
Func<TEntry, TKey> keySelector,
Func<TEntry, TKey> parentKeySelector)
{
if (elements == null)
throw new ArgumentNullException(nameof(elements));
if (keySelector == null)
throw new ArgumentNullException(nameof(keySelector));
if (parentKeySelector == null)
throw new ArgumentNullException(nameof(parentKeySelector));
{
ArgumentNullException.ThrowIfNull(elements);
ArgumentNullException.ThrowIfNull(keySelector);
ArgumentNullException.ThrowIfNull(parentKeySelector);
var dic = elements.ToDictionary(keySelector, x => new TreeNode<TEntry>(x));
@ -75,18 +70,17 @@ public static class EnumerableExtensions
}
public static IEnumerable<IEnumerable<TEntry>> MakeParts<TEntry>(this IEnumerable<TEntry> collection, int partLength)
{
ArgumentNullException.ThrowIfNull(collection);
if (partLength <= 0)
throw new ArgumentOutOfRangeException(nameof(partLength), partLength, "Length must be positive integer");
return MakePartsIterator(collection, partLength);
}
private static IEnumerable<IEnumerable<TEntry>> MakePartsIterator<TEntry>(this IEnumerable<TEntry> collection, int partLength)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (partLength <= 0)
throw new ArgumentOutOfRangeException(nameof(partLength), partLength, "Length must be positive integer");
return MakePartsIterator(collection, partLength);
}
private static IEnumerable<IEnumerable<TEntry>> MakePartsIterator<TEntry>(this IEnumerable<TEntry> collection, int partLength)
{
var part = new List<TEntry>(partLength);
foreach (var entry in collection)

View File

@ -1,20 +1,14 @@
global using System;
global using System.Collections.Generic;
global using System.ComponentModel.DataAnnotations;
global using System.ComponentModel.DataAnnotations;
global using System.ComponentModel.DataAnnotations.Schema;
global using System.Configuration;
global using System.Data;
global using System.Data.Common;
global using System.Diagnostics;
global using System.IO;
global using System.Linq;
global using System.Reflection;
global using System.Security.Cryptography;
global using System.ServiceModel;
global using System.Text;
global using System.Text.RegularExpressions;
global using System.Threading;
global using System.Threading.Tasks;
global using System.Xml;
global using System.Xml.Linq;
global using System.Xml.XPath;

View File

@ -50,9 +50,9 @@ public class BackupPortalTask : PortalTaskBase
}
public void Init(int tenantId, string fromConfigPath, string toFilePath, int limit)
{
if (string.IsNullOrEmpty(toFilePath))
throw new ArgumentNullException(nameof(toFilePath));
{
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(toFilePath);
BackupFilePath = toFilePath;
Limit = limit;
Init(tenantId, fromConfigPath);
@ -124,24 +124,24 @@ public class BackupPortalTask : PortalTaskBase
var command = connection.CreateCommand();
command.CommandText = "show tables";
tables = ExecuteList(command).Select(r => Convert.ToString(r[0])).ToList();
}
}
/* using (var dbManager = new DbManager("default", 100000))
{
tables = dbManager.ExecuteList("show tables;").Select(r => Convert.ToString(r[0])).ToList();
}*/
var stepscount = tables.Count * 4; // (schema + data) * (dump + zip)
if (ProcessStorage)
{
var tenants = _tenantManager.GetTenants(false).Select(r => r.Id);
foreach (var t in tenants)
{
files.AddRange(GetFiles(t));
}
stepscount += files.Count * 2 + 1;
Logger.Debug("files:" + files.Count);
}
}*/
var stepscount = tables.Count * 4; // (schema + data) * (dump + zip)
if (ProcessStorage)
{
var tenants = _tenantManager.GetTenants(false).Select(r => r.Id);
foreach (var t in tenants)
{
files.AddRange(GetFiles(t));
}
stepscount += files.Count * 2 + 1;
Logger.Debug("files:" + files.Count);
}
SetStepsCount(stepscount);
@ -200,9 +200,9 @@ public class BackupPortalTask : PortalTaskBase
private IEnumerable<BackupFileInfo> GetFiles(int tenantId)
{
var files = GetFilesToProcess(tenantId).ToList();
var exclude = BackupRecordContext.Backups.AsQueryable().Where(b => b.TenantId == tenantId && b.StorageType == 0 && b.StoragePath != null).ToList();
files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains($"/file_{e.StoragePath}/"))).ToList();
var files = GetFilesToProcess(tenantId).ToList();
var exclude = BackupRecordContext.Backups.AsQueryable().Where(b => b.TenantId == tenantId && b.StorageType == 0 && b.StoragePath != null).ToList();
files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains($"/file_{e.StoragePath}/"))).ToList();
return files;
}
@ -214,16 +214,16 @@ public class BackupPortalTask : PortalTaskBase
Logger.DebugFormat("dump table scheme start {0}", t);
using (var connection = DbFactory.OpenConnection())
{
var command = connection.CreateCommand();
command.CommandText = $"SHOW CREATE TABLE `{t}`";
var command = connection.CreateCommand();
command.CommandText = $"SHOW CREATE TABLE `{t}`";
var createScheme = ExecuteList(command);
var creates = new StringBuilder();
creates.Append($"DROP TABLE IF EXISTS `{t}`;");
var creates = new StringBuilder();
creates.Append($"DROP TABLE IF EXISTS `{t}`;");
creates.AppendLine();
creates.Append(createScheme
.Select(r => Convert.ToString(r[1]))
.FirstOrDefault());
creates.Append(';');
.FirstOrDefault());
creates.Append(';');
var path = CrossPlatform.PathCombine(dir, t);
using (var stream = File.OpenWrite(path))
@ -278,8 +278,8 @@ public class BackupPortalTask : PortalTaskBase
return;
}
Logger.DebugFormat("dump table data start {0}", t);
bool searchWithPrimary;
Logger.DebugFormat("dump table data start {0}", t);
bool searchWithPrimary;
string primaryIndex;
var primaryIndexStep = 0;
var primaryIndexStart = 0;
@ -288,8 +288,8 @@ public class BackupPortalTask : PortalTaskBase
using (var connection = DbFactory.OpenConnection())
{
var command = connection.CreateCommand();
command.CommandText = string.Format($"SHOW COLUMNS FROM `{t}`");
var command = connection.CreateCommand();
command.CommandText = string.Format($"SHOW COLUMNS FROM `{t}`");
columns = ExecuteList(command).Select(r => "`" + Convert.ToString(r[0]) + "`").ToList();
if (command.CommandText.Contains("tenants_quota") || command.CommandText.Contains("webstudio_settings"))
{
@ -299,16 +299,16 @@ public class BackupPortalTask : PortalTaskBase
using (var connection = DbFactory.OpenConnection())
{
var command = connection.CreateCommand();
command.CommandText = $"select COLUMN_NAME from information_schema.`COLUMNS` where TABLE_SCHEMA = '{connection.Database}' and TABLE_NAME = '{t}' and COLUMN_KEY = 'PRI' and DATA_TYPE = 'int'";
var command = connection.CreateCommand();
command.CommandText = $"select COLUMN_NAME from information_schema.`COLUMNS` where TABLE_SCHEMA = '{connection.Database}' and TABLE_NAME = '{t}' and COLUMN_KEY = 'PRI' and DATA_TYPE = 'int'";
primaryIndex = ExecuteList(command).ConvertAll(r => Convert.ToString(r[0])).FirstOrDefault();
}
using (var connection = DbFactory.OpenConnection())
{
var command = connection.CreateCommand();
command.CommandText = $"SHOW INDEXES FROM {t} WHERE COLUMN_NAME='{primaryIndex}' AND seq_in_index=1";
var command = connection.CreateCommand();
command.CommandText = $"SHOW INDEXES FROM {t} WHERE COLUMN_NAME='{primaryIndex}' AND seq_in_index=1";
var isLeft = ExecuteList(command);
searchWithPrimary = isLeft.Count == 1;
}
@ -316,8 +316,8 @@ public class BackupPortalTask : PortalTaskBase
if (searchWithPrimary)
{
using var connection = DbFactory.OpenConnection();
var command = connection.CreateCommand();
command.CommandText = $"select max({primaryIndex}), min({primaryIndex}) from {t}";
var command = connection.CreateCommand();
command.CommandText = $"select max({primaryIndex}), min({primaryIndex}) from {t}";
var minMax = ExecuteList(command).ConvertAll(r => new Tuple<int, int>(Convert.ToInt32(r[0]), Convert.ToInt32(r[1]))).FirstOrDefault();
primaryIndexStart = minMax.Item2;
primaryIndexStep = (minMax.Item1 - minMax.Item2) / count;
@ -397,8 +397,8 @@ public class BackupPortalTask : PortalTaskBase
private void SaveToFile(string path, string t, IReadOnlyCollection<string> columns, List<object[]> data)
{
Logger.DebugFormat("save to file {0}", t);
List<object[]> portion;
while ((portion = data.Take(BatchLimit).ToList()).Count > 0)
List<object[]> portion;
while ((portion = data.Take(BatchLimit).ToList()).Count > 0)
{
using (var sw = new StreamWriter(path, true))
using (var writer = new JsonTextWriter(sw))
@ -414,9 +414,9 @@ public class BackupPortalTask : PortalTaskBase
sw.Write("(");
for (var i = 0; i < obj.Length; i++)
{
var value = obj[i];
if (value is byte[] byteArray)
{
var value = obj[i];
if (value is byte[] byteArray)
{
sw.Write("0x");
foreach (var b in byteArray)
@ -426,8 +426,8 @@ public class BackupPortalTask : PortalTaskBase
}
else
{
var ser = new JsonSerializer();
ser.Serialize(writer, value);
var ser = new JsonSerializer();
ser.Serialize(writer, value);
}
if (i != obj.Length - 1)
{
@ -518,9 +518,9 @@ public class BackupPortalTask : PortalTaskBase
if (!WorkContext.IsMono && filePath.Length > MaxLength)
{
filePath = @"\\?\" + filePath;
}
using (var fileStream = await storage.GetReadStreamAsync(file.Domain, file.Path))
}
using (var fileStream = await storage.GetReadStreamAsync(file.Domain, file.Path))
using (var tmpFile = File.OpenWrite(filePath))
{
await fileStream.CopyToAsync(tmpFile);
@ -553,10 +553,10 @@ public class BackupPortalTask : PortalTaskBase
private List<IGrouping<string, BackupFileInfo>> GetFilesGroup()
{
var files = GetFilesToProcess(TenantId).ToList();
var exclude = BackupRecordContext.Backups.AsQueryable().Where(b => b.TenantId == TenantId && b.StorageType == 0 && b.StoragePath != null).ToList();
files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains($"/file_{e.StoragePath}/"))).ToList();
var files = GetFilesToProcess(TenantId).ToList();
var exclude = BackupRecordContext.Backups.AsQueryable().Where(b => b.TenantId == TenantId && b.StorageType == 0 && b.StoragePath != null).ToList();
files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains($"/file_{e.StoragePath}/"))).ToList();
return files.GroupBy(file => file.Module).ToList();
}
@ -616,9 +616,9 @@ public class BackupPortalTask : PortalTaskBase
}
Logger.DebugFormat("end saving table {0}", table.Name);
}
SetCurrentStepProgress((int)(++tablesProcessed * 100 / (double)tablesCount));
}
SetCurrentStepProgress((int)(++tablesProcessed * 100 / (double)tablesCount));
}
}
@ -640,8 +640,8 @@ public class BackupPortalTask : PortalTaskBase
var file1 = file;
ActionInvoker.Try(state =>
{
var f = (BackupFileInfo)state;
using var fileStream = storage.GetReadStreamAsync(f.Domain, f.Path).Result;
var f = (BackupFileInfo)state;
using var fileStream = storage.GetReadStreamAsync(f.Domain, f.Path).Result;
writer.WriteEntry(file1.GetZipKey(), fileStream);
}, file, 5, error => Logger.WarnFormat("can't backup file ({0}:{1}): {2}", file1.Module, file1.Path, error));

View File

@ -62,10 +62,7 @@ public class RestorePortalTask : PortalTaskBase
public void Init(string toConfigPath, string fromFilePath, int tenantId = -1, ColumnMapper columnMapper = null, string upgradesPath = null)
{
if (fromFilePath == null)
{
throw new ArgumentNullException(nameof(fromFilePath));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(fromFilePath);
if (!File.Exists(fromFilePath))
{
@ -291,8 +288,8 @@ public class RestorePortalTask : PortalTaskBase
}
using var stream = dataReader.GetEntry(key);
try
{
storage.SaveAsync(file.Domain, adjustedPath, module != null ? module.PrepareData(key, stream, _columnMapper) : stream).Wait();
{
storage.SaveAsync(file.Domain, adjustedPath, module != null ? module.PrepareData(key, stream, _columnMapper) : stream).Wait();
}
catch (Exception error)
{
@ -322,14 +319,14 @@ public class RestorePortalTask : PortalTaskBase
private void DoDeleteStorage(IEnumerable<string> storageModules, IEnumerable<Tenant> tenants)
{
Logger.Debug("begin delete storage");
foreach (var tenant in tenants)
{
foreach (var module in storageModules)
{
var storage = StorageFactory.GetStorage(ConfigPath, tenant.Id.ToString(), module);
var domains = StorageFactoryConfig.GetDomainList(ConfigPath, module).ToList();
Logger.Debug("begin delete storage");
foreach (var tenant in tenants)
{
foreach (var module in storageModules)
{
var storage = StorageFactory.GetStorage(ConfigPath, tenant.Id.ToString(), module);
var domains = StorageFactoryConfig.GetDomainList(ConfigPath, module).ToList();
domains.Add(string.Empty); //instead storage.DeleteFiles("\\", "*.*", true);
@ -337,10 +334,10 @@ public class RestorePortalTask : PortalTaskBase
{
ActionInvoker.Try(
state =>
{
if (storage.IsDirectoryAsync((string)state).Result)
{
storage.DeleteFilesAsync((string)state, "\\", "*.*", true).Wait();
{
if (storage.IsDirectoryAsync((string)state).Result)
{
storage.DeleteFilesAsync((string)state, "\\", "*.*", true).Wait();
}
},
domain,
@ -381,10 +378,10 @@ public class RestorePortalTask : PortalTaskBase
"where id = '{2}'",
(int)TenantStatus.Active,
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"),
tenantId);
var command = connection.CreateCommand().WithTimeout(120);
command.CommandText = commandText;
command.ExecuteNonQuery();
tenantId);
var command = connection.CreateCommand().WithTimeout(120);
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}

View File

@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

View File

@ -1,6 +1,4 @@
global using System;
global using System.Collections.Generic;
global using System.Globalization;
global using System.Globalization;
global using System.Security.Cryptography;
global using System.Text;
@ -19,5 +17,4 @@ global using ASC.Web.Studio.Core.Notify;
global using Microsoft.AspNetCore.Http;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Options;
global using Microsoft.Extensions.Primitives;
global using Microsoft.Extensions.Primitives;

View File

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ProduceReferenceAssembly>false</ProduceReferenceAssembly>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

View File

@ -71,26 +71,23 @@ public abstract class BaseStorage : IDataStore
return DomainsExpires.ContainsKey(domain) ? DomainsExpires[domain] : DomainsExpires[string.Empty];
}
public Task<Uri> GetUriAsync(string path)
public Task<Uri> GetUriAsync(string path)
{
return GetUriAsync(string.Empty, path);
return GetUriAsync(string.Empty, path);
}
public Task<Uri> GetUriAsync(string domain, string path)
public Task<Uri> GetUriAsync(string domain, string path)
{
return GetPreSignedUriAsync(domain, path, TimeSpan.MaxValue, null);
return GetPreSignedUriAsync(domain, path, TimeSpan.MaxValue, null);
}
public Task<Uri> GetPreSignedUriAsync(string domain, string path, TimeSpan expire, IEnumerable<string> headers)
public Task<Uri> GetPreSignedUriAsync(string domain, string path, TimeSpan expire, IEnumerable<string> headers)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
if (string.IsNullOrEmpty(Tenant) && IsSupportInternalUri)
{
return GetInternalUriAsync(domain, path, expire, headers);
return GetInternalUriAsync(domain, path, expire, headers);
}
var headerAttr = string.Empty;
@ -109,16 +106,16 @@ public abstract class BaseStorage : IDataStore
{
var expireString = expire.TotalMinutes.ToString(CultureInfo.InvariantCulture);
int currentTenantId;
var currentTenant = TenantManager.GetCurrentTenant(false);
if (currentTenant != null)
{
currentTenantId = currentTenant.Id;
}
else if (!TenantPath.TryGetTenant(Tenant, out currentTenantId))
{
currentTenantId = 0;
}
int currentTenantId;
var currentTenant = TenantManager.GetCurrentTenant(false);
if (currentTenant != null)
{
currentTenantId = currentTenant.Id;
}
else if (!TenantPath.TryGetTenant(Tenant, out currentTenantId))
{
currentTenantId = 0;
}
var auth = TemailValidationKeyProvider.GetEmailKey(currentTenantId, path.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar) + "." + headerAttr + "." + expireString);
query = $"{(path.IndexOf('?') >= 0 ? "&" : "?")}{Constants.QueryExpire}={expireString}&{Constants.QueryAuth}={auth}";
@ -139,169 +136,169 @@ public abstract class BaseStorage : IDataStore
new MonoUri(virtualPath, virtualPath.LocalPath.TrimEnd('/') + EnsureLeadingSlash(path.Replace('\\', '/')) + query) :
new MonoUri(virtualPath.ToString().TrimEnd('/') + EnsureLeadingSlash(path.Replace('\\', '/')) + query, UriKind.Relative);
return Task.FromResult<Uri>(uri);
return Task.FromResult<Uri>(uri);
}
public virtual Task<Uri> GetInternalUriAsync(string domain, string path, TimeSpan expire, IEnumerable<string> headers)
public virtual Task<Uri> GetInternalUriAsync(string domain, string path, TimeSpan expire, IEnumerable<string> headers)
{
return null;
}
public abstract Task<Stream> GetReadStreamAsync(string domain, string path);
public abstract Task<Stream> GetReadStreamAsync(string domain, string path);
public abstract Task<Stream> GetReadStreamAsync(string domain, string path, int offset);
public abstract Task<Uri> SaveAsync(string domain, string path, Stream stream);
public abstract Task<Uri> SaveAsync(string domain, string path, Stream stream, ACL acl);
public abstract Task<Uri> SaveAsync(string domain, string path, Stream stream);
public abstract Task<Uri> SaveAsync(string domain, string path, Stream stream, ACL acl);
public Task<Uri> SaveAsync(string domain, string path, Stream stream, string attachmentFileName)
public Task<Uri> SaveAsync(string domain, string path, Stream stream, string attachmentFileName)
{
if (!string.IsNullOrEmpty(attachmentFileName))
{
return SaveWithAutoAttachmentAsync(domain, path, stream, attachmentFileName);
return SaveWithAutoAttachmentAsync(domain, path, stream, attachmentFileName);
}
return SaveAsync(domain, path, stream);
return SaveAsync(domain, path, stream);
}
protected abstract Task<Uri> SaveWithAutoAttachmentAsync(string domain, string path, Stream stream, string attachmentFileName);
protected abstract Task<Uri> SaveWithAutoAttachmentAsync(string domain, string path, Stream stream, string attachmentFileName);
public abstract Task<Uri> SaveAsync(string domain, string path, Stream stream, string contentType,
string contentDisposition);
public abstract Task<Uri> SaveAsync(string domain, string path, Stream stream, string contentEncoding, int cacheDays);
public abstract Task<Uri> SaveAsync(string domain, string path, Stream stream, string contentType,
string contentDisposition);
public abstract Task<Uri> SaveAsync(string domain, string path, Stream stream, string contentEncoding, int cacheDays);
#region chunking
public virtual Task<string> InitiateChunkedUploadAsync(string domain, string path)
public virtual Task<string> InitiateChunkedUploadAsync(string domain, string path)
{
throw new NotImplementedException();
}
public virtual Task<string> UploadChunkAsync(string domain, string path, string uploadId, Stream stream, long defaultChunkSize, int chunkNumber, long chunkLength)
public virtual Task<string> UploadChunkAsync(string domain, string path, string uploadId, Stream stream, long defaultChunkSize, int chunkNumber, long chunkLength)
{
throw new NotImplementedException();
}
public virtual Task<Uri> FinalizeChunkedUploadAsync(string domain, string path, string uploadId, Dictionary<int, string> eTags)
public virtual Task<Uri> FinalizeChunkedUploadAsync(string domain, string path, string uploadId, Dictionary<int, string> eTags)
{
throw new NotImplementedException();
}
public virtual Task AbortChunkedUploadAsync(string domain, string path, string uploadId)
public virtual Task AbortChunkedUploadAsync(string domain, string path, string uploadId)
{
throw new NotImplementedException();
}
#endregion
public abstract Task DeleteAsync(string domain, string path);
public abstract Task DeleteFilesAsync(string domain, string folderPath, string pattern, bool recursive);
public abstract Task DeleteFilesAsync(string domain, List<string> paths);
public abstract Task DeleteFilesAsync(string domain, string folderPath, DateTime fromDate, DateTime toDate);
public abstract Task MoveDirectoryAsync(string srcdomain, string srcdir, string newdomain, string newdir);
public abstract Task<Uri> MoveAsync(string srcdomain, string srcpath, string newdomain, string newpath, bool quotaCheckFileSize = true);
public abstract Task<Uri> SaveTempAsync(string domain, out string assignedPath, Stream stream);
public abstract IAsyncEnumerable<string> ListDirectoriesRelativeAsync(string domain, string path, bool recursive);
public abstract IAsyncEnumerable<string> ListFilesRelativeAsync(string domain, string path, string pattern, bool recursive);
public abstract Task DeleteAsync(string domain, string path);
public abstract Task DeleteFilesAsync(string domain, string folderPath, string pattern, bool recursive);
public abstract Task DeleteFilesAsync(string domain, List<string> paths);
public abstract Task DeleteFilesAsync(string domain, string folderPath, DateTime fromDate, DateTime toDate);
public abstract Task MoveDirectoryAsync(string srcdomain, string srcdir, string newdomain, string newdir);
public abstract Task<Uri> MoveAsync(string srcdomain, string srcpath, string newdomain, string newpath, bool quotaCheckFileSize = true);
public abstract Task<Uri> SaveTempAsync(string domain, out string assignedPath, Stream stream);
public abstract IAsyncEnumerable<string> ListDirectoriesRelativeAsync(string domain, string path, bool recursive);
public abstract IAsyncEnumerable<string> ListFilesRelativeAsync(string domain, string path, string pattern, bool recursive);
public abstract Task<bool> IsFileAsync(string domain, string path);
public abstract Task<bool> IsDirectoryAsync(string domain, string path);
public abstract Task DeleteDirectoryAsync(string domain, string path);
public abstract Task<long> GetFileSizeAsync(string domain, string path);
public abstract Task<long> GetDirectorySizeAsync(string domain, string path);
public abstract Task<long> ResetQuotaAsync(string domain);
public abstract Task<long> GetUsedQuotaAsync(string domain);
public abstract Task<Uri> CopyAsync(string srcdomain, string path, string newdomain, string newpath);
public abstract Task CopyDirectoryAsync(string srcdomain, string dir, string newdomain, string newdir);
public abstract Task<bool> IsDirectoryAsync(string domain, string path);
public abstract Task DeleteDirectoryAsync(string domain, string path);
public abstract Task<long> GetFileSizeAsync(string domain, string path);
public abstract Task<long> GetDirectorySizeAsync(string domain, string path);
public abstract Task<long> ResetQuotaAsync(string domain);
public abstract Task<long> GetUsedQuotaAsync(string domain);
public abstract Task<Uri> CopyAsync(string srcdomain, string path, string newdomain, string newpath);
public abstract Task CopyDirectoryAsync(string srcdomain, string dir, string newdomain, string newdir);
public Task<Stream> GetReadStreamAsync(string path)
public Task<Stream> GetReadStreamAsync(string path)
{
return GetReadStreamAsync(string.Empty, path);
return GetReadStreamAsync(string.Empty, path);
}
public Task<Uri> SaveAsync(string path, Stream stream, string attachmentFileName)
public Task<Uri> SaveAsync(string path, Stream stream, string attachmentFileName)
{
return SaveAsync(string.Empty, path, stream, attachmentFileName);
return SaveAsync(string.Empty, path, stream, attachmentFileName);
}
public Task<Uri> SaveAsync(string path, Stream stream)
public Task<Uri> SaveAsync(string path, Stream stream)
{
return SaveAsync(string.Empty, path, stream);
return SaveAsync(string.Empty, path, stream);
}
public async Task DeleteAsync(string path)
public async Task DeleteAsync(string path)
{
await DeleteAsync(string.Empty, path);
await DeleteAsync(string.Empty, path);
}
public async Task DeleteFilesAsync(string folderPath, string pattern, bool recursive)
public async Task DeleteFilesAsync(string folderPath, string pattern, bool recursive)
{
await DeleteFilesAsync(string.Empty, folderPath, pattern, recursive);
await DeleteFilesAsync(string.Empty, folderPath, pattern, recursive);
}
public Task<Uri> MoveAsync(string srcpath, string newdomain, string newpath)
public Task<Uri> MoveAsync(string srcpath, string newdomain, string newpath)
{
return MoveAsync(string.Empty, srcpath, newdomain, newpath);
return MoveAsync(string.Empty, srcpath, newdomain, newpath);
}
public Task<Uri> SaveTempAsync(out string assignedPath, Stream stream)
public Task<Uri> SaveTempAsync(out string assignedPath, Stream stream)
{
return SaveTempAsync(string.Empty, out assignedPath, stream);
return SaveTempAsync(string.Empty, out assignedPath, stream);
}
public IAsyncEnumerable<string> ListDirectoriesRelativeAsync(string path, bool recursive)
public IAsyncEnumerable<string> ListDirectoriesRelativeAsync(string path, bool recursive)
{
return ListDirectoriesRelativeAsync(string.Empty, path, recursive);
return ListDirectoriesRelativeAsync(string.Empty, path, recursive);
}
public IAsyncEnumerable<Uri> ListFilesAsync(string path, string pattern, bool recursive)
public IAsyncEnumerable<Uri> ListFilesAsync(string path, string pattern, bool recursive)
{
return ListFilesAsync(string.Empty, path, pattern, recursive);
return ListFilesAsync(string.Empty, path, pattern, recursive);
}
public async IAsyncEnumerable<Uri> ListFilesAsync(string domain, string path, string pattern, bool recursive)
public async IAsyncEnumerable<Uri> ListFilesAsync(string domain, string path, string pattern, bool recursive)
{
var filePaths = ListFilesRelativeAsync(domain, path, pattern, recursive);
var filePaths = ListFilesRelativeAsync(domain, path, pattern, recursive);
await foreach(var paths in filePaths)
{
yield return await GetUriAsync(domain, CrossPlatform.PathCombine(PathUtils.Normalize(path), paths));
}
await foreach (var paths in filePaths)
{
yield return await GetUriAsync(domain, CrossPlatform.PathCombine(PathUtils.Normalize(path), paths));
}
public Task<bool> IsFileAsync(string path)
{
return IsFileAsync(string.Empty, path);
}
public Task<bool> IsDirectoryAsync(string path)
public Task<bool> IsFileAsync(string path)
{
return IsDirectoryAsync(string.Empty, path);
return IsFileAsync(string.Empty, path);
}
public async Task DeleteDirectoryAsync(string path)
public Task<bool> IsDirectoryAsync(string path)
{
await DeleteDirectoryAsync(string.Empty, path);
return IsDirectoryAsync(string.Empty, path);
}
public Task<long> GetFileSizeAsync(string path)
public async Task DeleteDirectoryAsync(string path)
{
return GetFileSizeAsync(string.Empty, path);
await DeleteDirectoryAsync(string.Empty, path);
}
public Task<long> GetDirectorySizeAsync(string path)
public Task<long> GetFileSizeAsync(string path)
{
return GetDirectorySizeAsync(string.Empty, path);
return GetFileSizeAsync(string.Empty, path);
}
public Task<Uri> CopyAsync(string path, string newdomain, string newpath)
public Task<long> GetDirectorySizeAsync(string path)
{
return CopyAsync(string.Empty, path, newdomain, newpath);
return GetDirectorySizeAsync(string.Empty, path);
}
public async Task CopyDirectoryAsync(string dir, string newdomain, string newdir)
public Task<Uri> CopyAsync(string path, string newdomain, string newpath)
{
await CopyDirectoryAsync(string.Empty, dir, newdomain, newdir);
return CopyAsync(string.Empty, path, newdomain, newpath);
}
public async Task CopyDirectoryAsync(string dir, string newdomain, string newdir)
{
await CopyDirectoryAsync(string.Empty, dir, newdomain, newdir);
}
public virtual IDataStore Configure(string tenant, Handler handlerConfig, Module moduleConfig, IDictionary<string, string> props)
@ -316,13 +313,13 @@ public abstract class BaseStorage : IDataStore
return this;
}
public abstract Task<string> SavePrivateAsync(string domain, string path, Stream stream, DateTime expires);
public abstract Task DeleteExpiredAsync(string domain, string path, TimeSpan oldThreshold);
public abstract Task<string> SavePrivateAsync(string domain, string path, Stream stream, DateTime expires);
public abstract Task DeleteExpiredAsync(string domain, string path, TimeSpan oldThreshold);
public abstract string GetUploadForm(string domain, string directoryPath, string redirectTo, long maxUploadSize,
string contentType, string contentDisposition, string submitLabel);
public abstract Task<string> GetUploadedUrlAsync(string domain, string directoryPath);
public abstract Task<string> GetUploadedUrlAsync(string domain, string directoryPath);
public abstract string GetUploadUrl();
public abstract string GetPostParams(string domain, string directoryPath, long maxUploadSize, string contentType,

View File

@ -55,25 +55,10 @@ public class CrossModuleTransferUtility
public Task CopyFileAsync(string srcDomain, string srcPath, string destDomain, string destPath)
{
if (srcDomain == null)
{
throw new ArgumentNullException(nameof(srcDomain));
}
if (srcPath == null)
{
throw new ArgumentNullException(nameof(srcPath));
}
if (destDomain == null)
{
throw new ArgumentNullException(nameof(destDomain));
}
if (destPath == null)
{
throw new ArgumentNullException(nameof(destPath));
}
ArgumentNullException.ThrowIfNull(srcDomain);
ArgumentNullException.ThrowIfNull(srcPath);
ArgumentNullException.ThrowIfNull(destDomain);
ArgumentNullException.ThrowIfNull(destPath);
return InternalCopyFileAsync(srcDomain, srcPath, destDomain, destPath);
}

View File

@ -82,27 +82,21 @@ public class DiscDataStore : BaseStorage
public string GetPhysicalPath(string domain, string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
var pathMap = GetPath(domain);
return (pathMap.PhysicalPath + EnsureLeadingSlash(path)).Replace('\\', '/');
}
public override Task<Stream> GetReadStreamAsync(string domain, string path)
public override Task<Stream> GetReadStreamAsync(string domain, string path)
{
return Task.FromResult(GetReadStream(domain, path, true));
return Task.FromResult(GetReadStream(domain, path, true));
}
public Stream GetReadStream(string domain, string path, bool withDecription)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
var target = GetTarget(domain, path);
@ -116,10 +110,7 @@ public class DiscDataStore : BaseStorage
public override Task<Stream> GetReadStreamAsync(string domain, string path, int offset)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
var target = GetTarget(domain, path);
@ -131,24 +122,24 @@ public class DiscDataStore : BaseStorage
stream.Seek(offset, SeekOrigin.Begin);
}
return Task.FromResult(stream);
return Task.FromResult(stream);
}
throw new FileNotFoundException("File not found", Path.GetFullPath(target));
}
public override Task<Uri> SaveAsync(string domain, string path, Stream stream, string contentType, string contentDisposition)
public override Task<Uri> SaveAsync(string domain, string path, Stream stream, string contentType, string contentDisposition)
{
return SaveAsync(domain, path, stream);
return SaveAsync(domain, path, stream);
}
public override Task<Uri> SaveAsync(string domain, string path, Stream stream, string contentEncoding, int cacheDays)
public override Task<Uri> SaveAsync(string domain, string path, Stream stream, string contentEncoding, int cacheDays)
{
return SaveAsync(domain, path, stream);
return SaveAsync(domain, path, stream);
}
public override Task<Uri> SaveAsync(string domain, string path, Stream stream)
public override Task<Uri> SaveAsync(string domain, string path, Stream stream)
{
Logger.Debug("Save " + path);
@ -158,23 +149,16 @@ public class DiscDataStore : BaseStorage
QuotaController.QuotaUsedCheck(buffered.Length);
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (buffered == null)
{
throw new ArgumentNullException(nameof(stream));
}
ArgumentNullException.ThrowIfNull(path);
ArgumentNullException.ThrowIfNull(stream);
//Try seek to start
return InternalSaveAsync(domain, path, buffered);
}
return InternalSaveAsync(domain, path, buffered);
}
private async Task<Uri> InternalSaveAsync(string domain, string path, Stream buffered)
{
//Try seek to start
private async Task<Uri> InternalSaveAsync(string domain, string path, Stream buffered)
{
//Try seek to start
if (buffered.CanSeek)
{
buffered.Seek(0, SeekOrigin.Begin);
@ -195,7 +179,7 @@ public class DiscDataStore : BaseStorage
else
{
using var fs = File.Open(target, FileMode.Create);
await buffered.CopyToAsync(fs);
await buffered.CopyToAsync(fs);
fslen = fs.Length;
}
@ -203,30 +187,30 @@ public class DiscDataStore : BaseStorage
_crypt.EncryptFile(target);
return await GetUriAsync(domain, path);
return await GetUriAsync(domain, path);
}
public override Task<Uri> SaveAsync(string domain, string path, Stream stream, ACL acl)
public override Task<Uri> SaveAsync(string domain, string path, Stream stream, ACL acl)
{
return SaveAsync(domain, path, stream);
return SaveAsync(domain, path, stream);
}
#region chunking
public override async Task<string> UploadChunkAsync(string domain, string path, string uploadId, Stream stream, long defaultChunkSize, int chunkNumber, long chunkLength)
public override async Task<string> UploadChunkAsync(string domain, string path, string uploadId, Stream stream, long defaultChunkSize, int chunkNumber, long chunkLength)
{
var target = GetTarget(domain, path);
var mode = chunkNumber == 0 ? FileMode.Create : FileMode.Append;
using (var fs = new FileStream(target, mode))
{
await stream.CopyToAsync(fs);
await stream.CopyToAsync(fs);
}
return string.Format("{0}_{1}", chunkNumber, uploadId);
}
public override Task<Uri> FinalizeChunkedUploadAsync(string domain, string path, string uploadId, Dictionary<int, string> eTags)
public override Task<Uri> FinalizeChunkedUploadAsync(string domain, string path, string uploadId, Dictionary<int, string> eTags)
{
var target = GetTarget(domain, path);
@ -243,27 +227,24 @@ public class DiscDataStore : BaseStorage
_crypt.EncryptFile(target);
return GetUriAsync(domain, path);
return GetUriAsync(domain, path);
}
public override Task AbortChunkedUploadAsync(string domain, string path, string uploadId)
public override Task AbortChunkedUploadAsync(string domain, string path, string uploadId)
{
var target = GetTarget(domain, path);
if (File.Exists(target))
{
File.Delete(target);
}
return Task.CompletedTask;
return Task.CompletedTask;
}
#endregion
public override Task DeleteAsync(string domain, string path)
public override Task DeleteAsync(string domain, string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
var target = GetTarget(domain, path);
@ -273,7 +254,7 @@ public class DiscDataStore : BaseStorage
File.Delete(target);
QuotaUsedDelete(domain, size);
return Task.CompletedTask; ;
return Task.CompletedTask; ;
}
else
{
@ -281,12 +262,9 @@ public class DiscDataStore : BaseStorage
}
}
public override Task DeleteFilesAsync(string domain, List<string> paths)
public override Task DeleteFilesAsync(string domain, List<string> paths)
{
if (paths == null)
{
throw new ArgumentNullException(nameof(paths));
}
ArgumentNullException.ThrowIfNull(paths);
foreach (var path in paths)
{
@ -303,15 +281,12 @@ public class DiscDataStore : BaseStorage
QuotaUsedDelete(domain, size);
}
return Task.CompletedTask;
return Task.CompletedTask;
}
public override Task DeleteFilesAsync(string domain, string folderPath, string pattern, bool recursive)
public override Task DeleteFilesAsync(string domain, string folderPath, string pattern, bool recursive)
{
if (folderPath == null)
{
throw new ArgumentNullException(nameof(folderPath));
}
ArgumentNullException.ThrowIfNull(folderPath);
//Return dirs
var targetDir = GetTarget(domain, folderPath);
@ -324,20 +299,17 @@ public class DiscDataStore : BaseStorage
File.Delete(entry);
QuotaUsedDelete(domain, size);
}
return Task.CompletedTask;
return Task.CompletedTask;
}
else
{
throw new DirectoryNotFoundException($"Directory '{targetDir}' not found");
throw new DirectoryNotFoundException($"Directory '{targetDir}' not found");
}
}
public override Task DeleteFilesAsync(string domain, string folderPath, DateTime fromDate, DateTime toDate)
public override Task DeleteFilesAsync(string domain, string folderPath, DateTime fromDate, DateTime toDate)
{
if (folderPath == null)
{
throw new ArgumentNullException(nameof(folderPath));
}
ArgumentNullException.ThrowIfNull(folderPath);
//Return dirs
var targetDir = GetTarget(domain, folderPath);
@ -357,13 +329,13 @@ public class DiscDataStore : BaseStorage
}
else
{
throw new DirectoryNotFoundException($"Directory '{targetDir}' not found");
throw new DirectoryNotFoundException($"Directory '{targetDir}' not found");
}
return Task.CompletedTask;
return Task.CompletedTask;
}
public override Task MoveDirectoryAsync(string srcdomain, string srcdir, string newdomain, string newdir)
public override Task MoveDirectoryAsync(string srcdomain, string srcdir, string newdomain, string newdir)
{
var target = GetTarget(srcdomain, srcdir);
var newtarget = GetTarget(newdomain, newdir);
@ -376,20 +348,13 @@ public class DiscDataStore : BaseStorage
Directory.Move(target, newtarget);
return Task.CompletedTask;
return Task.CompletedTask;
}
public override Task<Uri> MoveAsync(string srcdomain, string srcpath, string newdomain, string newpath, bool quotaCheckFileSize = true)
public override Task<Uri> MoveAsync(string srcdomain, string srcpath, string newdomain, string newpath, bool quotaCheckFileSize = true)
{
if (srcpath == null)
{
throw new ArgumentNullException(nameof(srcpath));
}
if (newpath == null)
{
throw new ArgumentNullException(nameof(srcpath));
}
ArgumentNullException.ThrowIfNull(srcpath);
ArgumentNullException.ThrowIfNull(newpath);
var target = GetTarget(srcdomain, srcpath);
var newtarget = GetTarget(newdomain, newpath);
@ -418,15 +383,12 @@ public class DiscDataStore : BaseStorage
{
throw new FileNotFoundException("File not found", Path.GetFullPath(target));
}
return GetUriAsync(newdomain, newpath);
return GetUriAsync(newdomain, newpath);
}
public override Task<bool> IsDirectoryAsync(string domain, string path)
public override Task<bool> IsDirectoryAsync(string domain, string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
//Return dirs
var targetDir = GetTarget(domain, path);
@ -434,15 +396,12 @@ public class DiscDataStore : BaseStorage
{
targetDir += Path.DirectorySeparatorChar;
}
return Task.FromResult(!string.IsNullOrEmpty(targetDir) && Directory.Exists(targetDir));
return Task.FromResult(!string.IsNullOrEmpty(targetDir) && Directory.Exists(targetDir));
}
public override Task DeleteDirectoryAsync(string domain, string path)
public override Task DeleteDirectoryAsync(string domain, string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
//Return dirs
var targetDir = GetTarget(domain, path);
@ -452,12 +411,12 @@ public class DiscDataStore : BaseStorage
throw new Exception("targetDir is null");
}
if (!targetDir.EndsWith(Path.DirectorySeparatorChar.ToString()))
if (!targetDir.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
targetDir += Path.DirectorySeparatorChar;
}
if (!Directory.Exists(targetDir)) return Task.CompletedTask;
if (!Directory.Exists(targetDir)) return Task.CompletedTask;
var entries = Directory.GetFiles(targetDir, "*.*", SearchOption.AllDirectories);
var size = entries.Select(entry => _crypt.GetFileSize(entry)).Sum();
@ -469,59 +428,56 @@ public class DiscDataStore : BaseStorage
Directory.Delete(targetDir, true);
QuotaUsedDelete(domain, size);
return Task.CompletedTask;
return Task.CompletedTask;
}
public override Task<long> GetFileSizeAsync(string domain, string path)
public override Task<long> GetFileSizeAsync(string domain, string path)
{
var target = GetTarget(domain, path);
if (File.Exists(target))
{
return Task.FromResult(_crypt.GetFileSize(target));
return Task.FromResult(_crypt.GetFileSize(target));
}
throw new FileNotFoundException("file not found " + target);
}
public override Task<long> GetDirectorySizeAsync(string domain, string path)
public override Task<long> GetDirectorySizeAsync(string domain, string path)
{
var target = GetTarget(domain, path);
if (Directory.Exists(target))
{
return Task.FromResult(Directory.GetFiles(target, "*.*", SearchOption.AllDirectories)
.Select(entry => _crypt.GetFileSize(entry))
.Sum());
return Task.FromResult(Directory.GetFiles(target, "*.*", SearchOption.AllDirectories)
.Select(entry => _crypt.GetFileSize(entry))
.Sum());
}
throw new FileNotFoundException("directory not found " + target);
}
public override Task<Uri> SaveTempAsync(string domain, out string assignedPath, Stream stream)
public override Task<Uri> SaveTempAsync(string domain, out string assignedPath, Stream stream)
{
assignedPath = Guid.NewGuid().ToString();
return SaveAsync(domain, assignedPath, stream);
return SaveAsync(domain, assignedPath, stream);
}
public override async Task<string> SavePrivateAsync(string domain, string path, Stream stream, DateTime expires)
public override async Task<string> SavePrivateAsync(string domain, string path, Stream stream, DateTime expires)
{
var result = await SaveAsync(domain, path, stream);
return result.ToString();
var result = await SaveAsync(domain, path, stream);
return result.ToString();
}
public override Task DeleteExpiredAsync(string domain, string folderPath, TimeSpan oldThreshold)
public override Task DeleteExpiredAsync(string domain, string folderPath, TimeSpan oldThreshold)
{
if (folderPath == null)
{
throw new ArgumentNullException(nameof(folderPath));
}
ArgumentNullException.ThrowIfNull(folderPath);
//Return dirs
var targetDir = GetTarget(domain, folderPath);
if (!Directory.Exists(targetDir))
{
return Task.CompletedTask;
return Task.CompletedTask;
}
var entries = Directory.GetFiles(targetDir, "*.*", SearchOption.TopDirectoryOnly);
@ -537,7 +493,7 @@ public class DiscDataStore : BaseStorage
}
}
return Task.CompletedTask;
return Task.CompletedTask;
}
public override string GetUploadForm(string domain, string directoryPath, string redirectTo, long maxUploadSize, string contentType, string contentDisposition, string submitLabel)
@ -545,7 +501,7 @@ public class DiscDataStore : BaseStorage
throw new NotSupportedException("This operation supported only on s3 storage");
}
public override Task<string> GetUploadedUrlAsync(string domain, string directoryPath)
public override Task<string> GetUploadedUrlAsync(string domain, string directoryPath)
{
throw new NotSupportedException("This operation supported only on s3 storage");
}
@ -560,12 +516,9 @@ public class DiscDataStore : BaseStorage
throw new NotSupportedException("This operation supported only on s3 storage");
}
public override IAsyncEnumerable<string> ListDirectoriesRelativeAsync(string domain, string path, bool recursive)
public override IAsyncEnumerable<string> ListDirectoriesRelativeAsync(string domain, string path, bool recursive)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
//Return dirs
var targetDir = GetTarget(domain, path);
@ -577,20 +530,17 @@ public class DiscDataStore : BaseStorage
if (Directory.Exists(targetDir))
{
var entries = Directory.GetDirectories(targetDir, "*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
var tmp = Array.ConvertAll(
entries,
x => x.Substring(targetDir.Length));
return tmp.ToAsyncEnumerable();
var tmp = Array.ConvertAll(
entries,
x => x.Substring(targetDir.Length));
return tmp.ToAsyncEnumerable();
}
return AsyncEnumerable.Empty<string>();
return AsyncEnumerable.Empty<string>();
}
public override IAsyncEnumerable<string> ListFilesRelativeAsync(string domain, string path, string pattern, bool recursive)
public override IAsyncEnumerable<string> ListFilesRelativeAsync(string domain, string path, string pattern, bool recursive)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
//Return dirs
var targetDir = GetTarget(domain, path);
@ -602,39 +552,36 @@ public class DiscDataStore : BaseStorage
if (Directory.Exists(targetDir))
{
var entries = Directory.GetFiles(targetDir, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
var tmp = Array.ConvertAll(
entries,
x => x.Substring(targetDir.Length));
return tmp.ToAsyncEnumerable();
var tmp = Array.ConvertAll(
entries,
x => x.Substring(targetDir.Length));
return tmp.ToAsyncEnumerable();
}
return AsyncEnumerable.Empty<string>();
return AsyncEnumerable.Empty<string>();
}
public override Task<bool> IsFileAsync(string domain, string path)
public override Task<bool> IsFileAsync(string domain, string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
//Return dirs
var target = GetTarget(domain, path);
var result = File.Exists(target);
return Task.FromResult(result);
return Task.FromResult(result);
}
public override async Task<long> ResetQuotaAsync(string domain)
public override async Task<long> ResetQuotaAsync(string domain)
{
if (QuotaController != null)
{
var size = await GetUsedQuotaAsync(domain);
var size = await GetUsedQuotaAsync(domain);
QuotaController.QuotaUsedSet(Modulename, domain, DataList.GetData(domain), size);
}
return 0;
}
public override Task<long> GetUsedQuotaAsync(string domain)
public override Task<long> GetUsedQuotaAsync(string domain)
{
var target = GetTarget(domain, string.Empty);
long size = 0;
@ -644,20 +591,13 @@ public class DiscDataStore : BaseStorage
var entries = Directory.GetFiles(target, "*.*", SearchOption.AllDirectories);
size = entries.Select(entry => _crypt.GetFileSize(entry)).Sum();
}
return Task.FromResult(size);
return Task.FromResult(size);
}
public override Task<Uri> CopyAsync(string srcdomain, string srcpath, string newdomain, string newpath)
public override Task<Uri> CopyAsync(string srcdomain, string srcpath, string newdomain, string newpath)
{
if (srcpath == null)
{
throw new ArgumentNullException(nameof(srcpath));
}
if (newpath == null)
{
throw new ArgumentNullException(nameof(srcpath));
}
ArgumentNullException.ThrowIfNull(srcpath);
ArgumentNullException.ThrowIfNull(newpath);
var target = GetTarget(srcdomain, srcpath);
var newtarget = GetTarget(newdomain, newpath);
@ -678,10 +618,10 @@ public class DiscDataStore : BaseStorage
{
throw new FileNotFoundException("File not found", Path.GetFullPath(target));
}
return GetUriAsync(newdomain, newpath);
return GetUriAsync(newdomain, newpath);
}
public override Task CopyDirectoryAsync(string srcdomain, string srcdir, string newdomain, string newdir)
public override Task CopyDirectoryAsync(string srcdomain, string srcdir, string newdomain, string newdir)
{
var target = GetTarget(srcdomain, srcdir);
var newtarget = GetTarget(newdomain, newdir);
@ -690,7 +630,7 @@ public class DiscDataStore : BaseStorage
var diTarget = new DirectoryInfo(newtarget);
CopyAll(diSource, diTarget, newdomain);
return Task.CompletedTask;
return Task.CompletedTask;
}
@ -701,10 +641,7 @@ public class DiscDataStore : BaseStorage
public Stream GetWriteStream(string domain, string path, FileMode fileMode)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
var target = GetTarget(domain, path);
CreateDirectory(target);
@ -714,10 +651,7 @@ public class DiscDataStore : BaseStorage
public void Decrypt(string domain, string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
var target = GetTarget(domain, path);
@ -731,10 +665,10 @@ public class DiscDataStore : BaseStorage
}
}
protected override Task<Uri> SaveWithAutoAttachmentAsync(string domain, string path, Stream stream, string attachmentFileName)
{
return SaveAsync(domain, path, stream);
}
protected override Task<Uri> SaveWithAutoAttachmentAsync(string domain, string path, Stream stream, string attachmentFileName)
{
return SaveAsync(domain, path, stream);
}
private void CopyAll(DirectoryInfo source, DirectoryInfo target, string newdomain)
{
@ -765,7 +699,7 @@ public class DiscDataStore : BaseStorage
{
if (domain != null && _mappedPaths.TryGetValue(domain, out var value))
{
return value;
return value;
}
return _mappedPaths[string.Empty].AppendDomain(domain);
@ -802,10 +736,7 @@ public class DiscDataStore : BaseStorage
public void Encrypt(string domain, string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
ArgumentNullException.ThrowIfNull(path);
var target = GetTarget(domain, path);

View File

@ -1,19 +1,12 @@
global using System;
global using System.Collections.Concurrent;
global using System.Collections.Generic;
global using System.Collections.Concurrent;
global using System.Globalization;
global using System.IO;
global using System.Linq;
global using System.Net;
global using System.Net.Http;
global using System.Runtime.Serialization;
global using System.Security.Cryptography;
global using System.ServiceModel;
global using System.Text;
global using System.Text.Json;
global using System.Text.Json.Serialization;
global using System.Threading;
global using System.Threading.Tasks;
global using System.Web;
global using Amazon;

View File

@ -29,10 +29,7 @@ public static class TenantPath
{
public static string CreatePath(string tenant)
{
if (tenant == null)
{
throw new ArgumentNullException(nameof(tenant));
}
ArgumentNullException.ThrowIfNull(tenant);
if (long.TryParse(tenant, NumberStyles.Integer, CultureInfo.InvariantCulture, out var tenantId))
{

View File

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<NoWarn>NU1701</NoWarn>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

View File

@ -1,12 +1,7 @@
global using System;
global using System.Collections.Generic;
global using System.Data;
global using System.Data;
global using System.Diagnostics;
global using System.Globalization;
global using System.IO;
global using System.Linq;
global using System.Net;
global using System.Net.Http;
global using System.Net.Http.Headers;
global using System.Reflection;
global using System.Runtime.Serialization;
@ -14,8 +9,6 @@ global using System.Security.Cryptography.Pkcs;
global using System.Security.Cryptography.X509Certificates;
global using System.Text;
global using System.Text.Json.Serialization;
global using System.Threading;
global using System.Threading.Tasks;
global using System.Web;
global using System.Xml.Linq;
global using System.Xml.XPath;

View File

@ -107,20 +107,9 @@ public class OAuth20TokenHelper
var clientSecret = loginProvider.ClientSecret;
var redirectUri = loginProvider.RedirectUri;
if (string.IsNullOrEmpty(authCode))
{
throw new ArgumentNullException(nameof(authCode));
}
if (string.IsNullOrEmpty(clientID))
{
throw new ArgumentNullException(nameof(clientID));
}
if (string.IsNullOrEmpty(clientSecret))
{
throw new ArgumentNullException(nameof(clientSecret));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(authCode);
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(clientID);
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(clientSecret);
var data = $"code={HttpUtility.UrlEncode(authCode)}&client_id={HttpUtility.UrlEncode(clientID)}&client_secret={HttpUtility.UrlEncode(clientSecret)}";

View File

@ -31,10 +31,7 @@ public static class RequestHelper
public static string PerformRequest(string uri, string contentType = "", string method = "GET", string body = "", Dictionary<string, string> headers = null, int timeout = 30000)
{
if (string.IsNullOrEmpty(uri))
{
throw new ArgumentNullException(nameof(uri));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(uri);
var request = new HttpRequestMessage();
request.RequestUri = new Uri(uri);

View File

@ -73,20 +73,9 @@ public class DocuSignLoginProvider : Consumer, IOAuthProvider
public OAuth20Token GetAccessToken(string authCode)
{
if (string.IsNullOrEmpty(authCode))
{
throw new ArgumentNullException(nameof(authCode));
}
if (string.IsNullOrEmpty(ClientID))
{
throw new ArgumentException(nameof(ClientID));
}
if (string.IsNullOrEmpty(ClientSecret))
{
throw new ArgumentException(nameof(ClientSecret));
}
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(authCode);
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(ClientID);
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(ClientSecret);
var data = $"grant_type=authorization_code&code={authCode}";
var headers = new Dictionary<string, string> { { "Authorization", AuthHeader } };

View File

@ -204,10 +204,7 @@ public class LoginProfile
public static bool HasProfile(HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
ArgumentNullException.ThrowIfNull(request);
return new Uri(request.GetDisplayUrl()).HasProfile();
}
@ -239,10 +236,7 @@ public class LoginProfile
internal void SetField(string name, string value)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
ArgumentNullException.ThrowIfNull(name);
if (!string.IsNullOrEmpty(value))
{
@ -328,10 +322,7 @@ public class LoginProfile
internal void FromSerializedString(string serialized)
{
if (serialized == null)
{
throw new ArgumentNullException(nameof(serialized));
}
ArgumentNullException.ThrowIfNull(serialized);
_fields = serialized.Split(PairSeparator).ToDictionary(x => x.Split(KeyValueSeparator)[0], y => y.Split(KeyValueSeparator)[1]);
}
@ -355,10 +346,7 @@ public class LoginProfile
protected LoginProfile(Signature signature, InstanceCrypto instanceCrypto, SerializationInfo info) : this(signature, instanceCrypto)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
ArgumentNullException.ThrowIfNull(info);
var transformed = (string)info.GetValue(QueryParamName, typeof(string));
FromTransport(transformed);

View File

@ -5,6 +5,7 @@
<ApplicationIcon />
<OutputType>Library</OutputType>
<StartupObject />
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

View File

@ -1,26 +1,23 @@
global using System;
global using System.Collections.Generic;
global using System.Data;
global using System.Linq;
global using System.Data;
global using ASC.Common;
global using ASC.Common.Mapping;
global using ASC.Core;
global using ASC.Core.Common.EF;
global using ASC.Feed.Models;
global using ASC.Core.Common.EF.Model;
global using ASC.Core.Tenants;
global using ASC.Core.Users;
global using ASC.Common.Mapping;
global using ASC.Feed.Mapping;
global using ASC.Feed.Data;
global using ASC.Feed.Core;
global using AutoMapper;
global using ASC.Feed.Data;
global using ASC.Feed.Mapping;
global using ASC.Feed.Models;
global using Autofac;
global using AutoMapper;
global using Microsoft.EntityFrameworkCore;
global using Microsoft.EntityFrameworkCore.Migrations;
global using Microsoft.EntityFrameworkCore.Infrastructure;
global using Microsoft.EntityFrameworkCore.Migrations;
global using Newtonsoft.Json;

View File

@ -5,6 +5,7 @@
<ApplicationIcon />
<OutputType>Library</OutputType>
<StartupObject />
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

View File

@ -1,11 +1,8 @@
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Net;
global using System.Net;
global using System.Net.Sockets;
global using System.Runtime.Serialization;
global using System.Web;
global using ASC.Common;
global using ASC.Common.Caching;
global using ASC.Common.Logging;
@ -15,11 +12,11 @@ global using ASC.Core.Common.EF;
global using ASC.Core.Common.EF.Context;
global using ASC.Core.Common.EF.Model;
global using ASC.Core.Common.Settings;
global using AutoMapper;
global using AutoMapper.QueryableExtensions;
global using Microsoft.AspNetCore.Http;
global using Microsoft.AspNetCore.Http.Extensions;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.Options;
global using AutoMapper;
global using AutoMapper.QueryableExtensions;

View File

@ -5,6 +5,7 @@
<ApplicationIcon />
<OutputType>Library</OutputType>
<StartupObject />
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">

View File

@ -1,33 +1,29 @@
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading;
global using System.Web;
global using System.Web;
global using ASC.Common;
global using ASC.Common.Logging;
global using ASC.Common.Mapping;
global using ASC.Core;
global using ASC.Core.Common.EF;
global using ASC.Core.Common.EF.Model;
global using ASC.MessagingSystem.Mapping;
global using ASC.MessagingSystem.Core;
global using ASC.MessagingSystem.Core.Sender;
global using ASC.MessagingSystem.Data;
global using ASC.MessagingSystem.Mapping;
global using ASC.MessagingSystem.Models;
global using AutoMapper;
global using Microsoft.AspNetCore.Http;
global using Microsoft.EntityFrameworkCore;
global using Microsoft.EntityFrameworkCore.Migrations;
global using Microsoft.EntityFrameworkCore.Metadata;
global using Microsoft.EntityFrameworkCore.Infrastructure;
global using Microsoft.EntityFrameworkCore.Metadata;
global using Microsoft.EntityFrameworkCore.Migrations;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Options;
global using Microsoft.Extensions.Primitives;
global using AutoMapper;
global using Newtonsoft.Json;
global using UAParser;

View File

@ -6,6 +6,7 @@
<Product>ASC.Notify.Textile</Product>
<Copyright>(c) Ascensio System SIA. All rights reserved</Copyright>
<ProduceReferenceAssembly>false</ProduceReferenceAssembly>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugType>full</DebugType>

View File

@ -1,7 +1,4 @@
global using System;
global using System.IO;
global using System.Linq;
global using System.Reflection;
global using System.Reflection;
global using System.Text;
global using System.Text.RegularExpressions;
global using System.Web;

View File

@ -12,6 +12,7 @@
<Copyright>(c) Ascensio System SIA. All rights reserved</Copyright>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<ProduceReferenceAssembly>false</ProduceReferenceAssembly>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugType>full</DebugType>

View File

@ -1,19 +1,18 @@
namespace Textile
namespace Textile;
public class BlockModifier
{
public class BlockModifier
protected BlockModifier()
{
protected BlockModifier()
{
}
}
public virtual string ModifyLine(string line)
{
return line;
}
public virtual string ModifyLine(string line)
{
return line;
}
public virtual string Conclude(string line)
{
return line;
}
public virtual string Conclude(string line)
{
return line;
}
}

View File

@ -1,10 +1,9 @@
namespace Textile
namespace Textile;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class BlockModifierAttribute : Attribute
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class BlockModifierAttribute : Attribute
public BlockModifierAttribute()
{
public BlockModifierAttribute()
{
}
}
}

View File

@ -10,142 +10,141 @@
// You must not remove this notice, or any other, from this software.
#endregion
namespace Textile.Blocks
{
public static class BlockAttributesParser
{
public static StyleReader Styler { get; set; }
namespace Textile.Blocks;
/// <summary>
///
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
static public string ParseBlockAttributes(string input)
public static class BlockAttributesParser
{
public static StyleReader Styler { get; set; }
/// <summary>
///
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
static public string ParseBlockAttributes(string input)
{
return ParseBlockAttributes(input, "");
}
/// <summary>
///
/// </summary>
/// <param name="input"></param>
/// <param name="element"></param>
/// <returns></returns>
static public string ParseBlockAttributes(string input, string element)
{
var style = string.Empty;
var cssClass = string.Empty;
var lang = string.Empty;
var colspan = string.Empty;
var rowspan = string.Empty;
var id = string.Empty;
if (Styler != null)
{
return ParseBlockAttributes(input, "");
style = GetStyle(element, style);
}
/// <summary>
///
/// </summary>
/// <param name="input"></param>
/// <param name="element"></param>
/// <returns></returns>
static public string ParseBlockAttributes(string input, string element)
if (input.Length == 0)
return style.Length > 0 ? " style=\"" + style + "\"" : "";
Match m;
var matched = input;
if (element == "td")
{
var style = string.Empty;
var cssClass = string.Empty;
var lang = string.Empty;
var colspan = string.Empty;
var rowspan = string.Empty;
var id = string.Empty;
if (Styler != null)
{
style = GetStyle(element, style);
}
if (input.Length == 0)
return style.Length > 0 ? " style=\"" + style + "\"" : "";
Match m;
var matched = input;
if (element == "td")
{
// column span
m = Regex.Match(matched, @"\\(\d+)");
if (m.Success)
colspan = m.Groups[1].Value;
// row span
m = Regex.Match(matched, @"/(\d+)");
if (m.Success)
rowspan = m.Groups[1].Value;
// vertical align
m = Regex.Match(matched, @"(" + Globals.VerticalAlignPattern + @")");
if (m.Success)
style += "vertical-align:" + Globals.VerticalAlign[m.Captures[0].Value] + ";";
}
// First, match custom styles
m = Regex.Match(matched, @"\{([^}]*)\}");
// column span
m = Regex.Match(matched, @"\\(\d+)");
if (m.Success)
{
style += m.Groups[1].Value + ";";
matched = matched.Replace(m.ToString(), "");
}
// Then match the language
m = Regex.Match(matched, @"\[([^()]+)\]");
colspan = m.Groups[1].Value;
// row span
m = Regex.Match(matched, @"/(\d+)");
if (m.Success)
{
lang = m.Groups[1].Value;
matched = matched.Replace(m.ToString(), "");
}
rowspan = m.Groups[1].Value;
// vertical align
m = Regex.Match(matched, @"(" + Globals.VerticalAlignPattern + @")");
if (m.Success)
style += "vertical-align:" + Globals.VerticalAlign[m.Captures[0].Value] + ";";
}
// Match classes and IDs after that
m = Regex.Match(matched, @"\(([^()]+)\)");
// First, match custom styles
m = Regex.Match(matched, @"\{([^}]*)\}");
if (m.Success)
{
style += m.Groups[1].Value + ";";
matched = matched.Replace(m.ToString(), "");
}
// Then match the language
m = Regex.Match(matched, @"\[([^()]+)\]");
if (m.Success)
{
lang = m.Groups[1].Value;
matched = matched.Replace(m.ToString(), "");
}
// Match classes and IDs after that
m = Regex.Match(matched, @"\(([^()]+)\)");
if (m.Success)
{
cssClass = m.Groups[1].Value;
matched = matched.Replace(m.ToString(), "");
// Separate the public class and the ID
m = Regex.Match(cssClass, @"^(.*)#(.*)$");
if (m.Success)
{
cssClass = m.Groups[1].Value;
matched = matched.Replace(m.ToString(), "");
// Separate the public class and the ID
m = Regex.Match(cssClass, @"^(.*)#(.*)$");
if (m.Success)
{
cssClass = m.Groups[1].Value;
id = m.Groups[2].Value;
}
if (Styler != null && !string.IsNullOrEmpty(cssClass))
{
style = GetStyle("." + cssClass, style);
}
id = m.Groups[2].Value;
}
// Get the padding on the left
m = Regex.Match(matched, @"([(]+)");
if (m.Success)
if (Styler != null && !string.IsNullOrEmpty(cssClass))
{
style += "padding-left:" + m.Groups[1].Length + "em;";
matched = matched.Replace(m.ToString(), "");
style = GetStyle("." + cssClass, style);
}
// Get the padding on the right
m = Regex.Match(matched, @"([)]+)");
if (m.Success)
{
style += "padding-right:" + m.Groups[1].Length + "em;";
matched = matched.Replace(m.ToString(), "");
}
// Get the text alignment
m = Regex.Match(matched, "(" + Globals.HorizontalAlignPattern + ")");
if (m.Success)
style += "text-align:" + Globals.HorizontalAlign[m.Groups[1].Value] + ";";
return
(style.Length > 0 ? " style=\"" + style + "\"" : "") +
(cssClass.Length > 0 ? " class=\"" + cssClass + "\"" : "") +
(lang.Length > 0 ? " lang=\"" + lang + "\"" : "") +
(id.Length > 0 ? " id=\"" + id + "\"" : "") +
(colspan.Length > 0 ? " colspan=\"" + colspan + "\"" : "") +
(rowspan.Length > 0 ? " rowspan=\"" + rowspan + "\"" : "")
;
}
private static string GetStyle(string element, string style)
// Get the padding on the left
m = Regex.Match(matched, @"([(]+)");
if (m.Success)
{
var styled = Styler.GetStyle(element);
if (!string.IsNullOrEmpty(styled))
{
style += styled;
}
return style;
style += "padding-left:" + m.Groups[1].Length + "em;";
matched = matched.Replace(m.ToString(), "");
}
// Get the padding on the right
m = Regex.Match(matched, @"([)]+)");
if (m.Success)
{
style += "padding-right:" + m.Groups[1].Length + "em;";
matched = matched.Replace(m.ToString(), "");
}
// Get the text alignment
m = Regex.Match(matched, "(" + Globals.HorizontalAlignPattern + ")");
if (m.Success)
style += "text-align:" + Globals.HorizontalAlign[m.Groups[1].Value] + ";";
return
(style.Length > 0 ? " style=\"" + style + "\"" : "") +
(cssClass.Length > 0 ? " class=\"" + cssClass + "\"" : "") +
(lang.Length > 0 ? " lang=\"" + lang + "\"" : "") +
(id.Length > 0 ? " id=\"" + id + "\"" : "") +
(colspan.Length > 0 ? " colspan=\"" + colspan + "\"" : "") +
(rowspan.Length > 0 ? " rowspan=\"" + rowspan + "\"" : "")
;
}
private static string GetStyle(string element, string style)
{
var styled = Styler.GetStyle(element);
if (!string.IsNullOrEmpty(styled))
{
style += styled;
}
return style;
}
}

View File

@ -1,10 +1,9 @@
namespace Textile.Blocks
namespace Textile.Blocks;
public class BoldPhraseBlockModifier : PhraseBlockModifier
{
public class BoldPhraseBlockModifier : PhraseBlockModifier
public override string ModifyLine(string line)
{
public override string ModifyLine(string line)
{
return PhraseModifierFormat(line, @"\*\*", "b");
}
return PhraseModifierFormat(line, @"\*\*", "b");
}
}

View File

@ -1,17 +1,16 @@
namespace Textile.Blocks
{
public class CapitalsBlockModifier : BlockModifier
{
public override string ModifyLine(string line)
{
var me = new MatchEvaluator(CapitalsFormatMatchEvaluator);
line = Regex.Replace(line, @"(?<=^|\s|" + Globals.PunctuationPattern + @")(?<caps>[A-Z][A-Z0-9]+)(?=$|\s|" + Globals.PunctuationPattern + @")", me);
return line;
}
namespace Textile.Blocks;
private string CapitalsFormatMatchEvaluator(Match m)
{
return @"<span class=""caps"">" + m.Groups["caps"].Value + @"</span>";
}
public class CapitalsBlockModifier : BlockModifier
{
public override string ModifyLine(string line)
{
var me = new MatchEvaluator(CapitalsFormatMatchEvaluator);
line = Regex.Replace(line, @"(?<=^|\s|" + Globals.PunctuationPattern + @")(?<caps>[A-Z][A-Z0-9]+)(?=$|\s|" + Globals.PunctuationPattern + @")", me);
return line;
}
private string CapitalsFormatMatchEvaluator(Match m)
{
return @"<span class=""caps"">" + m.Groups["caps"].Value + @"</span>";
}
}

View File

@ -1,10 +1,9 @@
namespace Textile.Blocks
namespace Textile.Blocks;
public class CitePhraseBlockModifier : PhraseBlockModifier
{
public class CitePhraseBlockModifier : PhraseBlockModifier
public override string ModifyLine(string line)
{
public override string ModifyLine(string line)
{
return PhraseModifierFormat(line, @"\?\?", "cite");
}
return PhraseModifierFormat(line, @"\?\?", "cite");
}
}

View File

@ -10,47 +10,46 @@
// You must not remove this notice, or any other, from this software.
#endregion
namespace Textile.Blocks
namespace Textile.Blocks;
public class CodeBlockModifier : BlockModifier
{
public class CodeBlockModifier : BlockModifier
public override string ModifyLine(string line)
{
public override string ModifyLine(string line)
{
// Replace "@...@" zones with "<code>" tags.
var me = new MatchEvaluator(CodeFormatMatchEvaluator);
line = Regex.Replace(line,
@"(?<before>^|([\s\([{]))" + // before
"@" +
@"(\|(?<lang>\w+)\|)?" + // lang
"(?<code>[^@]+)" + // code
"@" +
@"(?<after>$|([\]}])|(?=" + Globals.PunctuationPattern + @"{1,2}|\s|$))", // after
me);
// Encode the contents of the "<code>" tags so that we don't
// generate formatting out of it.
line = NoTextileEncoder.EncodeNoTextileZones(line,
@"(?<=(^|\s)<code(" + Globals.HtmlAttributesPattern + @")>)",
@"(?=</code>)");
return line;
}
public override string Conclude(string line)
{
// Recode everything except "<" and ">";
line = NoTextileEncoder.DecodeNoTextileZones(line,
@"(?<=(^|\s)<code(" + Globals.HtmlAttributesPattern + @")>)",
@"(?=</code>)",
new string[] { "<", ">" });
return line;
}
public string CodeFormatMatchEvaluator(Match m)
{
var res = m.Groups["before"].Value + "<code";
if (m.Groups["lang"].Length > 0)
res += " language=\"" + m.Groups["lang"].Value + "\"";
res += ">" + m.Groups["code"].Value + "</code>" + m.Groups["after"].Value;
return res;
}
// Replace "@...@" zones with "<code>" tags.
var me = new MatchEvaluator(CodeFormatMatchEvaluator);
line = Regex.Replace(line,
@"(?<before>^|([\s\([{]))" + // before
"@" +
@"(\|(?<lang>\w+)\|)?" + // lang
"(?<code>[^@]+)" + // code
"@" +
@"(?<after>$|([\]}])|(?=" + Globals.PunctuationPattern + @"{1,2}|\s|$))", // after
me);
// Encode the contents of the "<code>" tags so that we don't
// generate formatting out of it.
line = NoTextileEncoder.EncodeNoTextileZones(line,
@"(?<=(^|\s)<code(" + Globals.HtmlAttributesPattern + @")>)",
@"(?=</code>)");
return line;
}
}
public override string Conclude(string line)
{
// Recode everything except "<" and ">";
line = NoTextileEncoder.DecodeNoTextileZones(line,
@"(?<=(^|\s)<code(" + Globals.HtmlAttributesPattern + @")>)",
@"(?=</code>)",
new string[] { "<", ">" });
return line;
}
public string CodeFormatMatchEvaluator(Match m)
{
var res = m.Groups["before"].Value + "<code";
if (m.Groups["lang"].Length > 0)
res += " language=\"" + m.Groups["lang"].Value + "\"";
res += ">" + m.Groups["code"].Value + "</code>" + m.Groups["after"].Value;
return res;
}
}

View File

@ -1,10 +1,9 @@
namespace Textile.Blocks
namespace Textile.Blocks;
public class DeletedPhraseBlockModifier : PhraseBlockModifier
{
public class DeletedPhraseBlockModifier : PhraseBlockModifier
public override string ModifyLine(string line)
{
public override string ModifyLine(string line)
{
return PhraseModifierFormat(line, @"\-", "del");
}
return PhraseModifierFormat(line, @"\-", "del");
}
}

View File

@ -1,10 +1,9 @@
namespace Textile.Blocks
namespace Textile.Blocks;
public class EmphasisPhraseBlockModifier : PhraseBlockModifier
{
public class EmphasisPhraseBlockModifier : PhraseBlockModifier
public override string ModifyLine(string line)
{
public override string ModifyLine(string line)
{
return PhraseModifierFormat(line, @"_", "em");
}
return PhraseModifierFormat(line, @"_", "em");
}
}

View File

@ -10,13 +10,12 @@
// You must not remove this notice, or any other, from this software.
#endregion
namespace Textile.Blocks
namespace Textile.Blocks;
public class FootNoteReferenceBlockModifier : BlockModifier
{
public class FootNoteReferenceBlockModifier : BlockModifier
public override string ModifyLine(string line)
{
public override string ModifyLine(string line)
{
return Regex.Replace(line, @"\b\[([0-9]+)\](\W)", "<sup><a href=\"#fn$1\">$1</a></sup>$2");
}
return Regex.Replace(line, @"\b\[([0-9]+)\](\W)", "<sup><a href=\"#fn$1\">$1</a></sup>$2");
}
}

View File

@ -10,79 +10,78 @@
// You must not remove this notice, or any other, from this software.
#endregion
namespace Textile.Blocks
namespace Textile.Blocks;
public class GlyphBlockModifier : BlockModifier
{
public class GlyphBlockModifier : BlockModifier
public override string ModifyLine(string line)
{
public override string ModifyLine(string line)
line = Regex.Replace(line, "\"\\z", "\" ");
// fix: hackish
string[,] glyphs = {
{ @"([^\s[{(>_*])?\'(?(1)|(\s|s\b|" + Globals.PunctuationPattern + @"))", "$1&#8217;$2" }, // single closing
{ @"\'", "&#8216;" }, // single opening
{ @"([^\s[{(>_*])?""(?(1)|(\s|" + Globals.PunctuationPattern + @"))", "$1&#8221;$2" }, // double closing
{ @"""", "&#8220;" }, // double opening
{ @"\b( )?\.{3}", "$1&#8230;" }, // ellipsis
{ @"\b([A-Z][A-Z0-9]{2,})\b(?:[(]([^)]*)[)])", "<acronym title=\"$2\">$1</acronym>" }, // 3+ uppercase acronym
{ @"(\s)?--(\s)?", "$1&#8212;$2" }, // em dash
{ @"\s-\s", " &#8211; " }, // en dash
{ @"(\d+)( )?x( )?(\d+)", "$1$2&#215;$3$4" }, // dimension sign
{ @"\b ?[([](TM|tm)[])]", "&#8482;" }, // trademark
{ @"\b ?[([](R|r)[])]", "&#174;" }, // registered
{ @"\b ?[([](C|c)[])]", "&#169;" } // copyright
};
var sb = new StringBuilder();
if (!Regex.IsMatch(line, "<.*>"))
{
line = Regex.Replace(line, "\"\\z", "\" ");
// fix: hackish
string[,] glyphs = {
{ @"([^\s[{(>_*])?\'(?(1)|(\s|s\b|" + Globals.PunctuationPattern + @"))", "$1&#8217;$2" }, // single closing
{ @"\'", "&#8216;" }, // single opening
{ @"([^\s[{(>_*])?""(?(1)|(\s|" + Globals.PunctuationPattern + @"))", "$1&#8221;$2" }, // double closing
{ @"""", "&#8220;" }, // double opening
{ @"\b( )?\.{3}", "$1&#8230;" }, // ellipsis
{ @"\b([A-Z][A-Z0-9]{2,})\b(?:[(]([^)]*)[)])", "<acronym title=\"$2\">$1</acronym>" }, // 3+ uppercase acronym
{ @"(\s)?--(\s)?", "$1&#8212;$2" }, // em dash
{ @"\s-\s", " &#8211; " }, // en dash
{ @"(\d+)( )?x( )?(\d+)", "$1$2&#215;$3$4" }, // dimension sign
{ @"\b ?[([](TM|tm)[])]", "&#8482;" }, // trademark
{ @"\b ?[([](R|r)[])]", "&#174;" }, // registered
{ @"\b ?[([](C|c)[])]", "&#169;" } // copyright
};
var sb = new StringBuilder();
if (!Regex.IsMatch(line, "<.*>"))
// If no HTML, do a simple search & replace.
for (var i = 0; i < glyphs.GetLength(0); ++i)
{
// If no HTML, do a simple search & replace.
for (var i = 0; i < glyphs.GetLength(0); ++i)
{
line = Regex.Replace(line, glyphs[i, 0], glyphs[i, 1]);
}
sb.Append(line);
line = Regex.Replace(line, glyphs[i, 0], glyphs[i, 1]);
}
else
{
var splits = Regex.Split(line, "(<.*?>)");
var offtags = "code|pre|notextile";
var codepre = false;
foreach (var split in splits)
{
var modifiedSplit = split;
if (modifiedSplit.Length == 0)
continue;
if (Regex.IsMatch(modifiedSplit, @"<(" + offtags + ")>"))
codepre = true;
if (Regex.IsMatch(modifiedSplit, @"<\/(" + offtags + ")>"))
codepre = false;
if (!Regex.IsMatch(modifiedSplit, "<.*>") && !codepre)
{
for (var i = 0; i < glyphs.GetLength(0); ++i)
{
modifiedSplit = Regex.Replace(modifiedSplit, glyphs[i, 0], glyphs[i, 1]);
}
}
// do htmlspecial if between <code>
if (codepre)
{
//TODO: htmlspecialchars(line)
//line = Regex.Replace(line, @"&lt;(\/?" + offtags + ")&gt;", "<$1>");
//line = line.Replace("&amp;#", "&#");
}
sb.Append(modifiedSplit);
}
}
return sb.ToString();
sb.Append(line);
}
else
{
var splits = Regex.Split(line, "(<.*?>)");
var offtags = "code|pre|notextile";
var codepre = false;
foreach (var split in splits)
{
var modifiedSplit = split;
if (modifiedSplit.Length == 0)
continue;
if (Regex.IsMatch(modifiedSplit, @"<(" + offtags + ")>"))
codepre = true;
if (Regex.IsMatch(modifiedSplit, @"<\/(" + offtags + ")>"))
codepre = false;
if (!Regex.IsMatch(modifiedSplit, "<.*>") && !codepre)
{
for (var i = 0; i < glyphs.GetLength(0); ++i)
{
modifiedSplit = Regex.Replace(modifiedSplit, glyphs[i, 0], glyphs[i, 1]);
}
}
// do htmlspecial if between <code>
if (codepre)
{
//TODO: htmlspecialchars(line)
//line = Regex.Replace(line, @"&lt;(\/?" + offtags + ")&gt;", "<$1>");
//line = line.Replace("&amp;#", "&#");
}
sb.Append(modifiedSplit);
}
}
return sb.ToString();
}
}

View File

@ -11,46 +11,45 @@
#endregion
namespace Textile.Blocks
namespace Textile.Blocks;
public class HyperLinkBlockModifier : BlockModifier
{
public class HyperLinkBlockModifier : BlockModifier
private readonly string _rel = string.Empty;
public override string ModifyLine(string line)
{
private readonly string m_rel = string.Empty;
line = Regex.Replace(line,
@"(?<pre>[\s[{(]|" + Globals.PunctuationPattern + @")?" + // $pre
"\"" + // start
Globals.BlockModifiersPattern + // attributes
"(?<text>[\\w\\W]+?)" + // text
@"\s?" +
@"(?:\((?<title>[^)]+)\)(?=""))?" + // title
"\":" +
@"""(?<url>\S+[^""]+)""" + // url
@"(?<slash>\/)?" + // slash
@"(?<post>[^\w\/;]*)" + // post
@"(?=\s|$)",
new MatchEvaluator(HyperLinksFormatMatchEvaluator));
return line;
}
public override string ModifyLine(string line)
{
line = Regex.Replace(line,
@"(?<pre>[\s[{(]|" + Globals.PunctuationPattern + @")?" + // $pre
"\"" + // start
Globals.BlockModifiersPattern + // attributes
"(?<text>[\\w\\W]+?)" + // text
@"\s?" +
@"(?:\((?<title>[^)]+)\)(?=""))?" + // title
"\":" +
@"""(?<url>\S+[^""]+)""" + // url
@"(?<slash>\/)?" + // slash
@"(?<post>[^\w\/;]*)" + // post
@"(?=\s|$)",
new MatchEvaluator(HyperLinksFormatMatchEvaluator));
return line;
}
private string HyperLinksFormatMatchEvaluator(Match m)
{
//TODO: check the URL
var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "a");
if (m.Groups["title"].Length > 0)
atts += " title=\"" + m.Groups["title"].Value + "\"";
var linkText = m.Groups["text"].Value.Trim(' ');
private string HyperLinksFormatMatchEvaluator(Match m)
{
//TODO: check the URL
var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "a");
if (m.Groups["title"].Length > 0)
atts += " title=\"" + m.Groups["title"].Value + "\"";
var linkText = m.Groups["text"].Value.Trim(' ');
var str = m.Groups["pre"].Value + "<a ";
if (!string.IsNullOrEmpty(m_rel))
str += "ref=\"" + m_rel + "\" ";
str += "href=\"" +
m.Groups["url"].Value + m.Groups["slash"].Value + "\"" +
atts +
">" + linkText + "</a>" + m.Groups["post"].Value;
return str;
}
var str = m.Groups["pre"].Value + "<a ";
if (!string.IsNullOrEmpty(_rel))
str += "ref=\"" + _rel + "\" ";
str += "href=\"" +
m.Groups["url"].Value + m.Groups["slash"].Value + "\"" +
atts +
">" + linkText + "</a>" + m.Groups["post"].Value;
return str;
}
}

View File

@ -10,60 +10,59 @@
// You must not remove this notice, or any other, from this software.
#endregion
namespace Textile.Blocks
namespace Textile.Blocks;
public class ImageBlockModifier : BlockModifier
{
public class ImageBlockModifier : BlockModifier
public override string ModifyLine(string line)
{
public override string ModifyLine(string line)
line = Regex.Replace(line,
@"\!" + // opening !
@"(?<algn>\<|\=|\>)?" + // optional alignment atts
Globals.BlockModifiersPattern + // optional style, public class atts
@"(?:\. )?" + // optional dot-space
@"(?<url>[^\s(!]+)" + // presume this is the src
@"\s?" + // optional space
@"(?:\((?<title>([^\)]+))\))?" +// optional title
@"\!" + // closing
@"(?::(?<href>(\S+)))?" + // optional href
@"(?=\s|\.|,|;|\)|\||$)", // lookahead: space or simple punctuation or end of string
new MatchEvaluator(ImageFormatMatchEvaluator)
);
return line;
}
string ImageFormatMatchEvaluator(Match m)
{
var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "img");
if (m.Groups["algn"].Length > 0)
atts += " align=\"" + Globals.ImageAlign[m.Groups["algn"].Value] + "\"";
if (m.Groups["title"].Length > 0)
{
line = Regex.Replace(line,
@"\!" + // opening !
@"(?<algn>\<|\=|\>)?" + // optional alignment atts
Globals.BlockModifiersPattern + // optional style, public class atts
@"(?:\. )?" + // optional dot-space
@"(?<url>[^\s(!]+)" + // presume this is the src
@"\s?" + // optional space
@"(?:\((?<title>([^\)]+))\))?" +// optional title
@"\!" + // closing
@"(?::(?<href>(\S+)))?" + // optional href
@"(?=\s|\.|,|;|\)|\||$)", // lookahead: space or simple punctuation or end of string
new MatchEvaluator(ImageFormatMatchEvaluator)
);
return line;
atts += " title=\"" + m.Groups["title"].Value + "\"";
atts += " alt=\"" + m.Groups["title"].Value + "\"";
}
else
{
atts += " alt=\"\"";
}
// Get Image Size?
var res = "<img src=\"" + m.Groups["url"].Value + "\"" + atts + " />";
if (m.Groups["href"].Length > 0)
{
var href = m.Groups["href"].Value;
var end = string.Empty;
var endMatch = Regex.Match(href, @"(.*)(?<end>\.|,|;|\))$");
if (m.Success && !string.IsNullOrEmpty(endMatch.Groups["end"].Value))
{
href = href[0..^1];
end = endMatch.Groups["end"].Value;
}
res = "<a href=\"" + Globals.EncodeHTMLLink(href) + "\">" + res + "</a>" + end;
}
string ImageFormatMatchEvaluator(Match m)
{
var atts = BlockAttributesParser.ParseBlockAttributes(m.Groups["atts"].Value, "img");
if (m.Groups["algn"].Length > 0)
atts += " align=\"" + Globals.ImageAlign[m.Groups["algn"].Value] + "\"";
if (m.Groups["title"].Length > 0)
{
atts += " title=\"" + m.Groups["title"].Value + "\"";
atts += " alt=\"" + m.Groups["title"].Value + "\"";
}
else
{
atts += " alt=\"\"";
}
// Get Image Size?
var res = "<img src=\"" + m.Groups["url"].Value + "\"" + atts + " />";
if (m.Groups["href"].Length > 0)
{
var href = m.Groups["href"].Value;
var end = string.Empty;
var endMatch = Regex.Match(href, @"(.*)(?<end>\.|,|;|\))$");
if (m.Success && !string.IsNullOrEmpty(endMatch.Groups["end"].Value))
{
href = href[0..^1];
end = endMatch.Groups["end"].Value;
}
res = "<a href=\"" + Globals.EncodeHTMLLink(href) + "\">" + res + "</a>" + end;
}
return res;
}
return res;
}
}

View File

@ -1,10 +1,9 @@
namespace Textile.Blocks
namespace Textile.Blocks;
public class InsertedPhraseBlockModifier : PhraseBlockModifier
{
public class InsertedPhraseBlockModifier : PhraseBlockModifier
public override string ModifyLine(string line)
{
public override string ModifyLine(string line)
{
return PhraseModifierFormat(line, @"\+", "ins");
}
return PhraseModifierFormat(line, @"\+", "ins");
}
}

View File

@ -1,10 +1,9 @@
namespace Textile.Blocks
namespace Textile.Blocks;
public class ItalicPhraseBlockModifier : PhraseBlockModifier
{
public class ItalicPhraseBlockModifier : PhraseBlockModifier
public override string ModifyLine(string line)
{
public override string ModifyLine(string line)
{
return PhraseModifierFormat(line, @"__", "i");
}
return PhraseModifierFormat(line, @"__", "i");
}
}

View File

@ -11,22 +11,21 @@
#endregion
namespace Textile.Blocks
{
public class NoTextileBlockModifier : BlockModifier
{
public override string ModifyLine(string line)
{
line = NoTextileEncoder.EncodeNoTextileZones(line, @"(?<=^|\s)<notextile>", @"</notextile>(?=(\s|$)?)");
line = NoTextileEncoder.EncodeNoTextileZones(line, @"==", @"==");
return line;
}
namespace Textile.Blocks;
public override string Conclude(string line)
{
line = NoTextileEncoder.DecodeNoTextileZones(line, @"(?<=^|\s)<notextile>", @"</notextile>(?=(\s|$)?)");
line = NoTextileEncoder.DecodeNoTextileZones(line, @"==", @"==");
return line;
}
public class NoTextileBlockModifier : BlockModifier
{
public override string ModifyLine(string line)
{
line = NoTextileEncoder.EncodeNoTextileZones(line, @"(?<=^|\s)<notextile>", @"</notextile>(?=(\s|$)?)");
line = NoTextileEncoder.EncodeNoTextileZones(line, @"==", @"==");
return line;
}
public override string Conclude(string line)
{
line = NoTextileEncoder.DecodeNoTextileZones(line, @"(?<=^|\s)<notextile>", @"</notextile>(?=(\s|$)?)");
line = NoTextileEncoder.DecodeNoTextileZones(line, @"==", @"==");
return line;
}
}

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