├── .editorconfig
├── .gitattributes
├── .gitignore
├── LICENSE.md
├── NStandard.Analyzer
├── MeasureGenerator.cs
└── NStandard.Analyzer.csproj
├── NStandard.Caching
└── NStandard.Caching.csproj
├── NStandard.Compress
├── NStandard.Compress.csproj
├── ZipStream.StaticDataSource.cs
├── ZipStream.UpdateScope.cs
└── ZipStream.cs
├── NStandard.Debug
├── NStandard.Debug.csproj
└── ObjectExtensions.cs
├── NStandard.Dev
├── AnyDev.Func.cs
├── BitStream.cs
├── ConvertEx.Base32Converter.cs
├── Data
│ └── Mathematics
│ │ ├── IMathFunction.cs
│ │ ├── MathBinary.cs
│ │ ├── MathConstant.cs
│ │ ├── MathLambda.cs
│ │ ├── MathNodeType.cs
│ │ └── MathSqrt.cs
├── Obsolete
│ ├── Evaluator.cs
│ ├── NowOffsetScope.cs
│ ├── NowOffsetScopeAccessor.cs
│ ├── NowScope.cs
│ ├── NowScopeAccessor.cs
│ ├── NumericalEvaluator.cs
│ ├── NumericalRTEvaluator.cs
│ └── Reference
│ │ ├── GAC.cs
│ │ └── GACFolders.cs
├── Threading
│ ├── Cron.cs
│ ├── CronFieldType.cs
│ └── Scheduler.cs
└── [NoRelease] NStandard.Dev.csproj
├── NStandard.Diagnostics
├── Concurrency.cs
├── NStandard.Diagnostics.csproj
├── TestId.cs
├── TestReport.cs
└── TestResult.cs
├── NStandard.Encoding
├── EncodingEx.cs
└── NStandard.Encoding.csproj
├── NStandard.Json.Net
├── Converters
│ ├── DateOnlyConverter.cs
│ ├── IPAddressConverter.cs
│ ├── LazyConverter.cs
│ ├── PhysicalAddressConverter.cs
│ └── VariantConverter.cs
├── NStandard.Json.Net.csproj
└── README.md
├── NStandard.Json
├── Converters
│ ├── DateOnlyConverter.cs
│ ├── IPAddressConverter.cs
│ ├── LazyConverter.cs
│ ├── NetDoubleConverter.cs
│ ├── NetSingleConverter.cs
│ ├── PhysicalAddressConverter.cs
│ └── VariantConverter.cs
├── NStandard.Json.csproj
└── README.md
├── NStandard.Runtime
├── AssemblyContext.cs
├── DotNetFramework.cs
├── NStandard.Runtime.csproj
└── SdkType.cs
├── NStandard.Trees
├── AvlTree.cs
├── BinaryNodeType.cs
├── NStandard.Trees.csproj
└── OldTree.cs
├── NStandard.Windows
├── Doc2Code.tt
├── Doc2Code.txt
├── NStandard - Backup.Windows.csproj
├── NStandard.Windows.csproj
├── Native
│ ├── Service
│ │ ├── NativeMethods.cs
│ │ ├── SERVICE_DESCRIPTIONW.cs
│ │ ├── ScmRights.cs
│ │ ├── ServiceConfigInfoLevel.cs
│ │ ├── ServiceControls.cs
│ │ ├── ServiceErrorControl.cs
│ │ ├── ServiceRights.cs
│ │ ├── ServiceStartType.cs
│ │ ├── ServiceState.cs
│ │ ├── ServiceStatus.cs
│ │ └── ServiceType.cs
│ └── Types
│ │ └── GenericRights.cs
├── ShellProcess.cs
└── WindowsService.cs
├── NStandard.lutconfig
├── NStandard.sln
├── NStandard
├── !Any
│ ├── Any.Chain.cs
│ ├── Any.Compose.cs
│ ├── Any.Flat.cs
│ ├── Any.Forward.cs
│ ├── Any.ReDim.cs
│ ├── Any.Struct.cs
│ ├── Any.Text.cs
│ ├── Any.Zip.cs
│ ├── Any.Zip.tt
│ └── Any.cs
├── !Design
│ ├── ISliceCount.cs
│ └── ISliceLength.cs
├── !DotNet
│ └── System
│ │ ├── Collections
│ │ ├── IStructuralComparable.cs
│ │ └── IStructuralEquatable.cs
│ │ ├── FormattableString.cs
│ │ ├── HashCode.cs
│ │ ├── Reflection
│ │ └── CustomAttributeExtensions.cs
│ │ ├── Runtime
│ │ └── CompilerServices
│ │ │ ├── FormattableStringFactory.cs
│ │ │ └── ITuple.cs
│ │ ├── SR - partial.cs
│ │ ├── Security
│ │ └── Cryptography
│ │ │ ├── HashAlgorithmName.cs
│ │ │ ├── Oids.cs
│ │ │ ├── RSAEncryptionPadding.cs
│ │ │ ├── RSAEncryptionPaddingMode.cs
│ │ │ ├── RSASignaturePadding.cs
│ │ │ └── RSASignaturePaddingMode.cs
│ │ └── Tuple.cs
├── !Extensions
│ ├── AppDomainExtensions.cs
│ ├── ArrayExtensions - Jagged - ToMultiple.cs
│ ├── ArrayExtensions - Jagged.cs
│ ├── ArrayExtensions - Multiple - ToJagged.cs
│ ├── ArrayExtensions.Deconstruct.cs
│ ├── ArrayExtensions.Deconstruct.tt
│ ├── ArrayExtensions.Each.cs
│ ├── ArrayExtensions.IndexOf.cs
│ ├── ArrayExtensions.Let.cs
│ ├── ArrayExtensions.Locate.cs
│ ├── ArrayExtensions.Select.cs
│ ├── ArrayExtensions.String.cs
│ ├── ArrayExtensions.cs
│ ├── CharExtensions.cs
│ ├── DateOnlyExtensions.cs
│ ├── DateTimeExtensions.cs
│ ├── DateTimeOffsetExtensions.cs
│ ├── DelegateExtensions.cs
│ ├── EnumExtensions.cs
│ ├── FuncExtensions.cs
│ ├── IDisposeableExtension.cs
│ ├── Int32Extensions.cs
│ ├── Int64Extensions.cs
│ ├── ObjectExtensions.cs
│ ├── SpanExtensions.cs
│ ├── SpanExtensions.tt
│ ├── StringExtensions.cs
│ ├── System.Collections
│ │ ├── Generic
│ │ │ └── LinkedListExtensions.cs
│ │ └── IEnumerableExtensions.cs
│ ├── System.Drawing
│ │ └── ColorExtensions.cs
│ ├── System.IO
│ │ ├── Compression
│ │ │ └── ZipFileExtensions.cs
│ │ └── StreamExtensions.cs
│ ├── System.Net
│ │ └── IPAddressExtensions.cs
│ ├── System.Text
│ │ ├── Json
│ │ │ └── JsonElementExtensions.cs
│ │ └── StringBuilderExtensions.cs
│ ├── System.Threading.Tasks
│ │ └── TaskExtensions.cs
│ ├── SystemReflection
│ │ ├── AssemblyExtensions.cs
│ │ ├── EventInfoExtensions.cs
│ │ ├── ICustomAttributeProviderExtensions.cs
│ │ └── PropertyInfoExtensions.cs
│ ├── TimeOnlyExtensions.cs
│ ├── TypeExtensions.cs
│ ├── UInt32Extensions.cs
│ └── UInt64Extensions.cs
├── !Static
│ ├── ArrayEx.cs
│ ├── BitConverterEx.cs
│ ├── Collections
│ │ └── Generic
│ │ │ └── EnumerableEx.cs
│ ├── ConvertEx.Base58Converter.cs
│ ├── ConvertEx.cs
│ ├── DateOnlyEx.cs
│ ├── DateTimeEx.cs
│ ├── DateTimeOffsetEx.cs
│ ├── Drawing
│ │ └── ColorEx.cs
│ ├── EnumEx.cs
│ ├── GuidEx.cs
│ ├── Linq
│ │ └── Expressions
│ │ │ └── ExpressionExtensions.cs
│ ├── MathEx.Ceiling.cs
│ ├── MathEx.Ceiling.tt
│ ├── MathEx.Combin.cs
│ ├── MathEx.Combin.tt
│ ├── MathEx.Floor.cs
│ ├── MathEx.Floor.tt
│ ├── MathEx.Permut.cs
│ ├── MathEx.Permut.tt
│ ├── MathEx.cs
│ ├── Net
│ │ └── IPAddressEx.cs
│ ├── ObjectEx.cs
│ ├── RangeEx.cs
│ ├── Reflection
│ │ └── MethodInfoEx.cs
│ ├── StringEx.cs
│ └── TypeEx.cs
├── !internal
│ ├── ArrayMapper.cs
│ ├── BitOperations.cs
│ ├── ExceptionResource.cs
│ ├── Flater.cs
│ └── IndicesStepper.cs
├── Algorithm
│ ├── PatternSearcher.cs
│ ├── SnowflakeWorker.cs
│ └── SnowflakeWorker128.cs
├── Caching
│ ├── !Delegates.cs
│ ├── Cache.cs
│ └── CacheSet.cs
├── ChainOrigin.cs
├── Collections
│ ├── ArrayVisitor.cs
│ ├── Counter.cs
│ ├── FixedSizeQueue.cs
│ ├── HashMap.cs
│ ├── Interval.cs
│ ├── Sequence.cs
│ ├── Sliding.cs
│ └── SlidingMode.cs
├── ConsoleContext.cs
├── Converts
│ ├── BytesConvert.cs
│ └── StringConvert.cs
├── Data
│ ├── DataFrame.cs
│ ├── Fraction.cs
│ ├── Moment.cs
│ └── MomentType.cs
├── DataBinding
│ ├── IDiff.cs
│ └── ValueDiff.cs
├── DateMode.cs
├── DateOnlyType.cs
├── DateTimeType.cs
├── Design
│ └── ObsoleteMessage.cs
├── Discards.cs
├── DpContainer.cs
├── Drawing
│ └── RgbaColor.cs
├── Dynamic.cs
├── EnumOption.cs
├── Evaluators
│ ├── Bracket.cs
│ ├── Evaluator.cs
│ ├── Node.cs
│ ├── NodeType.cs
│ └── NumericalEvaluator.cs
├── Flows
│ ├── BytesFlow.cs
│ ├── GuidFlow.cs
│ ├── HashFlow.cs
│ ├── IPAddressFlow.cs
│ ├── NumberFlow.cs
│ └── StringFlow.cs
├── FuncDelegates.cs
├── IO
│ └── SequenceInputStream.cs
├── ISingleton.cs
├── Infrastructure
│ └── ChainIterator.cs
├── Linq
│ └── DependencyCollector.cs
├── Lock.cs
├── Locks
│ ├── InstanceLockParser.cs
│ └── TypeLockParser.cs
├── Measures
│ ├── IMeasurable.cs
│ ├── IMeasureConvertible.cs
│ ├── IMeasureExtensions.cs
│ └── MeasureAttribute.cs
├── MinMaxPair.cs
├── NStandard.csproj
├── Native.cs
├── Ref.cs
├── Reflection
│ ├── FieldReflector.cs
│ ├── MethodReflector.cs
│ ├── PropertyReflector.cs
│ ├── Reflector.cs
│ ├── TypeFieldReflector.cs
│ ├── TypeMethodReflector.cs
│ ├── TypePropertyReflector.cs
│ └── TypeReflector.cs
├── ResourceAccessor.cs
├── Schema
│ ├── Loop.cs
│ └── LoopFor.cs
├── Scope.cs
├── Security
│ ├── !Asymmetric
│ │ ├── !internal
│ │ │ ├── PemNode.cs
│ │ │ └── RsaConverter.cs
│ │ └── RsaProvider.cs
│ ├── !Hash
│ │ ├── Md5Hasher.cs
│ │ └── Sha1Hasher.cs
│ └── !Symmetric
│ │ ├── AesCipher.cs
│ │ ├── AesProvider.cs
│ │ ├── DesCipher.cs
│ │ ├── DesProvider.cs
│ │ ├── SymmetricCipher.cs
│ │ ├── SymmetricProvider.cs
│ │ ├── TripleDesCipher.cs
│ │ └── TripleDesProvider.cs
├── Snowflake.cs
├── State.cs
├── StructTuple.cs
├── StructTuple.tt
├── Text
│ └── Json
│ │ ├── Converters
│ │ ├── JsonAsConverter.cs
│ │ ├── JsonImplConverter.cs
│ │ └── JsonValueConverter.cs
│ │ ├── IJsonValue.cs
│ │ ├── JsonAsAttribute.cs
│ │ ├── JsonImplAttribute.cs
│ │ ├── JsonValueAttribute.cs
│ │ └── JsonXmlSerializer.cs
├── TimePointValue.cs
├── Trees
│ ├── BinaryTree.cs
│ ├── IBinaryTree.cs
│ ├── ITreeVisitable.cs
│ ├── Tree.cs
│ └── TreeNode.cs
├── UnitValues
│ ├── ISummable.cs
│ ├── IUnitValue.cs
│ └── IUnitValueExtensions.cs
├── Usable.cs
├── Usings.cs
├── Val.cs
├── ValueTuples
│ └── IndexAndValue.cs
├── Variant.cs
└── YearWeekPair.cs
├── README.md
├── README.zh.md
├── Tests
├── NStandard.NET45.Test
│ ├── FormattableStringTests.cs
│ ├── HashCodeTests.cs
│ ├── IntervalTests.cs
│ ├── NStandard.NET45.Test.csproj
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── TupleTests.cs
│ └── packages.config
└── NStandard.Test
│ ├── !Extensions
│ ├── !System.Collections
│ │ └── !Generic
│ │ │ └── LinkedListExtensionsTests.cs
│ ├── !System.Net
│ │ └── IPAddressExtensionsTests.cs
│ ├── !System.Reflection
│ │ └── EventInfoExtensionsTests.cs
│ ├── !System.Threading
│ │ └── !Tasks
│ │ │ └── TaskExtensionsTests.cs
│ ├── AppDomainExtensionsTests.cs
│ ├── ArrayExtensionsTests.cs
│ ├── AssemblyExtensionsTests.cs
│ ├── DateTimeExtensionsTests.cs
│ ├── ObjectExtensionsTests.cs
│ ├── StringExtensionsTests.cs
│ └── TypeExtensionsTests.cs
│ ├── !FeatureTests.cs
│ ├── !Static
│ ├── ArrayExTests.cs
│ ├── Collections
│ │ └── Generic
│ │ │ └── EnumerableExTests.cs
│ ├── ConvertExTests.cs
│ ├── Drawing
│ │ └── ColorExTests.cs
│ ├── EnumExTests.cs
│ ├── GuidEx.cs
│ ├── Linq
│ │ └── Expressions
│ │ │ └── ExpressionExTests.cs
│ ├── MathExTests.cs
│ ├── ObjectExTests.cs
│ ├── RangeExTests.cs
│ ├── Reflection
│ │ └── MethodInfoExTests.cs
│ └── StringExTests.cs
│ ├── !data-structures
│ ├── IntClass.cs
│ └── IntStrcut.cs
│ ├── !extern
│ ├── IEnumerableExtensions.MaxOrDefault.cs
│ ├── IEnumerableExtensions.WhereMax.cs
│ └── IEnumerableExtensions.WhereMin.cs
│ ├── AnyTests.cs
│ ├── ArrayVisitorTests.cs
│ ├── CacheContainerTests.cs
│ ├── CacheTests.cs
│ ├── ChainPropertyTests.cs
│ ├── Collections
│ ├── CounterTests.cs
│ ├── FixedSizeQueueTests.cs
│ ├── HashMapTests.cs
│ ├── IntervalTests.cs
│ └── SequnceTests.cs
│ ├── ConsoleContextTests.cs
│ ├── Data
│ ├── FractionTests.cs
│ ├── MathFunctionTests.cs
│ └── MomentTests.cs
│ ├── DateTimeExTests.cs
│ ├── DpContainerTests - DpCoin.cs
│ ├── DpContainerTests - DpFib.cs
│ ├── DpContainerTests - DpKnapsacks.cs
│ ├── DpContainerTests - DpLIS.cs
│ ├── Drawing
│ └── RgbaColorTests.cs
│ ├── DynamicTests.cs
│ ├── EnumOptionTests.cs
│ ├── Evaluators
│ └── NumberEvaluatorTests.cs
│ ├── Flows
│ ├── GuidFlowTests.cs
│ ├── IPAddressFlowTests.cs
│ └── StringFlowTests.cs
│ ├── IO
│ └── SequenceInputStreamTests.cs
│ ├── ISliceTests.cs
│ ├── Json
│ ├── DateOnlyTests.cs
│ ├── JsonTests.cs
│ ├── NetAddressTests.cs
│ ├── UnderlyingTests.cs
│ └── VariantTests.cs
│ ├── Locks
│ ├── InstanceLockTest.cs
│ └── TypeLockTest.cs
│ ├── Measures
│ ├── LengthTests.cs
│ ├── StorageCapacityTests.cs
│ └── WeightTests.cs
│ ├── NStandard.Test.csproj
│ ├── RefTests.cs
│ ├── Reference
│ └── DotNetFrameworkTests.cs
│ ├── ReflectorTests.cs
│ ├── RuntimeTests.cs
│ ├── Schema
│ ├── LoopForTests.cs
│ └── LoopTests.cs
│ ├── ScopeTests.cs
│ ├── Security
│ └── ProviderTests.cs
│ ├── SingletonTests.cs
│ ├── SlidingTests.cs
│ ├── SnowflakeTests.cs
│ ├── SpanExtensionsTests.cs
│ ├── StateTests.cs
│ ├── StructTupleTests.cs
│ ├── Text
│ └── Json
│ │ ├── JsonImplConverterTests.cs
│ │ └── JsonXmlSerializerTests.cs
│ ├── Threading
│ └── CronTests.cs
│ ├── TimePointValueTests.cs
│ ├── Trees
│ ├── AvlTreeTests.cs
│ ├── BinaryTreeConstructor.cs
│ ├── BinaryTreeTests.cs
│ └── TreeTests.cs
│ ├── UsableTests.cs
│ ├── ValTests.cs
│ └── VariantTests.cs
├── docs
├── cn
│ ├── Any.Chain.md
│ ├── Any.Flat.md
│ ├── Any.Forward.md
│ ├── Any.ReDim.md
│ ├── Any.Zip.md
│ ├── ArrayExtensions.md
│ ├── Compatibility.md
│ ├── DateTimeExtensions.md
│ ├── DpContainer.md
│ ├── Evaluator.md
│ ├── SequenceInputStream.md
│ ├── State.md
│ └── UnitValue.md
├── en
│ ├── Any.Chain.md
│ ├── Any.Flat.md
│ ├── Any.Forward.md
│ ├── Any.ReDim.md
│ ├── Any.Zip.md
│ ├── ArrayExtensions.md
│ ├── Compatibility.md
│ ├── DateTimeExtensions.md
│ ├── DpContainer.md
│ ├── Evaluator.md
│ ├── SequenceInputStream.md
│ ├── State.md
│ └── UnitValue.md
└── images
│ ├── State-001.png
│ ├── State-002.png
│ ├── State-003.png
│ ├── State-004.png
│ ├── State-005.png
│ ├── State-006.png
│ ├── image-20221227131745251.png
│ ├── image-20221227134222183.png
│ └── image-20221227134321883.png
├── nstandard.png
├── push.cmd
└── testEnvironments.json
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 zmjack
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/NStandard.Caching/NStandard.Caching.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | NStandard
6 | DotNet Core extensions for system library.
7 | zmjack
8 | LICENSE.md
9 | https://github.com/zmjack/NStandard
10 | https://github.com/zmjack/NStandard
11 | git
12 | System Standard Extension
13 | 0.5.0
14 | false
15 | nstandard.png
16 | Copyright © nstandard.net 2020
17 | NStandard.Caching
18 |
19 |
20 |
21 |
22 | True
23 |
24 |
25 |
26 | True
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/NStandard.Compress/NStandard.Compress.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | net5.0;net6.0;net7.0;
6 | netstandard2.0;netstandard2.1;
7 | net451;net452;net46;net461;net462;net47;net471;net472;net48;
8 |
9 | preview
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/NStandard.Compress/ZipStream.StaticDataSource.cs:
--------------------------------------------------------------------------------
1 | using ICSharpCode.SharpZipLib.Zip;
2 | using System.IO;
3 |
4 | namespace Dawnx.Compress;
5 |
6 | public partial class ZipStream
7 | {
8 | private class StaticDataSource : IStaticDataSource
9 | {
10 | private readonly Stream StoredStream;
11 |
12 | public StaticDataSource(Stream stream)
13 | {
14 | StoredStream = stream;
15 | }
16 |
17 | public Stream GetSource() => StoredStream;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/NStandard.Compress/ZipStream.UpdateScope.cs:
--------------------------------------------------------------------------------
1 | using NStandard;
2 |
3 | namespace Dawnx.Compress;
4 |
5 | public partial class ZipStream
6 | {
7 | public class UpdateScope : Scope
8 | {
9 | public readonly ZipStream Model;
10 |
11 | public UpdateScope(ZipStream model)
12 | {
13 | Model = model;
14 | Model.ZipFile.BeginUpdate();
15 | }
16 |
17 | public override void Disposing()
18 | {
19 | Model.ZipFile.CommitUpdate();
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/NStandard.Debug/NStandard.Debug.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | preview
6 |
7 |
8 |
9 | none
10 | false
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/NStandard.Dev/Data/Mathematics/IMathFunction.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Data.Mathematics;
2 |
3 | public interface IMathFunction
4 | {
5 | public MathNodeType NodeType { get; }
6 | public string GetText();
7 | }
8 |
--------------------------------------------------------------------------------
/NStandard.Dev/Data/Mathematics/MathBinary.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace NStandard.Data.Mathematics;
4 |
5 | [DebuggerDisplay("{GetText()}")]
6 | public class MathBinary : IMathFunction
7 | {
8 | public MathNodeType NodeType { get; }
9 | public IMathFunction Left { get; }
10 | public IMathFunction Right { get; }
11 |
12 | public static readonly MathNodeType[] ValidNodes = [MathNodeType.Add, MathNodeType.Subtract, MathNodeType.Multiply, MathNodeType.Divide];
13 |
14 | public MathBinary(MathNodeType type, IMathFunction left, IMathFunction right)
15 | {
16 | if (type == MathNodeType.Add) NodeType = MathNodeType.Add;
17 | else if (type == MathNodeType.Subtract) NodeType = MathNodeType.Subtract;
18 | else if (type == MathNodeType.Multiply) NodeType = MathNodeType.Multiply;
19 | else if (type == MathNodeType.Divide) NodeType = MathNodeType.Divide;
20 | else throw new NotImplementedException();
21 |
22 | Left = left;
23 | Right = right;
24 | }
25 |
26 | public string GetText()
27 | {
28 | return NodeType switch
29 | {
30 | MathNodeType.Add => $"{Left.GetText()} + {Right.GetText()}",
31 | MathNodeType.Subtract => $"{Left.GetText()} - {Right.GetText()}",
32 | MathNodeType.Multiply => $"{Left.GetText()} · {Right.GetText()}",
33 | MathNodeType.Divide => $"{Left.GetText()} / {Right.GetText()}",
34 | _ => throw new NotImplementedException(),
35 | };
36 | }
37 |
38 | public override string ToString()
39 | {
40 | return GetText();
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/NStandard.Dev/Data/Mathematics/MathNodeType.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Data.Mathematics;
2 |
3 | public enum MathNodeType
4 | {
5 | None,
6 | Constant,
7 | Lambda,
8 |
9 | Add,
10 | Subtract,
11 | Multiply,
12 | Divide,
13 |
14 | Sqrt,
15 | }
16 |
--------------------------------------------------------------------------------
/NStandard.Dev/Data/Mathematics/MathSqrt.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace NStandard.Data.Mathematics;
4 |
5 | [DebuggerDisplay("{GetText()}")]
6 | public class MathSqrt : IMathFunction
7 | {
8 | public MathNodeType NodeType => MathNodeType.Sqrt;
9 |
10 | public IMathFunction Constant { get; }
11 | public int Value { get; }
12 |
13 | public MathSqrt(IMathFunction constant, int value)
14 | {
15 | Constant = constant;
16 | Value = value;
17 | }
18 |
19 | public static MathBinary operator -(MathSqrt left, IMathFunction right)
20 | {
21 | return new MathBinary(MathNodeType.Subtract, left, right);
22 | }
23 |
24 | public string GetText()
25 | {
26 | if (Value == 2)
27 | {
28 | return $"\\sqrt{{{Constant.GetText()}}}";
29 | }
30 | else
31 | {
32 | return $"\\sqrt[{-Value}]{{{Constant.GetText()}}}";
33 | }
34 | }
35 | public override string ToString()
36 | {
37 | return GetText();
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/NStandard.Dev/Obsolete/NowOffsetScope.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard
2 | {
3 | public class NowOffsetScope : Scope
4 | {
5 | public DateTimeOffset Now;
6 | internal NowOffsetScope() { Now = DateTimeOffset.Now; }
7 | internal NowOffsetScope(Func store) { Now = store(DateTimeOffset.Now); }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/NStandard.Dev/Obsolete/NowOffsetScopeAccessor.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard
2 | {
3 | public class NowOffsetScopeAccessor
4 | {
5 | public static readonly NowOffsetScopeAccessor Instance = new();
6 |
7 | internal NowOffsetScopeAccessor() { }
8 |
9 | public bool HasAnyScope => NowOffsetScope.Scopes.Count > 0;
10 |
11 | public DateTimeOffset Current
12 | {
13 | get
14 | {
15 | var scope = NowOffsetScope.Current;
16 | if (scope is null) throw new InvalidOperationException($"No {nameof(NowOffsetScope)} found.");
17 | return scope.Now;
18 | }
19 | }
20 | public DateTimeOffset? CurrentOrDefault => NowOffsetScope.Current?.Now;
21 |
22 | public DateTimeOffset Outermost
23 | {
24 | get
25 | {
26 | var scope = NowOffsetScope.Scopes.LastOrDefault();
27 | if (scope is null) throw new InvalidOperationException($"No {nameof(NowOffsetScope)} found.");
28 | return scope.Now;
29 | }
30 | }
31 | public DateTimeOffset? OutermostOrDefault => NowOffsetScope.Scopes.LastOrDefault()?.Now;
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/NStandard.Dev/Obsolete/NowScope.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard
2 | {
3 | public class NowScope : Scope
4 | {
5 | public DateTime Now;
6 | internal NowScope() { Now = DateTime.Now; }
7 | internal NowScope(Func store) { Now = store(DateTime.Now); }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/NStandard.Dev/Obsolete/NowScopeAccessor.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard
2 | {
3 | public class NowScopeAccessor
4 | {
5 | public static readonly NowScopeAccessor Instance = new();
6 |
7 | internal NowScopeAccessor() { }
8 |
9 | public bool HasAnyScope => NowScope.Scopes.Count > 0;
10 |
11 | public DateTime Current
12 | {
13 | get
14 | {
15 | var scope = NowScope.Current;
16 | if (scope is null) throw new InvalidOperationException($"No {nameof(NowScope)} found.");
17 | return scope.Now;
18 | }
19 | }
20 | public DateTime? CurrentOrDefault => NowScope.Current?.Now;
21 |
22 | public DateTime Outermost
23 | {
24 | get
25 | {
26 | var scope = NowScope.Scopes.LastOrDefault();
27 | if (scope is null) throw new InvalidOperationException($"No {nameof(NowScope)} found.");
28 | return scope.Now;
29 | }
30 | }
31 | public DateTime? OutermostOrDefault => NowScope.Scopes.LastOrDefault()?.Now;
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/NStandard.Dev/Obsolete/Reference/GACFolders.cs:
--------------------------------------------------------------------------------
1 | #if false
2 | using System;
3 |
4 | namespace NStandard.Reference
5 | {
6 | [Flags]
7 | public enum GACFolders
8 | {
9 | All = Shared | SDK | NuGet | Reserved | Packs,
10 | Shared = 1,
11 | SDK = 2,
12 | NuGet = 4,
13 | Reserved = 8,
14 | Packs = 16,
15 | }
16 | }
17 | #endif
18 |
--------------------------------------------------------------------------------
/NStandard.Dev/Threading/CronFieldType.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Threading
2 | {
3 | public enum CronFieldType
4 | {
5 | Ingore = -1,
6 | Any = 0,
7 | Specified = 1,
8 | Last = 2,
9 | Workday = 3,
10 | LastWorkday = 4,
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/NStandard.Dev/Threading/Scheduler.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 |
3 | namespace NStandard.Threading
4 | {
5 | public abstract class Scheduler
6 | {
7 | public static Thread Thread;
8 | public static bool SigAbort { get; private set; }
9 | public static DateTime LastExecutionTime { get; private set; }
10 |
11 | [MethodImpl(MethodImplOptions.Synchronized)]
12 | public static void Start(TimeSpan interval)
13 | {
14 | SigAbort = false;
15 | if (Thread == null)
16 | {
17 | Thread = new Thread(() =>
18 | {
19 | while (true)
20 | {
21 | if (SigAbort) break;
22 | var now = DateTime.Now;
23 |
24 | LastExecutionTime = now;
25 | Thread.Sleep(interval);
26 | }
27 | Thread = null;
28 | SigAbort = false;
29 | });
30 | Thread.Start();
31 | }
32 | else throw new InvalidOperationException();
33 | }
34 |
35 | public static void Stop() => SigAbort = true;
36 |
37 | public abstract void Task(DateTime now);
38 |
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/NStandard.Dev/[NoRelease] NStandard.Dev.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | NStandard
6 | NStandard.Dev
7 | preview
8 | true
9 | enable
10 | enable
11 |
12 |
13 |
14 | none
15 | false
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/NStandard.Diagnostics/NStandard.Diagnostics.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | net5.0;net6.0;net7.0;
6 | netstandard2.0;netstandard2.1;
7 | net35;net451;net452;net46;net461;net462;net47;net471;net472;net48;
8 |
9 | preview
10 |
11 |
12 |
13 | none
14 | false
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/NStandard.Diagnostics/TestId.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Diagnostics;
2 |
3 | public struct TestId
4 | {
5 | public int ThreadId { get; set; }
6 | public int InvokeNumber { get; set; }
7 |
8 | public TestId(int threadId, int invokeNumber)
9 | {
10 | ThreadId = threadId;
11 | InvokeNumber = invokeNumber;
12 | }
13 |
14 | public override string ToString()
15 | {
16 | return $"Thread:{ThreadId}({InvokeNumber})";
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/NStandard.Diagnostics/TestReport.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 |
4 | namespace NStandard.Diagnostics;
5 |
6 | public class TestReport
7 | {
8 | public TestReport(TestResult[] results)
9 | {
10 | Results = results;
11 | }
12 |
13 | public TimeSpan? AverageElapsed { get; private set; }
14 | public TimeSpan? TotalElapsed { get; private set; }
15 | public TimeSpan? MinElapsed { get; private set; }
16 | public TimeSpan? MaxElapsed { get; private set; }
17 |
18 | private TestResult[] _results;
19 | public TestResult[] Results
20 | {
21 | get => _results;
22 | set
23 | {
24 | _results = value;
25 | var allTicks = value.Where(x => x.Success).Select(x => x.Elapsed.Ticks);
26 | if (allTicks.Any())
27 | {
28 | AverageElapsed = new TimeSpan((long)allTicks.Average());
29 | TotalElapsed = new TimeSpan(allTicks.Sum());
30 | MinElapsed = new TimeSpan(allTicks.Min());
31 | MaxElapsed = new TimeSpan(allTicks.Max());
32 | }
33 | else
34 | {
35 | AverageElapsed = default;
36 | TotalElapsed = default;
37 | MinElapsed = default;
38 | MaxElapsed = default;
39 | }
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/NStandard.Diagnostics/TestResult.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace NStandard.Diagnostics;
4 |
5 | public struct TestResult
6 | {
7 | public int ThreadId { get; set; }
8 | public int InvokeNumber { get; set; }
9 | public bool Success { get; set; }
10 |
11 | public TRet Return { get; set; }
12 | public TimeSpan Elapsed { get; set; }
13 | public Exception Exception { get; set; }
14 |
15 | public override string ToString()
16 | {
17 | return $"{{ Id: {ThreadId}:{InvokeNumber}, Success = {Success}, Elapsed = {Elapsed} }}";
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/NStandard.Encoding/NStandard.Encoding.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | net5.0;net6.0;net7.0;net8.0;
6 | netstandard2.0;netstandard2.1;
7 | net46;net461;net462;net47;net471;net472;net48;
8 |
9 | 0.8.5
10 | preview
11 | NStandard
12 | DotNet Core extensions for system library.
13 | zmjack
14 | LICENSE.md
15 | https://github.com/zmjack/NStandard
16 | https://github.com/zmjack/NStandard
17 | git
18 | System Standard Extension
19 | true
20 | nstandard.png
21 | Copyright © nstandard.net 2020
22 | NStandard.Encoding
23 |
24 |
25 |
26 | none
27 | false
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 | True
37 |
38 |
39 |
40 | True
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/NStandard.Json.Net/Converters/DateOnlyConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 |
4 | namespace NStandard.Json.Net.Converters;
5 |
6 | #if NET6_0_OR_GREATER
7 | public class DateOnlyConverter : JsonConverter
8 | {
9 | public override bool CanConvert(Type objectType) => objectType == typeof(DateOnly) || objectType == typeof(DateOnly?);
10 |
11 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
12 | {
13 | return reader.TokenType switch
14 | {
15 | JsonToken.Null => null,
16 | JsonToken.String => DateOnly.FromDateTime(DateTime.Parse(reader.Value as string).ToLocalTime()),
17 | JsonToken.Date => DateOnly.FromDateTime((DateTime)reader.Value),
18 | _ => throw new NotSupportedException($"{reader.TokenType} is not supported."),
19 | };
20 | }
21 |
22 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
23 | {
24 | var valueType = value.GetType();
25 | if (!CanConvert(valueType)) throw new InvalidOperationException($"The converter specified on '{writer.Path}' is not compatible with the type '{typeof(DateOnly)}'.");
26 | serializer.Serialize(writer, ((DateOnly)value).ToString("O"));
27 | }
28 | }
29 | #endif
30 |
--------------------------------------------------------------------------------
/NStandard.Json.Net/Converters/IPAddressConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Net;
4 |
5 | namespace NStandard.Json.Net.Converters;
6 |
7 | public class IPAddressConverter : JsonConverter
8 | {
9 | public override bool CanConvert(Type objectType) => objectType == typeof(IPAddress);
10 |
11 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
12 | {
13 | return reader.TokenType switch
14 | {
15 | JsonToken.Null => null,
16 | JsonToken.String => IPAddress.Parse(reader.Value as string),
17 | _ => throw new NotSupportedException($"{reader.TokenType} is not supported."),
18 | };
19 | }
20 |
21 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
22 | {
23 | var valueType = value.GetType();
24 | if (!CanConvert(valueType)) throw new InvalidOperationException($"The converter specified on '{writer.Path}' is not compatible with the type '{typeof(IPAddress)}'.");
25 | serializer.Serialize(writer, ((IPAddress)value).ToString());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/NStandard.Json.Net/Converters/PhysicalAddressConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 | using System.Net.NetworkInformation;
4 | using System.Text;
5 |
6 | namespace NStandard.Json.Net.Converters;
7 |
8 | public class PhysicalAddressConverter : JsonConverter
9 | {
10 | public override bool CanConvert(Type objectType) => objectType == typeof(PhysicalAddress);
11 |
12 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
13 | {
14 | return reader.TokenType switch
15 | {
16 | JsonToken.Null => null,
17 | JsonToken.String => PhysicalAddress.Parse(reader.Value as string),
18 | _ => throw new NotSupportedException($"{reader.TokenType} is not supported."),
19 | };
20 | }
21 |
22 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
23 | {
24 | var valueType = value.GetType();
25 | if (!CanConvert(valueType)) throw new InvalidOperationException($"The converter specified on '{writer.Path}' is not compatible with the type '{typeof(PhysicalAddress)}'.");
26 |
27 | var bytes = ((PhysicalAddress)value).GetAddressBytes();
28 | var enumerator = bytes.GetEnumerator();
29 | var sb = new StringBuilder(30);
30 | if (enumerator.MoveNext())
31 | {
32 | sb.Append(((byte)enumerator.Current).ToString("X2"));
33 | while (enumerator.MoveNext())
34 | {
35 | sb.Append('-');
36 | sb.Append(((byte)enumerator.Current).ToString("X2"));
37 | }
38 | }
39 |
40 | serializer.Serialize(writer, sb.ToString());
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/NStandard.Json.Net/Converters/VariantConverter.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using System;
3 |
4 | namespace NStandard.Json.Net.Converters;
5 |
6 | public class VariantConverter : JsonConverter
7 | {
8 | public override bool CanConvert(Type objectType) => objectType.IsType(typeof(Variant));
9 |
10 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
11 | {
12 | return reader.TokenType switch
13 | {
14 | JsonToken.Null => new Variant((string)null),
15 | JsonToken.None => new Variant((string)null),
16 | JsonToken.Undefined => new Variant((string)null),
17 | JsonToken.Integer => new Variant((int)reader.Value),
18 | JsonToken.Float => new Variant((double)reader.Value),
19 | JsonToken.String => new Variant(reader.Value as string),
20 | JsonToken.Boolean => new Variant((bool)reader.Value),
21 | JsonToken.Date => new Variant((DateTime)reader.Value),
22 | _ => throw new NotSupportedException($"{reader.TokenType} is not supported."),
23 | };
24 | }
25 |
26 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
27 | {
28 | var valueType = value.GetType();
29 | if (!CanConvert(valueType)) throw new InvalidOperationException($"The converter specified on '{writer.Path}' is not compatible with the type '{typeof(Variant)}'.");
30 | serializer.Serialize(writer, (value as Variant).ToString());
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/NStandard.Json.Net/NStandard.Json.Net.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | net5.0;net6.0;net7.0;
6 | netstandard2.0;netstandard2.1;
7 | net35;net451;net452;net46;net461;net462;net47;net471;net472;net48;
8 |
9 | preview
10 | zmjack
11 | 0.7.0
12 | nstandard.net
13 |
14 | Json extensions for Newtonsoft.Json.
15 | - Includes built-in type compatibility, such as Lazy, DateOnly, etc.
16 |
17 | Copyright © nstandard.net 2021
18 | LICENSE.md
19 | nstandard.net
20 | nstandard.png
21 | https://github.com/zmjack/NStandard
22 | git
23 | Json Extension
24 | true
25 |
26 |
27 |
28 | none
29 | false
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 | True
39 |
40 |
41 |
42 | True
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/NStandard.Json.Net/README.md:
--------------------------------------------------------------------------------
1 | # NStandard.Json.Net
2 |
3 | **Json** extensions for **Newtonsoft.Json**.
4 |
5 | - Includes built-in type compatibility , such as **Lazy\**.
6 |
7 |
8 |
9 |
10 | ## Built-in compatibility
11 |
12 | **Lazy\** is a commonly used type, but his serialization is not very easy to use.
13 |
14 | For example,
15 |
16 | ```csharp
17 | var lazy = new Lazy(123);
18 | var output = System.Text.Json.JsonSerializer.Serialize(lazy);
19 | ```
20 |
21 | The output is
22 |
23 | ```json
24 | {"IsValueCreated":true,"Value":123}
25 | ```
26 |
27 | We can find that the **IsValueCreated** field is meaningless in **Json**.
28 |
29 |
30 |
31 | So, we hope it can be simplified. Use these code:
32 |
33 | ```csharp
34 | using System.Text.Json;
35 | using NStandard.Json;
36 | ```
37 |
38 | ```csharp
39 | var options = new JsonSerializerOptions();
40 | options.Converters.Add(new LazyConverter());
41 |
42 | // Serialize
43 | var lazy = new Lazy(123);
44 | var output = JsonSerializer.Serialize(lazy, options);
45 | // The output is: 123
46 |
47 | // Deserialize
48 | var backLazy = JsonSerializer.Deserialize>(output, options);
49 | var value = backLazy.Value;
50 | // The value is: 123
51 | ```
52 |
53 |
54 |
55 | ## Use in AspNet Core
56 |
57 | You need to install the **Microsoft.AspNetCore.Mvc.NewtonsoftJson** package first.
58 |
59 | Use the following code to enable the extension in the **AspNet Core** application.
60 |
61 | ```csharp
62 | services
63 | .AddControllersWithViews()
64 | .AddNewtonsoftJson(options =>
65 | {
66 | options.SerializerSettings.Converters.Add(new LazyConverter());
67 | });
68 | ```
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/NStandard.Json/Converters/DateOnlyConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text.Json;
3 | using System.Text.Json.Serialization;
4 |
5 | namespace NStandard.Json.Converters;
6 |
7 | #if NET6_0_OR_GREATER
8 | public class DateOnlyConverter : JsonConverter
9 | {
10 | public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
11 | {
12 | var str = reader.GetString();
13 | var dt = DateTime.Parse(str).ToLocalTime();
14 | return DateOnly.FromDateTime(dt);
15 | }
16 |
17 | public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
18 | {
19 | var isoDate = value.ToString("O");
20 | writer.WriteStringValue(isoDate);
21 | }
22 | }
23 | #endif
24 |
--------------------------------------------------------------------------------
/NStandard.Json/Converters/IPAddressConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net;
3 | using System.Text.Json;
4 | using System.Text.Json.Serialization;
5 |
6 | namespace NStandard.Json.Converters;
7 |
8 | public class IPAddressConverter : JsonConverter
9 | {
10 | public override bool CanConvert(Type objectType) => objectType == typeof(IPAddress);
11 |
12 | public override IPAddress Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
13 | {
14 | var str = reader.GetString();
15 | return IPAddress.Parse(str);
16 | }
17 |
18 | public override void Write(Utf8JsonWriter writer, IPAddress value, JsonSerializerOptions options)
19 | {
20 | writer.WriteStringValue(value.ToString());
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/NStandard.Json/Converters/LazyConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text.Json;
3 | using System.Text.Json.Serialization;
4 |
5 | namespace NStandard.Json.Converters;
6 |
7 | public class LazyConverter : JsonConverterFactory
8 | {
9 | public override bool CanConvert(Type typeToConvert)
10 | {
11 | if (!typeToConvert.IsGenericType) return false;
12 | return typeToConvert.GetGenericTypeDefinition() == typeof(Lazy<>);
13 | }
14 |
15 | public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
16 | {
17 | var wrappedType = typeToConvert.GetGenericArguments()[0];
18 | var converter = (JsonConverter)Activator.CreateInstance(typeof(LazyConverter<>).MakeGenericType(wrappedType));
19 | return converter;
20 | }
21 | }
22 |
23 | public class LazyConverter : JsonConverter>
24 | {
25 | private Lazy CreateLazy(TValue value)
26 | {
27 | var lazy = new Lazy(() => value);
28 | var ret = lazy.Value;
29 | return lazy;
30 | }
31 |
32 | public override bool CanConvert(Type objectType) => objectType == typeof(Lazy);
33 |
34 | public override Lazy Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
35 | {
36 | if (reader.TokenType == JsonTokenType.Null) return null;
37 | var value = JsonSerializer.Deserialize(ref reader, options);
38 | return CreateLazy(value);
39 | }
40 |
41 | public override void Write(Utf8JsonWriter writer, Lazy value, JsonSerializerOptions options)
42 | {
43 | JsonSerializer.Serialize(writer, value.Value, typeof(TValue), options);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/NStandard.Json/Converters/NetDoubleConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text.Json;
3 | using System.Text.Json.Serialization;
4 |
5 | namespace NStandard.Json.Converters;
6 |
7 | public class NetDoubleConverter : JsonConverter
8 | {
9 | public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
10 | {
11 | if (reader.TokenType == JsonTokenType.String)
12 | {
13 | var str = reader.GetString();
14 | return str switch
15 | {
16 | "Infinity" => double.PositiveInfinity,
17 | "-Infinity" => double.NegativeInfinity,
18 | _ => double.NaN,
19 | };
20 | }
21 | return reader.GetDouble();
22 | }
23 |
24 | public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options)
25 | {
26 | if (double.IsNaN(value)) writer.WriteStringValue("NaN");
27 | else if (double.IsPositiveInfinity(value)) writer.WriteStringValue("Infinity");
28 | else if (double.IsNegativeInfinity(value)) writer.WriteStringValue("-Infinity");
29 | else writer.WriteNumberValue(value);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/NStandard.Json/Converters/NetSingleConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text.Json;
3 | using System.Text.Json.Serialization;
4 |
5 | namespace NStandard.Json.Converters;
6 |
7 | public class NetSingleConverter : JsonConverter
8 | {
9 | public override float Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
10 | {
11 | if (reader.TokenType == JsonTokenType.String)
12 | {
13 | var str = reader.GetString();
14 | return str switch
15 | {
16 | "Infinity" => float.PositiveInfinity,
17 | "-Infinity" => float.NegativeInfinity,
18 | _ => float.NaN,
19 | };
20 | }
21 | return reader.GetSingle();
22 | }
23 |
24 | public override void Write(Utf8JsonWriter writer, float value, JsonSerializerOptions options)
25 | {
26 | if (float.IsNaN(value)) writer.WriteStringValue("NaN");
27 | else if (float.IsPositiveInfinity(value)) writer.WriteStringValue("Infinity");
28 | else if (float.IsNegativeInfinity(value)) writer.WriteStringValue("-Infinity");
29 | else writer.WriteNumberValue(value);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/NStandard.Json/Converters/PhysicalAddressConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net.NetworkInformation;
3 | using System.Text;
4 | using System.Text.Json;
5 | using System.Text.Json.Serialization;
6 |
7 | namespace NStandard.Json.Converters;
8 |
9 | public class PhysicalAddressConverter : JsonConverter
10 | {
11 | public override bool CanConvert(Type objectType) => objectType == typeof(PhysicalAddress);
12 |
13 | public override PhysicalAddress Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
14 | {
15 | var str = reader.GetString();
16 | return PhysicalAddress.Parse(str);
17 | }
18 |
19 | public override void Write(Utf8JsonWriter writer, PhysicalAddress value, JsonSerializerOptions options)
20 | {
21 | var bytes = ((PhysicalAddress)value).GetAddressBytes();
22 | var enumerator = bytes.GetEnumerator();
23 | var sb = new StringBuilder(30);
24 | if (enumerator.MoveNext())
25 | {
26 | sb.Append(((byte)enumerator.Current).ToString("X2"));
27 | while (enumerator.MoveNext())
28 | {
29 | sb.Append('-');
30 | sb.Append(((byte)enumerator.Current).ToString("X2"));
31 | }
32 | }
33 |
34 | writer.WriteStringValue(sb.ToString());
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/NStandard.Json/Converters/VariantConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text.Json;
3 | using System.Text.Json.Serialization;
4 |
5 | namespace NStandard.Json.Converters;
6 |
7 | public class VariantConverter : JsonConverter
8 | {
9 | public override bool CanConvert(Type objectType) => objectType.IsType(typeof(Variant));
10 |
11 | public override Variant Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
12 | {
13 | return reader.TokenType switch
14 | {
15 | JsonTokenType.None => new Variant(null as string),
16 | JsonTokenType.Null => new Variant(null as string),
17 | JsonTokenType.String => reader.GetString(),
18 | JsonTokenType.Number => reader.GetDouble(),
19 | JsonTokenType.False => false,
20 | JsonTokenType.True => true,
21 | _ => throw new NotSupportedException($"{reader.TokenType} is not supported."),
22 | };
23 | }
24 |
25 | public override void Write(Utf8JsonWriter writer, Variant value, JsonSerializerOptions options)
26 | {
27 | writer.WriteStringValue(value.ToString());
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/NStandard.Runtime/NStandard.Runtime.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | net5.0;net6.0;net7.0;net8.0;
6 | netstandard2.0;netstandard2.1;
7 |
8 | 1.9.0
9 | preview
10 | true
11 | zmjack
12 | Copyright © nstandard.net 2020
13 | nstandard.net
14 | DotNet extensions for system library.
15 | LICENSE.md
16 | nstandard.net
17 | nstandard.png
18 | https://github.com/zmjack/NStandard
19 | git
20 | System Standard Extension
21 | NStandard.Runtime
22 |
23 |
24 |
25 | none
26 | false
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 | True
40 |
41 |
42 |
43 | True
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/NStandard.Runtime/SdkType.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Runtime;
2 |
3 | public static class SdkType
4 | {
5 | public const string Legacy = "";
6 | public const string Core = "Microsoft.NET.Sdk";
7 | public const string Web = "Microsoft.NET.Sdk.Web";
8 | }
9 |
--------------------------------------------------------------------------------
/NStandard.Trees/BinaryNodeType.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Trees;
2 |
3 | public enum BinaryNodeType
4 | {
5 | LeftNode = -1,
6 | RootNode = 0,
7 | RightNode = 1,
8 | }
9 |
--------------------------------------------------------------------------------
/NStandard.Trees/NStandard.Trees.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | preview
6 | enable
7 |
8 |
9 |
10 | none
11 | false
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/NStandard.Windows/NStandard - Backup.Windows.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | True
6 |
7 |
8 |
9 | none
10 | false
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/NStandard.Windows/NStandard.Windows.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | preview
6 | True
7 | 0.0.1
8 |
9 |
10 |
11 | none
12 | false
13 |
14 |
15 |
16 |
17 | TextTemplatingFileGenerator
18 | Doc2Code.txt
19 |
20 |
21 | True
22 | True
23 | Doc2Code.tt
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/NStandard.Windows/Native/Service/SERVICE_DESCRIPTIONW.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices;
2 |
3 | namespace NStandard.Windows.Native.Service;
4 |
5 | internal struct SERVICE_DESCRIPTIONW
6 | {
7 | [MarshalAs(UnmanagedType.LPWStr)] public string Description;
8 | }
9 |
--------------------------------------------------------------------------------
/NStandard.Windows/Native/Service/ScmRights.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace NStandard.Windows.Native.Service;
4 |
5 | [Flags]
6 | internal enum ScmRights
7 | {
8 | None = 0,
9 | SC_MANAGER_ALL_ACCESS = 0xF003F,
10 | SC_MANAGER_CREATE_SERVICE = 0x0002,
11 | SC_MANAGER_CONNECT = 0x0001,
12 | SC_MANAGER_ENUMERATE_SERVICE = 0x0004,
13 | SC_MANAGER_LOCK = 0x0008,
14 | SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020,
15 | SC_MANAGER_QUERY_LOCK_STATUS = 0x0010,
16 | }
17 |
--------------------------------------------------------------------------------
/NStandard.Windows/Native/Service/ServiceControls.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace NStandard.Windows.Native.Service;
4 |
5 | [Flags]
6 | internal enum ServiceControls : uint
7 | {
8 | SERVICE_CONTROL_CONTINUE = 0x00000003,
9 | SERVICE_CONTROL_INTERROGATE = 0x00000004,
10 | SERVICE_CONTROL_NETBINDADD = 0x00000007,
11 | SERVICE_CONTROL_NETBINDDISABLE = 0x0000000A,
12 | SERVICE_CONTROL_NETBINDENABLE = 0x00000009,
13 | SERVICE_CONTROL_NETBINDREMOVE = 0x00000008,
14 | SERVICE_CONTROL_PARAMCHANGE = 0x00000006,
15 | SERVICE_CONTROL_PAUSE = 0x00000002,
16 | SERVICE_CONTROL_STOP = 0x00000001,
17 | }
18 |
--------------------------------------------------------------------------------
/NStandard.Windows/Native/Service/ServiceErrorControl.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Windows.Native.Service;
2 |
3 | public enum ServiceErrorControl
4 | {
5 | ///
6 | /// The startup program logs the error in the event log, if possible. If the last-known-good configuration is being started, the startup operation fails. Otherwise, the system is restarted with the last-known good configuration.
7 | ///
8 | SERVICE_ERROR_CRITICAL = 0x00000003,
9 |
10 | ///
11 | /// The startup program ignores the error and continues the startup operation.
12 | ///
13 | SERVICE_ERROR_IGNORE = 0x00000000,
14 |
15 | ///
16 | /// The startup program logs the error in the event log but continues the startup operation.
17 | ///
18 | SERVICE_ERROR_NORMAL = 0x00000001,
19 |
20 | ///
21 | /// The startup program logs the error in the event log. If the last-known-good configuration is being started, the startup operation continues. Otherwise, the system is restarted with the last-known-good configuration.
22 | ///
23 | SERVICE_ERROR_SEVERE = 0x00000002,
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/NStandard.Windows/Native/Service/ServiceStartType.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Windows.Native.Service;
2 |
3 | public enum ServiceStartType
4 | {
5 | ///
6 | /// A service started automatically by the service control manager during system startup. For more information, see Automatically Starting Services.
7 | ///
8 | SERVICE_AUTO_START = 0x00000002,
9 |
10 | ///
11 | /// A device driver started by the system loader. This value is valid only for driver services.
12 | ///
13 | SERVICE_BOOT_START = 0x00000000,
14 |
15 | ///
16 | /// A service started by the service control manager when a process calls the StartService function. For more information, see Starting Services on Demand.
17 | ///
18 | SERVICE_DEMAND_START = 0x00000003,
19 |
20 | ///
21 | /// A service that cannot be started. Attempts to start the service result in the error code ERROR_SERVICE_DISABLED.
22 | ///
23 | SERVICE_DISABLED = 0x00000004,
24 |
25 | ///
26 | /// A device driver started by the IoInitSystem function. This value is valid only for driver services.
27 | ///
28 | SERVICE_SYSTEM_START = 0x00000001,
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/NStandard.Windows/Native/Service/ServiceState.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Windows.Native.Service;
2 |
3 | internal enum ServiceState : int
4 | {
5 | SERVICE_STOPPED = 0x00000001,
6 | SERVICE_START_PENDING = 0x00000002,
7 | SERVICE_STOP_PENDING = 0x00000003,
8 | SERVICE_RUNNING = 0x00000004,
9 | SERVICE_CONTINUE_PENDING = 0x00000005,
10 | SERVICE_PAUSE_PENDING = 0x00000006,
11 | SERVICE_PAUSED = 0x00000007,
12 | }
13 |
--------------------------------------------------------------------------------
/NStandard.Windows/Native/Service/ServiceStatus.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices;
2 |
3 | namespace NStandard.Windows.Native.Service;
4 |
5 | [StructLayout(LayoutKind.Sequential)]
6 | internal struct ServiceStatus
7 | {
8 | public uint dwServiceType;
9 | public ServiceState dwCurrentState;
10 | public uint dwControlsAccepted;
11 | public uint dwWin32ExitCode;
12 | public uint dwServiceSpecificExitCode;
13 | public uint dwCheckPoint;
14 | public uint dwWaitHint;
15 | }
16 |
--------------------------------------------------------------------------------
/NStandard.Windows/Native/Service/ServiceType.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Windows.Native.Service;
2 |
3 | internal enum ServiceType
4 | {
5 | ///
6 | /// Reserved.
7 | ///
8 | SERVICE_ADAPTER = 0x00000004,
9 |
10 | ///
11 | /// File system driver service.
12 | ///
13 | SERVICE_FILE_SYSTEM_DRIVER = 0x00000002,
14 |
15 | ///
16 | /// Driver service.
17 | ///
18 | SERVICE_KERNEL_DRIVER = 0x00000001,
19 |
20 | ///
21 | /// Reserved.
22 | ///
23 | SERVICE_RECOGNIZER_DRIVER = 0x00000008,
24 |
25 | ///
26 | /// Service that runs in its own process.
27 | ///
28 | SERVICE_WIN32_OWN_PROCESS = 0x00000010,
29 |
30 | ///
31 | /// Service that shares a process with one or more other services. For more information, see Service Programs.
32 | ///
33 | SERVICE_WIN32_SHARE_PROCESS = 0x00000020,
34 | }
35 |
--------------------------------------------------------------------------------
/NStandard.Windows/Native/Types/GenericRights.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace NStandard.Windows.Native.Types;
4 |
5 | [Flags]
6 | internal enum GenericRights : uint
7 | {
8 | GENERIC_READ = 0x80000000,
9 | GENERIC_WRITE = 0x40000000,
10 | GENERIC_EXECUTE = 0x20000000,
11 | GENERIC_ALL = 0x10000000,
12 | }
13 |
--------------------------------------------------------------------------------
/NStandard.lutconfig:
--------------------------------------------------------------------------------
1 |
2 |
3 | true
4 | true
5 | 180000
6 |
--------------------------------------------------------------------------------
/NStandard/!Any/Any.Compose.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public static partial class Any
4 | {
5 | ///
6 | /// Takes two functions and returns a function.
7 | ///
8 | ///
9 | public static Func Compose(Func pipe)
10 | {
11 | return x => pipe(x);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/NStandard/!Any/Any.Forward.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public static partial class Any
4 | {
5 | ///
6 | /// Computes the element by path and returns the element.
7 | ///
8 | ///
9 | ///
10 | ///
11 | ///
12 | public static IEnumerable Forward(T seed, Func forward) where T : class
13 | {
14 | T current = seed;
15 | while (true)
16 | {
17 | if (current is null) break;
18 | yield return current;
19 | current = forward(current);
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/NStandard/!Any/Any.ReDim.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 |
3 | namespace NStandard;
4 |
5 | public static partial class Any
6 | {
7 | private static ArgumentException Exception_IncompatibleRank(string paramName) => new("The lengths can not be incompatible with the array.", paramName);
8 | private static ArgumentException Exception_VariableMustBeArray(string paramName) => new($"The {paramName} must be an array.", paramName);
9 |
10 | ///
11 | /// Reallocates storage space for an array variable.
12 | ///
13 | ///
14 | ///
15 | ///
16 | ///
17 | public static void ReDim(ref TArray variable, params int[] lengths) where TArray : class, ICollection, IEnumerable, IList, ICloneable
18 | {
19 | var type = variable.GetType();
20 | if (!type.IsArray) throw Exception_VariableMustBeArray(nameof(variable));
21 |
22 | var origin = (variable as Array)!;
23 | if (lengths.Length != origin.Rank) throw Exception_IncompatibleRank(nameof(lengths));
24 |
25 | var elementType = type.GetElementType()!;
26 | var newArray = Array.CreateInstance(elementType, lengths);
27 | var originLengths = origin.GetLengths();
28 |
29 | var stepper = new IndicesStepper(0, Zip(originLengths, lengths).Select(pair => Math.Min(pair.Item1, pair.Item2)).ToArray());
30 | foreach (var indices in stepper)
31 | {
32 | newArray.SetValue(origin.GetValue(indices), indices);
33 | }
34 | variable = (newArray as TArray)!;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/NStandard/!Any/Any.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public static partial class Any
4 | {
5 | ///
6 | /// Creates a instance by the specified function.
7 | ///
8 | ///
9 | ///
10 | ///
11 | public static T Create(Func func) => func();
12 |
13 | ///
14 | /// Swaps the values of two instances.
15 | ///
16 | ///
17 | ///
18 | ///
19 | public static void Swap(ref T a, ref T b)
20 | {
21 | var tmp = a;
22 | a = b;
23 | b = tmp;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/NStandard/!Design/ISliceCount.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public interface ISliceCount
4 | {
5 | int Count { get; }
6 | TRet Slice(int start, int length);
7 | }
8 |
--------------------------------------------------------------------------------
/NStandard/!Design/ISliceLength.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public interface ISliceLength
4 | {
5 | int Length { get; }
6 | TRet Slice(int start, int length);
7 | }
8 |
--------------------------------------------------------------------------------
/NStandard/!DotNet/System/Collections/IStructuralComparable.cs:
--------------------------------------------------------------------------------
1 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER
2 | #else
3 | // Licensed to the .NET Foundation under one or more agreements.
4 | // The .NET Foundation licenses this file to you under the MIT license.
5 | // See the LICENSE file in the project root for more information.
6 |
7 | namespace System.Collections;
8 |
9 | public interface IStructuralComparable
10 | {
11 | int CompareTo(object other, IComparer comparer);
12 | }
13 | #endif
14 |
--------------------------------------------------------------------------------
/NStandard/!DotNet/System/Collections/IStructuralEquatable.cs:
--------------------------------------------------------------------------------
1 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER
2 | #else
3 | // Licensed to the .NET Foundation under one or more agreements.
4 | // The .NET Foundation licenses this file to you under the MIT license.
5 | // See the LICENSE file in the project root for more information.
6 |
7 | namespace System.Collections;
8 |
9 | public interface IStructuralEquatable
10 | {
11 | bool Equals(object other, IEqualityComparer comparer);
12 | int GetHashCode(IEqualityComparer comparer);
13 | }
14 | #endif
15 |
--------------------------------------------------------------------------------
/NStandard/!DotNet/System/Runtime/CompilerServices/ITuple.cs:
--------------------------------------------------------------------------------
1 | #if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || NET471_OR_GREATER
2 | #else
3 | // Licensed to the .NET Foundation under one or more agreements.
4 | // The .NET Foundation licenses this file to you under the MIT license.
5 | // See the LICENSE file in the project root for more information.
6 |
7 | namespace System.Runtime.CompilerServices;
8 |
9 | ///
10 | /// This interface is required for types that want to be indexed into by dynamic patterns.
11 | ///
12 | public interface ITuple
13 | {
14 | ///
15 | /// The number of positions in this data structure.
16 | ///
17 | int Length { get; }
18 |
19 | ///
20 | /// Get the element at position .
21 | ///
22 | object? this[int index] { get; }
23 | }
24 | #endif
25 |
--------------------------------------------------------------------------------
/NStandard/!DotNet/System/SR - partial.cs:
--------------------------------------------------------------------------------
1 | namespace System;
2 |
3 | internal static class SR
4 | {
5 | #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
6 | #else
7 | internal static string Format(string resourceFormat, object p1) => string.Format(resourceFormat, p1);
8 | internal static string Format(string resourceFormat, object p1, object p2) => string.Format(resourceFormat, p1, p2);
9 | #endif
10 |
11 | #if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
12 | #else
13 | internal static string @HashCode_HashCodeNotSupported => "HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.";
14 | internal static string @HashCode_EqualityNotSupported => "HashCode is a mutable struct and should not be compared with other HashCodes.";
15 | #endif
16 |
17 | #if NET5_0_OR_GREATER || NETSTANDARD2_0_OR_GREATER || NET40_OR_GREATER
18 | #else
19 | internal static string @ArgumentException_TupleIncorrectType => "Argument must be of type {0}.";
20 | internal static string @ArgumentException_TupleLastArgumentNotATuple => "The last element of an eight element tuple must be a Tuple.";
21 | internal static string @Argument_EnumTypeDoesNotMatch => "The argument type, '{0}', is not the same as the enum type '{1}'.";
22 | #endif
23 |
24 | #if NET5_0_OR_GREATER || NETSTANDARD2_0_OR_GREATER || NET46_OR_GREATER
25 | #else
26 | internal static string @Cryptography_HashAlgorithmNameNullOrEmpty => "The hash algorithm name cannot be null or empty.";
27 | internal static string @Cryptography_InvalidHashAlgorithmOid => "The specified OID ({0}) does not represent a known hash algorithm.";
28 |
29 | internal static string @ArgumentOutOfRange_Range => @"Valid values are between {0} and {1}, inclusive.";
30 | #endif
31 | }
32 |
--------------------------------------------------------------------------------
/NStandard/!DotNet/System/Security/Cryptography/RSAEncryptionPaddingMode.cs:
--------------------------------------------------------------------------------
1 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_3_OR_GREATER || NET46_OR_GREATER
2 | #else
3 | // Licensed to the .NET Foundation under one or more agreements.
4 | // The .NET Foundation licenses this file to you under the MIT license.
5 |
6 | namespace System.Security.Cryptography;
7 |
8 | ///
9 | /// Specifies the padding mode to use with RSA encryption or decryption operations.
10 | ///
11 | public enum RSAEncryptionPaddingMode
12 | {
13 | ///
14 | /// PKCS #1 v1.5.
15 | ///
16 | ///
17 | /// This mode corresponds to the RSAES-PKCS1-v1_5 encryption scheme described in the PKCS #1 RSA Encryption Standard.
18 | /// It is supported for compatibility with existing applications.
19 | ///
20 | Pkcs1,
21 |
22 | ///
23 | /// Optimal Asymmetric Encryption Padding.
24 | ///
25 | ///
26 | /// This mode corresponds to the RSAES-OEAP encryption scheme described in the PKCS #1 RSA Encryption Standard.
27 | /// It is recommended for new applications.
28 | ///
29 | Oaep,
30 | }
31 | #endif
32 |
--------------------------------------------------------------------------------
/NStandard/!DotNet/System/Security/Cryptography/RSASignaturePaddingMode.cs:
--------------------------------------------------------------------------------
1 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_3_OR_GREATER || NET46_OR_GREATER
2 | #else
3 | // Licensed to the .NET Foundation under one or more agreements.
4 | // The .NET Foundation licenses this file to you under the MIT license.
5 |
6 | namespace System.Security.Cryptography;
7 |
8 | ///
9 | /// Specifies the padding mode to use with RSA signature creation or verification operations.
10 | ///
11 | public enum RSASignaturePaddingMode
12 | {
13 | ///
14 | /// PKCS #1 v1.5.
15 | ///
16 | ///
17 | /// This corresponds to the RSASSA-PKCS1-v1.5 signature scheme of the PKCS #1 RSA Encryption Standard.
18 | /// It is supported for compatibility with existing applications.
19 | ///
20 | Pkcs1,
21 |
22 | ///
23 | /// Probabilistic Signature Scheme.
24 | ///
25 | ///
26 | /// This corresponds to the RSASSA-PKCS1-v1.5 signature scheme of the PKCS #1 RSA Encryption Standard.
27 | /// It is recommended for new applications.
28 | ///
29 | Pss,
30 | }
31 | #endif
32 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/AppDomainExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using System.Reflection;
3 |
4 | namespace NStandard;
5 |
6 | [EditorBrowsable(EditorBrowsableState.Never)]
7 | public static class AppDomainExtensions
8 | {
9 | //TODO: Long-term Maintenance
10 | public static Assembly? GetCoreLibAssembly(this AppDomain @this)
11 | {
12 | var assemblies = @this.GetAssemblies();
13 | foreach (var assembly in assemblies)
14 | {
15 | switch (assembly.GetName().Name)
16 | {
17 | // "System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"
18 | // "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
19 | case "System.Private.CoreLib":
20 | case "mscorlib": return assembly;
21 | }
22 | }
23 | return null;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/ArrayExtensions.String.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public static partial class ArrayExtensions
4 | {
5 | }
6 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/CharExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | [EditorBrowsable(EditorBrowsableState.Never)]
6 | public static class CharExtensions
7 | {
8 | ///
9 | /// Gets the length of the specified char as Ascii.
10 | ///
11 | ///
12 | ///
13 | public static int GetLengthA(this char @this) => @this < 0x100 ? 1 : 2;
14 |
15 | ///
16 | /// Converts the value of a Unicode character to its lowercase equivalent.
17 | ///
18 | ///
19 | ///
20 | public static char ToLower(this char @this) => char.ToLower(@this);
21 |
22 | ///
23 | /// Converts the value of a Unicode character to its uppercase equivalent.
24 | ///
25 | ///
26 | ///
27 | public static char ToUpper(this char @this) => char.ToUpper(@this);
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/DelegateExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using System.Linq.Expressions;
3 |
4 | namespace NStandard;
5 |
6 | [EditorBrowsable(EditorBrowsableState.Never)]
7 | public static class DelegateExtensions
8 | {
9 | ///
10 | /// Convert a function to its higher-order form.
11 | ///
12 | ///
13 | ///
14 | ///
15 | ///
16 | public static Func Higher(this Func @this, int degree)
17 | {
18 | var parameter = Expression.Parameter(typeof(TSelf), "Param_0");
19 | var func = Expression.Constant(@this);
20 | Expression higher = parameter;
21 | for (int i = 0; i < degree; i++)
22 | higher = Expression.Invoke(func, higher);
23 | var lambda = Expression.Lambda>(higher, parameter);
24 | return lambda.Compile();
25 | }
26 |
27 | ///
28 | /// Convert a function to its higher-order form.
29 | ///
30 | ///
31 | ///
32 | ///
33 | ///
34 | public static UnaryFunc Higher(this UnaryFunc @this, int degree)
35 | {
36 | var parameter = Expression.Parameter(typeof(TSelf), "Param_0");
37 | var func = Expression.Constant(@this);
38 | Expression higher = parameter;
39 | for (int i = 0; i < degree; i++)
40 | higher = Expression.Invoke(func, higher);
41 | var lambda = Expression.Lambda>(higher, parameter);
42 | return lambda.Compile();
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/EnumExtensions.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Static;
2 | using System.ComponentModel;
3 | using System.Reflection;
4 |
5 | namespace NStandard;
6 |
7 | [EditorBrowsable(EditorBrowsableState.Never)]
8 | public static class EnumExtensions
9 | {
10 | public static long ToInt64(this Enum @this) => (long)Convert.ChangeType(@this, typeof(long));
11 |
12 | public static T[] GetFlags(this T @this) where T : Enum
13 | {
14 | return EnumEx.GetFlags().Where(x => @this.HasFlag(x)).ToArray();
15 | }
16 |
17 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER
18 | #else
19 | public static bool HasFlag(this Enum @this, Enum flag)
20 | {
21 | if (flag == null) throw new ArgumentNullException(nameof(flag));
22 |
23 | if (@this.GetType() != flag.GetType())
24 | {
25 | throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), @this.GetType()));
26 | }
27 |
28 | return (ToInt64(@this) & ToInt64(flag)) > 0;
29 | }
30 | #endif
31 |
32 | ///
33 | /// Get the attribute of enum.
34 | ///
35 | public static TAttribute? GetAttribute(this Enum enumValue) where TAttribute : Attribute
36 | {
37 | return enumValue
38 | .GetType()
39 | .GetMember(enumValue.ToString())
40 | .FirstOrDefault()?
41 | .GetCustomAttribute();
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/FuncExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | [EditorBrowsable(EditorBrowsableState.Never)]
6 | public static class FuncExtensions
7 | {
8 | ///
9 | /// Takes two functions and returns a function.
10 | ///
11 | ///
12 | ///
13 | ///
14 | public static Func Compose(this Func @this, Func pipe)
15 | {
16 | return x => pipe(@this(x));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/IDisposeableExtension.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | [EditorBrowsable(EditorBrowsableState.Never)]
6 | public static class IDisposableExtension
7 | {
8 | public static void DisposeAll(this T[] @this) where T : IDisposable
9 | {
10 | foreach (var item in @this)
11 | {
12 | item.Dispose();
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/Int32Extensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | [EditorBrowsable(EditorBrowsableState.Never)]
6 | public static class Int32Extensions
7 | {
8 | ///
9 | /// Returns whether the specified number is odd.
10 | ///
11 | ///
12 | ///
13 | public static bool IsOdd(this int @this) => (@this & 1) == 1;
14 |
15 | ///
16 | /// Returns whether the specified number is even.
17 | ///
18 | ///
19 | ///
20 | public static bool IsEven(this int @this) => (@this & 1) == 0;
21 |
22 | ///
23 | /// Gets the positive integer modulus. (Unlike the operator %, this method always returns a positive number)
24 | ///
25 | ///
26 | ///
27 | ///
28 | public static int Mod(this int @this, int mod)
29 | {
30 | if (@this < 0)
31 | return @this % mod + mod;
32 | else return @this % mod;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/Int64Extensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | [EditorBrowsable(EditorBrowsableState.Never)]
6 | public static class Int64Extensions
7 | {
8 | ///
9 | /// Returns whether the specified number is odd.
10 | ///
11 | ///
12 | ///
13 | public static bool IsOdd(this long @this) => (@this & 1) == 1;
14 |
15 | ///
16 | /// Returns whether the specified number is even.
17 | ///
18 | ///
19 | ///
20 | public static bool IsEven(this long @this) => (@this & 1) == 0;
21 |
22 | ///
23 | /// Gets the positive integer modulus. (Unlike the operator %, this method always returns a positive number)
24 | ///
25 | ///
26 | ///
27 | ///
28 | public static long Mod(this long @this, long mod)
29 | {
30 | if (@this < 0)
31 | return @this % mod + mod;
32 | else return @this % mod;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/System.Collections/Generic/LinkedListExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | [EditorBrowsable(EditorBrowsableState.Never)]
6 | public static class LinkedListExtensions
7 | {
8 | public static IEnumerable> GetNodes(this LinkedList @this)
9 | {
10 | for (var node = @this.First; node != null; node = node.Next)
11 | {
12 | yield return node;
13 | }
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/System.Drawing/ColorExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using System.Drawing;
3 |
4 | namespace NStandard;
5 |
6 | [EditorBrowsable(EditorBrowsableState.Never)]
7 | public static class ColorExtensions
8 | {
9 | public static float GetHueOfHsv(this Color @this) => @this.GetHue();
10 |
11 | public static float GetSaturationOfHsv(this Color @this)
12 | {
13 | var rgb = new[] { @this.R, @this.G, @this.B };
14 | double min = rgb.Min();
15 | double max = rgb.Max();
16 |
17 | if (max == 0) return 0;
18 | else return (float)((max - min) / max);
19 | }
20 |
21 | public static float GetValueOfHsv(this Color @this)
22 | {
23 | var rgb = new[] { @this.R, @this.G, @this.B };
24 | double max = rgb.Max();
25 | return (float)(max / 255);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/System.IO/StreamExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | [EditorBrowsable(EditorBrowsableState.Never)]
6 | public static class StreamExtensions
7 | {
8 | public delegate void ReadingHandler(byte[] buffer, int readLength);
9 | public delegate void WritingHandler(Stream toStream, byte[] buffer, int totalWrittenLength);
10 |
11 | public static void Scan(this Stream @this, int bufferSize, ReadingHandler handler)
12 | {
13 | var buffer = new byte[bufferSize];
14 | int readLength;
15 | while ((readLength = @this.Read(buffer, 0, bufferSize)) > 0)
16 | {
17 | handler(buffer, readLength);
18 | }
19 | }
20 |
21 | public static void ScanAndWriteTo(this Stream @this, Stream writeTarget, int bufferSize)
22 | {
23 | int totalWritten = 0;
24 | Scan(@this, bufferSize, (buffer, readLength) =>
25 | {
26 | writeTarget.Write(buffer, 0, readLength);
27 | totalWritten += readLength;
28 | });
29 | }
30 |
31 | public static void ScanAndWriteTo(this Stream @this, Stream writeTarget, int bufferSize, WritingHandler handler)
32 | {
33 | int totalWritten = 0;
34 | Scan(@this, bufferSize, (buffer, readLength) =>
35 | {
36 | writeTarget.Write(buffer, 0, readLength);
37 | totalWritten += readLength;
38 | handler(writeTarget, buffer, totalWritten);
39 | });
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/System.Net/IPAddressExtensions.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Static;
2 | using System.ComponentModel;
3 | using System.Net;
4 |
5 | namespace NStandard;
6 |
7 | [EditorBrowsable(EditorBrowsableState.Never)]
8 | public static class IPAddressExtensions
9 | {
10 | public static uint ToUInt32(this IPAddress @this)
11 | {
12 | var bytes = @this.GetAddressBytes();
13 | if (bytes.Length != 4) throw new InvalidCastException("The length of IPAddress must be 32 bits.");
14 |
15 | Array.Reverse(bytes);
16 | return BitConverter.ToUInt32(bytes, 0);
17 | }
18 |
19 | #if NET7_0_OR_GREATER
20 | public static UInt128 ToUInt128(this IPAddress @this)
21 | {
22 | var bytes = @this.GetAddressBytes();
23 | if (bytes.Length != 16) throw new InvalidCastException("The length of IPAddress must be 128 bits.");
24 |
25 | Array.Reverse(bytes);
26 | return BitConverterEx.ToUInt128(bytes, 0);
27 | }
28 | #endif
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/System.Text/Json/JsonElementExtensions.cs:
--------------------------------------------------------------------------------
1 | #if NET5_0
2 | using System;
3 | using System.Buffers;
4 | using System.Text.Json;
5 |
6 | namespace NStandard;
7 |
8 | public static class JsonElementExtensions
9 | {
10 | public static T? Deserialize(this JsonElement @this, JsonSerializerOptions? options = null)
11 | {
12 | var bufferWriter = new ArrayBufferWriter();
13 | using (var writer = new Utf8JsonWriter(bufferWriter))
14 | {
15 | @this.WriteTo(writer);
16 | }
17 | return JsonSerializer.Deserialize(bufferWriter.WrittenSpan, options)!;
18 | }
19 |
20 | public static object? Deserialize(this JsonElement @this, Type returnType, JsonSerializerOptions? options = null)
21 | {
22 | var bufferWriter = new ArrayBufferWriter();
23 | using (var writer = new Utf8JsonWriter(bufferWriter))
24 | {
25 | @this.WriteTo(writer);
26 | }
27 | return JsonSerializer.Deserialize(bufferWriter.WrittenSpan, returnType, options)!;
28 | }
29 | }
30 | #endif
31 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/System.Text/StringBuilderExtensions.cs:
--------------------------------------------------------------------------------
1 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER
2 | #else
3 | using System.ComponentModel;
4 | using System.Text;
5 |
6 | namespace NStandard;
7 |
8 | [EditorBrowsable(EditorBrowsableState.Never)]
9 | public static class StringBuilderExtensions
10 | {
11 | public static void Clear(this StringBuilder @this)
12 | {
13 | @this.Length = 0;
14 | }
15 | }
16 | #endif
17 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/System.Threading.Tasks/TaskExtensions.cs:
--------------------------------------------------------------------------------
1 | #if NET5_0_OR_GREATER || NETSTANDARD2_0_OR_GREATER || NET40_OR_GREATER
2 | using System;
3 | using System.ComponentModel;
4 | using System.Threading.Tasks;
5 |
6 | namespace NStandard;
7 |
8 | [EditorBrowsable(EditorBrowsableState.Never)]
9 | public static class TaskExtensions
10 | {
11 | public static void Catch(this Task @this, Action onException)
12 | {
13 | try { @this.Wait(); }
14 | catch (Exception ex) { onException(ex); }
15 | }
16 |
17 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER
18 | public static async Task CatchAsync(this Task @this, Action onException)
19 | {
20 | await Task.Run(() =>
21 | {
22 | try { @this.Wait(); }
23 | catch (Exception ex) { onException(ex); }
24 | });
25 | }
26 | #else
27 | public static Task CatchAsync(this Task @this, Action onException)
28 | {
29 | return Task.Factory.StartNew(() =>
30 | {
31 | try { @this.Wait(); }
32 | catch (Exception ex) { onException(ex); }
33 | });
34 | }
35 | #endif
36 |
37 | }
38 | #endif
39 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/SystemReflection/EventInfoExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using System.Reflection;
3 |
4 | namespace NStandard;
5 |
6 | [EditorBrowsable(EditorBrowsableState.Never)]
7 | public static class EventInfoExtensions
8 | {
9 | public static void AddEventHandler(this EventInfo @this, object declaringObject, MethodInfo method)
10 | {
11 | @this.AddEventHandler(declaringObject, Delegate.CreateDelegate(@this.EventHandlerType!, method));
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/SystemReflection/ICustomAttributeProviderExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using System.Reflection;
3 |
4 | namespace NStandard;
5 |
6 | [EditorBrowsable(EditorBrowsableState.Never)]
7 | public static class ICustomAttributeProviderExtensions
8 | {
9 | public static bool HasAttribute(this ICustomAttributeProvider @this, bool inherit = true) where TAttribute : Attribute
10 | {
11 | return @this.GetCustomAttributes(typeof(TAttribute), inherit).Any();
12 | }
13 |
14 | public static bool HasAttribute(this ICustomAttributeProvider @this, Type attribute, bool inherit = true)
15 | {
16 | return @this.GetCustomAttributes(attribute, inherit).Any();
17 | }
18 |
19 | public static Attribute[] GetAttributesViaName(this ICustomAttributeProvider @this, string fullName, bool inherit = true)
20 | {
21 | return @this.GetCustomAttributes(inherit).Where(x => x.GetType().FullName == fullName).OfType().ToArray();
22 | }
23 |
24 | public static Attribute? GetAttributeViaName(this ICustomAttributeProvider @this, string fullName, bool inherit = true)
25 | {
26 | return @this.GetCustomAttributes(inherit).Where(x => x.GetType().FullName == fullName).FirstOrDefault() as Attribute;
27 | }
28 |
29 | public static bool HasAttributeViaName(this ICustomAttributeProvider @this, string fullName, bool inherit = true)
30 | {
31 | return @this.GetCustomAttributes(inherit).Where(x => x.GetType().FullName == fullName).Any();
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/SystemReflection/PropertyInfoExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using System.Reflection;
3 |
4 | namespace NStandard;
5 |
6 | [EditorBrowsable(EditorBrowsableState.Never)]
7 | public static class PropertyInfoExtensions
8 | {
9 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER
10 | #else
11 | public static object GetValue(this PropertyInfo @this, object obj) => @this.GetValue(obj, null);
12 | public static void SetValue(this PropertyInfo @this, object obj, object value) => @this.SetValue(obj, value, null);
13 | #endif
14 | }
15 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/UInt32Extensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | [EditorBrowsable(EditorBrowsableState.Never)]
6 | public static class UInt32Extensions
7 | {
8 | ///
9 | /// Gets the positive integer modulus. (Unlike the operator %, this method always returns a positive number)
10 | ///
11 | ///
12 | ///
13 | ///
14 | public static uint Mod(this uint @this, uint mod)
15 | {
16 | if (@this < 0)
17 | return @this % mod + mod;
18 | else return @this % mod;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/NStandard/!Extensions/UInt64Extensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | [EditorBrowsable(EditorBrowsableState.Never)]
6 | public static class UInt64Extensions
7 | {
8 | ///
9 | /// Gets the positive integer modulus. (Unlike the operator %, this method always returns a positive number)
10 | ///
11 | ///
12 | ///
13 | ///
14 | public static ulong Mod(this ulong @this, ulong mod)
15 | {
16 | if (@this < 0)
17 | return @this % mod + mod;
18 | else return @this % mod;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/NStandard/!Static/Collections/Generic/EnumerableEx.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Static.Collections.Generic;
2 |
3 | public static class EnumerableEx
4 | {
5 | public static IEnumerable Concat(IEnumerable> enumerables)
6 | {
7 | foreach (var enumerable in enumerables)
8 | foreach (var item in enumerable)
9 | yield return item;
10 | }
11 |
12 | public static IEnumerable Concat(params IEnumerable[] enumerables)
13 | {
14 | foreach (var enumerable in enumerables)
15 | foreach (var item in enumerable)
16 | yield return item;
17 | }
18 |
19 | public static IEnumerable Create(int count, Func generate)
20 | {
21 | for (int i = 0; i < count; i++)
22 | yield return generate(i);
23 | }
24 |
25 | public static IEnumerable Create(T start, Func generate, Func condition)
26 | {
27 | int i = 0;
28 | for (T item = start; condition(item, i); item = generate(item))
29 | {
30 | yield return item;
31 | i++;
32 | }
33 | }
34 |
35 | public static IEnumerable CreateFromLinked(TSelf @this, Func selector)
36 | {
37 | var select = @this;
38 | while (select is not null)
39 | {
40 | yield return select;
41 | select = selector(select);
42 | }
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/NStandard/!Static/ConvertEx.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Static;
2 |
3 | public static partial class ConvertEx
4 | {
5 | ///
6 | /// Returns an object of the specified type and whose value is equivalent to the specified object.
7 | /// (Enhance: Support Nullable types.)
8 | ///
9 | /// An object that implements the System.IConvertible interface.
10 | /// The type of object to return.
11 | public static object? ChangeType(object value, Type conversionType)
12 | {
13 | if (conversionType.IsNullableValue())
14 | {
15 | if (value is null) return null;
16 | else return Convert.ChangeType(value, conversionType.GetGenericArguments()[0]);
17 | }
18 | else
19 | {
20 | if (value is null) return conversionType.CreateDefault();
21 | else return Convert.ChangeType(value, conversionType);
22 | }
23 | }
24 |
25 | public static string ToBase58String(byte[] bytes) => Base58Converter.ToBase58String(bytes);
26 | public static byte[] FromBase58String(string str) => Base58Converter.FromBase58String(str);
27 |
28 | //TODO: Functions are being designed.
29 | //public static string ToBase32String(byte[] bytes) => Base32Converter.ToBase32String(bytes);
30 | //public static byte[] FromBase32String(string str) => Base32Converter.FromBase32String(str);
31 | }
32 |
--------------------------------------------------------------------------------
/NStandard/!Static/GuidEx.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Static;
2 |
3 | public static class GuidEx
4 | {
5 | public const string EmptyString = "00000000-0000-0000-0000-000000000000";
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/NStandard/!Static/Linq/Expressions/ExpressionExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Linq.Expressions;
2 | using System.Reflection;
3 |
4 | namespace NStandard.Static.Linq.Expressions;
5 |
6 | public static class ExpressionEx
7 | {
8 | ///
9 | /// Get setter expression.
10 | ///
11 | public static Expression> GetSetterExpression(Expression> expression)
12 | {
13 | if (expression.Body is MemberExpression member)
14 | {
15 | var property = (PropertyInfo)member.Member;
16 | var setMethod = property.GetSetMethod() ?? throw new NotSupportedException($"SetMethod not found. ({expression})");
17 | var param = Expression.Parameter(typeof(T), "x");
18 | var prop = Expression.Parameter(typeof(TProperty), "p");
19 | var setter =
20 | Expression.Lambda>(
21 | Expression.Call(param, setMethod, prop),
22 | param,
23 | prop
24 | );
25 | return setter;
26 | }
27 | else throw new NotSupportedException("Only MemberExpression is supported.");
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/NStandard/!Static/MathEx.Permut.tt:
--------------------------------------------------------------------------------
1 | <#@ template debug="false" hostspecific="false" language="C#" #>
2 | <#@ assembly name="System.Core" #>
3 | <#@ import namespace="System.Linq" #>
4 | <#@ import namespace="System.Text" #>
5 | <#@ import namespace="System.Collections.Generic" #>
6 | <#@ output extension=".cs" #>
7 | //
8 | using System;
9 |
10 | namespace NStandard.Static;
11 |
12 | public static partial class MathEx
13 | {
14 | <#=Code("int")#>
15 |
16 | <#=Code("long")#>
17 | }
18 |
19 | <#+
20 | private string Code(string type)
21 | {
22 | return $"""
23 | ///
24 | /// Returns the number of permutations for a given number of items that can be selected.
25 | ///
26 | /// The number of items.
27 | /// The number of items in each permutation.
28 | ///
29 | public static {type} Permut({type} number, {type} chosen)
30 | {"{"}
31 | if (chosen < 0) throw new ArgumentException("The choice must be greater than zero.", nameof(chosen));
32 | if (number < chosen) throw new ArgumentException("The total must be greater than or equal to the choice.", nameof(chosen));
33 |
34 | {type} ret = 1;
35 | checked
36 | {"{"}
37 | for ({type} i = number; i > number - chosen; i--)
38 | {"{"}
39 | ret *= i;
40 | {"}"}
41 | {"}"}
42 | return ret;
43 | {"}"}
44 | """;
45 | }
46 | #>
47 |
--------------------------------------------------------------------------------
/NStandard/!Static/Net/IPAddressEx.cs:
--------------------------------------------------------------------------------
1 | using System.Net;
2 |
3 | namespace NStandard.Static.Net;
4 |
5 | public static class IPAddressEx
6 | {
7 | public static IPAddress Create(uint value)
8 | {
9 | var bytes = BitConverter.GetBytes(value);
10 | Array.Reverse(bytes);
11 | return new IPAddress(bytes);
12 | }
13 |
14 | #if NET7_0_OR_GREATER
15 | public static IPAddress Create(UInt128 value)
16 | {
17 | var bytes = BitConverterEx.GetBytes(value);
18 | Array.Reverse(bytes);
19 | return new IPAddress(bytes);
20 | }
21 | #endif
22 | }
23 |
--------------------------------------------------------------------------------
/NStandard/!Static/ObjectEx.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Static;
2 |
3 | public static class ObjectEx
4 | {
5 | public static void AcceptPropValues(object source, object provider) => AcceptPropValues(source, provider, null);
6 | public static void AcceptPropValues(object source, object provider, string[]? names)
7 | {
8 | var sourceProps = source.GetType().GetProperties();
9 | var providerProps = provider.GetType().GetProperties();
10 |
11 | names ??= sourceProps.Select(x => x.Name).Intersect(providerProps.Select(x => x.Name)).ToArray();
12 |
13 | foreach (var name in names)
14 | {
15 | var sourceProp = sourceProps.First(x => x.Name == name);
16 | var providerProp = providerProps.First(x => x.Name == name);
17 |
18 | if (sourceProp.PropertyType == providerProp.PropertyType)
19 | sourceProp.SetValue(source, providerProp.GetValue(provider));
20 | }
21 | }
22 |
23 | ///
24 | /// Determines whether the specified objects are equal to each other.
25 | ///
26 | ///
27 | ///
28 | ///
29 | public static bool CrossEquals(params T[] objs)
30 | {
31 | if (objs.Length < 2) return true;
32 |
33 | foreach (var window in objs.Slide(2, true))
34 | {
35 | if (!Equals(window[0], window[1])) return false;
36 | }
37 | return true;
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/NStandard/!Static/Reflection/MethodInfoEx.cs:
--------------------------------------------------------------------------------
1 | using System.Linq.Expressions;
2 | using System.Reflection;
3 |
4 | namespace NStandard.Static.Reflection;
5 |
6 | public static class MethodInfoEx
7 | {
8 | ///
9 | /// Get MethodInfo from a method.
10 | ///
11 | ///
12 | ///
13 | ///
14 | public static MethodInfo GetMethodInfo(Expression> methodSelector)
15 | {
16 | var unary = (methodSelector.Body as UnaryExpression) ?? throw new ArgumentException("The method selector must point to a method.", nameof(methodSelector));
17 | var operand = (unary.Operand as MethodCallExpression) ?? throw new ArgumentException("The operand must be MethodCallExpression.");
18 | var constant = (operand.Object as ConstantExpression) ?? throw new ArgumentException("The operand object must be ConstantExpression.");
19 | var method = (constant.Value as MethodInfo) ?? throw new ArgumentException("The value of operand object must be MethodInfo.");
20 | return method;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/NStandard/!Static/TypeEx.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 |
3 | namespace NStandard.Static;
4 |
5 | public static class TypeEx
6 | {
7 | public const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
8 | }
9 |
--------------------------------------------------------------------------------
/NStandard/!internal/BitOperations.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | internal class BitOperations
4 | {
5 | public static uint RotateLeft(uint value, int offset)
6 | {
7 | return (value << offset) | (value >> (32 - offset));
8 | }
9 |
10 | public static uint RotateRight(uint value, int offset)
11 | {
12 | return (value >> offset) | (value << (32 - offset));
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/NStandard/Caching/!Delegates.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Caching;
2 |
3 | ///
4 | ///
5 | ///
6 | ///
7 | /// Expiration Time
8 | public delegate DateTime UpdateCacheExpirationDelegate(DateTime cacheTime);
9 | public delegate void CacheUpdateEventDelegate(DateTime cacheTime, T value);
10 |
--------------------------------------------------------------------------------
/NStandard/Caching/Cache.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 |
3 | namespace NStandard.Caching;
4 |
5 | public class Cache
6 | {
7 | public static UpdateCacheExpirationDelegate DefaultUpdateExpirationMethod { get; set; } = x => DateTime.MaxValue;
8 |
9 | public Func? CacheMethod { get; set; }
10 | public UpdateCacheExpirationDelegate? UpdateExpirationMethod { get; set; }
11 | public event CacheUpdateEventDelegate? OnCacheUpdated;
12 |
13 | public DateTime CacheTime { get; protected set; }
14 | public DateTime Expiration { get; protected set; }
15 |
16 | public Cache() { }
17 | public Cache(Func? cacheMethod)
18 | {
19 | CacheMethod = cacheMethod;
20 | }
21 |
22 | protected T? _Value;
23 |
24 | public T? Value
25 | {
26 | [MethodImpl(MethodImplOptions.Synchronized)]
27 | get
28 | {
29 | if (DateTime.Now >= Expiration) Update();
30 | return _Value;
31 | }
32 | }
33 |
34 | [MethodImpl(MethodImplOptions.Synchronized)]
35 | public void Update()
36 | {
37 | if (CacheMethod is null) throw new InvalidOperationException("No cache method is set.");
38 |
39 | CacheTime = DateTime.Now;
40 | Expiration = (UpdateExpirationMethod ?? DefaultUpdateExpirationMethod)(CacheTime);
41 | _Value = CacheMethod();
42 | OnCacheUpdated?.Invoke(CacheTime, _Value);
43 | }
44 |
45 | [MethodImpl(MethodImplOptions.Synchronized)]
46 | public void Expire() => Expiration = DateTime.MinValue;
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/NStandard/Caching/CacheSet.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 |
3 | namespace NStandard.Caching;
4 |
5 | public class CacheSet : Dictionary> where TKey : notnull
6 | {
7 | public Func?>? CacheMethodBuilder;
8 | public UpdateCacheExpirationDelegate? UpdateExpirationMethod;
9 |
10 | public CacheSet() { }
11 | public CacheSet(Func?>? cacheMethodBuilder)
12 | {
13 | CacheMethodBuilder = cacheMethodBuilder;
14 | }
15 |
16 | public new Cache this[TKey key]
17 | {
18 | [MethodImpl(MethodImplOptions.Synchronized)]
19 | get
20 | {
21 | if (!ContainsKey(key))
22 | {
23 | base[key] = new Cache
24 | {
25 | CacheMethod = CacheMethodBuilder?.Invoke(key),
26 | UpdateExpirationMethod = UpdateExpirationMethod,
27 | };
28 | }
29 | return base[key];
30 | }
31 | }
32 |
33 | [MethodImpl(MethodImplOptions.Synchronized)]
34 | public void UpdateAll()
35 | {
36 | foreach (var key in Keys)
37 | {
38 | base[key].Update();
39 | }
40 | }
41 |
42 | [MethodImpl(MethodImplOptions.Synchronized)]
43 | public void ExpireAll()
44 | {
45 | foreach (var key in Keys)
46 | {
47 | base[key].Expire();
48 | }
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/NStandard/ChainOrigin.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public enum ChainOrigin
4 | {
5 | Begin = 0,
6 | Current = 1,
7 | End = 2,
8 | }
9 |
--------------------------------------------------------------------------------
/NStandard/Collections/FixedSizeQueue.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Collections;
2 |
3 | public class FixedSizeQueue
4 | {
5 | protected readonly T?[] _store;
6 | protected readonly int _maxIndex;
7 |
8 | protected int _fillCount;
9 |
10 | public int Capacity { get; }
11 | public bool IsFilled { get; protected set; }
12 |
13 | public FixedSizeQueue(int capacity)
14 | {
15 | if (capacity < 1) throw new ArgumentException("The capacity must be greater than or equal to 1.", nameof(capacity));
16 |
17 | Capacity = capacity;
18 | _store = new T[capacity];
19 | _maxIndex = capacity - 1;
20 | }
21 |
22 | public void Enqueue(T? obj)
23 | {
24 | var startIndex = IsFilled ? 0 : _maxIndex - _fillCount;
25 | for (int i = startIndex; i < _maxIndex; i++)
26 | {
27 | _store[i] = _store[i + 1];
28 | }
29 | _store[_maxIndex] = obj;
30 |
31 | if (!IsFilled)
32 | {
33 | _fillCount++;
34 | if (_fillCount == Capacity) IsFilled = true;
35 | }
36 | }
37 |
38 | public T? this[int i]
39 | {
40 | get
41 | {
42 | if (i <= _maxIndex) return _store[i];
43 | else throw new IndexOutOfRangeException($"Index out of range (0 to {_maxIndex}).");
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/NStandard/Collections/Sequence.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 |
3 | namespace NStandard.Collections;
4 |
5 | public class Sequence : IEnumerable, IList
6 | {
7 | private readonly List _list = [];
8 |
9 | public Sequence()
10 | {
11 | Clear();
12 | }
13 |
14 | public T this[int index] { get => ((IList)_list)[index]; set => ((IList)_list)[index] = value; }
15 |
16 | public int Count => ((ICollection)_list).Count;
17 |
18 | public bool IsReadOnly => ((ICollection)_list).IsReadOnly;
19 |
20 | public void Add(T value)
21 | {
22 | _list.Add(value);
23 | }
24 |
25 | public void Add(IEnumerable values)
26 | {
27 | _list.AddRange(values);
28 | }
29 |
30 | public void Clear()
31 | {
32 | _list.Clear();
33 | }
34 |
35 | public bool Contains(T item)
36 | {
37 | return ((ICollection)_list).Contains(item);
38 | }
39 |
40 | public void CopyTo(T[] array, int arrayIndex)
41 | {
42 | ((ICollection)_list).CopyTo(array, arrayIndex);
43 | }
44 |
45 | public IEnumerator GetEnumerator()
46 | {
47 | return _list.GetEnumerator();
48 | }
49 |
50 | public int IndexOf(T item)
51 | {
52 | return ((IList)_list).IndexOf(item);
53 | }
54 |
55 | public void Insert(int index, T item)
56 | {
57 | ((IList)_list).Insert(index, item);
58 | }
59 |
60 | public bool Remove(T item)
61 | {
62 | return ((ICollection)_list).Remove(item);
63 | }
64 |
65 | public void RemoveAt(int index)
66 | {
67 | ((IList)_list).RemoveAt(index);
68 | }
69 |
70 | IEnumerator IEnumerable.GetEnumerator()
71 | {
72 | return _list.GetEnumerator();
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/NStandard/Collections/SlidingMode.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Collections;
2 |
3 | [Flags]
4 | public enum SlidingMode
5 | {
6 | None = 0,
7 | PadLeft = 1,
8 | PadRight = 2,
9 | PadBoth = PadLeft | PadRight,
10 | }
11 |
--------------------------------------------------------------------------------
/NStandard/Data/MomentType.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Data;
2 |
3 | public enum MomentType
4 | {
5 | Undefined = 0,
6 |
7 | [Obsolete("Not supported")]
8 | Nanosecond = 1,
9 | [Obsolete("Not supported")]
10 | Microsecond = Nanosecond * 0b1000,
11 |
12 | Millisecond = Microsecond * 0b1000,
13 | Second = Millisecond * 0b1000,
14 | Minute = Second * 0b100,
15 | Hour = Minute * 0b100,
16 | Day = Hour * 0b100,
17 | Week = Day * 0b10,
18 | Month = Day * 0b100,
19 | Quarter = Month * 0b10,
20 | Year = Month * 0b100,
21 | }
22 |
--------------------------------------------------------------------------------
/NStandard/DataBinding/IDiff.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.DataBinding;
2 |
3 | public interface IDiff
4 | {
5 | T? OldValue { get; set; }
6 | T? NewValue { get; set; }
7 | T? Value { get; set; }
8 | }
9 |
--------------------------------------------------------------------------------
/NStandard/DataBinding/ValueDiff.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace NStandard.DataBinding;
4 |
5 | ///
6 | /// A value which describe a difference in state.
7 | ///
8 | ///
9 | [DebuggerDisplay("{OldValue} → {NewValue}")]
10 | public sealed class ValueDiff : IDiff
11 | {
12 | public T? OldValue { get; set; }
13 | public T? NewValue { get; set; }
14 | public T? Value
15 | {
16 | get => NewValue;
17 | set
18 | {
19 | OldValue = NewValue;
20 | NewValue = value;
21 | }
22 | }
23 |
24 | public ValueDiff()
25 | {
26 | }
27 |
28 | public ValueDiff(T value)
29 | {
30 | OldValue = value;
31 | NewValue = value;
32 | }
33 |
34 | public ValueDiff(T oldValue, T newValue)
35 | {
36 | OldValue = oldValue;
37 | NewValue = newValue;
38 | }
39 |
40 | ///
41 | /// Creates a shallow copy of the original object.
42 | ///
43 | ///
44 | public ValueDiff Clone()
45 | {
46 | return new ValueDiff
47 | {
48 | OldValue = OldValue,
49 | NewValue = NewValue,
50 | };
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/NStandard/DateMode.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | ///
4 | /// Indicates Weekday or Weekend.
5 | ///
6 | [Flags]
7 | public enum DayMode
8 | {
9 | ///
10 | /// Undefined.
11 | ///
12 | Undefined,
13 |
14 | ///
15 | /// Indicates Monday, Tuesday, Wednesday, Thursday, Friday.
16 | ///
17 | Weekday = 1,
18 |
19 | ///
20 | /// Indicates Saturday, Sunday.
21 | ///
22 | Weekend = 2,
23 | }
24 |
--------------------------------------------------------------------------------
/NStandard/DateOnlyType.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public enum DateOnlyType
4 | {
5 | Unspecified,
6 | Year = 1,
7 | Month = 2,
8 | Day = 4,
9 | }
10 |
--------------------------------------------------------------------------------
/NStandard/DateTimeType.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | [Flags]
4 | public enum DateTimeType
5 | {
6 | Unspecified,
7 | Year = 1,
8 | Month = 2,
9 | Day = 4,
10 | Hour = 8,
11 | Minute = 16,
12 | Second = 32,
13 | }
14 |
--------------------------------------------------------------------------------
/NStandard/Design/ObsoleteMessage.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard.Design;
4 |
5 | [EditorBrowsable(EditorBrowsableState.Advanced)]
6 | public static class ObsoleteMessage
7 | {
8 | public const string MayChangeOrBeRemoved = "This API may change or be removed in future releases.";
9 | }
10 |
--------------------------------------------------------------------------------
/NStandard/Discards.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | [Obsolete("Maybe it will be removed in the future.")]
4 | public class Discards
5 | {
6 | public static readonly Discards _ = new();
7 | private Discards() { }
8 | }
9 |
--------------------------------------------------------------------------------
/NStandard/DpContainer.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public static class DpContainer
4 | {
5 | ///
6 | /// Provides dynamic programing feature.
7 | ///
8 | ///
9 | ///
10 | ///
11 | ///
12 | public static DefaultDpContainer Create(Func, TIn, TOut> stateTransferFunc) where TIn : notnull
13 | {
14 | return new(stateTransferFunc);
15 | }
16 | }
17 |
18 | public abstract class DpContainer : Dictionary where TIn : notnull
19 | {
20 | public abstract TOut StateTransfer(TIn param);
21 |
22 | public new TOut this[TIn key]
23 | {
24 | get
25 | {
26 | var @this = this as Dictionary;
27 | if (!ContainsKey(key)) @this[key] = StateTransfer(key);
28 | return @this[key];
29 | }
30 | set => (this as Dictionary)[key] = value;
31 | }
32 | }
33 |
34 | public class DefaultDpContainer : DpContainer where TIn : notnull
35 | {
36 | private readonly Func, TIn, TOut> StateTransferFunc;
37 |
38 | public DefaultDpContainer(Func, TIn, TOut> stateTransferFunc)
39 | {
40 | StateTransferFunc = stateTransferFunc;
41 | }
42 |
43 | public override TOut StateTransfer(TIn param) => StateTransferFunc(this, param);
44 | }
45 |
--------------------------------------------------------------------------------
/NStandard/Evaluators/Bracket.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard.Evaluators;
4 |
5 | public struct Bracket(string start, string end)
6 | {
7 | public string Start = start;
8 | public string End = end;
9 |
10 | [EditorBrowsable(EditorBrowsableState.Never)]
11 | public void Deconstruct(out string start, out string end)
12 | {
13 | start = Start;
14 | end = End;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/NStandard/Evaluators/Node.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Evaluators;
2 |
3 | public class Node(NodeType type, string value, int index = -1)
4 | {
5 | public NodeType NodeType { get; internal set; } = type;
6 | public int Index { get; internal set; } = index;
7 | public string Value { get; internal set; } = value;
8 | }
9 |
--------------------------------------------------------------------------------
/NStandard/Evaluators/NodeType.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Evaluators;
2 |
3 | [Flags]
4 | public enum NodeType
5 | {
6 | Unspecified = 0,
7 | Operand = 1,
8 | Parameter = 2,
9 | UnaryOperator = 4,
10 | BinaryOperator = 8,
11 | StartBracket = 1024,
12 | EndBracket = 2048,
13 | }
14 |
--------------------------------------------------------------------------------
/NStandard/Flows/BytesFlow.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Converts;
2 | using NStandard.Static;
3 |
4 | namespace NStandard.Flows;
5 |
6 | public static class BytesFlow
7 | {
8 | public static string Base58(byte[] bytes) => ConvertEx.ToBase58String(bytes);
9 | public static string Base64(byte[] bytes) => Convert.ToBase64String(bytes);
10 | public static string HexString(byte[] bytes) => BytesConvert.ToHexString(bytes);
11 | public static string UrlSafeBase64(byte[] bytes) => StringConvert.ConvertBase64ToUrlSafeBase64(Convert.ToBase64String(bytes));
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/NStandard/Flows/GuidFlow.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Flows;
2 |
3 | public static class GuidFlow
4 | {
5 | public static string HexString(Guid guid) => BytesFlow.HexString(guid.ToByteArray());
6 | public static string Base58(Guid guid) => BytesFlow.Base58(guid.ToByteArray());
7 | public static string Base64(Guid guid) => BytesFlow.Base64(guid.ToByteArray());
8 | public static string UrlSafeBase64(Guid guid) => BytesFlow.UrlSafeBase64(guid.ToByteArray());
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/NStandard/Flows/HashFlow.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Security;
2 |
3 | namespace NStandard.Flows;
4 |
5 | public static class HashFlow
6 | {
7 | public static byte[] MD5(byte[] bytes) => Md5Hasher.Hash(bytes);
8 | public static byte[] SHA1(byte[] bytes) => Sha1Hasher.Hash(bytes);
9 | }
10 |
--------------------------------------------------------------------------------
/NStandard/Flows/IPAddressFlow.cs:
--------------------------------------------------------------------------------
1 | using System.Net;
2 |
3 | namespace NStandard.Flows;
4 |
5 | public static class IPAddressFlow
6 | {
7 | public static long Int64(IPAddress ip) => BitConverter.ToUInt32(ip.GetAddressBytes().Reverse().ToArray(), 0);
8 | public static IPAddress IPAddress(long int64) => System.Net.IPAddress.Parse(int64.ToString());
9 | }
10 |
--------------------------------------------------------------------------------
/NStandard/Flows/NumberFlow.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 |
3 | namespace NStandard.Flows;
4 |
5 | public static class NumberFlow
6 | {
7 | public static double DefaultIfNonNormal(double number) => IsNormal(number) ? number : 0;
8 | public static float DefaultIfNonNormal(float number) => IsNormal(number) ? number : 0;
9 |
10 | #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER
11 | [MethodImpl(MethodImplOptions.AggressiveInlining)]
12 | #endif
13 | private unsafe static int SingleToInt32Bits(float value)
14 | {
15 | return *(int*)(&value);
16 | }
17 |
18 | private static bool IsNormal(float f)
19 | {
20 | int num = SingleToInt32Bits(f);
21 | num &= 0x7FFFFFFF;
22 | if (num < 2139095040 && num != 0)
23 | {
24 | return (num & 0x7F800000) != 0;
25 | }
26 | return false;
27 | }
28 |
29 | private static bool IsNormal(double d)
30 | {
31 | long num = BitConverter.DoubleToInt64Bits(d);
32 | num &= 0x7FFFFFFFFFFFFFFFL;
33 | if (num < 9218868437227405312L && num != 0L)
34 | {
35 | return (num & 0x7FF0000000000000L) != 0;
36 | }
37 | return false;
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/NStandard/FuncDelegates.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public delegate TOperand UnaryFunc(TOperand operand);
4 | public delegate TOperand BinaryFunc(TOperand left, TOperand right);
5 |
--------------------------------------------------------------------------------
/NStandard/ISingleton.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public static class Singleton where T : class, ISingleton, new()
4 | {
5 | private static readonly object _sync = new();
6 | private static T? _instance = null;
7 |
8 | ///
9 | /// Get or create a thread-safe singleton instance.
10 | ///
11 | ///
12 | public static T? GetOrCreate()
13 | {
14 | if (_instance is null)
15 | {
16 | lock (_sync)
17 | {
18 | if (_instance is null)
19 | {
20 | _instance = new T();
21 | _instance.OnInit();
22 | }
23 | }
24 | }
25 | return _instance;
26 | }
27 |
28 | public static void Destory()
29 | {
30 | if (_instance is not null)
31 | {
32 | lock (_sync)
33 | {
34 | _instance = null;
35 | }
36 | }
37 | }
38 | }
39 |
40 | public static class StaticSingleton where T : class, ISingleton, new()
41 | {
42 | ///
43 | /// Get the static singleton instance.
44 | ///
45 | public static readonly T Instance;
46 |
47 | static StaticSingleton()
48 | {
49 | Instance = new T();
50 | Instance.OnInit();
51 | }
52 | }
53 |
54 | public interface ISingleton where TSelf : ISingleton
55 | {
56 | #if NET7_0_OR_GREATER
57 | ///
58 | /// Use or to get a singleton instance.
59 | ///
60 | public abstract static TSelf Instance { get; }
61 | #endif
62 | void OnInit();
63 | }
64 |
--------------------------------------------------------------------------------
/NStandard/Infrastructure/ChainIterator.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Infrastructure;
2 |
3 | public struct ChainIterator
4 | {
5 | public ChainOrigin Origin { get; set; }
6 | public T[] Iterators { get; set; }
7 | public int Cursor { get; set; }
8 | public T Current => Iterators[Cursor];
9 | }
10 |
--------------------------------------------------------------------------------
/NStandard/Locks/TypeLockParser.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Flows;
2 | using System.Threading;
3 |
4 | namespace NStandard.Locks;
5 |
6 | public class TypeLockParser
7 | {
8 | public string LockName { get; }
9 |
10 | public TypeLockParser(string lockName)
11 | {
12 | LockName = lockName;
13 | }
14 |
15 | public virtual Lock Parse(Type type)
16 | {
17 | return new Lock(string.Intern($"[{StringFlow.UrlEncode(LockName)}<{type.FullName}>]"));
18 | }
19 | public virtual Lock Parse()
20 | {
21 | return new Lock(string.Intern($"[{StringFlow.UrlEncode(LockName)}<{typeof(TType).FullName}>]"));
22 | }
23 |
24 | public virtual Lock ParseThreadLock(Type type)
25 | {
26 | return new Lock(string.Intern($"[({Thread.CurrentThread.ManagedThreadId}){StringFlow.UrlEncode(LockName)}<{type.FullName}>]"));
27 | }
28 | public virtual Lock ParseThreadLock()
29 | {
30 | return new Lock(string.Intern($"[({Thread.CurrentThread.ManagedThreadId}){StringFlow.UrlEncode(LockName)}<{typeof(TType).FullName}>]"));
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/NStandard/Measures/IMeasurable.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Measures;
2 |
3 | [Obsolete("Use IMeasurable instead.")]
4 | public interface IMeasurable
5 | {
6 | TValue Value { get; set; }
7 | }
8 |
9 | public interface IAdditionMeasurable where TSelf : IMeasurable, IAdditionMeasurable
10 | {
11 | #if NET7_0_OR_GREATER
12 | static abstract bool ForceAggregate { get; }
13 | #endif
14 | bool CanAggregate(TSelf other);
15 | }
16 |
17 | public interface IMeasurable
18 | {
19 | #if NET7_0_OR_GREATER
20 | static abstract string Measure { get; }
21 | #endif
22 | decimal Value { get; set; }
23 | }
24 |
--------------------------------------------------------------------------------
/NStandard/Measures/IMeasureConvertible.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Measures;
2 |
3 | public interface IMeasureConvertible where T : IMeasurable
4 | {
5 | bool CanConvert();
6 | T Convert();
7 | }
8 |
--------------------------------------------------------------------------------
/NStandard/Measures/MeasureAttribute.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Measures;
2 |
3 | [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
4 | public class MeasureAttribute : Attribute
5 | {
6 | public double Coef { get; set; }
7 |
8 | public MeasureAttribute(double coef)
9 | {
10 | Coef = coef;
11 | }
12 | }
13 |
14 | [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
15 | public class MeasureAttribute : Attribute
16 | {
17 | public string Name { get; set; }
18 |
19 | public MeasureAttribute(string name)
20 | {
21 | Name = name;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/NStandard/MinMaxPair.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | public static class MinMaxPair
6 | {
7 | public static MinMaxPair Create(T min, T max)
8 | {
9 | return new MinMaxPair(min, max);
10 | }
11 | }
12 |
13 | public struct MinMaxPair(T min, T max)
14 | {
15 | public T Min { get; set; } = min;
16 | public T Max { get; set; } = max;
17 |
18 | [EditorBrowsable(EditorBrowsableState.Never)]
19 | public void Deconstruct(out T min, out T max)
20 | {
21 | min = Min;
22 | max = Max;
23 | }
24 |
25 | #if NET5_0_OR_GREATER
26 | public static implicit operator MinMaxPair((T Min, T Max) tuple)
27 | {
28 | return new MinMaxPair
29 | {
30 | Min = tuple.Min,
31 | Max = tuple.Max,
32 | };
33 | }
34 | #endif
35 | }
36 |
--------------------------------------------------------------------------------
/NStandard/Ref.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace NStandard;
4 |
5 | [DebuggerDisplay("{Target}")]
6 | public class Ref(T target)
7 | {
8 | public T Target { get; set; } = target;
9 |
10 | public static implicit operator Ref(T target)
11 | {
12 | return new Ref(target);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/NStandard/Reflection/FieldReflector.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 |
3 | namespace NStandard.Reflection;
4 |
5 | public class FieldReflector : Reflector
6 | {
7 | public readonly FieldInfo FieldInfo;
8 | public readonly object? DeclaringObject;
9 |
10 | public FieldReflector(FieldInfo fieldInfo, object? declaringObj) : this(fieldInfo, fieldInfo.FieldType, declaringObj) { }
11 | public FieldReflector(FieldInfo fieldInfo, Type type, object? declaringObj) : base(type, declaringObj)
12 | {
13 | FieldInfo = fieldInfo;
14 | DeclaringObject = declaringObj;
15 | Object = Value;
16 | }
17 |
18 | public virtual object? Value
19 | {
20 | get => DeclaringObject?.Pipe(FieldInfo.GetValue);
21 | set
22 | {
23 | if (DeclaringObject is not null)
24 | FieldInfo.SetValue(DeclaringObject, value);
25 | else throw new AccessViolationException();
26 | }
27 | }
28 | public virtual object? GetValue() => FieldInfo.GetValue(DeclaringObject);
29 | public void SetValue(object? value) => FieldInfo.SetValue(DeclaringObject, value);
30 | }
31 |
32 | public class FieldReflector(FieldInfo fieldInfo, object? declaringObj) : FieldReflector(fieldInfo, typeof(T), declaringObj)
33 | {
34 | public new T? Value
35 | {
36 | get => base.Value is null ? default : (T)base.Value;
37 | set => base.Value = value;
38 | }
39 | public new T? GetValue() => (T?)base.GetValue();
40 | public void SetValue(T value) => base.SetValue(value);
41 | }
42 |
--------------------------------------------------------------------------------
/NStandard/Reflection/MethodReflector.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 |
3 | namespace NStandard.Reflection;
4 |
5 | public class MethodReflector(MethodInfo methodInfo, object? declaringObj)
6 | {
7 | public readonly MethodInfo MethodInfo = methodInfo;
8 | public object? DeclaringObject = declaringObj;
9 |
10 | public object? Call(params object[] parameters)
11 | {
12 | return MethodInfo is null
13 | ? throw new ArgumentNullException("The method can not be null")
14 | : MethodInfo.Invoke(DeclaringObject, parameters);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/NStandard/Reflection/PropertyReflector.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 |
3 | namespace NStandard.Reflection;
4 |
5 | public class PropertyReflector : Reflector
6 | {
7 | public readonly PropertyInfo PropertyInfo;
8 | public readonly object? DeclaringObject;
9 |
10 | public PropertyReflector(PropertyInfo propertyInfo, object? declaringObj) : this(propertyInfo, propertyInfo.PropertyType, declaringObj) { }
11 | public PropertyReflector(PropertyInfo propertyInfo, Type type, object? declaringObj) : base(type, declaringObj)
12 | {
13 | PropertyInfo = propertyInfo;
14 | DeclaringObject = declaringObj;
15 | Object = Value;
16 | }
17 |
18 | public virtual object? Value
19 | {
20 | get => DeclaringObject?.Pipe(PropertyInfo.GetValue);
21 | set
22 | {
23 | if (DeclaringObject is not null)
24 | {
25 | PropertyInfo.SetValue(DeclaringObject, value!);
26 | }
27 | else throw new AccessViolationException();
28 | }
29 | }
30 | public virtual object? GetValue() => PropertyInfo.GetValue(DeclaringObject!);
31 | public void SetValue(object? value) => PropertyInfo.SetValue(DeclaringObject!, value!);
32 | }
33 |
34 | public class PropertyReflector(PropertyInfo propertyInfo, object? declaringObj) : PropertyReflector(propertyInfo, typeof(T), declaringObj)
35 | {
36 | public new T? Value
37 | {
38 | get => base.Value is null ? default : (T)base.Value;
39 | set => base.Value = value;
40 | }
41 |
42 | public new T? GetValue() => (T?)base.GetValue();
43 | public void SetValue(T? value) => base.SetValue(value);
44 | }
45 |
--------------------------------------------------------------------------------
/NStandard/Reflection/TypeFieldReflector.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 |
3 | namespace NStandard.Reflection;
4 |
5 | public class TypeFieldReflector(FieldInfo fieldInfo, Type type) : TypeReflector(type)
6 | {
7 | public readonly FieldInfo FieldInfo = fieldInfo;
8 |
9 | public TypeFieldReflector(FieldInfo fieldInfo) : this(fieldInfo, fieldInfo.FieldType)
10 | {
11 | }
12 |
13 | public virtual object? GetValue(object? obj) => FieldInfo.GetValue(obj);
14 | public void SetValue(object obj, object? value) => FieldInfo.SetValue(obj, value);
15 | }
16 |
17 | public class TypeFieldReflector(FieldInfo fieldInfo) : TypeFieldReflector(fieldInfo, typeof(T))
18 | {
19 | public new T? GetValue(object obj) => (T?)base.GetValue(obj);
20 | public void SetValue(object obj, T? value) => base.SetValue(obj, value);
21 | }
22 |
--------------------------------------------------------------------------------
/NStandard/Reflection/TypeMethodReflector.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 |
3 | namespace NStandard.Reflection;
4 |
5 | public class TypeMethodReflector
6 | {
7 | public readonly MethodInfo MethodInfo;
8 |
9 | public TypeMethodReflector(MethodInfo methodInfo)
10 | {
11 | MethodInfo = methodInfo;
12 | }
13 |
14 | public object? Invoke(object obj, params object[] parameters) => MethodInfo.Invoke(obj, parameters);
15 | }
16 |
--------------------------------------------------------------------------------
/NStandard/Reflection/TypePropertyReflector.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 |
3 | namespace NStandard.Reflection;
4 |
5 | public class TypePropertyReflector(PropertyInfo propertyInfo, Type type) : TypeReflector(type)
6 | {
7 | public readonly PropertyInfo PropertyInfo = propertyInfo;
8 |
9 | public TypePropertyReflector(PropertyInfo propertyInfo) : this(propertyInfo, propertyInfo.PropertyType)
10 | {
11 | }
12 |
13 | public virtual object? GetValue(object? obj) => PropertyInfo.GetValue(obj!);
14 | public void SetValue(object? obj, object? value) => PropertyInfo.SetValue(obj!, value!);
15 | }
16 |
17 | public class TypePropertyReflector(PropertyInfo propertyInfo) : TypePropertyReflector(propertyInfo, typeof(T))
18 | {
19 | public new T? GetValue(object? obj) => (T?)base.GetValue(obj);
20 | public void SetValue(object? obj, T value) => base.SetValue(obj!, value);
21 | }
22 |
--------------------------------------------------------------------------------
/NStandard/ResourceAccessor.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 |
3 | namespace NStandard;
4 |
5 | public class ResourceAccessor
6 | {
7 | public Assembly Assembly { get; }
8 | public string? Namespace { get; }
9 | public string[] ResourceNames { get; }
10 |
11 | public ResourceAccessor(Assembly assembly)
12 | {
13 | Assembly = assembly;
14 | var names = assembly.GetManifestResourceNames();
15 | ResourceNames = names;
16 |
17 | if (names.Any())
18 | {
19 | var name = names[0];
20 | var index = name.IndexOf('.');
21 | Namespace = name.Substring(0, index);
22 | }
23 | else Namespace = null;
24 | }
25 |
26 | public Stream? OpenStream(string name)
27 | {
28 | if (Namespace is not null)
29 | return Assembly.GetManifestResourceStream($"{Namespace}.{name}")!;
30 | else return null;
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/NStandard/Schema/LoopFor.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 |
3 | namespace NStandard.Schema;
4 |
5 | public static class LoopFor
6 | {
7 | public static LoopFor Create(Func init, Predicate predicate, Func final) where T : struct
8 | {
9 | return new LoopFor(init, predicate, final);
10 | }
11 | }
12 |
13 | public class LoopFor : IEnumerable where T : struct
14 | {
15 | public IEnumerable Enumerable { get; private set; }
16 |
17 | public LoopFor(Func init, Predicate predicate, Func final)
18 | {
19 | Enumerable = BuildEnumerable(init, predicate, final);
20 | }
21 |
22 | public LoopFor(IEnumerable enumerable)
23 | {
24 | Enumerable = enumerable;
25 | }
26 |
27 | private IEnumerable BuildEnumerable(Func init, Predicate predicate, Func final)
28 | {
29 | for (var param = init(); predicate(param); param = final(param))
30 | {
31 | yield return param;
32 | }
33 | }
34 |
35 | public IEnumerator GetEnumerator() => Enumerable.GetEnumerator();
36 | IEnumerator IEnumerable.GetEnumerator() => Enumerable.GetEnumerator();
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/NStandard/Security/!Hash/Md5Hasher.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 |
3 | namespace NStandard.Security;
4 |
5 | public static class Md5Hasher
6 | {
7 | public static byte[] Hash(Stream inputStream) => MD5.Create().ComputeHash(inputStream);
8 | public static byte[] Hash(byte[] buffer, int offset, int count) => MD5.Create().ComputeHash(buffer, offset, count);
9 | public static byte[] Hash(byte[] buffer) => MD5.Create().ComputeHash(buffer);
10 | }
11 |
--------------------------------------------------------------------------------
/NStandard/Security/!Hash/Sha1Hasher.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 |
3 | namespace NStandard.Security;
4 |
5 | public static class Sha1Hasher
6 | {
7 | public static byte[] Hash(Stream inputStream) => SHA1.Create().ComputeHash(inputStream);
8 | public static byte[] Hash(byte[] buffer, int offset, int count) => SHA1.Create().ComputeHash(buffer, offset, count);
9 | public static byte[] Hash(byte[] buffer) => SHA1.Create().ComputeHash(buffer);
10 | }
11 |
--------------------------------------------------------------------------------
/NStandard/Security/!Symmetric/AesCipher.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Security;
2 |
3 | public class AesCipher : SymmetricCipher
4 | {
5 | public override int IVLength => 16;
6 | }
7 |
--------------------------------------------------------------------------------
/NStandard/Security/!Symmetric/AesProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 |
3 | namespace NStandard.Security;
4 |
5 | public class AesProvider : SymmetricProvider
6 | {
7 | public override byte[] EmptyIV => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
8 |
9 | ///
10 | /// Create an AesProvider.
11 | ///
12 | ///
13 | ///
14 | public AesProvider(CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(cipher, padding)
15 | {
16 | }
17 |
18 | ///
19 | /// Create an AesProvider.
20 | ///
21 | /// The length of Key must be 16, 24 or 32.
22 | ///
23 | ///
24 | public AesProvider(byte[] key, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(key, cipher, padding)
25 | {
26 | }
27 |
28 | protected override SymmetricAlgorithm CreateAlgorithm() => Aes.Create();
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/NStandard/Security/!Symmetric/DesCipher.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Security;
2 |
3 | public class DesCipher : SymmetricCipher
4 | {
5 | public override int IVLength => 8;
6 | }
7 |
--------------------------------------------------------------------------------
/NStandard/Security/!Symmetric/DesProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 |
3 | namespace NStandard.Security;
4 |
5 | public class DesProvider : SymmetricProvider
6 | {
7 | public override byte[] EmptyIV => [0, 0, 0, 0, 0, 0, 0, 0];
8 |
9 | ///
10 | /// Create a DesProvider.
11 | ///
12 | ///
13 | ///
14 | public DesProvider(CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(cipher, padding)
15 | {
16 | }
17 |
18 | ///
19 | /// Create a DesProvider.
20 | ///
21 | /// The length of Key must be 8.
22 | ///
23 | ///
24 | public DesProvider(byte[] key, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(key, cipher, padding)
25 | {
26 | }
27 |
28 | protected override SymmetricAlgorithm CreateAlgorithm() => DES.Create();
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/NStandard/Security/!Symmetric/SymmetricCipher.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Security;
2 |
3 | public abstract class SymmetricCipher where TSelf : SymmetricCipher, new()
4 | {
5 | public abstract int IVLength { get; }
6 | public byte[]? Cipher { get; set; }
7 | public byte[]? IV { get; set; }
8 |
9 | public byte[] ToBytes()
10 | {
11 | return [.. Cipher, .. IV];
12 | }
13 |
14 | public TSelf FromBytes(byte[] bytes)
15 | {
16 | var pair = new TSelf
17 | {
18 | Cipher = bytes.Slice(0, -IVLength),
19 | IV = bytes.Slice(-IVLength),
20 | };
21 | return pair;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/NStandard/Security/!Symmetric/TripleDesCipher.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Security;
2 |
3 | public class TripleDesCipher : SymmetricCipher
4 | {
5 | public override int IVLength => 8;
6 | }
7 |
--------------------------------------------------------------------------------
/NStandard/Security/!Symmetric/TripleDesProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography;
2 |
3 | namespace NStandard.Security;
4 |
5 | public class TripleDesProvider : SymmetricProvider
6 | {
7 | public override byte[] EmptyIV => [0, 0, 0, 0, 0, 0, 0, 0];
8 |
9 | ///
10 | /// Create a .
11 | ///
12 | ///
13 | ///
14 | public TripleDesProvider(CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(cipher, padding)
15 | {
16 | }
17 |
18 | ///
19 | /// Create a .
20 | ///
21 | /// The length of Key must be 8.
22 | ///
23 | ///
24 | public TripleDesProvider(byte[] key, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(key, cipher, padding)
25 | {
26 | }
27 |
28 | protected override SymmetricAlgorithm CreateAlgorithm() => TripleDES.Create();
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/NStandard/Snowflake.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Algorithm;
2 |
3 | namespace NStandard;
4 |
5 | public static class Snowflake
6 | {
7 | public static long WorkerId
8 | {
9 | get => _worker.WorkerId;
10 | set => _worker.WorkerId = value;
11 | }
12 |
13 | public static long DataCenterId
14 | {
15 | get => _worker.DataCenterId;
16 | set => _worker.DataCenterId = value;
17 | }
18 |
19 | private static readonly SnowflakeWorker _worker = new(0, 0);
20 |
21 | ///
22 | /// Generate a snowflake ID with default WorkerId and DataCenterId.
23 | ///
24 | ///
25 | public static long NewId() => _worker.NewId();
26 | }
27 |
28 | #if NET7_0_OR_GREATER
29 | public static class Snowflake128
30 | {
31 | public static Int128 WorkerId
32 | {
33 | get => _worker.WorkerId;
34 | set => _worker.WorkerId = value;
35 | }
36 |
37 | public static Int128 DataCenterId
38 | {
39 | get => _worker.DataCenterId;
40 | set => _worker.DataCenterId = value;
41 | }
42 |
43 | private static readonly SnowflakeWorker128 _worker = new(0, 0);
44 |
45 | ///
46 | /// Generate a snowflake ID with default WorkerId and DataCenterId.
47 | ///
48 | ///
49 | public static Int128 NewId() => _worker.NewId();
50 |
51 | ///
52 | /// Generate a snowflake ID with default WorkerId and DataCenterId.
53 | ///
54 | ///
55 | public static Guid NewGuid() => _worker.NewGuid();
56 | }
57 | #endif
58 |
--------------------------------------------------------------------------------
/NStandard/Text/Json/Converters/JsonImplConverter.cs:
--------------------------------------------------------------------------------
1 | #if NET5_0_OR_GREATER
2 | using System;
3 | using System.Text.Json;
4 | using System.Text.Json.Serialization;
5 |
6 | namespace NStandard.Text.Json.Converters;
7 |
8 | public class JsonImplConverter : JsonConverter where TDeserialize : T, new()
9 | {
10 | public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
11 | {
12 | return JsonSerializer.Deserialize(ref reader, options);
13 | }
14 |
15 | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
16 | {
17 | if (value is null)
18 | {
19 | JsonSerializer.Serialize(writer, null, options);
20 | }
21 | else
22 | {
23 | var type = value.GetType();
24 | JsonSerializer.Serialize(writer, value, type, options);
25 | }
26 | }
27 | }
28 | #endif
29 |
--------------------------------------------------------------------------------
/NStandard/Text/Json/Converters/JsonValueConverter.cs:
--------------------------------------------------------------------------------
1 | #if NET5_0_OR_GREATER
2 | using System;
3 | using System.Text.Json;
4 | using System.Text.Json.Serialization;
5 |
6 | namespace NStandard.Text.Json.Converters;
7 |
8 | public class JsonValueConverter : JsonConverter where T : IJsonValue, new()
9 | {
10 | public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
11 | {
12 | var value = JsonSerializer.Deserialize(ref reader, options);
13 | var instance = new T
14 | {
15 | RawValue = value,
16 | };
17 | return instance;
18 | }
19 |
20 | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
21 | {
22 | if (value is null || value.Value is null)
23 | {
24 | JsonSerializer.Serialize(writer, null, options);
25 | }
26 | else
27 | {
28 | var type = value.Value.GetType();
29 | JsonSerializer.Serialize(writer, value.Value, type, options);
30 | }
31 | }
32 | }
33 | #endif
34 |
--------------------------------------------------------------------------------
/NStandard/Text/Json/IJsonValue.cs:
--------------------------------------------------------------------------------
1 | #if NET5_0_OR_GREATER
2 | using System.Text.Json;
3 | #endif
4 |
5 | namespace NStandard.Text.Json;
6 |
7 | public interface IJsonValue
8 | {
9 | object? Value { get; }
10 |
11 | #if NET5_0_OR_GREATER
12 | JsonElement RawValue { set; }
13 | #endif
14 | }
15 |
--------------------------------------------------------------------------------
/NStandard/Text/Json/JsonAsAttribute.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Text.Json;
2 |
3 | #if NET5_0_OR_GREATER
4 | using NStandard.Text.Json.Converters;
5 | using System.Text.Json.Serialization;
6 |
7 | ///
8 | /// Serialize instance by interface type.
9 | ///
10 | ///
11 | ///
12 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
13 | public class JsonAsAttribute : JsonConverterAttribute where T : TSerialize, new()
14 | {
15 | public JsonAsAttribute() : base(typeof(JsonAsConverter))
16 | {
17 | }
18 | }
19 | #else
20 | ///
21 | /// Serialize instance by interface type.
22 | ///
23 | ///
24 | ///
25 | [Obsolete("Must be manually configured based on the actual serializer used.")]
26 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
27 | public class JsonAsAttribute : Attribute where T : TSerialize, new()
28 | {
29 | public JsonAsAttribute()
30 | {
31 | }
32 | }
33 | #endif
34 |
--------------------------------------------------------------------------------
/NStandard/Text/Json/JsonImplAttribute.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Text.Json;
2 |
3 | #if NET5_0_OR_GREATER
4 | using NStandard.Text.Json.Converters;
5 | using System.Text.Json.Serialization;
6 |
7 | ///
8 | /// Serialize interface by instance type.
9 | ///
10 | ///
11 | ///
12 | [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)]
13 | public class JsonImplAttribute : JsonConverterAttribute where TDeserialize : T, new()
14 | {
15 | public JsonImplAttribute() : base(typeof(JsonImplConverter))
16 | {
17 | }
18 | }
19 | #else
20 | ///
21 | /// Serialize interface by instance type.
22 | ///
23 | ///
24 | ///
25 | [Obsolete("Must be manually configured based on the actual serializer used.")]
26 | [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)]
27 | public class JsonImplAttribute : Attribute where TDeserialize : T, new()
28 | {
29 | public JsonImplAttribute()
30 | {
31 | }
32 | }
33 | #endif
34 |
--------------------------------------------------------------------------------
/NStandard/Text/Json/JsonValueAttribute.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Text.Json;
2 |
3 | #if NET5_0_OR_GREATER
4 | using NStandard.Text.Json.Converters;
5 | using System.Text.Json.Serialization;
6 |
7 | ///
8 | /// Serialize interface by the value instance type.
9 | ///
10 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
11 | public class JsonValueAttribute : JsonConverterAttribute where T : IJsonValue, new()
12 | {
13 | public JsonValueAttribute() : base(typeof(JsonValueConverter))
14 | {
15 | }
16 | }
17 | #else
18 | [Obsolete("Must be manually configured based on the actual serializer used.")]
19 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)]
20 | public class JsonValueAttribute : Attribute where T : IJsonValue, new()
21 | {
22 | public JsonValueAttribute()
23 | {
24 | }
25 | }
26 | #endif
27 |
--------------------------------------------------------------------------------
/NStandard/TimePointValue.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard;
2 |
3 | public static class TimePointValue
4 | {
5 | public static TimePointValue Create(TValue value) => new(value);
6 | }
7 |
8 | public struct TimePointValue
9 | {
10 | public TimePointValue() : this(default) { }
11 | public TimePointValue(TValue? value)
12 | {
13 | TimePoint = DateTime.Now;
14 | _value = value;
15 | }
16 |
17 | public DateTime TimePoint { get; private set; }
18 | public TimeSpan TimeSpan => DateTime.Now - TimePoint;
19 |
20 | private TValue? _value;
21 | public TValue? Value
22 | {
23 | get => _value;
24 | set
25 | {
26 | if (!Equals(_value, value))
27 | {
28 | _value = value;
29 | TimePoint = DateTime.Now;
30 | }
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/NStandard/Trees/BinaryTree.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Trees;
2 |
3 | public class BinaryTree : IBinaryTree, TModel>
4 | {
5 | public BinaryTree() { }
6 | public BinaryTree(TModel model)
7 | {
8 | Model = model;
9 | }
10 |
11 | public TModel? Model { get; set; }
12 | public BinaryTree? Parent { get; set; }
13 |
14 | private BinaryTree? _left;
15 | public BinaryTree? LeftNode
16 | {
17 | get => _left;
18 | set
19 | {
20 | if (value is not null)
21 | {
22 | value.Parent = this;
23 | _left = value;
24 | }
25 | else
26 | {
27 | if (_left is not null)
28 | {
29 | _left.Parent = null;
30 | }
31 | _left = null;
32 | }
33 | }
34 | }
35 |
36 | private BinaryTree? _right;
37 | public BinaryTree? RightNode
38 | {
39 | get => _right;
40 | set
41 | {
42 | if (value is not null)
43 | {
44 | value.Parent = this;
45 | _right = value;
46 | }
47 | else
48 | {
49 | if (_right is not null)
50 | {
51 | _right.Parent = null;
52 | }
53 | _right = null;
54 | }
55 | }
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/NStandard/Trees/ITreeVisitable.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Trees;
2 |
3 | public interface ITreeVisitable
4 | {
5 | IEnumerable RecursiveNodes { get; }
6 | IEnumerable NonLeaves { get; }
7 | IEnumerable Leaves { get; }
8 | TSelf Visit(Func predicate);
9 | }
10 |
--------------------------------------------------------------------------------
/NStandard/UnitValues/ISummable.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.UnitValues;
2 |
3 | [Obsolete("Plan to remove.")]
4 | public interface ISummable where TUnitValue : struct, IUnitValue
5 | {
6 | void QuickSum(IEnumerable values);
7 | void QuickAverage(IEnumerable values);
8 | }
9 |
--------------------------------------------------------------------------------
/NStandard/UnitValues/IUnitValue.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.UnitValues;
2 |
3 | [Obsolete("Use IMeasurable instead.")]
4 | public interface IUnitValue
5 | {
6 | string Unit { get; set; }
7 | }
8 |
9 | [Obsolete("Use IMeasurable instead.")]
10 | public interface IUnitValue : IUnitValue
11 | {
12 | TValue Value { get; }
13 | TValue GetValue(string unit);
14 | }
15 |
--------------------------------------------------------------------------------
/NStandard/UnitValues/IUnitValueExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard;
4 |
5 | [Obsolete("Plan to remove.")]
6 | [EditorBrowsable(EditorBrowsableState.Never)]
7 | public static class IUnitValueExtensions
8 | {
9 | public static TUnitValue Unit(this TUnitValue @this, string unit) where TUnitValue : struct, UnitValues.IUnitValue
10 | {
11 | @this.Unit = unit;
12 | return @this;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/NStandard/Usings.cs:
--------------------------------------------------------------------------------
1 | global using System;
2 | global using System.Collections.Generic;
3 | global using System.IO;
4 | global using System.Linq;
5 |
--------------------------------------------------------------------------------
/NStandard/Val.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace NStandard;
4 |
5 | [DebuggerDisplay("{Target}")]
6 | public struct Val(T target)
7 | {
8 | public T Target { get; set; } = target;
9 |
10 | public static implicit operator Val(T target)
11 | {
12 | return new Val(target);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/NStandard/ValueTuples/IndexAndValue.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace NStandard.ValueTuples;
4 |
5 | public struct IndexAndValue
6 | {
7 | public int Index;
8 | public TValue Value;
9 |
10 | public IndexAndValue(int index, TValue value)
11 | {
12 | Index = index;
13 | Value = value;
14 | }
15 |
16 | [EditorBrowsable(EditorBrowsableState.Never)]
17 | public void Deconstruct(out int index, out TValue value)
18 | {
19 | index = Index;
20 | value = Value;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/NStandard/YearWeekPair.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace NStandard;
4 |
5 | [DebuggerDisplay("Week {Week}, {Year}")]
6 | public record struct YearWeekPair(int Year, int Week);
7 |
--------------------------------------------------------------------------------
/Tests/NStandard.NET45.Test/FormattableStringTests.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.VisualStudio.TestTools.UnitTesting;
2 | using System;
3 | using System.Runtime.CompilerServices;
4 |
5 | namespace NStandard.NET45.Test
6 | {
7 | [TestClass]
8 | public class FormattableStringTests
9 | {
10 | [TestMethod]
11 | public void FormattableStringTest()
12 | {
13 | var now = DateTime.Now;
14 | var formattable = FormattableStringFactory.Create("Hello NStandard. ({0})", now);
15 | Assert.AreEqual($"Hello NStandard. ({now})", formattable.ToString());
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Tests/NStandard.NET45.Test/HashCodeTests.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.VisualStudio.TestTools.UnitTesting;
2 | using System;
3 |
4 | namespace NStandard.NET45.Test
5 | {
6 | [TestClass]
7 | public class HashCodeTests
8 | {
9 | [TestMethod]
10 | public void Test1()
11 | {
12 | var bytes = new byte[] { 1, 2, 3, 4, 5 };
13 | var first = HashCode.Combine(bytes);
14 | var second = HashCode.Combine(bytes);
15 | Assert.AreEqual(first, second);
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Tests/NStandard.NET45.Test/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | [assembly: AssemblyTitle("NStandard.NET45.Test")]
5 | [assembly: AssemblyDescription("")]
6 | [assembly: AssemblyConfiguration("")]
7 | [assembly: AssemblyCompany("")]
8 | [assembly: AssemblyProduct("NStandard.NET45.Test")]
9 | [assembly: AssemblyCopyright("Copyright © 2021")]
10 | [assembly: AssemblyTrademark("")]
11 | [assembly: AssemblyCulture("")]
12 |
13 | [assembly: ComVisible(false)]
14 |
15 | [assembly: Guid("cfb18713-2221-456b-82a7-4f0302ba527e")]
16 |
17 | // [assembly: AssemblyVersion("1.0.*")]
18 | [assembly: AssemblyVersion("1.0.0.0")]
19 | [assembly: AssemblyFileVersion("1.0.0.0")]
20 |
--------------------------------------------------------------------------------
/Tests/NStandard.NET45.Test/TupleTests.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.VisualStudio.TestTools.UnitTesting;
2 | using System;
3 | using System.Linq;
4 |
5 | namespace NStandard.NET45.Test
6 | {
7 | [TestClass]
8 | public class TupleTests
9 | {
10 | [TestMethod]
11 | public void Test1()
12 | {
13 | var arr = new[]
14 | {
15 | Tuple.Create(3, 2),
16 | Tuple.Create(3, 1),
17 | };
18 | var ordered = arr.OrderBy(x => x).ToArray();
19 | Assert.AreEqual(1, ordered[0].Item2);
20 | Assert.AreEqual(2, ordered[1].Item2);
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Tests/NStandard.NET45.Test/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Extensions/!System.Collections/!Generic/LinkedListExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 |
3 | namespace NStandard.Test;
4 |
5 | public class LinkedListExtensionsTests
6 | {
7 | [Fact]
8 | public void Test1()
9 | {
10 | var arr = new[] { 1, 2, 3, 4, 5 };
11 | var list = new LinkedList(arr);
12 | LinkedListNode node;
13 |
14 | node = list.GetNodes().First(x => x.Value == 1);
15 | Assert.Null(node.Previous);
16 | Assert.Equal(2, node.Next.Value);
17 |
18 | node = list.GetNodes().First(x => x.Value == 3);
19 | Assert.Equal(2, node.Previous.Value);
20 | Assert.Equal(4, node.Next.Value);
21 |
22 | node = list.GetNodes().First(x => x.Value == 5);
23 | Assert.Equal(4, node.Previous.Value);
24 | Assert.Null(node.Next);
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Extensions/!System.Net/IPAddressExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Static.Net;
2 | using System.Net;
3 | using Xunit;
4 |
5 | namespace NStandard.Test;
6 |
7 | public class IPAddressExtensionsTests
8 | {
9 | [Fact]
10 | public void IPv4Test()
11 | {
12 | var uint32 = IPAddress.Parse("255.0.255.0").ToUInt32();
13 | Assert.Equal(0xFF00FF00, uint32);
14 |
15 | var str = IPAddressEx.Create(uint32).ToString();
16 | Assert.Equal("255.0.255.0", str);
17 | }
18 |
19 | #if NET7_0_OR_GREATER
20 | [Fact]
21 | public void IPv6Test2()
22 | {
23 | var uint128 = IPAddress.Parse("FFFF:0000:FFFF:0000:FFFF:0000:FFFF:0000").ToUInt128();
24 | Assert.Equal(new UInt128(0xFFFF0000FFFF0000, 0xFFFF0000FFFF0000), uint128);
25 |
26 | var str = IPAddressEx.Create(uint128).ToString();
27 | Assert.Equal("ffff:0:ffff:0:ffff:0:ffff:0", str);
28 | }
29 | #endif
30 | }
31 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Extensions/!System.Reflection/EventInfoExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 |
3 | namespace NStandard.Test;
4 |
5 | public class EventInfoExtensionsTests
6 | {
7 | private class OneClass
8 | {
9 | public static void Func(List list) => list.Add(DateTime.Now);
10 | public event Action> Event;
11 | public void CallEvent(List list) => Event?.Invoke(list);
12 | }
13 |
14 | [Fact]
15 | public void Test1()
16 | {
17 | var one = new OneClass();
18 | var eventType = typeof(OneClass).GetEvent(nameof(OneClass.Event));
19 | var functionType = typeof(OneClass).GetMethod(nameof(OneClass.Func));
20 |
21 | one.Event += OneClass.Func;
22 | eventType.AddEventHandler(one, functionType);
23 |
24 | var list = new List();
25 | one.CallEvent(list);
26 | Assert.Equal(2, list.Count);
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Extensions/!System.Threading/!Tasks/TaskExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 |
3 | namespace NStandard.Test;
4 |
5 | public class TaskExtensionsTests
6 | {
7 | [Fact]
8 | public void CatchTest()
9 | {
10 | var task = Task.Run(() =>
11 | {
12 | Thread.Sleep(1000);
13 | throw new InvalidOperationException("Exception...");
14 | });
15 |
16 | Exception exception = null;
17 | task.Catch(ex => exception = ex);
18 | Assert.Equal("Exception...", exception.InnerException.Message);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Extensions/AppDomainExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | using Xunit;
2 |
3 | namespace NStandard.Test;
4 |
5 | public class AppDomainExtensionsTests
6 | {
7 | [Fact]
8 | public void Test1()
9 | {
10 | var coreLib = AppDomain.CurrentDomain.GetCoreLibAssembly();
11 | var sr = coreLib.GetType("System.SR").GetDeclaredMethodViaQualifiedName("System.String GetResourceString(System.String)");
12 | var resourceString = sr.Invoke(null, ["Argument_EnumTypeDoesNotMatch"]);
13 |
14 | Assert.Equal("The argument type, '{0}', is not the same as the enum type '{1}'.", resourceString);
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Extensions/AssemblyExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using Xunit;
3 |
4 | namespace NStandard.Test;
5 |
6 | public class AssemblyExtensionsTests
7 | {
8 | public interface IA { }
9 |
10 | public class A : IA { }
11 | public class B : A { }
12 | [Mark]
13 | public class C : B { }
14 |
15 | public class MarkAttribute : Attribute { }
16 |
17 | [Fact]
18 | public void Test1()
19 | {
20 | var assembly = Assembly.GetExecutingAssembly();
21 |
22 | Assert.Equal([typeof(B)], assembly.GetTypesWhichExtends(false));
23 | Assert.Equal([typeof(B), typeof(C)], assembly.GetTypesWhichExtends(true));
24 |
25 | Assert.Equal([typeof(A), typeof(B), typeof(C)], assembly.GetTypesWhichImplements());
26 | Assert.Equal([typeof(C)], assembly.GetTypesWhichMarkedAs());
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Static/Collections/Generic/EnumerableExTests.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Static.Collections.Generic;
2 | using Xunit;
3 |
4 | namespace NStandard.Test;
5 |
6 | public class EnumerableExTests
7 | {
8 | [Fact]
9 | public void Test1()
10 | {
11 | static IEnumerable Range(int start, int end)
12 | {
13 | for (int i = start; i <= end; i++)
14 | {
15 | yield return i;
16 | }
17 | }
18 |
19 | var ranges = new[]
20 | {
21 | Range(1, 3),
22 | Range(4, 6),
23 | Range(7, 9),
24 | }.AsEnumerable();
25 |
26 | var s = EnumerableEx.Concat(ranges).Join("");
27 | Assert.Equal("123456789", s);
28 | }
29 |
30 | [Fact]
31 | public void Test2()
32 | {
33 | var s = new string(EnumerableEx.Concat("123", "456", "789").ToArray());
34 | Assert.Equal("123456789", s);
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Static/ConvertExTests.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Static;
2 | using System.Text;
3 | using Xunit;
4 |
5 | namespace NStandard.Test;
6 |
7 | public class ConvertExTests
8 | {
9 | [Fact]
10 | public void ChangeTypeTest()
11 | {
12 | DateTime? ndt, expected;
13 |
14 | ndt = ConvertEx.ChangeType("2019/12/11 8:58:57", typeof(DateTime?)) as DateTime?;
15 | expected = (DateTime?)DateTime.Parse("2019/12/11 8:58:57");
16 | Assert.Equal(expected, ndt);
17 |
18 | ndt = ConvertEx.ChangeType(null, typeof(DateTime?)) as DateTime?;
19 | Assert.Null(ndt);
20 |
21 | Assert.Throws(() => Convert.ChangeType("2019/12/11 8:58:57", typeof(DateTime?)));
22 | }
23 |
24 | [Fact]
25 | public void Base58Test()
26 | {
27 | Assert.Equal("zpsEBKbce3iT", ConvertEx.ToBase58String("NStandard".Pipe(Encoding.UTF8.GetBytes)));
28 | Assert.Equal("NStandard", ConvertEx.FromBase58String("zpsEBKbce3iT").Pipe(Encoding.UTF8.GetString));
29 |
30 | Assert.Equal("111zpsEBKbce3iT", ConvertEx.ToBase58String("\0\0\0NStandard".Pipe(Encoding.UTF8.GetBytes)));
31 | Assert.Equal("\0\0\0NStandard", ConvertEx.FromBase58String("111zpsEBKbce3iT").Pipe(Encoding.UTF8.GetString));
32 | }
33 |
34 | [Fact]
35 | public void Base32Test()
36 | {
37 | }
38 |
39 | }
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Static/Drawing/ColorExTests.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Static.Drawing;
2 | using System.Drawing;
3 | using Xunit;
4 |
5 | namespace NStandard.Test;
6 |
7 | public class ColorExTests
8 | {
9 | [Fact]
10 | public void AhsvTest()
11 | {
12 | var random = new Random();
13 | int step(int i) => random.Next(256 - i) % 3 + 1;
14 |
15 | for (var r = 0; r < 256; r += step(r))
16 | {
17 | for (var g = 0; g < 256; g += step(g))
18 | {
19 | for (var b = 0; b < 256; b += step(b))
20 | {
21 | var color = Color.FromArgb(r, g, b);
22 | var ashvColor = ColorEx.CreateFromAhsv
23 | (color.GetHueOfHsv(), color.GetSaturationOfHsv(), color.GetValueOfHsv());
24 |
25 | Assert.Equal(color, ashvColor);
26 | }
27 | }
28 | }
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Static/GuidEx.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Static;
2 | using Xunit;
3 |
4 | namespace NStandard.Test;
5 |
6 | public class GuidExTest
7 | {
8 | [Fact]
9 | public void Test1()
10 | {
11 | Assert.Equal(Guid.Empty.ToString(), GuidEx.EmptyString);
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Static/Linq/Expressions/ExpressionExTests.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Static.Linq.Expressions;
2 | using System.Linq.Expressions;
3 | using Xunit;
4 | namespace NStandard.Test;
5 |
6 | public class ExpressionExTests
7 | {
8 | public class Model
9 | {
10 | public string Name { get; set; }
11 | public int Value { get; set; }
12 | }
13 |
14 | [Fact]
15 | public void Test1()
16 | {
17 | var model = new Model { Name = "A" };
18 | Expression> exp = x => x.Value;
19 | var setter = ExpressionEx.GetSetterExpression(exp).Compile();
20 | setter(model, 100);
21 | Assert.Equal(100, model.Value);
22 | }
23 | }
24 |
25 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Static/ObjectExTests.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Static;
2 | using Xunit;
3 |
4 | namespace NStandard.Test;
5 |
6 | public class ObjectExTests
7 | {
8 | private class Cls
9 | {
10 | public int A { get; set; }
11 | public int B { get; set; }
12 | }
13 |
14 | [Fact]
15 | public void Test1()
16 | {
17 | var a = new Cls { A = 123, B = 234 };
18 |
19 | ObjectEx.AcceptPropValues(a, new { A = 111 });
20 | Assert.Equal(111, a.A);
21 | Assert.Equal(234, a.B);
22 | }
23 |
24 | [Fact]
25 | public void CrossEqualsTest()
26 | {
27 | Assert.True(ObjectEx.CrossEquals(1, 1, 1));
28 | Assert.False(ObjectEx.CrossEquals(1, 1, 2));
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!Static/Reflection/MethodInfoExTests.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Static.Reflection;
2 | using Xunit;
3 |
4 | namespace NStandard.Test;
5 |
6 | public class MethodInfoExTests
7 | {
8 | [Fact]
9 | public void Test()
10 | {
11 | var method1 = MethodInfoEx.GetMethodInfo(() => MethodInfoEx.GetMethodInfo);
12 | var method2 = MethodInfoEx.GetMethodInfo(() => MethodInfoEx.GetMethodInfo);
13 | Assert.Equal(method1, method2);
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!data-structures/IntClass.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Test;
2 |
3 | public class IntClass
4 | {
5 | public int Value { get; set; }
6 | }
7 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!data-structures/IntStrcut.cs:
--------------------------------------------------------------------------------
1 | namespace NStandard.Test;
2 |
3 | public struct IntStrcut
4 | {
5 | public int Value { get; set; }
6 | }
7 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!extern/IEnumerableExtensions.MaxOrDefault.cs:
--------------------------------------------------------------------------------
1 | namespace LinqSharp;
2 |
3 | public static partial class IEnumerableExtensions
4 | {
5 | public static int MaxOrDefault(this IEnumerable source, int @default = default(int)) => source.Any() ? source.Max() : @default;
6 | }
7 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!extern/IEnumerableExtensions.WhereMax.cs:
--------------------------------------------------------------------------------
1 | namespace LinqSharp;
2 |
3 | public static partial class IEnumerableExtensions
4 | {
5 | public static IEnumerable WhereMax(this IEnumerable source, Func selector)
6 | {
7 | if (source.Any())
8 | {
9 | var max = source.Max(selector);
10 | return source.Where(x => selector(x).Equals(max));
11 | }
12 | else return source;
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/!extern/IEnumerableExtensions.WhereMin.cs:
--------------------------------------------------------------------------------
1 | namespace LinqSharp;
2 |
3 | public static partial class IEnumerableExtensions
4 | {
5 | public static IEnumerable WhereMin(this IEnumerable source, Func selector)
6 | {
7 | if (source.Any())
8 | {
9 | var min = source.Min(selector);
10 | return source.Where(x => selector(x).Equals(min));
11 | }
12 | else return source;
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Tests/NStandard.Test/ArrayVisitorTests.cs:
--------------------------------------------------------------------------------
1 | using NStandard.Collections;
2 | using Xunit;
3 |
4 | namespace NStandard.Test;
5 |
6 | public class ArrayVisitorTests
7 | {
8 | [Fact]
9 | public void TypeNotSameTest()
10 | {
11 | var src = new string[4, 4].Let((i0, i1) => $"{i0}, {i1}");
12 | var visitor = new ArrayVisitor