From ae106f64c6137c500ac69a6515c3992099d65df8 Mon Sep 17 00:00:00 2001 From: Kingcean Date: Wed, 13 Nov 2024 19:36:13 +0800 Subject: [PATCH] Improve code style. --- .../Collection/Dictionary/KeyedDataMapping.cs | 5 +- Core/Collection/List/ListExtensions.cs | 100 ++++++++++++------ Core/Collection/List/StringsConverter.cs | 67 +++++++++++- Core/Data/Query/SimpleCondition.cs | 45 ++++---- Core/IO/File/FileSystemInfoUtility.cs | 7 +- Core/IO/Stream/CharsReader.cs | 9 +- Core/Maths/Arithmetic/Operation.cs | 13 +-- Core/Maths/Boolean/Operations.cs | 12 +-- Core/Maths/Boolean/Operators.cs | 12 +-- Core/Maths/Statistics/Average.cs | 60 ++++++----- Core/Reflection/Objects/ObjectConvert.cs | 3 + Core/Security/Token/JsonWebToken.cs | 13 +-- Core/Security/Token/OAuth.cs | 21 ++-- Core/Text/Json/ArrayNode.cs | 10 +- Core/Text/Json/ObjectNode.cs | 8 +- UnitTest/Maths/ArithmeticTest.cs | 15 ++- UnitTest/Net/HttpClientUnitTest.cs | 2 +- 17 files changed, 245 insertions(+), 157 deletions(-) diff --git a/Core/Collection/Dictionary/KeyedDataMapping.cs b/Core/Collection/Dictionary/KeyedDataMapping.cs index 7f76fa8b..d2f91dc8 100644 --- a/Core/Collection/Dictionary/KeyedDataMapping.cs +++ b/Core/Collection/Dictionary/KeyedDataMapping.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; +using Trivial.Reflection; namespace Trivial.Collection; @@ -30,7 +31,7 @@ public T this[string key] { get { - if (key == null) throw new ArgumentNullException(nameof(key), "key should not be null."); + if (key == null) throw ObjectConvert.ArgumentNull(nameof(key)); key = key.Trim().ToLowerInvariant(); if (string.IsNullOrEmpty(key)) throw new ArgumentException("key should not be empty.", nameof(key)); if (mapping.TryGetValue(key, out var r)) return r; @@ -56,7 +57,7 @@ public T this[string key] set { - if (key == null) throw new ArgumentNullException(nameof(key), "key should not be null."); + if (key == null) throw ObjectConvert.ArgumentNull(nameof(key)); key = key.Trim().ToLowerInvariant(); if (string.IsNullOrEmpty(key) || value is null) return; try diff --git a/Core/Collection/List/ListExtensions.cs b/Core/Collection/List/ListExtensions.cs index 67aabad0..22296d7b 100644 --- a/Core/Collection/List/ListExtensions.cs +++ b/Core/Collection/List/ListExtensions.cs @@ -28,7 +28,7 @@ public static partial class ListExtensions /// dict or key was null. public static bool TryGetNotEmptyValue(this IDictionary dict, string key, out string value) { - if (dict == null) throw new ArgumentNullException(nameof(dict), "dict should not be null."); + if (dict == null) throw ObjectConvert.ArgumentNull(nameof(dict)); value = dict.TryGetValue(key, out var v) && !string.IsNullOrEmpty(v) ? v : null; return v != null; } @@ -42,7 +42,7 @@ public static bool TryGetNotEmptyValue(this IDictionary dict, st /// dict or key was null. public static string TryGetNotEmptyValue(this IDictionary dict, string key) { - if (dict == null) throw new ArgumentNullException(nameof(dict), "dict should not be null."); + if (dict == null) throw ObjectConvert.ArgumentNull(nameof(dict)); return dict.TryGetValue(key, out var v) && !string.IsNullOrEmpty(v) ? v : null; } @@ -55,7 +55,7 @@ public static string TryGetNotEmptyValue(this IDictionary dict, /// true if clear the others of the property before adding; otherwise, false. public static void Add(this List> list, TKey key, TValue value, bool clearOthers = false) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); if (clearOthers) list.Remove(key); list.Add(new KeyValuePair(key, value)); } @@ -68,7 +68,7 @@ public static void Add(this List> list, /// The style. public static void Add(this IList list, string s, ConsoleTextStyle style = null) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); list.Add(new ConsoleText(s, style)); } @@ -80,7 +80,7 @@ public static void Add(this IList list, string s, ConsoleTextStyle /// The style. public static void Add(this IList list, StringBuilder s, ConsoleTextStyle style = null) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); list.Add(new ConsoleText(s, style)); } @@ -93,7 +93,7 @@ public static void Add(this IList list, StringBuilder s, ConsoleTex /// The style. public static void Add(this IList list, char c, int repeatCount = 1, ConsoleTextStyle style = null) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); list.Add(new ConsoleText(c, repeatCount, style)); } @@ -106,7 +106,7 @@ public static void Add(this IList list, char c, int repeatCount = 1 /// The value. public static void Insert(this IList> list, int index, TKey key, TValue value) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); list.Insert(index, new KeyValuePair(key, value)); } @@ -180,7 +180,7 @@ public static List PadEnd(IEnumerable col, int count, T value = default /// col is null. public static void PadBeginTo(IList col, int count, T value = default) { - if (col == null) throw new ArgumentNullException(nameof(col), "col should not be null."); + if (col == null) throw ObjectConvert.ArgumentNull(nameof(col)); if (count < 0) { for (var i = 0; i < count; i++) @@ -210,7 +210,7 @@ public static void PadBeginTo(IList col, int count, T value = default) /// count is less than 0. public static void PadEndTo(ICollection col, int count, T value = default) { - if (col == null) throw new ArgumentNullException(nameof(col), "col should not be null."); + if (col == null) throw ObjectConvert.ArgumentNull(nameof(col)); if (count < 0) { if (col is not IList list) throw new ArgumentOutOfRangeException(nameof(count), "count should be a natural number."); @@ -298,7 +298,7 @@ public static IEnumerable Union(IEnumerable source, JsonObjectNo /// The keys. public static IEnumerable Keys(this IEnumerable> list) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); return list.Select(item => item.Key).Distinct(); } @@ -310,7 +310,7 @@ public static IEnumerable Keys(this IEnumerableThe values. public static IEnumerable GetValues(this IEnumerable> list, TKey key) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); return key != null ? list.Where(item => key.Equals(item.Key)).Select(item => item.Value) : list.Where(item => item.Key == null).Select(item => item.Value); } @@ -322,7 +322,7 @@ public static IEnumerable GetValues(this IEnumerableThe value items. public static IEnumerable GetValueItems(this IEnumerable> list, TKey key) where TList : IEnumerable { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); return key != null ? list.Where(item => key.Equals(item.Key)).SelectMany(item => item.Value) : list.Where(item => item.Key == null).SelectMany(item => item.Value); } @@ -336,7 +336,7 @@ public static IEnumerable GetValueItems(this IEnume /// true if has; otherwise, false. public static bool TryGetValue(this IList> list, TKey key, int index, out TValue value) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); var col = list.GetValues(key).ToList(); if (list.Count <= index) { @@ -370,7 +370,7 @@ public static TValue GetValue(this IEnumerableindex is less than 0, or is equals to or greater than the length of the values of the specific key. public static IGrouping Get(this IEnumerable> list, TKey key) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); list = key == null ? list.Where(item => item.Key == null) : list.Where(item => key.Equals(item.Key)); return list.GroupBy(item => item.Key, item => item.Value).SingleOrDefault(); } @@ -383,7 +383,7 @@ public static IGrouping Get(this IEnumerabletrue if the instance contains an element with the specified key; otherwise, false. public static bool ContainsKey(this IEnumerable> list, TKey key) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); if (key == null) { foreach (var item in list) @@ -633,7 +633,7 @@ public static T[] CreateArray(int count, T item = default) /// The number of elements removed from the key value pairs. public static int Remove(this List> list, params TKey[] keys) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); var count = 0; foreach (var key in keys) { @@ -650,7 +650,7 @@ public static int Remove(this List> lis /// The key. public static int LastIndexOf(this IEnumerable> list, TKey key) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); return IndexOf(list.Reverse(), key); } @@ -661,7 +661,7 @@ public static int LastIndexOf(this IEnumerableThe key. public static int IndexOf(this IEnumerable> list, TKey key) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); var i = -1; if (key == null) { @@ -700,6 +700,16 @@ public static int IndexOf(this IEnumerable + /// Returns the first element of a sequence, or a null if the sequence contains no elements. + /// + /// The type of the elements of source. + /// The collection to return the first element of. + /// The default value used when no element. + /// The first element in source; or null, if empty. + public static T First(IEnumerable col, T defaultValue) where T : struct + => FirstOrNull(col) ?? defaultValue; + /// /// Returns the last element of a sequence, or a null if the sequence contains no elements. /// @@ -720,6 +730,16 @@ public static int IndexOf(this IEnumerable + /// Returns the last element of a sequence, or a null if the sequence contains no elements. + /// + /// The type of the elements of source. + /// The collection to return the last element of. + /// The default value used when no element. + /// The last element in source; or null, if empty. + public static T Last(IEnumerable col, T defaultValue) where T : struct + => LastOrNull(col) ?? defaultValue; + /// /// Searches for the specified object and returns the zero-based index array of the all occurrence within the entire key value pairs. /// @@ -729,7 +749,7 @@ public static int IndexOf(this IEnumerableThe number of elements in the section to search. public static IEnumerable AllIndexesOf(this IEnumerable list, T test, int index = 0, int? count = null) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); if (index > 0) list = list.Skip(index); if (count.HasValue) list = list.Take(count.Value); var i = -1; @@ -760,8 +780,8 @@ public static IEnumerable AllIndexesOf(this IEnumerable list, T test, /// The number of elements in the section to search. public static IEnumerable AllIndexesOf(this IEnumerable list, Func test, int index = 0, int? count = null) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); - if (test == null) throw new ArgumentNullException(nameof(test), "test should be a function to test."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); + if (test == null) throw ObjectConvert.ArgumentNull(nameof(test)); if (index > 0) list = list.Skip(index); if (count.HasValue) list = list.Take(count.Value); var i = -1; @@ -779,7 +799,7 @@ public static IEnumerable AllIndexesOf(this IEnumerable list, FuncThe key to test. public static IEnumerable AllIndexesOf(this IEnumerable> list, TKey key) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); var i = -1; if (key == null) { @@ -826,7 +846,7 @@ public static IEnumerable AllIndexesOf(this IEnumerabletrue if insert at last; otherwise, false. public static void Set(this List> list, TKey key, TValue value, bool insertAtLast = false) { - if (list == null) throw new ArgumentNullException(nameof(list), "list should not be null."); + if (list == null) throw ObjectConvert.ArgumentNull(nameof(list)); var i = insertAtLast ? -1 : list.IndexOf(key); if (i >= 0) { @@ -1049,7 +1069,7 @@ public static IList ToSynchronizedList(List list, object syncRoot, bool /// col is null. public static bool ContainsOnly(this IEnumerable col, IEnumerable keys, out List matched) { - if (col == null) throw new ArgumentNullException(nameof(col), "col should not be null."); + if (col == null) throw ObjectConvert.ArgumentNull(nameof(col)); matched = new(); if (keys == null) return !col.Any(); var b = true; @@ -1073,7 +1093,7 @@ public static bool ContainsOnly(this IEnumerable col, IEnumerablecol is null. public static bool ContainsOnly(this IEnumerable col, IEnumerable keys, out List matched, out List rest) { - if (col == null) throw new ArgumentNullException(nameof(col), "col should not be null."); + if (col == null) throw ObjectConvert.ArgumentNull(nameof(col)); matched = new(); if (keys == null) { @@ -1364,27 +1384,37 @@ internal static IEnumerable Select(IEnumerable l { i++; var vA = padding; + var skip = true; if (hasA) { hasA = a.MoveNext(); - if (hasA) vA = a.Current; - } - else - { - if (!hasB) yield break; + if (hasA) + { + skip = false; + vA = a.Current; + } + else + { + a.Dispose(); + } } var vB = padding; if (hasB) { hasB = b.MoveNext(); - if (hasB) vB = b.Current; - } - else - { - if (!hasA) yield break; + if (hasB) + { + skip = false; + vB = b.Current; + } + else + { + b.Dispose(); + } } + if (skip) yield break; yield return callback(vA, hasA, vB, hasB, i); } } diff --git a/Core/Collection/List/StringsConverter.cs b/Core/Collection/List/StringsConverter.cs index 79383e42..c1d956af 100644 --- a/Core/Collection/List/StringsConverter.cs +++ b/Core/Collection/List/StringsConverter.cs @@ -34,12 +34,31 @@ public static string ToResponseString(this IEnumerable col, /// Gets the server-sent event format string. /// /// The input collection. - /// The stream. + /// true if use \n instead of new line. /// A server-sent event format string. - public static void ToResponseString(this IEnumerable col, Stream stream) + public static async Task ToResponseStringAsync(this IAsyncEnumerable col, bool newLineN) + { + if (col == null) return null; + var sb = new StringBuilder(); + await foreach (var item in col) + { + if (item == null) continue; + item.ToResponseString(sb, newLineN); + } + + return sb.ToString(); + } + + /// + /// Gets the server-sent event format string. + /// + /// The input collection. + /// The stream. + /// The encoding; or null, by default, if uses UTF-8. + public static void WriteTo(this IEnumerable col, Stream stream, Encoding encoding = null) { - if (col == null) return; - var writer = new StreamWriter(stream, Encoding.UTF8); + if (col == null || stream == null) return; + var writer = new StreamWriter(stream, encoding ?? Encoding.UTF8); foreach (var item in col) { if (item == null) continue; @@ -49,6 +68,46 @@ public static void ToResponseString(this IEnumerable col, S } } + /// + /// Gets the server-sent event format string. + /// + /// The input collection. + /// The stream. + /// The encoding; or null, by default, if uses UTF-8. + /// A task that represents the asynchronous write operation. + public static async Task WriteToAsync(this IEnumerable col, Stream stream, Encoding encoding = null) + { + if (col == null || stream == null) return; + var writer = new StreamWriter(stream, encoding ?? Encoding.UTF8); + foreach (var item in col) + { + if (item == null) continue; + await writer.WriteAsync(item.ToResponseString(true)); + writer.Write('\n'); + await writer.FlushAsync(); + } + } + + /// + /// Gets the server-sent event format string. + /// + /// The input collection. + /// The stream. + /// The encoding; or null, by default, if uses UTF-8. + /// A task that represents the asynchronous write operation. + public static async Task WriteToAsync(this IAsyncEnumerable col, Stream stream, Encoding encoding = null) + { + if (col == null || stream == null) return; + var writer = new StreamWriter(stream, encoding ?? Encoding.UTF8); + await foreach (var item in col) + { + if (item == null) continue; + await writer.WriteAsync(item.ToResponseString(true)); + writer.Write('\n'); + await writer.FlushAsync(); + } + } + /// /// Generates a string collection. /// diff --git a/Core/Data/Query/SimpleCondition.cs b/Core/Data/Query/SimpleCondition.cs index 37515eaa..bbde1649 100644 --- a/Core/Data/Query/SimpleCondition.cs +++ b/Core/Data/Query/SimpleCondition.cs @@ -10,6 +10,7 @@ using System; using System.Collections.Generic; using Trivial.Maths; +using Trivial.Reflection; namespace Trivial.Data; @@ -139,7 +140,7 @@ public abstract class SimpleCondition : ISimpleCondition /// A comparing operator. public static DbCompareOperator GetLeftOperator(ISimpleInterval value) => value == null - ? throw new ArgumentNullException(nameof(value)) + ? throw ObjectConvert.ArgumentNull(nameof(value)) : (value.LeftOpen ? DbCompareOperator.Greater : DbCompareOperator.GreaterOrEqual); /// @@ -150,7 +151,7 @@ public static DbCompareOperator GetLeftOperator(ISimpleInterval value) /// A comparing operator. public static DbCompareOperator GetRightOperator(ISimpleInterval value) => value == null - ? throw new ArgumentNullException(nameof(value)) + ? throw ObjectConvert.ArgumentNull(nameof(value)) : (value.RightOpen ? DbCompareOperator.Less : DbCompareOperator.LessOrEqual); /// @@ -572,7 +573,7 @@ public Int32Condition(DbCompareOperator op, int value) : base(op, value) /// A condition from left bound of a specific simple interval. public static Int32Condition CreateFromLeft(StructValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); return new Int32Condition { Value = value.MinValue, @@ -587,7 +588,7 @@ public static Int32Condition CreateFromLeft(StructValueSimpleInterval value /// A condition from right bound of a specific simple interval. public static Int32Condition CreateFromRight(StructValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); return new Int32Condition { Value = value.MaxValue, @@ -602,7 +603,7 @@ public static Int32Condition CreateFromRight(StructValueSimpleInterval valu /// A condition from left bound of a specific simple interval. public static Int32Condition CreateFromLeft(NullableValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); if (!value.LeftBounded) return null; return new Int32Condition { @@ -618,7 +619,7 @@ public static Int32Condition CreateFromLeft(NullableValueSimpleInterval val /// A condition from right bound of a specific simple interval. public static Int32Condition CreateFromRight(NullableValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); if (!value.RightBounded) return null; return new Int32Condition { @@ -733,7 +734,7 @@ public Int64Condition(DbCompareOperator op, long value) : base(op, value) /// A condition from left bound of a specific simple interval. public static Int64Condition CreateFromLeft(StructValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); return new Int64Condition { Value = value.MinValue, @@ -748,7 +749,7 @@ public static Int64Condition CreateFromLeft(StructValueSimpleInterval valu /// A condition from right bound of a specific simple interval. public static Int64Condition CreateFromRight(StructValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); return new Int64Condition { Value = value.MaxValue, @@ -763,7 +764,7 @@ public static Int64Condition CreateFromRight(StructValueSimpleInterval val /// A condition from left bound of a specific simple interval. public static Int64Condition CreateFromLeft(NullableValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); if (!value.LeftBounded) return null; return new Int64Condition { @@ -779,7 +780,7 @@ public static Int64Condition CreateFromLeft(NullableValueSimpleInterval va /// A condition from right bound of a specific simple interval. public static Int64Condition CreateFromRight(NullableValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); if (!value.RightBounded) return null; return new Int64Condition { @@ -894,7 +895,7 @@ public SingleCondition(DbCompareOperator op, float value) : base(op, value) /// A condition from left bound of a specific simple interval. public static SingleCondition CreateFromLeft(StructValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); return new SingleCondition { Value = value.MinValue, @@ -909,7 +910,7 @@ public static SingleCondition CreateFromLeft(StructValueSimpleInterval va /// A condition from right bound of a specific simple interval. public static SingleCondition CreateFromRight(StructValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); return new SingleCondition { Value = value.MaxValue, @@ -924,7 +925,7 @@ public static SingleCondition CreateFromRight(StructValueSimpleInterval v /// A condition from left bound of a specific simple interval. public static SingleCondition CreateFromLeft(NullableValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); if (!value.LeftBounded) return null; return new SingleCondition { @@ -940,7 +941,7 @@ public static SingleCondition CreateFromLeft(NullableValueSimpleInterval /// A condition from right bound of a specific simple interval. public static SingleCondition CreateFromRight(NullableValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); if (!value.RightBounded) return null; return new SingleCondition { @@ -1055,7 +1056,7 @@ public DoubleCondition(DbCompareOperator op, double value) : base(op, value) /// A condition from left bound of a specific simple interval. public static DoubleCondition CreateFromLeft(StructValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); return new DoubleCondition { Value = value.MinValue, @@ -1070,7 +1071,7 @@ public static DoubleCondition CreateFromLeft(StructValueSimpleInterval v /// A condition from right bound of a specific simple interval. public static DoubleCondition CreateFromRight(StructValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); return new DoubleCondition { Value = value.MaxValue, @@ -1085,7 +1086,7 @@ public static DoubleCondition CreateFromRight(StructValueSimpleInterval /// A condition from left bound of a specific simple interval. public static DoubleCondition CreateFromLeft(NullableValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); if (!value.LeftBounded) return null; return new DoubleCondition { @@ -1101,7 +1102,7 @@ public static DoubleCondition CreateFromLeft(NullableValueSimpleInterval /// A condition from right bound of a specific simple interval. public static DoubleCondition CreateFromRight(NullableValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); if (!value.RightBounded) return null; return new DoubleCondition { @@ -1206,7 +1207,7 @@ public DateTimeCondition(IStructSimpleCondition copier) /// A condition from left bound of a specific simple interval. public static DateTimeCondition CreateFromLeft(StructValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); return new DateTimeCondition { Value = value.MinValue, @@ -1221,7 +1222,7 @@ public static DateTimeCondition CreateFromLeft(StructValueSimpleIntervalA condition from right bound of a specific simple interval. public static DateTimeCondition CreateFromRight(StructValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); return new DateTimeCondition { Value = value.MaxValue, @@ -1236,7 +1237,7 @@ public static DateTimeCondition CreateFromRight(StructValueSimpleIntervalA condition from left bound of a specific simple interval. public static DateTimeCondition CreateFromLeft(NullableValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); if (!value.LeftBounded) return null; return new DateTimeCondition { @@ -1252,7 +1253,7 @@ public static DateTimeCondition CreateFromLeft(NullableValueSimpleIntervalA condition from right bound of a specific simple interval. public static DateTimeCondition CreateFromRight(NullableValueSimpleInterval value) { - if (value == null) throw new ArgumentNullException("value"); + if (value == null) throw ObjectConvert.ArgumentNull(nameof(value)); if (!value.RightBounded) return null; return new DateTimeCondition { diff --git a/Core/IO/File/FileSystemInfoUtility.cs b/Core/IO/File/FileSystemInfoUtility.cs index 095b682b..0e27b370 100644 --- a/Core/IO/File/FileSystemInfoUtility.cs +++ b/Core/IO/File/FileSystemInfoUtility.cs @@ -7,6 +7,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Trivial.Reflection; using Trivial.Text; namespace Trivial.IO; @@ -548,7 +549,7 @@ public static DirectoryInfo TryGetDirectoryInfo(string folder, string folderName public static FileInfo GetFileInfo(string fileName) { var path = GetLocalPath(fileName); - if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException(nameof(fileName)); + if (string.IsNullOrWhiteSpace(path)) throw ObjectConvert.ArgumentNull(nameof(fileName)); path = Path.Combine(path, fileName); return new FileInfo(path); } @@ -566,8 +567,8 @@ public static FileInfo GetFileInfo(string fileName) public static FileInfo GetFileInfo(string folder, string fileName) { var path = GetLocalPath(folder); - if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException(nameof(folder)); - if (string.IsNullOrWhiteSpace(fileName)) throw new ArgumentNullException(nameof(fileName)); + if (string.IsNullOrWhiteSpace(path)) throw ObjectConvert.ArgumentNull(nameof(folder)); + if (string.IsNullOrWhiteSpace(fileName)) throw ObjectConvert.ArgumentNull(nameof(fileName)); path = Path.Combine(path, fileName); return new FileInfo(path); } diff --git a/Core/IO/Stream/CharsReader.cs b/Core/IO/Stream/CharsReader.cs index d97d364b..d52b0283 100644 --- a/Core/IO/Stream/CharsReader.cs +++ b/Core/IO/Stream/CharsReader.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Trivial.Reflection; namespace Trivial.IO; @@ -118,7 +119,7 @@ public override int Read() /// The current reader is closed. public override int Read(char[] buffer, int index, int count) { - if (buffer == null) throw new ArgumentNullException(nameof(buffer), "buffer should not be null"); + if (buffer == null) throw ObjectConvert.ArgumentNull(nameof(buffer)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), "index should not be negative."); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), "count should not be negative."); if (count == 0) return 0; @@ -402,7 +403,7 @@ public static IEnumerable ReadLines(TextReader reader, Action onRe /// The stream has disposed. public static IEnumerable ReadLines(Stream stream, Encoding encoding, bool removeEmptyLine = false) { - if (stream == null) throw new ArgumentNullException(nameof(stream), "stream should not be null."); + if (stream == null) throw ObjectConvert.ArgumentNull(nameof(stream)); var reader = new StreamReader(stream, encoding ?? Encoding.UTF8); var hasDisposed = false; return ReadLines(reader, isSucc => @@ -501,7 +502,7 @@ public static IEnumerable ReadLines(IEnumerable chars, bool remove /// An I/O error occurs. public static IEnumerable ReadLines(FileInfo file, Encoding encoding, bool removeEmptyLine = false) { - if (file == null) throw new ArgumentNullException(nameof(file), "file should not be null."); + if (file == null) throw ObjectConvert.ArgumentNull(nameof(file)); var reader = new StreamReader(file.FullName, encoding); var hasDisposed = false; return ReadLines(reader, isSucc => @@ -525,7 +526,7 @@ public static IEnumerable ReadLines(FileInfo file, Encoding encoding, bo /// Cannot read the file. public static IEnumerable ReadLines(FileInfo file, bool detectEncodingFromByteOrderMarks, bool removeEmptyLine = false) { - if (file == null) throw new ArgumentNullException(nameof(file), "file should not be null."); + if (file == null) throw ObjectConvert.ArgumentNull(nameof(file)); var reader = new StreamReader(file.FullName, detectEncodingFromByteOrderMarks); var hasDisposed = false; return ReadLines(reader, isSucc => diff --git a/Core/Maths/Arithmetic/Operation.cs b/Core/Maths/Arithmetic/Operation.cs index 4d9ecc86..cabc3366 100644 --- a/Core/Maths/Arithmetic/Operation.cs +++ b/Core/Maths/Arithmetic/Operation.cs @@ -12,6 +12,7 @@ using System.Collections.Generic; using System.Net.Http.Headers; using System.Text; +using Trivial.Reflection; namespace Trivial.Maths; @@ -30,8 +31,8 @@ public static partial class Arithmetic /// A result after leftValue minus rightValue. public static T Minus(IAdditionCapable leftValue, INegationCapable rightValue) { - if (leftValue is null) throw new ArgumentNullException(nameof(leftValue)); - if (rightValue is null) throw new ArgumentNullException(nameof(rightValue)); + if (leftValue is null) throw ObjectConvert.ArgumentNull(nameof(leftValue)); + if (rightValue is null) throw ObjectConvert.ArgumentNull(nameof(rightValue)); return leftValue.Plus(rightValue.Negate()); } @@ -45,8 +46,8 @@ public static T Minus(IAdditionCapable leftValue, INegationCapable righ /// A result after leftValue minus rightValue. public static T Minus(ISubtractionCapable leftValue, T rightValue) { - if (leftValue is null) throw new ArgumentNullException(nameof(leftValue)); - if (rightValue == null) throw new ArgumentNullException(nameof(rightValue)); + if (leftValue is null) throw ObjectConvert.ArgumentNull(nameof(leftValue)); + if (rightValue == null) throw ObjectConvert.ArgumentNull(nameof(rightValue)); return leftValue.Minus(rightValue); } @@ -60,8 +61,8 @@ public static T Minus(ISubtractionCapable leftValue, T rightValue) /// A result after leftValue plus rightValue. public static T Plus(IAdditionCapable leftValue, T rightValue) { - if (leftValue is null) throw new ArgumentNullException(nameof(leftValue)); - if (rightValue == null) throw new ArgumentNullException(nameof(rightValue)); + if (leftValue is null) throw ObjectConvert.ArgumentNull(nameof(leftValue)); + if (rightValue == null) throw ObjectConvert.ArgumentNull(nameof(rightValue)); return leftValue.Plus(rightValue); } diff --git a/Core/Maths/Boolean/Operations.cs b/Core/Maths/Boolean/Operations.cs index be2c20bc..fc5a0241 100644 --- a/Core/Maths/Boolean/Operations.cs +++ b/Core/Maths/Boolean/Operations.cs @@ -1,14 +1,4 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) 2010 Nanchang Jinchen Software Co., Ltd. All rights reserved. -// -// -// The calculators and operator symbols of boolean. -// -// Kingcean Tuan -// -------------------------------------------------------------------------------------------------------------------- - -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text.Json.Serialization; diff --git a/Core/Maths/Boolean/Operators.cs b/Core/Maths/Boolean/Operators.cs index 524ea5fc..266cdab3 100644 --- a/Core/Maths/Boolean/Operators.cs +++ b/Core/Maths/Boolean/Operators.cs @@ -1,14 +1,4 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) 2010 Nanchang Jinchen Software Co., Ltd. All rights reserved. -// -// -// The boolean related operators. -// -// Kingcean Tuan -// -------------------------------------------------------------------------------------------------------------------- - -using System; +using System; namespace Trivial.Maths; diff --git a/Core/Maths/Statistics/Average.cs b/Core/Maths/Statistics/Average.cs index d1a5e4fe..f00b98ab 100644 --- a/Core/Maths/Statistics/Average.cs +++ b/Core/Maths/Statistics/Average.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; +using Trivial.Reflection; namespace Trivial.Maths; @@ -476,12 +477,10 @@ public static decimal Mean(IEnumerable col) /// Computes the mode of a sequence of number. /// /// The input collection of number. - /// The count of the mode. /// The mode of the sequence of number. - /// col was null. - public static IEnumerable Mode(IEnumerable col, out int count) + public static IList Mode(IEnumerable col) { - if (col is null) throw new ArgumentNullException(nameof(col), "col should not be null."); + if (col is null) return null; var dict = new Dictionary(); foreach (var item in col) { @@ -490,13 +489,8 @@ public static IEnumerable Mode(IEnumerable col, out int count) } var arr = new List(); - if (dict.Count < 0) - { - count = 0; - return arr; - } - - count = dict.Max(ele => ele.Value); + if (dict.Count < 1) return arr; + var count = dict.Max(ele => ele.Value); foreach (var item in dict) { if (item.Value == count) arr.Add(item.Key); @@ -505,25 +499,22 @@ public static IEnumerable Mode(IEnumerable col, out int count) return arr; } - /// - /// Computes the mode of a sequence of number. - /// - /// The input collection of number. - /// The mode of the sequence of number. - public static IEnumerable Mode(IEnumerable col) - => Mode(col, out _); - /// /// Computes the median of a sequence of number. /// /// The input collection of number. /// A function to extract a key from an element. + /// The default value used when no element. /// The count of the median numbers. - /// The median of the sequence of number. - /// col was null. - public static TSource Median(IEnumerable col, Func keySelector, out int count) + /// The median of the sequence of number; or the defaultValue, if no element, in this case count is zero (0). + public static TSource Median(IEnumerable col, Func keySelector, TSource defaultValue, out int count) { - if (col is null) throw new ArgumentNullException(nameof(col), "col should not be null."); + if (col is null) + { + count = 0; + return defaultValue; + } + var list = col.Where(ele => ele is not null).OrderBy(keySelector).ToList(); var i = 0; var j = list.Count - 1; @@ -539,6 +530,16 @@ public static TSource Median(IEnumerable col, Func + /// Computes the median of a sequence of number. + /// + /// The input collection of number. + /// A function to extract a key from an element. + /// The count of the median numbers. + /// The median of the sequence of number; or the default value, if no element, in this case count is zero (0). + public static TSource Median(IEnumerable col, Func keySelector, out int count) + => Median(col, keySelector, default, out count); + /// /// Computes the median of a sequence of number. /// @@ -547,17 +548,20 @@ public static TSource Median(IEnumerable col, FuncThe median of the sequence of number. /// col was null. public static TSource Median(IEnumerable col, Func keySelector) - => Median(col, keySelector, out _); + { + var v = Median(col, keySelector, default, out var count); + if (count < 0) throw ObjectConvert.ArgumentNull(nameof(col)); + return v; + } /// /// Computes the median of a sequence of number. /// /// The input collection of number. /// The count of the median numbers. - /// The median of the sequence of number. - /// col was null. + /// The median of the sequence of number; or the default value, if no element, in this case count is zero (0). public static T Median(IEnumerable col, out int count) - => Median(col, ele => ele, out count); + => Median(col, ele => ele, default, out count); /// /// Computes the median of a sequence of number. @@ -566,5 +570,5 @@ public static T Median(IEnumerable col, out int count) /// The median of the sequence of number. /// col was null. public static T Median(IEnumerable col) - => Median(col, ele => ele, out _); + => Median(col, ele => ele); } diff --git a/Core/Reflection/Objects/ObjectConvert.cs b/Core/Reflection/Objects/ObjectConvert.cs index 6cc56ba1..af834b05 100644 --- a/Core/Reflection/Objects/ObjectConvert.cs +++ b/Core/Reflection/Objects/ObjectConvert.cs @@ -901,6 +901,9 @@ public static IEnumerable TryReadHexString(string hex) } } + internal static ArgumentNullException ArgumentNull(string paramName) + => new(paramName, string.Concat(paramName, " should not be null.")); + internal static bool Equals(T a, T b) where T : IEquatable { if (ReferenceEquals(a, b)) return true; diff --git a/Core/Security/Token/JsonWebToken.cs b/Core/Security/Token/JsonWebToken.cs index f2f6016e..f790ccab 100644 --- a/Core/Security/Token/JsonWebToken.cs +++ b/Core/Security/Token/JsonWebToken.cs @@ -6,6 +6,7 @@ using System.Text; using System.Text.Json.Serialization; +using Trivial.Reflection; using Trivial.Text; using Trivial.Web; @@ -275,7 +276,7 @@ private void Refresh() /// Verify failure. public static JsonWebToken Parse(string jwt, Func algorithmFactory, bool verify = true) { - if (string.IsNullOrWhiteSpace(jwt)) throw new ArgumentNullException(nameof(jwt), "jwt should not be null or empty."); + if (string.IsNullOrWhiteSpace(jwt)) throw ObjectConvert.ArgumentNull(nameof(jwt)); var prefix = $"{TokenInfo.BearerTokenType} "; if (jwt.IndexOf(prefix) == 0) { @@ -300,7 +301,7 @@ public static JsonWebToken Parse(string jwt, Func 0) throw new ArgumentNullException(nameof(algorithm), "algorithm should not be null."); + if (sign.Length > 0) throw ObjectConvert.ArgumentNull(nameof(algorithm)); } } @@ -327,7 +328,7 @@ public static JsonWebToken Parse(string jwt, FuncVerify failure. public static JsonWebToken Parse(string jwt, ISignatureProvider algorithm, bool verify = true) { - if (string.IsNullOrWhiteSpace(jwt)) throw new ArgumentNullException(nameof(jwt), "jwt should not be null or empty."); + if (string.IsNullOrWhiteSpace(jwt)) throw ObjectConvert.ArgumentNull(nameof(jwt)); var prefix = $"{TokenInfo.BearerTokenType} "; if (jwt.IndexOf(prefix) == 0) { @@ -347,7 +348,7 @@ public static JsonWebToken Parse(string jwt, ISignatureProvider algorithm, bo } else { - if (sign.Length > 0) throw new ArgumentNullException(nameof(algorithm), "algorithm should not be null."); + if (sign.Length > 0) throw ObjectConvert.ArgumentNull(nameof(algorithm)); } } @@ -378,7 +379,7 @@ public static JsonWebToken Parse(string jwt, ISignatureProvider algorithm, bo /// Verify failure. public static JsonWebToken Parse(TokenInfo token, Func algorithmFactory, bool verify = true) { - if (token == null) throw new ArgumentNullException(nameof(token), "token should not be null."); + if (token == null) throw ObjectConvert.ArgumentNull(nameof(token)); if (string.IsNullOrWhiteSpace(token.AccessToken)) throw new ArgumentException("The access token should not be null or empty.", nameof(token)); if (!string.IsNullOrEmpty(token.TokenType) && token.TokenType != TokenInfo.BearerTokenType) throw new ArgumentException("The token type should be Bearer.", nameof(token)); try @@ -407,7 +408,7 @@ public static JsonWebToken Parse(TokenInfo token, FuncVerify failure. public static JsonWebToken Parse(TokenInfo token, ISignatureProvider algorithm, bool verify = true) { - if (token == null) throw new ArgumentNullException(nameof(token), "token should not be null."); + if (token == null) throw ObjectConvert.ArgumentNull(nameof(token)); if (string.IsNullOrWhiteSpace(token.AccessToken)) throw new ArgumentException("The access token should not be null or empty.", nameof(token)); if (!string.IsNullOrEmpty(token.TokenType) && token.TokenType != TokenInfo.BearerTokenType) throw new ArgumentException("The token type should be Bearer.", nameof(token)); try diff --git a/Core/Security/Token/OAuth.cs b/Core/Security/Token/OAuth.cs index ecdd119e..5371a48b 100644 --- a/Core/Security/Token/OAuth.cs +++ b/Core/Security/Token/OAuth.cs @@ -16,6 +16,7 @@ using Trivial.Data; using Trivial.Net; +using Trivial.Reflection; using Trivial.Text; namespace Trivial.Security; @@ -284,7 +285,7 @@ public TokenRequest CreateTokenRequest(T body, IEnumerable scope = /// The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. public virtual Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken = default) { - if (request == null) throw new ArgumentNullException(nameof(request), "request should not be null"); + if (request == null) throw ObjectConvert.ArgumentNull(nameof(request)); var client = CreateHttpClient(); WriteAuthenticationHeaderValue(request.Headers); Sending?.Invoke(this, new SendingEventArgs(request)); @@ -302,7 +303,7 @@ public virtual Task SendAsync(HttpRequestMessage request, C /// The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. public virtual Task SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken = default) { - if (request == null) throw new ArgumentNullException(nameof(request), "request should not be null"); + if (request == null) throw ObjectConvert.ArgumentNull(nameof(request)); var client = CreateHttpClient(); WriteAuthenticationHeaderValue(request.Headers); Sending?.Invoke(this, new SendingEventArgs(request)); @@ -527,8 +528,8 @@ public async Task ResolveTokenAsync(TokenRequestBody content, Func ResolveTokenAsync(Uri requestUri, TokenRequestBody content, CancellationToken cancellationToken = default) { var uri = requestUri ?? TokenResolverUri; - if (uri == null) throw new ArgumentNullException(nameof(uri), "requestUri should not be null."); - if (content == null) throw new ArgumentNullException(nameof(content), "content should not be null."); + if (uri == null) throw ObjectConvert.ArgumentNull(nameof(uri)); + if (content == null) throw ObjectConvert.ArgumentNull(nameof(content)); var c = new TokenRequest(content, appInfo, Scope); var q = c.ToQueryData(); if (TokenRequestInfoValidator != null && !TokenRequestInfoValidator(q)) throw new InvalidOperationException("Cannot pass the request because it is not valid."); @@ -550,8 +551,8 @@ public Task ResolveTokenAsync(Uri requestUri, TokenRequestBody conten public Task ResolveTokenAsync(string requestUri, TokenRequestBody content, CancellationToken cancellationToken = default) { var uri = requestUri ?? TokenResolverUri?.OriginalString; - if (string.IsNullOrWhiteSpace(uri)) throw new ArgumentNullException(nameof(uri), "requestUri should not be null."); - if (content == null) throw new ArgumentNullException(nameof(content), "content should not be null."); + if (string.IsNullOrWhiteSpace(uri)) throw ObjectConvert.ArgumentNull(nameof(uri)); + if (content == null) throw ObjectConvert.ArgumentNull(nameof(content)); var c = new TokenRequest(content, appInfo, Scope); var q = c.ToQueryData(); if (TokenRequestInfoValidator != null && !TokenRequestInfoValidator(q)) throw new InvalidOperationException("Cannot pass the request because it is not valid."); @@ -574,8 +575,8 @@ public Task ResolveTokenAsync(string requestUri, TokenRequestBody con public Task ResolveTokenAsync(Uri requestUri, TokenRequestBody content, CancellationToken cancellationToken = default) where T : TokenInfo { var uri = requestUri ?? TokenResolverUri; - if (uri == null) throw new ArgumentNullException(nameof(uri), "requestUri should not be null."); - if (content == null) throw new ArgumentNullException(nameof(content), "content should not be null."); + if (uri == null) throw ObjectConvert.ArgumentNull(nameof(uri)); + if (content == null) throw ObjectConvert.ArgumentNull(nameof(content)); var c = new TokenRequest(content, appInfo, Scope); var q = c.ToQueryData(); if (TokenRequestInfoValidator != null && !TokenRequestInfoValidator(q)) throw new InvalidOperationException("Cannot pass the request because it is not valid."); @@ -598,8 +599,8 @@ public Task ResolveTokenAsync(Uri requestUri, TokenRequestBody content, Ca public Task ResolveTokenAsync(string requestUri, TokenRequestBody content, CancellationToken cancellationToken = default) where T : TokenInfo { var uri = requestUri ?? TokenResolverUri?.OriginalString; - if (string.IsNullOrWhiteSpace(uri)) throw new ArgumentNullException(nameof(uri), "requestUri should not be null."); - if (content == null) throw new ArgumentNullException(nameof(content), "content should not be null."); + if (string.IsNullOrWhiteSpace(uri)) throw ObjectConvert.ArgumentNull(nameof(uri)); + if (content == null) throw ObjectConvert.ArgumentNull(nameof(content)); var c = new TokenRequest(content, appInfo, Scope); var q = c.ToQueryData(); if (TokenRequestInfoValidator != null && !TokenRequestInfoValidator(q)) throw new InvalidOperationException("Cannot pass the request because it is not valid."); diff --git a/Core/Text/Json/ArrayNode.cs b/Core/Text/Json/ArrayNode.cs index 19bfe8d3..ef4db1f5 100644 --- a/Core/Text/Json/ArrayNode.cs +++ b/Core/Text/Json/ArrayNode.cs @@ -2674,7 +2674,7 @@ public void SetBase64(int index, Span bytes, Base64FormattingOptions optio { if (store.Count == index) AddItem(JsonValues.Null); #if NETFRAMEWORK - if (bytes == null) throw new ArgumentNullException(nameof(bytes), "bytes should not be null."); + if (bytes == null) throw ObjectConvert.ArgumentNull(nameof(bytes)); SetItem(index, Convert.ToBase64String(bytes.ToArray(), options)); #else SetItem(index, Convert.ToBase64String(bytes, options)); @@ -2982,7 +2982,7 @@ public IEnumerable Select(Func selector) /// public IEnumerable Select(Func selector) { - if (selector == null) throw new ArgumentNullException(nameof(selector), "selector was null."); + if (selector == null) throw ObjectConvert.ArgumentNull(nameof(selector)); var index = -1; foreach (var value in store) { @@ -3206,7 +3206,7 @@ public void AddBase64(byte[] inArray, Base64FormattingOptions options = Base64Fo public void AddBase64(Span bytes, Base64FormattingOptions options = Base64FormattingOptions.None) { #if NETFRAMEWORK - if (bytes == null) throw new ArgumentNullException(nameof(bytes), "bytes should not be null."); + if (bytes == null) throw ObjectConvert.ArgumentNull(nameof(bytes)); AddItem(new JsonStringNode(Convert.ToBase64String(bytes.ToArray(), options))); #else AddItem(new JsonStringNode(Convert.ToBase64String(bytes, options))); @@ -3685,7 +3685,7 @@ public void InsertBase64(int index, byte[] inArray, Base64FormattingOptions opti public void InsertBase64(int index, Span bytes, Base64FormattingOptions options = Base64FormattingOptions.None) { #if NETFRAMEWORK - if (bytes == null) throw new ArgumentNullException(nameof(bytes), "bytes should not be null."); + if (bytes == null) throw ObjectConvert.ArgumentNull(nameof(bytes)); InsertItem(index, new JsonStringNode(Convert.ToBase64String(bytes.ToArray(), options))); #else InsertItem(index, new JsonStringNode(Convert.ToBase64String(bytes, options))); @@ -4157,7 +4157,7 @@ public IEnumerable Where(JsonValueKind kind, Funcpredicate is null. public IEnumerable Where(Func predicate) { - if (predicate == null) throw new ArgumentNullException(nameof(predicate), "predicate was null."); + if (predicate == null) throw ObjectConvert.ArgumentNull(nameof(predicate)); var index = -1; foreach (var value in store) { diff --git a/Core/Text/Json/ObjectNode.cs b/Core/Text/Json/ObjectNode.cs index e040ff28..71310529 100644 --- a/Core/Text/Json/ObjectNode.cs +++ b/Core/Text/Json/ObjectNode.cs @@ -4542,7 +4542,7 @@ public void SetValueIfNotEmpty(string key, ICollection value) public void SetValue(string key, IEnumerable value, Func converter) { AssertKey(key); - if (converter == null) throw new ArgumentNullException(nameof(converter), "converter was null."); + if (converter == null) throw ObjectConvert.ArgumentNull(nameof(converter)); var arr = new JsonArrayNode(); foreach (var item in value) { @@ -7579,7 +7579,7 @@ public void WriteTo(string path, IndentStyles style = IndentStyles.Minified) /// Write failed because of unauthorized access exception. public void WriteTo(FileInfo file, IndentStyles style = IndentStyles.Minified) { - if (file == null) throw new ArgumentNullException(nameof(file), "file should not be null."); + if (file == null) throw ObjectConvert.ArgumentNull(nameof(file)); File.WriteAllText(file.FullName, ToString(style) ?? "null"); file.Refresh(); } @@ -8015,7 +8015,7 @@ public IDictionary> GetJsonValueKindGroups() /// public IEnumerable Select(Func selector) { - if (selector == null) throw new ArgumentNullException(nameof(selector), "selector was null."); + if (selector == null) throw ObjectConvert.ArgumentNull(nameof(selector)); foreach (var item in store) { var value = item.Value; @@ -8031,7 +8031,7 @@ public IEnumerable Select(Func selector) /// public JsonObjectNode Where(Func predicate) { - if (predicate == null) throw new ArgumentNullException(nameof(predicate), "predicate was null."); + if (predicate == null) throw ObjectConvert.ArgumentNull(nameof(predicate)); var json = new JsonObjectNode(); var i = -1; foreach (var item in store) diff --git a/UnitTest/Maths/ArithmeticTest.cs b/UnitTest/Maths/ArithmeticTest.cs index 8d76c7e9..a127be92 100644 --- a/UnitTest/Maths/ArithmeticTest.cs +++ b/UnitTest/Maths/ArithmeticTest.cs @@ -295,12 +295,17 @@ public void TestFormula() Assert.IsTrue(c[1]); Assert.IsFalse(c[2]); Assert.IsTrue(c[3]); - c = BooleanOperations.Calculate(BinaryBooleanOperator.Nor, [true, false, true, true], [false, false, false], true).ToList(); + c = BooleanOperations.Calculate(BinaryBooleanOperator.Or, [false, false, false], [true, false, true, true], true).ToList(); Assert.AreEqual(4, c.Count); - Assert.IsFalse(c[0]); - Assert.IsTrue(c[1]); - Assert.IsFalse(c[2]); - Assert.IsFalse(c[3]); + Assert.IsTrue(c[0]); + Assert.IsFalse(c[1]); + Assert.IsTrue(c[2]); + Assert.IsTrue(c[3]); + c = BooleanOperations.Calculate(BinaryBooleanOperator.Xor, [false], [true]).ToList(); + Assert.AreEqual(1, c.Count); + Assert.IsTrue(c[0]); + c = BooleanOperations.Calculate(BinaryBooleanOperator.Xnor, [], []).ToList(); + Assert.AreEqual(0, c.Count); var col = new List() { diff --git a/UnitTest/Net/HttpClientUnitTest.cs b/UnitTest/Net/HttpClientUnitTest.cs index 1a652532..02fa9942 100644 --- a/UnitTest/Net/HttpClientUnitTest.cs +++ b/UnitTest/Net/HttpClientUnitTest.cs @@ -82,7 +82,7 @@ public void TestServerSentEvent() sse = ServerSentEventInfo.Parse(s).ToList(); Assert.AreEqual(3, sse.Count); using var stream = new MemoryStream(); - sse.ToResponseString(stream); + sse.WriteTo(stream); stream.Seek(0, SeekOrigin.Begin); sse = ServerSentEventInfo.Parse(stream).ToList(); Assert.AreEqual(3, sse.Count);