diff --git a/src/VirtoCommerce.Platform.Caching/Redis/RedisPlatformMemoryCache.cs b/src/VirtoCommerce.Platform.Caching/Redis/RedisPlatformMemoryCache.cs index 17441d85da8..e097097acad 100644 --- a/src/VirtoCommerce.Platform.Caching/Redis/RedisPlatformMemoryCache.cs +++ b/src/VirtoCommerce.Platform.Caching/Redis/RedisPlatformMemoryCache.cs @@ -13,7 +13,7 @@ namespace VirtoCommerce.Platform.Redis { public class RedisPlatformMemoryCache : PlatformMemoryCache { - private static string _instanceId { get; } = $"{Environment.MachineName}_{Guid.NewGuid():N}"; + private static readonly string _instanceId = $"{Environment.MachineName}_{Guid.NewGuid():N}"; private bool _isSubscribed; private readonly ISubscriber _bus; private readonly RedisCachingOptions _redisCachingOptions; @@ -41,7 +41,7 @@ public RedisPlatformMemoryCache(IMemoryCache memoryCache private void CacheCancellableTokensRegistry_OnTokenCancelled(TokenCancelledEventArgs e) { - var message = new RedisCachingMessage { InstanceId = _instanceId, IsToken = true, CacheKeys = new[] { e.TokenKey } }; + var message = new RedisCachingMessage { InstanceId = _instanceId, IsToken = true, CacheKeys = [e.TokenKey] }; Publish(message); _log.LogTrace("Published token cancellation message {Message}", message.ToString()); } @@ -65,7 +65,7 @@ protected virtual void OnMessage(RedisChannel channel, RedisValue redisValue) { var message = JsonConvert.DeserializeObject(redisValue); - if (!string.IsNullOrEmpty(message.InstanceId) && !message.InstanceId.EqualsInvariant(_instanceId)) + if (!string.IsNullOrEmpty(message.InstanceId) && !message.InstanceId.EqualsIgnoreCase(_instanceId)) { _log.LogTrace("Received message {Message}", message.ToString()); @@ -95,7 +95,7 @@ public override bool TryGetValue(object key, out object value) protected override void EvictionCallback(object key, object value, EvictionReason reason, object state) { - var message = new RedisCachingMessage { InstanceId = _instanceId, CacheKeys = new[] { key } }; + var message = new RedisCachingMessage { InstanceId = _instanceId, CacheKeys = [key] }; Publish(message); _log.LogTrace("Published message {Message} to the Redis backplane", message); diff --git a/src/VirtoCommerce.Platform.Core/Common/EnumUtility.cs b/src/VirtoCommerce.Platform.Core/Common/EnumUtility.cs index f29105bfa07..79371dce0bf 100644 --- a/src/VirtoCommerce.Platform.Core/Common/EnumUtility.cs +++ b/src/VirtoCommerce.Platform.Core/Common/EnumUtility.cs @@ -36,7 +36,7 @@ public static T SafeParseFlags(string value, T defaultValue, string separator if (!string.IsNullOrEmpty(value)) { - var parts = value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries); + var parts = value.Split([separator], StringSplitOptions.RemoveEmptyEntries); foreach (var part in parts) { @@ -78,7 +78,8 @@ public static string SafeRemoveFlagFromEnumString(string value, T flag, char else { var parts = value.Split(separator, StringSplitOptions.RemoveEmptyEntries); - result = string.Join(separator, parts.Where(x => !x.EqualsInvariant(flag.ToString()))); + var flagString = flag.ToString(); + result = string.Join(separator, parts.Where(x => !x.EqualsIgnoreCase(flagString))); } } return result; diff --git a/src/VirtoCommerce.Platform.Core/Common/SemanticVersion.cs b/src/VirtoCommerce.Platform.Core/Common/SemanticVersion.cs index 25a9e0e4c26..44f771256f4 100644 --- a/src/VirtoCommerce.Platform.Core/Common/SemanticVersion.cs +++ b/src/VirtoCommerce.Platform.Core/Common/SemanticVersion.cs @@ -10,19 +10,16 @@ public class SemanticVersion : IComparable { private readonly Version _version; - public static readonly char[] Delimiters = { '.', '-' }; + public static readonly char[] Delimiters = ['.', '-']; - public static readonly Regex SemanticVersionStrictRegex = new Regex( + public static readonly Regex SemanticVersionStrictRegex = new( @"^(?([0-9]|[1-9][0-9]*)(\.([0-9]|[1-9][0-9]*)){2,3})" + @"(?>\-(?[0-9A-Za-z\-\.]+))?(?\+[0-9A-Za-z-]+)?$", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.Compiled); public SemanticVersion(Version version) { - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } + ArgumentNullException.ThrowIfNull(version); _version = NormalizeVersionValue(version); } @@ -46,8 +43,7 @@ public SemanticVersion(Version version) public bool IsCompatibleWithBySemVer(SemanticVersion other) { - if (other == null) - throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); //MAJOR version when you make incompatible API changes, var retVal = Major == other.Major; @@ -61,8 +57,7 @@ public bool IsCompatibleWithBySemVer(SemanticVersion other) public bool IsCompatibleWith(SemanticVersion other) { - if (other == null) - throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); var comparisonResult = CompareTo(other); return comparisonResult <= 0; @@ -81,7 +76,7 @@ public static SemanticVersion Parse(string value) { var normalizedVersion = NormalizeVersionValue(versionValue); var result = new SemanticVersion(normalizedVersion); - if (((ICollection)match.Groups).Any(x => x.Name.EqualsInvariant("Prerelease"))) + if (((ICollection)match.Groups).Any(x => x.Name.EqualsIgnoreCase("Prerelease"))) { result.Prerelease = match.Groups["Prerelease"].Value; } @@ -180,22 +175,27 @@ public override int GetHashCode() public int CompareTo(object obj) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); var other = (SemanticVersion)obj; var result = Major.CompareTo(other.Major); if (result != 0) + { return result; + } result = Minor.CompareTo(other.Minor); if (result != 0) + { return result; + } result = Patch.CompareTo(other.Patch); if (result != 0) + { return result; + } return CompareComponent(Prerelease, other.Prerelease, true); } @@ -205,12 +205,19 @@ private static int CompareComponent(string a, string b, bool nonemptyIsLower = f var aEmpty = string.IsNullOrEmpty(a); var bEmpty = string.IsNullOrEmpty(b); if (aEmpty && bEmpty) + { return 0; + } if (aEmpty) + { return nonemptyIsLower ? 1 : -1; + } + if (bEmpty) + { return nonemptyIsLower ? -1 : 1; + } var aComps = a.Split(Delimiters); var bComps = b.Split(Delimiters); @@ -227,17 +234,27 @@ private static int CompareComponent(string a, string b, bool nonemptyIsLower = f { r = aNum.CompareTo(bNum); if (r != 0) + { return r; + } } else { if (aIsNum) + { return -1; + } + if (bIsNum) + { return 1; + } + r = string.CompareOrdinal(ac, bc); if (r != 0) + { return r; + } } } diff --git a/src/VirtoCommerce.Platform.Core/Common/SortInfo.cs b/src/VirtoCommerce.Platform.Core/Common/SortInfo.cs index 65ac356bcb1..e13f75b270f 100644 --- a/src/VirtoCommerce.Platform.Core/Common/SortInfo.cs +++ b/src/VirtoCommerce.Platform.Core/Common/SortInfo.cs @@ -21,12 +21,15 @@ public enum SortDirection public class SortInfo : IEquatable { + private static readonly char[] _columnSeparators = [';']; + private static readonly char[] _directionSeparators = [':', '-']; + public string SortColumn { get; set; } public SortDirection SortDirection { get; set; } public override string ToString() { - return SortColumn + ":" + (SortDirection == SortDirection.Descending ? "desc" : "asc"); + return SortColumn + (SortDirection == SortDirection.Descending ? ":desc" : string.Empty); } public static string ToString(IEnumerable sortInfos) @@ -37,13 +40,16 @@ public static string ToString(IEnumerable sortInfos) public static IEnumerable Parse(string sortExpr) { var retVal = new List(); + if (string.IsNullOrEmpty(sortExpr)) + { return retVal; + } - var sortInfoStrings = sortExpr.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + var sortInfoStrings = sortExpr.Split(_columnSeparators, StringSplitOptions.RemoveEmptyEntries); foreach (var sortInfoString in sortInfoStrings) { - var parts = sortInfoString.Split(new[] { ':', '-' }, StringSplitOptions.RemoveEmptyEntries); + var parts = sortInfoString.Split(_directionSeparators, StringSplitOptions.RemoveEmptyEntries); if (parts.Any()) { var sortInfo = new SortInfo @@ -53,7 +59,7 @@ public static IEnumerable Parse(string sortExpr) }; if (parts.Length > 1) { - sortInfo.SortDirection = parts[1].StartsWith("desc", StringComparison.InvariantCultureIgnoreCase) ? SortDirection.Descending : SortDirection.Ascending; + sortInfo.SortDirection = parts[1].StartsWithIgnoreCase("desc") ? SortDirection.Descending : SortDirection.Ascending; } retVal.Add(sortInfo); } @@ -64,7 +70,7 @@ public static IEnumerable Parse(string sortExpr) public bool Equals(SortInfo other) { return other != null - && string.Equals(SortColumn, other.SortColumn, StringComparison.OrdinalIgnoreCase) + && SortColumn.EqualsIgnoreCase(other.SortColumn) && SortDirection == other.SortDirection; } diff --git a/src/VirtoCommerce.Platform.Core/Domain/AbstractTypeFactory.cs b/src/VirtoCommerce.Platform.Core/Domain/AbstractTypeFactory.cs index 5069060a385..6d63f42ea30 100644 --- a/src/VirtoCommerce.Platform.Core/Domain/AbstractTypeFactory.cs +++ b/src/VirtoCommerce.Platform.Core/Domain/AbstractTypeFactory.cs @@ -254,13 +254,10 @@ public static BaseType TryCreateInstance(string typeName, params object[] args) /// The TypeInfo instance for the specified type name. public static TypeInfo FindTypeInfoByName(string typeName) { - //Try find first direct type match from registered types - var result = _typeInfos.FirstOrDefault(x => x.TypeName.EqualsInvariant(typeName)); + //Try to find first direct type match from registered types //Then need to find in inheritance chain from registered types - if (result == null) - { - result = _typeInfos.FirstOrDefault(x => x.IsAssignableTo(typeName)); - } + var result = _typeInfos.FirstOrDefault(x => x.TypeName.EqualsIgnoreCase(typeName)) ?? + _typeInfos.FirstOrDefault(x => x.IsAssignableTo(typeName)); return result; } } @@ -378,7 +375,7 @@ public TypeInfo WithTypeName(string name) /// true if the associated type is assignable to the specified type name; otherwise, false. public bool IsAssignableTo(string typeName) { - return Type.GetTypeInheritanceChainTo(typeof(BaseType)).Concat(new[] { typeof(BaseType) }).Any(t => typeName.EqualsInvariant(t.Name)); + return Type.GetTypeInheritanceChainTo(typeof(BaseType)).Concat([typeof(BaseType)]).Any(t => typeName.EqualsIgnoreCase(t.Name)); } /// diff --git a/src/VirtoCommerce.Platform.Core/Extensions/ModuleCatalogExtensions.cs b/src/VirtoCommerce.Platform.Core/Extensions/ModuleCatalogExtensions.cs index 9d98ca13c0c..74f7e4c8161 100644 --- a/src/VirtoCommerce.Platform.Core/Extensions/ModuleCatalogExtensions.cs +++ b/src/VirtoCommerce.Platform.Core/Extensions/ModuleCatalogExtensions.cs @@ -10,7 +10,7 @@ public static bool IsModuleInstalled(this IModuleCatalog moduleCatalog, string m { return moduleCatalog.Modules .OfType() - .Any(x => x.Id.EqualsInvariant(moduleId) && x.IsInstalled); + .Any(x => x.Id.EqualsIgnoreCase(moduleId) && x.IsInstalled); } } } diff --git a/src/VirtoCommerce.Platform.Core/Extensions/StringExtensions.cs b/src/VirtoCommerce.Platform.Core/Extensions/StringExtensions.cs index 959a0e8850f..353e70348a5 100644 --- a/src/VirtoCommerce.Platform.Core/Extensions/StringExtensions.cs +++ b/src/VirtoCommerce.Platform.Core/Extensions/StringExtensions.cs @@ -19,17 +19,14 @@ public static partial class StringExtensions [GeneratedRegex(@"[\[, \]]")] private static partial Regex IllegalRegex(); - private static readonly Regex _emailRegex = new Regex(@"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-||_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+([a-z]+|\d|-|\.{0,1}|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])?([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$", RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1)); + private static readonly Regex _emailRegex = new(@"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-||_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+([a-z]+|\d|-|\.{0,1}|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])?([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$", RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1)); private static readonly string[] _allowedUriSchemes = [Uri.UriSchemeFile, Uri.UriSchemeFtp, Uri.UriSchemeHttp, Uri.UriSchemeHttps, Uri.UriSchemeMailto, Uri.UriSchemeNetPipe, Uri.UriSchemeNetTcp]; public static bool IsAbsoluteUrl(this string url) { - if (url == null) - { - throw new ArgumentNullException(url); - } + ArgumentNullException.ThrowIfNull(url); - var result = Uri.IsWellFormedUriString(url, UriKind.Absolute) && _allowedUriSchemes.Any(x => new Uri(url).Scheme.EqualsInvariant(x)); + var result = Uri.IsWellFormedUriString(url, UriKind.Absolute) && _allowedUriSchemes.ContainsIgnoreCase(new Uri(url).Scheme); return result; } @@ -99,24 +96,12 @@ public static string EmptyToNull(this string a) return string.IsNullOrEmpty(a) ? null : a; } - /// - /// Equalses the or null empty. - /// - /// The STR1. - /// The STR2. - /// Type of the comparison. - /// public static bool EqualsOrNullEmpty(this string str1, string str2, StringComparison comparisonType) { return string.Compare(str1 ?? "", str2 ?? "", comparisonType) == 0; } - /// - /// Equals invariant - /// - /// The STR1. - /// The STR2. - /// + [Obsolete("Use EqualsIgnoreCase()", DiagnosticId = "VC0010", UrlFormat = "https://docs.virtocommerce.org/products/products-virto3-versions")] public static bool EqualsInvariant(this string str1, string str2) { return string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase); @@ -132,6 +117,16 @@ public static bool ContainsIgnoreCase(this string value, string substring) return value.Contains(substring, StringComparison.OrdinalIgnoreCase); } + public static bool StartsWithIgnoreCase(this string value, string substring) + { + return value.StartsWith(substring, StringComparison.OrdinalIgnoreCase); + } + + public static bool EndsWithIgnoreCase(this string value, string substring) + { + return value.EndsWith(substring, StringComparison.OrdinalIgnoreCase); + } + public static string GetCurrencyName(this string isoCurrencySymbol) { @@ -170,20 +165,23 @@ public static string ToSpecificLangCode(this string lang) public static string Truncate(this string value, int maxLength, string suffix = "...") { if (string.IsNullOrEmpty(value)) + { return value; + } + return value.Length <= maxLength ? value : value.Substring(0, maxLength) + suffix; } public static string EscapeSearchTerm(this string term) { - char[] specialCharacters = { '+', '-', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '\\' }; + char[] specialCharacters = ['+', '-', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '\\']; var result = new StringBuilder(""); //'&&', '||', foreach (var ch in term) { if (specialCharacters.Any(x => x == ch)) { - result.Append("\\"); + result.Append('\\'); } result.Append(ch); } @@ -206,7 +204,7 @@ public static string EscapeSelector(this string attribute) public static string GenerateSlug(this string phrase) { - string str = phrase.RemoveAccent().ToLower(); + var str = phrase.RemoveAccent().ToLower(); str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); // invalid chars str = Regex.Replace(str, @"\s+", " ").Trim(); // convert multiple spaces into one space @@ -228,7 +226,7 @@ public static string GenerateSlug(this string phrase) /// public static string MakeFileNameWebSafe(this string fileName) { - string str = fileName.RemoveAccent().ToLower(); + var str = fileName.RemoveAccent().ToLower(); str = str.Replace("&", "-and-"); str = Regex.Replace(str, @"[^A-Za-z0-9_\-. ]", ""); // invalid chars str = Regex.Replace(str, @"\s+", "-").Trim(); // convert multiple spaces into one dash @@ -238,8 +236,8 @@ public static string MakeFileNameWebSafe(this string fileName) public static string RemoveAccent(this string txt) { - byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt); - return System.Text.Encoding.ASCII.GetString(bytes); + var bytes = Encoding.GetEncoding("Cyrillic").GetBytes(txt); + return Encoding.ASCII.GetString(bytes); } /// @@ -247,9 +245,9 @@ public static string RemoveAccent(this string txt) /// public static int ComputeLevenshteinDistance(this string s, string t) { - int n = s.Length; - int m = t.Length; - int[,] d = new int[n + 1, m + 1]; + var n = s.Length; + var m = t.Length; + var d = new int[n + 1, m + 1]; // Step 1 if (n == 0) @@ -263,22 +261,22 @@ public static int ComputeLevenshteinDistance(this string s, string t) } // Step 2 - for (int i = 0; i <= n; d[i, 0] = i++) + for (var i = 0; i <= n; d[i, 0] = i++) { } - for (int j = 0; j <= m; d[0, j] = j++) + for (var j = 0; j <= m; d[0, j] = j++) { } // Step 3 - for (int i = 1; i <= n; i++) + for (var i = 1; i <= n; i++) { //Step 4 - for (int j = 1; j <= m; j++) + for (var j = 1; j <= m; j++) { // Step 5 - int cost = (t[j - 1] == s[i - 1]) ? 0 : 1; + var cost = (t[j - 1] == s[i - 1]) ? 0 : 1; // Step 6 d[i, j] = Math.Min( @@ -290,9 +288,9 @@ public static int ComputeLevenshteinDistance(this string s, string t) return d[n, m]; } - public static Nullable ToNullable(this string s) where T : struct + public static T? ToNullable(this string s) where T : struct { - var result = new Nullable(); + var result = new T?(); try { if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0) @@ -311,20 +309,18 @@ public static Nullable ToNullable(this string s) where T : struct public static string[] LeftJoin(this IEnumerable left, IEnumerable right, string delimiter) { - if (right == null) - { - right = Enumerable.Empty(); - } + right ??= []; - return left.Join(right.DefaultIfEmpty(String.Empty), x => true, y => true, (x, y) => String.Join(delimiter, new[] { x, y }.Where(z => !String.IsNullOrEmpty(z)))).ToArray(); + return left.Join(right.DefaultIfEmpty(string.Empty), _ => true, _ => true, (x, y) => string.Join(delimiter, new[] { x, y }.Where(z => !string.IsNullOrEmpty(z)))).ToArray(); } public static string FirstCharToUpper(this string input) { - if (String.IsNullOrEmpty(input)) + if (string.IsNullOrEmpty(input)) { - throw new ArgumentException("input"); + return string.Empty; } + return input.First().ToString().ToUpper() + input.Substring(1); } diff --git a/src/VirtoCommerce.Platform.Core/JsonConverters/PolymorphJsonConverter.cs b/src/VirtoCommerce.Platform.Core/JsonConverters/PolymorphJsonConverter.cs index b79838cdc24..edc2542839a 100644 --- a/src/VirtoCommerce.Platform.Core/JsonConverters/PolymorphJsonConverter.cs +++ b/src/VirtoCommerce.Platform.Core/JsonConverters/PolymorphJsonConverter.cs @@ -9,19 +9,19 @@ namespace VirtoCommerce.Platform.Core.JsonConverters { public class PolymorphJsonConverter : JsonConverter - { + { /// /// Factory methods for create instances of proper classes during deserialization /// private static readonly ConcurrentDictionary> _convertFactories = new ConcurrentDictionary>(); /// - /// Cache for conversion possibility (to reduce AbstractTypeFactory calls thru reflection) + /// Cache for conversion possibility (to reduce AbstractTypeFactory calls via reflection) /// private static readonly ConcurrentDictionary _canConvertCache = new ConcurrentDictionary(); /// - /// Cache for instance creation method infos (to reduce AbstractTypeFactory calls thru reflection) + /// Cache for instance creation method infos (to reduce AbstractTypeFactory calls via reflection) /// private static readonly ConcurrentDictionary _createInstanceMethodsCache = new ConcurrentDictionary(); @@ -44,11 +44,10 @@ public override bool CanConvert(Type objectType) public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { - object result; var obj = JObject.Load(reader); // Create instances for overrides and discriminator-less cases - var factory = _convertFactories.GetOrAdd(objectType, obj2 => + var factory = _convertFactories.GetOrAdd(objectType, _ => { var key = CacheKey.With(nameof(PolymorphJsonConverter), objectType.FullName); var tryCreateInstance = _createInstanceMethodsCache.GetOrAdd(key, _ => typeof(AbstractTypeFactory<>) @@ -58,9 +57,9 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return tryCreateInstance?.Invoke(null, null); }); - result = factory(obj); - + var result = factory(obj); serializer.Populate(obj.CreateReader(), result); + return result; } @@ -70,7 +69,7 @@ public static void RegisterTypeForDiscriminator(Type type, string discriminator) { // Create discriminator-defined instances var typeName = type.Name; - var pt = obj.GetValue(discriminator, StringComparison.InvariantCultureIgnoreCase); + var pt = obj.GetValue(discriminator, StringComparison.OrdinalIgnoreCase); if (pt != null) { typeName = pt.Value(); @@ -79,9 +78,9 @@ public static void RegisterTypeForDiscriminator(Type type, string discriminator) var key = CacheKey.With(nameof(PolymorphJsonConverter), type.FullName, "+"/* To make a difference in keys for discriminator-specific methods */); var tryCreateInstance = _createInstanceMethodsCache.GetOrAdd(key, _ => typeof(AbstractTypeFactory<>) .MakeGenericType(type) - .GetMethod("TryCreateInstance", new Type[] { typeof(string) })); + .GetMethod("TryCreateInstance", [typeof(string)])); - var result = tryCreateInstance?.Invoke(null, new[] { typeName }); + var result = tryCreateInstance?.Invoke(null, [typeName]); if (result == null) { throw new NotSupportedException($"Unknown discriminator type name: {typeName}"); diff --git a/src/VirtoCommerce.Platform.Core/Modularity/FileModuleTypeLoader.cs b/src/VirtoCommerce.Platform.Core/Modularity/FileModuleTypeLoader.cs index f7af53f60b9..a62924f8723 100644 --- a/src/VirtoCommerce.Platform.Core/Modularity/FileModuleTypeLoader.cs +++ b/src/VirtoCommerce.Platform.Core/Modularity/FileModuleTypeLoader.cs @@ -5,16 +5,16 @@ namespace VirtoCommerce.Platform.Core.Modularity { /// - /// Loads modules from an arbitrary location on the filesystem. This typeloader is only called if + /// Loads modules from an arbitrary location on the filesystem. This type loader is only called if /// classes have a Ref parameter that starts with "file://". /// This class is only used on the Desktop version of the Prism Library. /// public class FileModuleTypeLoader : IModuleTypeLoader, IDisposable { - private const string RefFilePrefix = "file://"; + private const string _fileSchema = "file://"; - private readonly IAssemblyResolver assemblyResolver; - private readonly HashSet downloadedUris = new HashSet(); + private readonly IAssemblyResolver _assemblyResolver; + private readonly HashSet _downloadedUris = []; /// @@ -23,7 +23,7 @@ public class FileModuleTypeLoader : IModuleTypeLoader, IDisposable /// The assembly resolver. public FileModuleTypeLoader(IAssemblyResolver assemblyResolver) { - this.assemblyResolver = assemblyResolver; + _assemblyResolver = assemblyResolver; } /// @@ -63,37 +63,31 @@ private void RaiseLoadModuleCompleted(LoadModuleCompletedEventArgs e) } /// - /// Evaluates the property to see if the current typeloader will be able to retrieve the . + /// Evaluates the property to see if the current type loader will be able to retrieve the . /// Returns true if the property starts with "file://", because this indicates that the file /// is a local file. /// - /// Module that should have it's type loaded. + /// Module that should have its type loaded. /// - /// if the current typeloader is able to retrieve the module, otherwise . + /// if the current type loader is able to retrieve the module, otherwise . /// /// An is thrown if is null. public bool CanLoadModuleType(ModuleInfo moduleInfo) { - if (moduleInfo == null) - { - throw new System.ArgumentNullException("moduleInfo"); - } + ArgumentNullException.ThrowIfNull(moduleInfo); - return moduleInfo.Ref != null && moduleInfo.Ref.StartsWith(RefFilePrefix, StringComparison.Ordinal); + return moduleInfo.Ref != null && moduleInfo.Ref.StartsWith(_fileSchema, StringComparison.Ordinal); } /// /// Retrieves the . /// - /// Module that should have it's type loaded. + /// Module that should have its type loaded. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is rethrown as part of a completion event")] public void LoadModuleType(ModuleInfo moduleInfo) { - if (moduleInfo == null) - { - throw new System.ArgumentNullException("moduleInfo"); - } + ArgumentNullException.ThrowIfNull(moduleInfo); try { @@ -106,16 +100,9 @@ public void LoadModuleType(ModuleInfo moduleInfo) } else { - string path; - - if (moduleInfo.Ref.StartsWith(RefFilePrefix + "/", StringComparison.Ordinal)) - { - path = moduleInfo.Ref.Substring(RefFilePrefix.Length + 1); - } - else - { - path = moduleInfo.Ref.Substring(RefFilePrefix.Length); - } + var path = moduleInfo.Ref.StartsWith(_fileSchema + "/", StringComparison.Ordinal) + ? moduleInfo.Ref.Substring(_fileSchema.Length + 1) + : moduleInfo.Ref.Substring(_fileSchema.Length); var fileSize = -1L; if (File.Exists(path)) @@ -127,7 +114,7 @@ public void LoadModuleType(ModuleInfo moduleInfo) // Although this isn't asynchronous, nor expected to take very long, I raise progress changed for consistency. RaiseModuleDownloadProgressChanged(moduleInfo, 0, fileSize); - moduleInfo.Assembly = assemblyResolver.LoadAssemblyFrom(moduleInfo.Ref); + moduleInfo.Assembly = _assemblyResolver.LoadAssemblyFrom(moduleInfo.Ref); // Although this isn't asynchronous, nor expected to take very long, I raise progress changed for consistency. RaiseModuleDownloadProgressChanged(moduleInfo, fileSize, fileSize); @@ -146,17 +133,17 @@ public void LoadModuleType(ModuleInfo moduleInfo) private bool IsSuccessfullyDownloaded(Uri uri) { - lock (downloadedUris) + lock (_downloadedUris) { - return downloadedUris.Contains(uri); + return _downloadedUris.Contains(uri); } } private void RecordDownloadSuccess(Uri uri) { - lock (downloadedUris) + lock (_downloadedUris) { - downloadedUris.Add(uri); + _downloadedUris.Add(uri); } } @@ -174,12 +161,12 @@ public void Dispose() } /// - /// Disposes the associated . + /// Disposes the associated . /// /// When , it is being called from the Dispose method. protected virtual void Dispose(bool disposing) { - if (assemblyResolver is IDisposable disposableResolver) + if (_assemblyResolver is IDisposable disposableResolver) { disposableResolver.Dispose(); } diff --git a/src/VirtoCommerce.Platform.Core/Security/ClaimsPrincipalExtensions.cs b/src/VirtoCommerce.Platform.Core/Security/ClaimsPrincipalExtensions.cs index a60f51f4771..e3faf2f3c02 100644 --- a/src/VirtoCommerce.Platform.Core/Security/ClaimsPrincipalExtensions.cs +++ b/src/VirtoCommerce.Platform.Core/Security/ClaimsPrincipalExtensions.cs @@ -50,7 +50,7 @@ public static IList FindPermissions(this ClaimsPrincipal principal, foreach (var claim in principal.Claims) { var permission = Permission.TryCreateFromClaim(claim, jsonSettings); - if (permission != null && permission.Name.EqualsInvariant(permissionName)) + if (permission != null && permission.Name.EqualsIgnoreCase(permissionName)) { result.Add(permission); } diff --git a/src/VirtoCommerce.Platform.Core/Security/Permission.cs b/src/VirtoCommerce.Platform.Core/Security/Permission.cs index 51b37a80b0b..0eb9f1aefc7 100644 --- a/src/VirtoCommerce.Platform.Core/Security/Permission.cs +++ b/src/VirtoCommerce.Platform.Core/Security/Permission.cs @@ -27,7 +27,7 @@ public class Permission : ValueObject public static Permission TryCreateFromClaim(Claim claim, JsonSerializerSettings jsonSettings) { Permission result = null; - if (claim != null && claim.Type.EqualsInvariant(PlatformConstants.Security.Claims.PermissionClaimType)) + if (claim != null && claim.Type.EqualsIgnoreCase(PlatformConstants.Security.Claims.PermissionClaimType)) { result = AbstractTypeFactory.TryCreateInstance(); result.Name = claim.Value; diff --git a/src/VirtoCommerce.Platform.Core/Settings/SettingsExtension.cs b/src/VirtoCommerce.Platform.Core/Settings/SettingsExtension.cs index 3d53f683ea4..d77ac6299b7 100644 --- a/src/VirtoCommerce.Platform.Core/Settings/SettingsExtension.cs +++ b/src/VirtoCommerce.Platform.Core/Settings/SettingsExtension.cs @@ -60,7 +60,7 @@ private static async Task DeepLoadSettingsAsyncImpl(ISettingsManager manager, IH public static async Task DeepSaveSettingsAsync(this ISettingsManager manager, IHasSettings entry) { - await manager.DeepSaveSettingsAsync(new[] { entry }); + await manager.DeepSaveSettingsAsync([entry]); } /// /// Deep save entity and all nested objects settings values @@ -99,7 +99,7 @@ public static async Task DeepSaveSettingsAsync(this ISettingsManager manager, IE /// public static async Task DeepRemoveSettingsAsync(this ISettingsManager manager, IHasSettings entry) { - await manager.DeepRemoveSettingsAsync(new[] { entry }); + await manager.DeepRemoveSettingsAsync([entry]); } /// @@ -172,7 +172,7 @@ public static async Task SetValueAsync(this ISettingsManager manager, string { var objectSetting = await manager.GetObjectSettingAsync(name); objectSetting.Value = value; - await manager.SaveObjectSettingsAsync(new[] { objectSetting }); + await manager.SaveObjectSettingsAsync([objectSetting]); } public static TValue GetValue(this IEnumerable objectSettings, SettingDescriptor descriptor) @@ -190,7 +190,7 @@ public static TValue GetValue(this IEnumerable objec private static T GetValueInternal(this IEnumerable objectSettings, string settingName, T defaultValue) { var retVal = defaultValue; - var setting = objectSettings.FirstOrDefault(x => x.Name.EqualsInvariant(settingName)); + var setting = objectSettings.FirstOrDefault(x => x.Name.EqualsIgnoreCase(settingName)); if (setting != null && setting.Value != null) { retVal = (T)Convert.ChangeType(setting.Value, typeof(T), CultureInfo.InvariantCulture); diff --git a/src/VirtoCommerce.Platform.Data/Common/FileSystemCountriesService.cs b/src/VirtoCommerce.Platform.Data/Common/FileSystemCountriesService.cs index e003b95856f..7c1debcb2aa 100644 --- a/src/VirtoCommerce.Platform.Data/Common/FileSystemCountriesService.cs +++ b/src/VirtoCommerce.Platform.Data/Common/FileSystemCountriesService.cs @@ -38,7 +38,7 @@ public IList GetCountries() public Task> GetCountriesAsync() { var cacheKey = CacheKey.With(GetType(), nameof(GetCountriesAsync)); - return _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) => + return _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async _ => { var filePath = Path.GetFullPath(_platformOptions.CountriesFilePath); var countriesList = JsonConvert.DeserializeObject>(await File.ReadAllTextAsync(filePath)); @@ -53,13 +53,13 @@ public async Task> GetCountryRegionsAsync(string countryId) countryId = GetIso3Code(countryId); var cacheKey = CacheKey.With(GetType(), nameof(GetCountryRegionsAsync)); - var countries = await _memoryCache.GetOrCreateExclusive(cacheKey, async (cacheEntry) => + var countries = await _memoryCache.GetOrCreateExclusive(cacheKey, async _ => { var filePath = Path.GetFullPath(_platformOptions.CountryRegionsFilePath); return JsonConvert.DeserializeObject>(await File.ReadAllTextAsync(filePath)); }); - var country = countries.FirstOrDefault(x => x.Id.Equals(countryId, StringComparison.InvariantCultureIgnoreCase)); + var country = countries.FirstOrDefault(x => x.Id.EqualsIgnoreCase(countryId)); if (country != null) { return country.Regions.OrderBy(x => x.Name).ToList(); diff --git a/src/VirtoCommerce.Platform.Data/DynamicProperties/DynamicPropertyMetaDataResolver.cs b/src/VirtoCommerce.Platform.Data/DynamicProperties/DynamicPropertyMetaDataResolver.cs index f0aba3ae385..a4a68566816 100644 --- a/src/VirtoCommerce.Platform.Data/DynamicProperties/DynamicPropertyMetaDataResolver.cs +++ b/src/VirtoCommerce.Platform.Data/DynamicProperties/DynamicPropertyMetaDataResolver.cs @@ -45,7 +45,7 @@ public virtual async Task GetByNameAsync(string objectType, str var result = await _searchService.SearchAllNoCloneAsync(criteria); - return result.Distinct().ToDictionary(x => $"{x.ObjectType}__{x.Name}", StringComparer.InvariantCultureIgnoreCase).WithDefaultValue(null); + return result.Distinct().ToDictionary(x => $"{x.ObjectType}__{x.Name}", StringComparer.OrdinalIgnoreCase).WithDefaultValue(null); }); return dict[$"{objectType}__{propertyName}"]; diff --git a/src/VirtoCommerce.Platform.Data/DynamicProperties/DynamicPropertyService.cs b/src/VirtoCommerce.Platform.Data/DynamicProperties/DynamicPropertyService.cs index 0ff318a25b7..09a5139b146 100644 --- a/src/VirtoCommerce.Platform.Data/DynamicProperties/DynamicPropertyService.cs +++ b/src/VirtoCommerce.Platform.Data/DynamicProperties/DynamicPropertyService.cs @@ -34,7 +34,7 @@ public virtual IEnumerable AllRegisteredTypeNames public virtual void RegisterType() where T : IHasDynamicProperties { - if (!AbstractTypeFactory.AllTypeInfos.Any(t => t.Type == typeof(T))) + if (AbstractTypeFactory.AllTypeInfos.All(t => t.Type != typeof(T))) { AbstractTypeFactory.RegisterType(); } @@ -73,7 +73,7 @@ public virtual async Task SaveDynamicPropertiesAsync(DynamicP var dbExistProperties = (await repository.GetDynamicPropertiesForTypesAsync(properties.Select(x => x.ObjectType).Distinct().ToArray())).ToList(); foreach (var property in properties) { - var originalEntity = dbExistProperties.FirstOrDefault(x => property.IsTransient() ? x.Name.EqualsInvariant(property.Name) && x.ObjectType.EqualsInvariant(property.ObjectType) : x.Id.EqualsInvariant(property.Id)); + var originalEntity = dbExistProperties.FirstOrDefault(x => property.IsTransient() ? x.Name.EqualsIgnoreCase(property.Name) && x.ObjectType.EqualsIgnoreCase(property.ObjectType) : x.Id.EqualsIgnoreCase(property.Id)); var modifiedEntity = AbstractTypeFactory.TryCreateInstance().FromModel(property, pkMap); if (originalEntity != null) { @@ -84,7 +84,7 @@ public virtual async Task SaveDynamicPropertiesAsync(DynamicP repository.Add(modifiedEntity); } } - repository.UnitOfWork.Commit(); + await repository.UnitOfWork.CommitAsync(); pkMap.ResolvePrimaryKeys(); DynamicPropertiesCacheRegion.ExpireRegion(); @@ -116,6 +116,5 @@ public virtual async Task DeleteDynamicPropertiesAsync(string[] propertyIds) } #endregion - } } diff --git a/src/VirtoCommerce.Platform.Data/Extensions/DatabaseFacadeExtensions.cs b/src/VirtoCommerce.Platform.Data/Extensions/DatabaseFacadeExtensions.cs index 6879c458be3..6c6c8894816 100644 --- a/src/VirtoCommerce.Platform.Data/Extensions/DatabaseFacadeExtensions.cs +++ b/src/VirtoCommerce.Platform.Data/Extensions/DatabaseFacadeExtensions.cs @@ -1,4 +1,3 @@ -using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; @@ -15,7 +14,7 @@ public static void MigrateIfNotApplied(this DatabaseFacade databaseFacade, strin var platformMigrator = databaseFacade.GetService(); var appliedMigrations = databaseFacade.GetAppliedMigrations(); - if (!appliedMigrations.Any(x => x.EqualsInvariant(targetMigration))) + if (!appliedMigrations.ContainsIgnoreCase(targetMigration)) { platformMigrator.Migrate(targetMigration); } diff --git a/src/VirtoCommerce.Platform.Data/Localizations/TranslationService.cs b/src/VirtoCommerce.Platform.Data/Localizations/TranslationService.cs index dc7625f6d3e..a6e3a30be5d 100644 --- a/src/VirtoCommerce.Platform.Data/Localizations/TranslationService.cs +++ b/src/VirtoCommerce.Platform.Data/Localizations/TranslationService.cs @@ -33,7 +33,7 @@ public JObject GetTranslationDataForLanguage(string lang = null) return InnerGetTranslationData(_options.FallbackLanguage); }); - if (lang != null && !lang.EqualsInvariant(_options.FallbackLanguage)) + if (lang != null && !lang.EqualsIgnoreCase(_options.FallbackLanguage)) { var cacheKey = CacheKey.With(GetType(), "RequestedLanguageJson", lang); result = _memoryCache.GetOrCreateExclusive(cacheKey, cacheEntry => @@ -53,8 +53,8 @@ public JObject GetTranslationDataForLanguage(string lang = null) public string[] GetListOfInstalledLanguages() { - var cachekey = CacheKey.With(GetType(), nameof(GetListOfInstalledLanguages)); - var result = _memoryCache.GetOrCreateExclusive(cachekey, cacheEntry => + var cacheKey = CacheKey.With(GetType(), nameof(GetListOfInstalledLanguages)); + var result = _memoryCache.GetOrCreateExclusive(cacheKey, cacheEntry => { cacheEntry.AddExpirationToken(LocalizationCacheRegion.CreateChangeToken()); return _providers.SelectMany(x => x.GetListOfInstalledLanguages()).Distinct().ToArray(); @@ -80,7 +80,5 @@ protected JObject InnerGetTranslationData(string language) } return result; } - - } } diff --git a/src/VirtoCommerce.Platform.Data/Settings/LocalizableSettingService.cs b/src/VirtoCommerce.Platform.Data/Settings/LocalizableSettingService.cs index 492aa3a4956..36e85285228 100644 --- a/src/VirtoCommerce.Platform.Data/Settings/LocalizableSettingService.cs +++ b/src/VirtoCommerce.Platform.Data/Settings/LocalizableSettingService.cs @@ -58,7 +58,7 @@ public virtual async Task TranslateAsync(string key, string settingName, var values = await GetValuesAsync(settingName, languageCode); return values - ?.Where(x => x.Key.EqualsInvariant(key)) + ?.Where(x => x.Key.EqualsIgnoreCase(key)) .Select(x => x.Value) .FirstOrDefault()?.EmptyToNull() ?? key; } @@ -80,22 +80,21 @@ public virtual async Task> GetValuesAsync(string settingName, st .Select(item => new KeyValue { Key = item.Alias, - Value = item.LocalizedValues.FirstOrDefault(value => value.LanguageCode.EqualsInvariant(languageCode))?.Value.EmptyToNull() ?? item.Alias, + Value = item.LocalizedValues.FirstOrDefault(value => value.LanguageCode.EqualsIgnoreCase(languageCode))?.Value.EmptyToNull() ?? item.Alias, }) .ToList(); } // If language code is a two-letter code var languagePrefix = languageCode + "-"; - const StringComparison ignoreCase = StringComparison.OrdinalIgnoreCase; - if (languages.Any(x => x.StartsWith(languagePrefix, ignoreCase))) + if (languages.Any(x => x.StartsWithIgnoreCase(languagePrefix))) { return items .Select(item => new KeyValue { Key = item.Alias, - Value = item.LocalizedValues.FirstOrDefault(value => value.LanguageCode.StartsWith(languagePrefix, ignoreCase))?.Value.EmptyToNull() ?? item.Alias, + Value = item.LocalizedValues.FirstOrDefault(value => value.LanguageCode.StartsWithIgnoreCase(languagePrefix))?.Value.EmptyToNull() ?? item.Alias, }) .ToList(); } @@ -245,7 +244,7 @@ private async Task SaveSetting(ObjectSettingEntry setting) setting.Value = string.Empty; } - await _settingsManager.SaveObjectSettingsAsync(new[] { setting }); + await _settingsManager.SaveObjectSettingsAsync([setting]); } private async Task> GetLanguages() @@ -277,7 +276,7 @@ private async Task> GetItems(string settingName) .ToArray()); return values - .Select(x => new DictionaryItem { Alias = x, LocalizedValues = localizedValues.GetValueSafe(x) ?? Array.Empty(), }) + .Select(x => new DictionaryItem { Alias = x, LocalizedValues = localizedValues.GetValueSafe(x) ?? [] }) .ToList(); } @@ -318,7 +317,7 @@ private static bool IsShortTextDictionary(SettingDescriptor setting) private Task> GetLocalizedItems(string name, IList aliases = null) { var criteria = AbstractTypeFactory.TryCreateInstance(); - criteria.Names = new[] { name }; + criteria.Names = [name]; criteria.Aliases = aliases; return _localizedItemSearchService.SearchAllNoCloneAsync(criteria); diff --git a/src/VirtoCommerce.Platform.Modules/AssemblyLoading/RuntimeConfigExtensions.cs b/src/VirtoCommerce.Platform.Modules/AssemblyLoading/RuntimeConfigExtensions.cs index 3fce51ee864..4315bb87427 100644 --- a/src/VirtoCommerce.Platform.Modules/AssemblyLoading/RuntimeConfigExtensions.cs +++ b/src/VirtoCommerce.Platform.Modules/AssemblyLoading/RuntimeConfigExtensions.cs @@ -7,6 +7,7 @@ using System.Runtime.InteropServices; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; +using VirtoCommerce.Platform.Core.Common; namespace VirtoCommerce.Platform.Modules.AssemblyLoading { @@ -15,8 +16,6 @@ namespace VirtoCommerce.Platform.Modules.AssemblyLoading /// public static class RuntimeConfigExtensions { - private const string JsonExt = ".json"; - /// /// Tries to get additional probing paths using settings found in the runtimeconfig.json and runtimeconfig.dev.json files. /// @@ -40,7 +39,7 @@ public static IEnumerable TryGetAdditionalProbingPathFromRuntimeConfig( return result; } - var configDevPath = runtimeConfigPath.Substring(0, runtimeConfigPath.Length - JsonExt.Length) + ".dev.json"; + var configDevPath = Path.ChangeExtension(runtimeConfigPath, ".dev.json"); var devConfig = TryReadConfig(configDevPath); var tfm = config.runtimeOptions?.Tfm ?? devConfig?.runtimeOptions?.Tfm; @@ -59,7 +58,7 @@ public static IEnumerable TryGetAdditionalProbingPathFromRuntimeConfig( if (tfm != null) { var dotnet = Process.GetCurrentProcess().MainModule.FileName; - if (string.Equals(Path.GetFileNameWithoutExtension(dotnet), "dotnet", StringComparison.OrdinalIgnoreCase)) + if (Path.GetFileNameWithoutExtension(dotnet).EqualsIgnoreCase("dotnet")) { var dotnetHome = Path.GetDirectoryName(dotnet); result.Add(Path.Combine(dotnetHome, "store", RuntimeInformation.OSArchitecture.ToString().ToLowerInvariant(), tfm)); diff --git a/src/VirtoCommerce.Platform.Modules/AssemblyLoading/TPA.cs b/src/VirtoCommerce.Platform.Modules/AssemblyLoading/TPA.cs index e289e7d3dad..c22565294c9 100644 --- a/src/VirtoCommerce.Platform.Modules/AssemblyLoading/TPA.cs +++ b/src/VirtoCommerce.Platform.Modules/AssemblyLoading/TPA.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Runtime.InteropServices; +using VirtoCommerce.Platform.Core.Common; namespace VirtoCommerce.Platform.Modules.AssemblyLoading { @@ -36,7 +37,7 @@ static string[] GetTPAList() /// True if TPA list contains assembly with the same file name, otherwise false. public static bool ContainsAssembly(string assemblyFileName) { - return _TPAPaths.Any(x => x.EndsWith(Path.DirectorySeparatorChar + assemblyFileName, StringComparison.OrdinalIgnoreCase)); + return _TPAPaths.Any(x => x.EndsWithIgnoreCase(Path.DirectorySeparatorChar + assemblyFileName)); } } } diff --git a/src/VirtoCommerce.Platform.Modules/JsonConverters/ModuleIdentityJsonConverter.cs b/src/VirtoCommerce.Platform.Modules/JsonConverters/ModuleIdentityJsonConverter.cs index 6bd6f1be05b..5ddd9488be4 100644 --- a/src/VirtoCommerce.Platform.Modules/JsonConverters/ModuleIdentityJsonConverter.cs +++ b/src/VirtoCommerce.Platform.Modules/JsonConverters/ModuleIdentityJsonConverter.cs @@ -23,8 +23,8 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { var obj = JObject.Load(reader); - var id = obj.GetValue("id", StringComparison.InvariantCultureIgnoreCase)?.Value(); - var versionToken = (JObject)obj.GetValue("version", StringComparison.InvariantCultureIgnoreCase); + var id = obj.GetValue("id", StringComparison.OrdinalIgnoreCase)?.Value(); + var versionToken = (JObject)obj.GetValue("version", StringComparison.OrdinalIgnoreCase); if (id != null && versionToken != null) { diff --git a/src/VirtoCommerce.Platform.Modules/LoadContextAssemblyResolver.cs b/src/VirtoCommerce.Platform.Modules/LoadContextAssemblyResolver.cs index a7216dc5699..90add9d87b2 100644 --- a/src/VirtoCommerce.Platform.Modules/LoadContextAssemblyResolver.cs +++ b/src/VirtoCommerce.Platform.Modules/LoadContextAssemblyResolver.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Reflection; using System.Runtime.Loader; using Microsoft.Extensions.Logging; @@ -15,23 +14,21 @@ namespace VirtoCommerce.Platform.Modules public class LoadContextAssemblyResolver : IAssemblyResolver { - private readonly ILogger _logger; - private readonly Dictionary _loadedAssemblies = new Dictionary(); + private readonly Dictionary _loadedAssemblies = new(); private readonly bool _isDevelopmentEnvironment; - private readonly IList _ignoredAssemblies = new[] - { + private readonly IList _ignoredAssemblies = + [ "AspNet.Security.OpenIdConnect.Extensions", "AspNet.Security.OpenIdConnect.Primitives", "AspNet.Security.OpenIdConnect.Server", "OpenIddict.Mvc", "CryptoHelper", - "Microsoft.EntityFrameworkCore.Design" - }; + "Microsoft.EntityFrameworkCore.Design", + ]; public LoadContextAssemblyResolver(ILogger logger, bool isDevelopmentEnvironment) { - _logger = logger; _isDevelopmentEnvironment = isDevelopmentEnvironment; } @@ -83,7 +80,7 @@ private Assembly LoadAssemblyWithReferences(string assemblyPath, ManagedAssembly var mainAssemblyName = Path.GetFileNameWithoutExtension(assemblyPath); Assembly mainAssembly = null; - // Load all assembly referencies which we could get through .deps.json file + // Load all assembly references which we could get through .deps.json file foreach (var dependency in depsFilePath.ExtractDependenciesFromPath()) { try @@ -91,10 +88,10 @@ private Assembly LoadAssemblyWithReferences(string assemblyPath, ManagedAssembly var loadedAssembly = LoadAssemblyCached(dependency, loadContext); if (loadedAssembly == null) { - // Temprorary workaround to ensure seamless update to OpenIddictV3: - // skips unsuded OpenIddictV2 assemblies that might not be present on the machine from being loaded by modules (in Platform.Security package) + // Temporary workaround to ensure seamless update to OpenIddictV3: + // skips unused OpenIddictV2 assemblies that might not be present on the machine from being loaded by modules (in Platform.Security package) // will be removed later. - if (_ignoredAssemblies.Contains(dependency.Name.Name, StringComparer.OrdinalIgnoreCase)) + if (_ignoredAssemblies.ContainsIgnoreCase(dependency.Name.Name)) { continue; } @@ -102,7 +99,7 @@ private Assembly LoadAssemblyWithReferences(string assemblyPath, ManagedAssembly throw GenerateAssemblyLoadException(dependency.Name.Name, assemblyPath); } - if (mainAssemblyName.EqualsInvariant(loadedAssembly.GetName().Name)) + if (mainAssemblyName.EqualsIgnoreCase(loadedAssembly.GetName().Name)) { mainAssembly = loadedAssembly; } @@ -129,13 +126,13 @@ private ModuleInitializeException GenerateAssemblyLoadException(string assemblyP /// /// ManagedLibrary object containing library name and paths. /// ManagedAssemblyLoadContext object. - /// Retures loaded assembly (could be cached). + /// Returns loaded assembly (could be cached). private Assembly LoadAssemblyCached(ManagedLibrary managedLibrary, ManagedAssemblyLoadContext loadContext) { var assemblyName = managedLibrary.Name; - if (_loadedAssemblies.ContainsKey(assemblyName.Name)) + if (_loadedAssemblies.TryGetValue(assemblyName.Name, out var assembly)) { - return _loadedAssemblies[assemblyName.Name]; + return assembly; } var loadedAssembly = LoadAssemblyInternal(managedLibrary, loadContext); @@ -147,7 +144,7 @@ private Assembly LoadAssemblyCached(ManagedLibrary managedLibrary, ManagedAssemb } /// - /// Performs loading into AssemblyLoadContext.Default using LoadFromAssemblyName for TPA assemblies and LoadFromAssemblyPath for other dependecies. + /// Performs loading into AssemblyLoadContext.Default using LoadFromAssemblyName for TPA assemblies and LoadFromAssemblyPath for other dependencies. /// /// Based on https://github.com/natemcmaster/DotNetCorePlugins/blob/8f5c28fa70f0869a1af2e2904536268f184e71de/src/Plugins/Loader/ManagedLoadContext.cs Load method, /// but avoided FileNotFoundException from LoadFromAssemblyName trying only load TPA assemblies that way. @@ -220,7 +217,7 @@ private static Uri GetFileUri(string filePath) return null; } - if (!Uri.TryCreate(filePath, UriKind.Absolute, out Uri uri)) + if (!Uri.TryCreate(filePath, UriKind.Absolute, out var uri)) { return null; } diff --git a/src/VirtoCommerce.Platform.Modules/Local/FileMetadataProvider.cs b/src/VirtoCommerce.Platform.Modules/Local/FileMetadataProvider.cs index 8c286121855..467cb28dba2 100644 --- a/src/VirtoCommerce.Platform.Modules/Local/FileMetadataProvider.cs +++ b/src/VirtoCommerce.Platform.Modules/Local/FileMetadataProvider.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Runtime.InteropServices; using Microsoft.Extensions.Options; +using VirtoCommerce.Platform.Core.Common; using VirtoCommerce.Platform.Core.Modularity; namespace VirtoCommerce.Platform.Modules.Local; @@ -52,7 +53,7 @@ public Version GetVersion(string filePath) public Architecture? GetArchitecture(string filePath) { - if (!_options.AssemblyFileExtensions.Any(x => filePath.EndsWith(x, StringComparison.OrdinalIgnoreCase))) + if (!_options.AssemblyFileExtensions.Any(filePath.EndsWithIgnoreCase)) { return null; } diff --git a/src/VirtoCommerce.Platform.Modules/Local/LocalStorageModuleCatalog.cs b/src/VirtoCommerce.Platform.Modules/Local/LocalStorageModuleCatalog.cs index 7b47b5997e2..7d7600fd741 100644 --- a/src/VirtoCommerce.Platform.Modules/Local/LocalStorageModuleCatalog.cs +++ b/src/VirtoCommerce.Platform.Modules/Local/LocalStorageModuleCatalog.cs @@ -173,7 +173,7 @@ public override void Validate() foreach (var declaredDependency in module.Dependencies) { - var installedDependency = manifestModules.FirstOrDefault(x => x.Id.EqualsInvariant(declaredDependency.Id)); + var installedDependency = manifestModules.FirstOrDefault(x => x.Id.EqualsIgnoreCase(declaredDependency.Id)); if (installedDependency != null && !declaredDependency.Version.IsCompatibleWithBySemVer(installedDependency.Version)) { module.Errors.Add($"Module dependency {declaredDependency} is incompatible with installed {installedDependency.Version}"); @@ -327,12 +327,12 @@ private static string GetTargetLocalizationDirectoryPath(string targetDirectoryP private bool IsAssemblyRelatedFile(string path) { - return _options.AssemblyFileExtensions.Union(_options.AssemblyServiceFileExtensions).Any(x => path.EndsWith(x, StringComparison.OrdinalIgnoreCase)); + return _options.AssemblyFileExtensions.Union(_options.AssemblyServiceFileExtensions).Any(path.EndsWithIgnoreCase); } private bool IsAssemblyFile(string path) { - return _options.AssemblyFileExtensions.Any(x => path.EndsWith(x, StringComparison.OrdinalIgnoreCase)); + return _options.AssemblyFileExtensions.Any(path.EndsWithIgnoreCase); } private bool IsReferenceAssemblyFile(string path) @@ -352,7 +352,7 @@ private static string GetLastDirectoryName(string filePath) private bool IsLocalizationFile(string path) { - return _options.LocalizationFileExtensions.Any(x => path.EndsWith(x, StringComparison.OrdinalIgnoreCase)); + return _options.LocalizationFileExtensions.Any(path.EndsWithIgnoreCase); } private static string GetFileAbsoluteUri(string rootPath, string relativePath) diff --git a/src/VirtoCommerce.Platform.Modules/ModuleInstaller.cs b/src/VirtoCommerce.Platform.Modules/ModuleInstaller.cs index 001c8e81520..411294e04c4 100644 --- a/src/VirtoCommerce.Platform.Modules/ModuleInstaller.cs +++ b/src/VirtoCommerce.Platform.Modules/ModuleInstaller.cs @@ -45,12 +45,12 @@ public void Install(IEnumerable modules, IProgress().Where(x => x.IsInstalled).ToArray(); - //Check that incompatible modules does not installed + //Check that incompatible modules are not installed if (!module.Incompatibilities.IsNullOrEmpty()) { var installedIncompatibilities = allInstalledModules.Select(x => x.Identity).Join(module.Incompatibilities, x => x.Id, y => y.Id, (x, y) => new { x, y }) @@ -58,22 +58,23 @@ public void Install(IEnumerable modules, IProgress x.ToString())))); + var identitiesString = string.Join(", ", installedIncompatibilities.Select(x => x.ToString())); + Report(progress, ProgressMessageLevel.Error, $"{module} is incompatible with installed {identitiesString}. You should uninstall these modules first."); isValid = false; } } //Check that installable version compatible with already installed - var alreadyInstalledModule = allInstalledModules.FirstOrDefault(x => x.Id.EqualsInvariant(module.Id)); + var alreadyInstalledModule = allInstalledModules.FirstOrDefault(x => x.Id.EqualsIgnoreCase(module.Id)); if (alreadyInstalledModule != null && !alreadyInstalledModule.Version.IsCompatibleWithBySemVer(module.Version)) { if (alreadyInstalledModule.Version.Major < module.Version.Major) { - Report(progress, ProgressMessageLevel.Error, string.Format("Issue with {0}. Automated upgrade is not feasible due to a major version release; please opt for a custom upgrade to ensure a seamless transition.", module)); + Report(progress, ProgressMessageLevel.Error, $"Issue with {module}. Automated upgrade is not feasible due to a major version release; please opt for a custom upgrade to ensure a seamless transition."); } else { - Report(progress, ProgressMessageLevel.Error, string.Format("Issue with {0}. Automated downgrade is not feasible due to a major version release; please opt for a custom upgrade to ensure a seamless transition.", module)); + Report(progress, ProgressMessageLevel.Error, $"Issue with {module}. Automated downgrade is not feasible due to a major version release; please opt for a custom upgrade to ensure a seamless transition."); } isValid = false; } @@ -102,14 +103,14 @@ public void Install(IEnumerable modules, IProgress().Where(x => x.IsInstalled && x.Id == newModule.Id).First(); + var existModule = _extModuleCatalog.Modules.OfType().First(x => x.IsInstalled && x.Id == newModule.Id); var dstModuleDir = Path.Combine(_options.DiscoveryPath, existModule.Id); _fileManager.SafeDelete(dstModuleDir); Report(progress, ProgressMessageLevel.Info, "Updating '{0}' -> '{1}'", existModule, newModule); InnerInstall(newModule, progress); existModule.IsInstalled = false; newModule.IsInstalled = true; - changedModulesLog.AddRange(new[] { existModule, newModule }); + changedModulesLog.AddRange([existModule, newModule]); } scope.Complete(); } @@ -193,7 +194,7 @@ private bool HasMissedDependencies(ManifestModuleInfo module, IEnumerable() .Where(x => !x.IsInstalled) .Except(modules) diff --git a/src/VirtoCommerce.Platform.Web/ActionConstraints/HasFormValueAttribute.cs b/src/VirtoCommerce.Platform.Web/ActionConstraints/HasFormValueAttribute.cs index ce55fbdbc7d..02b097dd744 100644 --- a/src/VirtoCommerce.Platform.Web/ActionConstraints/HasFormValueAttribute.cs +++ b/src/VirtoCommerce.Platform.Web/ActionConstraints/HasFormValueAttribute.cs @@ -1,8 +1,7 @@ -using System; -using System.Linq; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ActionConstraints; using Microsoft.AspNetCore.Routing; +using VirtoCommerce.Platform.Core.Common; namespace VirtoCommerce.Platform.Web.ActionConstraints; @@ -20,9 +19,9 @@ public override bool IsValidForRequest(RouteContext routeContext, ActionDescript { var request = routeContext.HttpContext.Request; - return _allowedMethods.Contains(request.Method, StringComparer.OrdinalIgnoreCase) && + return _allowedMethods.ContainsIgnoreCase(request.Method) && !string.IsNullOrEmpty(request.ContentType) && - request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && + request.ContentType.StartsWithIgnoreCase("application/x-www-form-urlencoded") && !string.IsNullOrEmpty(request.Form[_name]); } } diff --git a/src/VirtoCommerce.Platform.Web/Controllers/Api/CommonController.cs b/src/VirtoCommerce.Platform.Web/Controllers/Api/CommonController.cs index db1a46f0868..94084832982 100644 --- a/src/VirtoCommerce.Platform.Web/Controllers/Api/CommonController.cs +++ b/src/VirtoCommerce.Platform.Web/Controllers/Api/CommonController.cs @@ -42,7 +42,7 @@ public async Task> GetCountryRegionsAsync(string c } /// - /// Get predefined login page background opitons + /// Get predefined login page background options /// [HttpGet] [AllowAnonymous] @@ -50,19 +50,19 @@ public async Task> GetCountryRegionsAsync(string c public ActionResult GetLoginPageUIOptions() { // options priority - first BackgroundUrl/PatternUrl then presets - string backgrounUrl = _loginPageOptions.BackgroundUrl; - string patternUrl = _loginPageOptions.PatternUrl; + var backgroundUrl = _loginPageOptions.BackgroundUrl; + var patternUrl = _loginPageOptions.PatternUrl; - if (string.IsNullOrWhiteSpace(backgrounUrl) && + if (string.IsNullOrWhiteSpace(backgroundUrl) && string.IsNullOrWhiteSpace(patternUrl) && !string.IsNullOrWhiteSpace(_loginPageOptions.Preset)) { - var preset = _loginPageOptions.Presets?.FirstOrDefault(x => x.Name.EqualsInvariant(_loginPageOptions.Preset)); - backgrounUrl = preset?.BackgroundUrl; + var preset = _loginPageOptions.Presets?.FirstOrDefault(x => x.Name.EqualsIgnoreCase(_loginPageOptions.Preset)); + backgroundUrl = preset?.BackgroundUrl; patternUrl = preset?.PatternUrl; } - return Ok(new { BackgroundUrl = backgrounUrl, PatternUrl = patternUrl }); + return Ok(new { BackgroundUrl = backgroundUrl, PatternUrl = patternUrl }); } } } diff --git a/src/VirtoCommerce.Platform.Web/Controllers/Api/ModulesController.cs b/src/VirtoCommerce.Platform.Web/Controllers/Api/ModulesController.cs index 2a05ce5dad6..ae89c022156 100644 --- a/src/VirtoCommerce.Platform.Web/Controllers/Api/ModulesController.cs +++ b/src/VirtoCommerce.Platform.Web/Controllers/Api/ModulesController.cs @@ -431,7 +431,7 @@ private void InstallModulesFromBundles(string[] moduleBundles, ModuleAutoInstall //Need install only latest versions foreach (var moduleVersionGroup in moduleVersionGroups) { - var alreadyInstalledModule = _externalModuleCatalog.Modules.OfType().FirstOrDefault(x => x.IsInstalled && x.Id.EqualsInvariant(moduleVersionGroup.Key)); + var alreadyInstalledModule = _externalModuleCatalog.Modules.OfType().FirstOrDefault(x => x.IsInstalled && x.Id.EqualsIgnoreCase(moduleVersionGroup.Key)); //skip already installed modules if (alreadyInstalledModule == null) { @@ -590,7 +590,7 @@ private IEnumerable GetDependingModulesRecursive(IEnumerable retVal.Add(module); var dependingModules = _externalModuleCatalog.Modules.OfType() .Where(x => x.IsInstalled) - .Where(x => x.DependsOn.Contains(module.Id, StringComparer.OrdinalIgnoreCase)) + .Where(x => x.DependsOn.ContainsIgnoreCase(module.Id)) .ToList(); if (dependingModules.Any()) { diff --git a/src/VirtoCommerce.Platform.Web/Controllers/Api/SecurityController.cs b/src/VirtoCommerce.Platform.Web/Controllers/Api/SecurityController.cs index 5ca9d76174c..196791e1eaf 100644 --- a/src/VirtoCommerce.Platform.Web/Controllers/Api/SecurityController.cs +++ b/src/VirtoCommerce.Platform.Web/Controllers/Api/SecurityController.cs @@ -431,7 +431,7 @@ public async Task> ChangeCurrentUserPassword([FromB { if (HttpContext.User.IsExternalSignIn()) { - return BadRequest(new SecurityResult { Errors = new[] { $"Could not change password for {HttpContext.User.GetAuthenticationMethod()} authentication method" } }); + return BadRequest(new SecurityResult { Errors = [$"Could not change password for {HttpContext.User.GetAuthenticationMethod()} authentication method"] }); } return await ChangePassword(User.Identity.Name, changePassword); @@ -462,12 +462,12 @@ public async Task> ChangePassword([FromRoute] strin if (!_passwordLoginOptions.Enabled) { - return BadRequest(new SecurityResult { Errors = new[] { "Password login is disabled" } }); + return BadRequest(new SecurityResult { Errors = ["Password login is disabled"] }); } if (changePassword.OldPassword == changePassword.NewPassword) { - return BadRequest(new SecurityResult { Errors = new[] { "You have used this password in the past. Choose another one." } }); + return BadRequest(new SecurityResult { Errors = ["You have used this password in the past. Choose another one."] }); } if (!IsUserEditable(userName)) @@ -517,7 +517,7 @@ public async Task> ResetPassword([FromRoute] string if (!_passwordLoginOptions.Enabled) { - return BadRequest(new SecurityResult { Errors = new[] { "Password login is disabled" } }); + return BadRequest(new SecurityResult { Errors = ["Password login is disabled"] }); } var user = await UserManager.FindByNameAsync(userName); @@ -721,7 +721,7 @@ public async Task> Update([FromBody] ApplicationUse return Forbid(); } - if (!applicationUser.Email.EqualsInvariant(user.Email)) + if (!applicationUser.Email.EqualsIgnoreCase(user.Email)) { // SetEmailAsync also: sets EmailConfirmed to false and updates the SecurityStamp await UserManager.SetEmailAsync(user, user.Email); @@ -878,7 +878,7 @@ public async Task> GetUserApiKeys([FromRoute] string [Authorize(PlatformPermissions.SecurityUpdate)] public async Task> SaveUserApiKey([FromBody] UserApiKey userApiKey) { - await _userApiKeyService.SaveApiKeysAsync(new[] { userApiKey }); + await _userApiKeyService.SaveApiKeysAsync([userApiKey]); return Ok(); } @@ -1064,7 +1064,7 @@ private Task GetCurrentUserAsync() private bool IsUserEditable(string userName) { - return _securityOptions.NonEditableUsers?.FirstOrDefault(x => x.EqualsInvariant(userName)) == null; + return _securityOptions.NonEditableUsers?.FirstOrDefault(x => x.EqualsIgnoreCase(userName)) == null; } private void LogUserNotFound(string idOrName) @@ -1095,7 +1095,7 @@ private ApplicationUser ReduceUserDetails(ApplicationUser user) private IList ReduceUsersDetails(IList users) { - return users?.Select(x => ReduceUserDetails(x)).ToList(); + return users?.Select(ReduceUserDetails).ToList(); } private async Task ValidatePassword(ApplicationUser user, string password) diff --git a/src/VirtoCommerce.Platform.Web/Extensions/ConfigurationExtensions.cs b/src/VirtoCommerce.Platform.Web/Extensions/ConfigurationExtensions.cs index 66954edb75c..424c2055b21 100644 --- a/src/VirtoCommerce.Platform.Web/Extensions/ConfigurationExtensions.cs +++ b/src/VirtoCommerce.Platform.Web/Extensions/ConfigurationExtensions.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; +using VirtoCommerce.Platform.Core.Common; namespace VirtoCommerce.Platform.Web.Extensions { @@ -33,7 +34,7 @@ public static int TryGetHttpsPort(this IConfiguration configuration) foreach (var address in addresses.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { var bindingAddress = BindingAddress.Parse(address); - if (bindingAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) + if (bindingAddress.Scheme.EqualsIgnoreCase("https")) { // If we find multiple different https ports specified, throw if (nullablePort.HasValue && nullablePort != bindingAddress.Port) diff --git a/src/VirtoCommerce.Platform.Web/PushNotifications/SignalRBuilderExtensions.cs b/src/VirtoCommerce.Platform.Web/PushNotifications/SignalRBuilderExtensions.cs index 0d5434b1d8e..7802ad85a47 100644 --- a/src/VirtoCommerce.Platform.Web/PushNotifications/SignalRBuilderExtensions.cs +++ b/src/VirtoCommerce.Platform.Web/PushNotifications/SignalRBuilderExtensions.cs @@ -23,7 +23,7 @@ public static ISignalRServerBuilder AddPushNotifications(this ISignalRServerBuil builder.Services.AddOptions().Bind(configuration.GetSection("PushNotifications")).ValidateDataAnnotations(); // SignalR scalability configuration. - if (scalabilityMode != null && !scalabilityMode.EqualsInvariant("None")) + if (scalabilityMode != null && !scalabilityMode.EqualsIgnoreCase("None")) { // Store full type information in JSON to deserialize push notifications on other instances @@ -36,7 +36,7 @@ public static ISignalRServerBuilder AddPushNotifications(this ISignalRServerBuil builder.Services.AddSingleton(); builder.Services.AddHostedService(); - if (scalabilityMode.EqualsInvariant("AzureSignalRService")) + if (scalabilityMode.EqualsIgnoreCase("AzureSignalRService")) { var azureSignalRConnectionString = configuration["PushNotifications:AzureSignalRService:ConnectionString"]; if (string.IsNullOrEmpty(azureSignalRConnectionString)) diff --git a/src/VirtoCommerce.Platform.Web/Security/Authentication/BasicAuthenticationHandler.cs b/src/VirtoCommerce.Platform.Web/Security/Authentication/BasicAuthenticationHandler.cs index aa451dc8b9d..6cb8756f0c0 100644 --- a/src/VirtoCommerce.Platform.Web/Security/Authentication/BasicAuthenticationHandler.cs +++ b/src/VirtoCommerce.Platform.Web/Security/Authentication/BasicAuthenticationHandler.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using VirtoCommerce.Platform.Core.Common; using VirtoCommerce.Platform.Core.Security; namespace VirtoCommerce.Platform.Web.Security.Authentication @@ -72,7 +73,7 @@ private bool TryGetEncodedCredentials(out string encodedCredentials) var headerValue = values.ToString(); const string scheme = "Basic "; - if (headerValue.StartsWith(scheme, StringComparison.OrdinalIgnoreCase)) + if (headerValue.StartsWithIgnoreCase(scheme)) { encodedCredentials = headerValue.Substring(scheme.Length).Trim(); } diff --git a/src/VirtoCommerce.Platform.Web/Security/ServiceCollectionExtensions.cs b/src/VirtoCommerce.Platform.Web/Security/ServiceCollectionExtensions.cs index b6d8909e191..261ea58a136 100644 --- a/src/VirtoCommerce.Platform.Web/Security/ServiceCollectionExtensions.cs +++ b/src/VirtoCommerce.Platform.Web/Security/ServiceCollectionExtensions.cs @@ -84,7 +84,7 @@ public static void UpdateServerCertificateIfNeed(this IApplicationBuilder app, S var certificateStorage = app.ApplicationServices.GetService(); var certificateService = app.ApplicationServices.GetService(); var possiblyOldCert = certificateStorage.Load(); // Previously stored cert (possibly old, default or just created by another platform instance) - if (!possiblyOldCert.SerialNumber.EqualsInvariant(currentCert.SerialNumber)) + if (!possiblyOldCert.SerialNumber.EqualsIgnoreCase(currentCert.SerialNumber)) { // Therefore, currentCert is newly generated and needs to be saved. // But we should check if old cert is stored if (possiblyOldCert.StoredInDb && !possiblyOldCert.Expired) @@ -110,9 +110,7 @@ public static void UpdateServerCertificateIfNeed(this IApplicationBuilder app, S public static void AddForwardedHeaders(this IServiceCollection services) { // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-6.0 - if (string.Equals( - Environment.GetEnvironmentVariable("ASPNETCORE_FORWARDEDHEADERS_ENABLED"), - "true", StringComparison.OrdinalIgnoreCase)) + if (Environment.GetEnvironmentVariable("ASPNETCORE_FORWARDEDHEADERS_ENABLED").EqualsIgnoreCase("true")) { services.Configure(options => { diff --git a/src/VirtoCommerce.Platform.Web/Startup.cs b/src/VirtoCommerce.Platform.Web/Startup.cs index 49c27060299..e42edcc6556 100644 --- a/src/VirtoCommerce.Platform.Web/Startup.cs +++ b/src/VirtoCommerce.Platform.Web/Startup.cs @@ -120,7 +120,7 @@ public void ConfigureServices(IServiceCollection services) var databaseProvider = Configuration.GetValue("DatabaseProvider", "SqlServer"); - // Optional Modules Dependecy Resolving + // Optional Modules Dependency Resolving services.Add(ServiceDescriptor.Singleton(typeof(IOptionalDependency<>), typeof(OptionalDependencyManager<>))); services.AddCustomSecurityHeaders(); @@ -572,7 +572,7 @@ public static ServerCertificate GetServerCertificate(ICertificateLoader certific { var result = certificateLoader.Load(); - if (result.SerialNumber.EqualsInvariant(ServerCertificate.SerialNumberOfVirtoPredefined) || + if (result.SerialNumber.EqualsIgnoreCase(ServerCertificate.SerialNumberOfVirtoPredefined) || result.Expired) { result = ServerCertificateService.CreateSelfSigned(); @@ -661,9 +661,9 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger< app.ExecuteSynchronized(() => { - // This method contents will run inside of critical section of instance distributed lock. + // This method contents will run inside critical section of instance distributed lock. // Main goal is to apply the migrations (Platform, Hangfire, modules) sequentially instance by instance. - // This ensures only one active EF-migration ran simultaneously to avoid DB-related side-effects. + // This ensures only one active EF-migration ran simultaneously to avoid DB-related side effects. // Apply platform migrations app.UsePlatformMigrations(Configuration); @@ -700,8 +700,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger< var mvcJsonOptions = app.ApplicationServices.GetService>(); - //Json converter that resolve a meta-data for all incoming objects of DynamicObjectProperty type - //in order to be able pass { name: "dynPropName", value: "myVal" } in the incoming requests for dynamic properties, and do not care about meta-data loading. see more details: PT-48 + //Json converter that resolves a meta-data for all incoming objects of DynamicObjectProperty type + //in order to be able to pass { name: "dynPropName", value: "myVal" } in the incoming requests for dynamic properties, and do not care about meta-data loading. see more details: PT-48 mvcJsonOptions.Value.SerializerSettings.Converters.Add(new DynamicObjectPropertyJsonConverter(app.ApplicationServices.GetService())); //The converter is responsible for the materialization of objects, taking into account the information on overriding diff --git a/src/VirtoCommerce.Platform.Web/Swagger/SwaggerServiceCollectionExtensions.cs b/src/VirtoCommerce.Platform.Web/Swagger/SwaggerServiceCollectionExtensions.cs index 7a6c7bddc1a..a8e732f6238 100644 --- a/src/VirtoCommerce.Platform.Web/Swagger/SwaggerServiceCollectionExtensions.cs +++ b/src/VirtoCommerce.Platform.Web/Swagger/SwaggerServiceCollectionExtensions.cs @@ -128,20 +128,20 @@ public static void AddSwagger(this IServiceCollection services, IConfiguration c private static bool DocInclusionPredicateCustomStrategy(ManifestModuleInfo[] modules, string docName, ApiDescription apiDesc) { // It's a UI endpoint, return all to correctly build swagger UI page - if (docName.EqualsInvariant(PlatformUIDocName)) + if (docName.EqualsIgnoreCase(PlatformUIDocName)) { return true; } // It's a platform endpoint. var currentAssembly = ((ControllerActionDescriptor)apiDesc.ActionDescriptor).ControllerTypeInfo.Assembly; - if (docName.EqualsInvariant(PlatformDocName) && currentAssembly.FullName?.StartsWith(docName) == true) + if (docName.EqualsIgnoreCase(PlatformDocName) && currentAssembly.FullName?.StartsWith(docName) == true) { return true; } // It's a module endpoint. - var module = modules.FirstOrDefault(m => m.ModuleName.EqualsInvariant(docName)); + var module = modules.FirstOrDefault(m => m.ModuleName.EqualsIgnoreCase(docName)); return module != null && module.Assembly == currentAssembly; }