From dfe1d86af2a575e3023ff6df991d52b49ddc4852 Mon Sep 17 00:00:00 2001 From: BlubbFish Date: Tue, 10 Dec 2019 20:20:45 +0100 Subject: [PATCH] Bleeding next --- .../Collections/CollectionCacheRepository.cs | 4 +- .../Configuration/PropertyDisplayAttribute.cs | 62 -- Swan.Tiny/Definitions.Types.cs | 50 -- .../DependencyContainer.cs | 424 ------------- ...ependencyContainerRegistrationException.cs | 13 - .../DependencyContainerResolveOptions.cs | 22 +- .../DependencyInjection/ObjectFactoryBase.cs | 10 +- .../DependencyInjection/RegisterOptions.cs | 103 +--- Swan.Tiny/Diagnostics/HighResolutionTimer.cs | 9 +- Swan.Tiny/Extensions.ByteArrays.cs | 464 --------------- Swan.Tiny/Extensions.Dictionaries.cs | 18 - Swan.Tiny/Extensions.Functional.cs | 131 ---- Swan.Tiny/Extensions.Reflection.cs | 151 ----- Swan.Tiny/Extensions.Strings.cs | 161 ----- Swan.Tiny/Extensions.ValueTypes.cs | 109 ---- Swan.Tiny/Extensions.cs | 116 ---- .../Formatters/Json.SerializerOptions.cs | 2 +- Swan.Tiny/Formatters/Json.cs | 134 +---- Swan.Tiny/Formatters/JsonPropertyAttribute.cs | 10 - .../Logging/LogMessageReceivedEventArgs.cs | 11 +- Swan.Tiny/Logging/Logger.cs | 367 +----------- Swan.Tiny/Mappers/ObjectMap.cs | 74 --- .../ObjectMapper.PropertyInfoComparer.cs | 20 - Swan.Tiny/Mappers/ObjectMapper.cs | 84 --- Swan.Tiny/Net/Dns/DnsClient.Interfaces.cs | 96 --- Swan.Tiny/Net/Dns/DnsClient.Request.cs | 559 ------------------ .../Net/Dns/DnsClient.ResourceRecords.cs | 344 ----------- Swan.Tiny/Net/Dns/DnsClient.Response.cs | 174 ------ Swan.Tiny/Net/Dns/DnsClient.cs | 65 -- Swan.Tiny/Net/Dns/DnsQueryException.cs | 29 - Swan.Tiny/Net/Dns/DnsQueryResult.cs | 131 ---- Swan.Tiny/Net/Dns/DnsRecord.cs | 240 -------- Swan.Tiny/Net/Dns/Enums.Dns.cs | 168 ------ Swan.Tiny/Net/Network.cs | 275 +-------- Swan.Tiny/ProcessRunner.cs | 19 - Swan.Tiny/Reflection/AttributeCache.cs | 94 --- Swan.Tiny/Reflection/ConstructorTypeCache.cs | 10 - Swan.Tiny/Reflection/ExtendedTypeInfo.cs | 9 - Swan.Tiny/Reflection/IPropertyProxy.cs | 22 - Swan.Tiny/Reflection/PropertyProxy.cs | 44 -- Swan.Tiny/Reflection/PropertyTypeCache.cs | 10 - Swan.Tiny/Reflection/TypeCache.cs | 26 - Swan.Tiny/StructEndiannessAttribute.cs | 27 - Swan.Tiny/SwanRuntime.cs | 168 +----- Swan.Tiny/Terminal.Output.cs | 55 -- Swan.Tiny/Terminal.Settings.cs | 24 - Swan.Tiny/Terminal.cs | 137 +---- Swan.Tiny/Threading/AtomicTypeBase.cs | 90 --- Swan.Tiny/Threading/ExclusiveTimer.cs | 72 --- Swan.Tiny/Threading/WaitEventFactory.cs | 8 - 50 files changed, 22 insertions(+), 5423 deletions(-) delete mode 100644 Swan.Tiny/Configuration/PropertyDisplayAttribute.cs delete mode 100644 Swan.Tiny/Mappers/ObjectMapper.PropertyInfoComparer.cs delete mode 100644 Swan.Tiny/Net/Dns/DnsClient.Interfaces.cs delete mode 100644 Swan.Tiny/Net/Dns/DnsClient.Request.cs delete mode 100644 Swan.Tiny/Net/Dns/DnsClient.ResourceRecords.cs delete mode 100644 Swan.Tiny/Net/Dns/DnsClient.Response.cs delete mode 100644 Swan.Tiny/Net/Dns/DnsClient.cs delete mode 100644 Swan.Tiny/Net/Dns/DnsQueryException.cs delete mode 100644 Swan.Tiny/Net/Dns/DnsQueryResult.cs delete mode 100644 Swan.Tiny/Net/Dns/DnsRecord.cs delete mode 100644 Swan.Tiny/Net/Dns/Enums.Dns.cs delete mode 100644 Swan.Tiny/Reflection/IPropertyProxy.cs delete mode 100644 Swan.Tiny/Reflection/PropertyProxy.cs delete mode 100644 Swan.Tiny/StructEndiannessAttribute.cs diff --git a/Swan.Tiny/Collections/CollectionCacheRepository.cs b/Swan.Tiny/Collections/CollectionCacheRepository.cs index 008b9a8..ef42e09 100644 --- a/Swan.Tiny/Collections/CollectionCacheRepository.cs +++ b/Swan.Tiny/Collections/CollectionCacheRepository.cs @@ -11,12 +11,12 @@ namespace Swan.Collections { public class CollectionCacheRepository { private readonly Lazy>> _data = new Lazy>>(() => new ConcurrentDictionary>(), true); - /// + /*/// /// Determines whether the cache contains the specified key. /// /// The key. /// true if the cache contains the key, otherwise false. - public Boolean ContainsKey(Type key) => this._data.Value.ContainsKey(key); + public Boolean ContainsKey(Type key) => this._data.Value.ContainsKey(key);*/ /// /// Retrieves the properties stored for the specified type. diff --git a/Swan.Tiny/Configuration/PropertyDisplayAttribute.cs b/Swan.Tiny/Configuration/PropertyDisplayAttribute.cs deleted file mode 100644 index f80a799..0000000 --- a/Swan.Tiny/Configuration/PropertyDisplayAttribute.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; - -namespace Swan.Configuration { - /// - /// An attribute used to include additional information to a Property for serialization. - /// - /// Previously we used DisplayAttribute from DataAnnotation. - /// - /// - [AttributeUsage(AttributeTargets.Property)] - public sealed class PropertyDisplayAttribute : Attribute { - /*/// - /// Gets or sets the name. - /// - /// - /// The name. - /// - public String Name { - get; set; - } - - /// - /// Gets or sets the description. - /// - /// - /// The description. - /// - public String Description { - get; set; - } - - /// - /// Gets or sets the name of the group. - /// - /// - /// The name of the group. - /// - public String GroupName { - get; set; - }*/ - - /// - /// Gets or sets the default value. - /// - /// - /// The default value. - /// - public Object DefaultValue { - get; set; - } - - /// - /// Gets or sets the format string to call with method ToString. - /// - /// - /// The format. - /// - public String Format { - get; set; - } - } -} diff --git a/Swan.Tiny/Definitions.Types.cs b/Swan.Tiny/Definitions.Types.cs index 75a31a3..5a4c97f 100644 --- a/Swan.Tiny/Definitions.Types.cs +++ b/Swan.Tiny/Definitions.Types.cs @@ -62,36 +62,6 @@ namespace Swan { #endregion - /*/// - /// Contains all basic types, including string, date time, and all of their nullable counterparts. - /// - /// - /// All basic types. - /// - public static IReadOnlyCollection AllBasicTypes { get; } = new ReadOnlyCollection(BasicTypesInfo.Value.Keys.ToArray()); - - /// - /// Gets all numeric types including their nullable counterparts. - /// Note that Booleans and Guids are not considered numeric types. - /// - /// - /// All numeric types. - /// - public static IReadOnlyCollection AllNumericTypes { - get; - } = new ReadOnlyCollection(BasicTypesInfo.Value.Where(kvp => kvp.Value.IsNumeric).Select(kvp => kvp.Key).ToArray()); - - /// - /// Gets all numeric types without their nullable counterparts. - /// Note that Booleans and Guids are not considered numeric types. - /// - /// - /// All numeric value types. - /// - public static IReadOnlyCollection AllNumericValueTypes { - get; - } = new ReadOnlyCollection(BasicTypesInfo.Value.Where(kvp => kvp.Value.IsNumeric && !kvp.Value.IsNullableValueType).Select(kvp => kvp.Key).ToArray());*/ - /// /// Contains all basic value types. i.e. excludes string and nullables. /// @@ -101,25 +71,5 @@ namespace Swan { public static IReadOnlyCollection AllBasicValueTypes { get; } = new ReadOnlyCollection(BasicTypesInfo.Value.Where(kvp => kvp.Value.IsValueType).Select(kvp => kvp.Key).ToArray()); - - /*/// - /// Contains all basic value types including the string type. i.e. excludes nullables. - /// - /// - /// All basic value and string types. - /// - public static IReadOnlyCollection AllBasicValueAndStringTypes { - get; - } = new ReadOnlyCollection(BasicTypesInfo.Value.Where(kvp => kvp.Value.IsValueType || kvp.Key == typeof(String)).Select(kvp => kvp.Key).ToArray()); - - /// - /// Gets all nullable value types. i.e. excludes string and all basic value types. - /// - /// - /// All basic nullable value types. - /// - public static IReadOnlyCollection AllBasicNullableValueTypes { - get; - } = new ReadOnlyCollection(BasicTypesInfo.Value.Where(kvp => kvp.Value.IsNullableValueType).Select(kvp => kvp.Key).ToArray());*/ } } diff --git a/Swan.Tiny/DependencyInjection/DependencyContainer.cs b/Swan.Tiny/DependencyInjection/DependencyContainer.cs index 6dbf95a..9e38667 100644 --- a/Swan.Tiny/DependencyInjection/DependencyContainer.cs +++ b/Swan.Tiny/DependencyInjection/DependencyContainer.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Reflection; namespace Swan.DependencyInjection { /// @@ -10,13 +8,8 @@ namespace Swan.DependencyInjection { /// /// public partial class DependencyContainer : IDisposable { - /*private readonly Object _autoRegisterLock = new Object();*/ - private Boolean _disposed; - /*static DependencyContainer() { - }*/ - /// /// Initializes a new instance of the class. /// @@ -25,8 +18,6 @@ namespace Swan.DependencyInjection { _ = this.Register(this); } - /*private DependencyContainer(DependencyContainer parent) : this() => this.Parent = parent;*/ - /// /// Lazy created Singleton instance of the container for simple scenarios. /// @@ -55,91 +46,8 @@ namespace Swan.DependencyInjection { GC.SuppressFinalize(this); } - /*/// - /// Gets the child container. - /// - /// A new instance of the class. - public DependencyContainer GetChildContainer() => new DependencyContainer(this);*/ - #region Registration - /*/// - /// Attempt to automatically register all non-generic classes and interfaces in the current app domain. - /// Types will only be registered if they pass the supplied registration predicate. - /// - /// What action to take when encountering duplicate implementations of an interface/base class. - /// Predicate to determine if a particular type should be registered. - public void AutoRegister(DependencyContainerDuplicateImplementationAction duplicateAction = DependencyContainerDuplicateImplementationAction.RegisterSingle, Func registrationPredicate = null) => this.AutoRegister(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), duplicateAction, registrationPredicate); - - /// - /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies - /// Types will only be registered if they pass the supplied registration predicate. - /// - /// Assemblies to process. - /// What action to take when encountering duplicate implementations of an interface/base class. - /// Predicate to determine if a particular type should be registered. - public void AutoRegister(IEnumerable assemblies, DependencyContainerDuplicateImplementationAction duplicateAction = DependencyContainerDuplicateImplementationAction.RegisterSingle, Func registrationPredicate = null) { - lock(this._autoRegisterLock) { - List types = assemblies.SelectMany(a => a.GetAllTypes()).Where(t => !IsIgnoredType(t, registrationPredicate)).ToList(); - - List concreteTypes = types.Where(type => type.IsClass && !type.IsAbstract && type != this.GetType() && type.DeclaringType != this.GetType() && !type.IsGenericTypeDefinition).ToList(); - - foreach(Type type in concreteTypes) { - try { - _ = this.RegisteredTypes.Register(type, String.Empty, GetDefaultObjectFactory(type, type)); - } catch(MethodAccessException) { - // Ignore methods we can't access - added for Silverlight - } - } - - IEnumerable abstractInterfaceTypes = types.Where(type => (type.IsInterface || type.IsAbstract) && type.DeclaringType != this.GetType() && !type.IsGenericTypeDefinition); - - foreach(Type type in abstractInterfaceTypes) { - Type localType = type; - List implementations = concreteTypes.Where(implementationType => localType.IsAssignableFrom(implementationType)).ToList(); - - if(implementations.Skip(1).Any()) { - if(duplicateAction == DependencyContainerDuplicateImplementationAction.Fail) { - throw new DependencyContainerRegistrationException(type, implementations); - } - - if(duplicateAction == DependencyContainerDuplicateImplementationAction.RegisterMultiple) { - _ = this.RegisterMultiple(type, implementations); - } - } - - Type firstImplementation = implementations.FirstOrDefault(); - - if(firstImplementation == null) { - continue; - } - - try { - _ = this.RegisteredTypes.Register(type, String.Empty, GetDefaultObjectFactory(type, firstImplementation)); - } catch(MethodAccessException) { - // Ignore methods we can't access - added for Silverlight - } - } - } - } - - /// - /// Creates/replaces a named container class registration with default options. - /// - /// Type to register. - /// Name of registration. - /// RegisterOptions for fluent API. - public RegisterOptions Register(Type registerType, String name = "") => this.RegisteredTypes.Register(registerType, name, GetDefaultObjectFactory(registerType, registerType)); - - /// - /// Creates/replaces a named container class registration with a given implementation and default options. - /// - /// Type to register. - /// Type to instantiate that implements RegisterType. - /// Name of registration. - /// RegisterOptions for fluent API. - public RegisterOptions Register(Type registerType, Type registerImplementation, String name = "") => this.RegisteredTypes.Register(registerType, name, GetDefaultObjectFactory(registerType, registerImplementation));*/ - /// /// Creates/replaces a named container class registration with a specific, strong referenced, instance. /// @@ -149,42 +57,6 @@ namespace Swan.DependencyInjection { /// RegisterOptions for fluent API. public RegisterOptions Register(Type registerType, Object instance, String name = "") => this.RegisteredTypes.Register(registerType, name, new InstanceFactory(registerType, registerType, instance)); - /*/// - /// Creates/replaces a named container class registration with a specific, strong referenced, instance. - /// - /// Type to register. - /// Type of instance to register that implements RegisterType. - /// Instance of RegisterImplementation to register. - /// Name of registration. - /// RegisterOptions for fluent API. - public RegisterOptions Register(Type registerType, Type registerImplementation, Object instance, String name = "") => this.RegisteredTypes.Register(registerType, name, new InstanceFactory(registerType, registerImplementation, instance)); - - /// - /// Creates/replaces a container class registration with a user specified factory. - /// - /// Type to register. - /// Factory/lambda that returns an instance of RegisterType. - /// Name of registration. - /// RegisterOptions for fluent API. - public RegisterOptions Register(Type registerType, Func, Object> factory, String name = "") => this.RegisteredTypes.Register(registerType, name, new DelegateFactory(registerType, factory)); - - /// - /// Creates/replaces a named container class registration with default options. - /// - /// Type to register. - /// Name of registration. - /// RegisterOptions for fluent API. - public RegisterOptions Register(String name = "") where TRegister : class => this.Register(typeof(TRegister), name); - - /// - /// Creates/replaces a named container class registration with a given implementation and default options. - /// - /// Type to register. - /// Type to instantiate that implements RegisterType. - /// Name of registration. - /// RegisterOptions for fluent API. - public RegisterOptions Register(String name = "") where TRegister : class where TRegisterImplementation : class, TRegister => this.Register(typeof(TRegister), typeof(TRegisterImplementation), name);*/ - /// /// Creates/replaces a named container class registration with a specific, strong referenced, instance. /// @@ -195,91 +67,6 @@ namespace Swan.DependencyInjection { // [Obsolete("NEED", false)] public RegisterOptions Register(TRegister instance, String name = "") where TRegister : class => this.Register(typeof(TRegister), instance, name); - /*/// - /// Creates/replaces a named container class registration with a specific, strong referenced, instance. - /// - /// Type to register. - /// Type of instance to register that implements RegisterType. - /// Instance of RegisterImplementation to register. - /// Name of registration. - /// RegisterOptions for fluent API. - public RegisterOptions Register(TRegisterImplementation instance, String name = "") where TRegister : class where TRegisterImplementation : class, TRegister => this.Register(typeof(TRegister), typeof(TRegisterImplementation), instance, name); - - /// - /// Creates/replaces a named container class registration with a user specified factory. - /// - /// Type to register. - /// Factory/lambda that returns an instance of RegisterType. - /// Name of registration. - /// RegisterOptions for fluent API. - public RegisterOptions Register(Func, TRegister> factory, String name = "") where TRegister : class { - if(factory == null) { - throw new ArgumentNullException(nameof(factory)); - } - - return this.Register(typeof(TRegister), factory, name); - } - - /// - /// Register multiple implementations of a type. - /// - /// Internally this registers each implementation using the full name of the class as its registration name. - /// - /// Type that each implementation implements. - /// Types that implement RegisterType. - /// MultiRegisterOptions for the fluent API. - public MultiRegisterOptions RegisterMultiple(IEnumerable implementationTypes) => this.RegisterMultiple(typeof(TRegister), implementationTypes); - - /// - /// Register multiple implementations of a type. - /// - /// Internally this registers each implementation using the full name of the class as its registration name. - /// - /// Type that each implementation implements. - /// Types that implement RegisterType. - /// MultiRegisterOptions for the fluent API. - public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable implementationTypes) { - if(implementationTypes == null) { - throw new ArgumentNullException(nameof(implementationTypes), "types is null."); - } - - foreach(Type type in implementationTypes.Where(type => !registrationType.IsAssignableFrom(type))) { - throw new ArgumentException($"types: The type {registrationType.FullName} is not assignable from {type.FullName}"); - } - - if(implementationTypes.Count() != implementationTypes.Distinct().Count()) { - IEnumerable queryForDuplicatedTypes = implementationTypes.GroupBy(i => i).Where(j => j.Count() > 1).Select(j => j.Key.FullName); - - String fullNamesOfDuplicatedTypes = String.Join(",\n", queryForDuplicatedTypes.ToArray()); - - throw new ArgumentException($"types: The same implementation type cannot be specified multiple times for {registrationType.FullName}\n\n{fullNamesOfDuplicatedTypes}"); - } - - List registerOptions = implementationTypes.Select(type => this.Register(registrationType, type, type.FullName)).ToList(); - - return new MultiRegisterOptions(registerOptions); - }*/ - - #endregion - - #region Unregistration - - /*/// - /// Remove a named container class registration. - /// - /// Type to unregister. - /// Name of registration. - /// true if the registration is successfully found and removed; otherwise, false. - public Boolean Unregister(String name = "") => this.Unregister(typeof(TRegister), name); - - /// - /// Remove a named container class registration. - /// - /// Type to unregister. - /// Name of registration. - /// true if the registration is successfully found and removed; otherwise, false. - public Boolean Unregister(Type registerType, String name = "") => this.RegisteredTypes.RemoveRegistration(new TypeRegistration(registerType, name));*/ - #endregion #region Resolution @@ -342,179 +129,6 @@ namespace Swan.DependencyInjection { // [Obsolete("NEED", false)] public Boolean CanResolve(String name = null, DependencyContainerResolveOptions options = null) where TResolveType : class => this.CanResolve(typeof(TResolveType), name, options); - /*/// - /// Attempts to resolve a type using the default options. - /// - /// Type to resolve. - /// Resolved type or default if resolve fails. - /// true if resolved successfully, false otherwise. - public Boolean TryResolve(Type resolveType, out Object resolvedType) { - try { - resolvedType = this.Resolve(resolveType); - return true; - } catch(DependencyContainerResolutionException) { - resolvedType = null; - return false; - } - } - - /// - /// Attempts to resolve a type using the given options. - /// - /// Type to resolve. - /// Resolution options. - /// Resolved type or default if resolve fails. - /// true if resolved successfully, false otherwise. - public Boolean TryResolve(Type resolveType, DependencyContainerResolveOptions options, out Object resolvedType) { - try { - resolvedType = this.Resolve(resolveType, options: options); - return true; - } catch(DependencyContainerResolutionException) { - resolvedType = null; - return false; - } - } - - /// - /// Attempts to resolve a type using the default options and given name. - /// - /// Type to resolve. - /// Name of registration. - /// Resolved type or default if resolve fails. - /// true if resolved successfully, false otherwise. - public Boolean TryResolve(Type resolveType, String name, out Object resolvedType) { - try { - resolvedType = this.Resolve(resolveType, name); - return true; - } catch(DependencyContainerResolutionException) { - resolvedType = null; - return false; - } - } - - /// - /// Attempts to resolve a type using the given options and name. - /// - /// Type to resolve. - /// Name of registration. - /// Resolution options. - /// Resolved type or default if resolve fails. - /// true if resolved successfully, false otherwise. - public Boolean TryResolve(Type resolveType, String name, DependencyContainerResolveOptions options, out Object resolvedType) { - try { - resolvedType = this.Resolve(resolveType, name, options); - return true; - } catch(DependencyContainerResolutionException) { - resolvedType = null; - return false; - } - } - - /// - /// Attempts to resolve a type using the default options. - /// - /// Type to resolve. - /// Resolved type or default if resolve fails. - /// true if resolved successfully, false otherwise. - public Boolean TryResolve(out TResolveType resolvedType) where TResolveType : class { - try { - resolvedType = this.Resolve(); - return true; - } catch(DependencyContainerResolutionException) { - resolvedType = default; - return false; - } - } - - /// - /// Attempts to resolve a type using the given options. - /// - /// Type to resolve. - /// Resolution options. - /// Resolved type or default if resolve fails. - /// true if resolved successfully, false otherwise. - public Boolean TryResolve(DependencyContainerResolveOptions options, out TResolveType resolvedType) where TResolveType : class { - try { - resolvedType = this.Resolve(options: options); - return true; - } catch(DependencyContainerResolutionException) { - resolvedType = default; - return false; - } - } - - /// - /// Attempts to resolve a type using the default options and given name. - /// - /// Type to resolve. - /// Name of registration. - /// Resolved type or default if resolve fails. - /// true if resolved successfully, false otherwise. - public Boolean TryResolve(String name, out TResolveType resolvedType) where TResolveType : class { - try { - resolvedType = this.Resolve(name); - return true; - } catch(DependencyContainerResolutionException) { - resolvedType = default; - return false; - } - } - - /// - /// Attempts to resolve a type using the given options and name. - /// - /// Type to resolve. - /// Name of registration. - /// Resolution options. - /// Resolved type or default if resolve fails. - /// true if resolved successfully, false otherwise. - public Boolean TryResolve(String name, DependencyContainerResolveOptions options, out TResolveType resolvedType) where TResolveType : class { - try { - resolvedType = this.Resolve(name, options); - return true; - } catch(DependencyContainerResolutionException) { - resolvedType = default; - return false; - } - } - - /// - /// Returns all registrations of a type. - /// - /// Type to resolveAll. - /// Whether to include un-named (default) registrations. - /// IEnumerable. - public IEnumerable ResolveAll(Type resolveType, Boolean includeUnnamed = false) => this.RegisteredTypes.Resolve(resolveType, includeUnnamed); - - /// - /// Returns all registrations of a type. - /// - /// Type to resolveAll. - /// Whether to include un-named (default) registrations. - /// IEnumerable. - public IEnumerable ResolveAll(Boolean includeUnnamed = true) where TResolveType : class => this.ResolveAll(typeof(TResolveType), includeUnnamed).Cast(); - - /// - /// Attempts to resolve all public property dependencies on the given object using the given resolve options. - /// - /// Object to "build up". - /// Resolve options to use. - public void BuildUp(Object input, DependencyContainerResolveOptions resolveOptions = null) { - if(resolveOptions == null) { - resolveOptions = DependencyContainerResolveOptions.Default; - } - - IEnumerable properties = input.GetType().GetProperties().Where(property => property.GetCacheGetMethod() != null && property.GetCacheSetMethod() != null && !property.PropertyType.IsValueType); - - foreach(PropertyInfo property in properties.Where(property => property.GetValue(input, null) == null)) { - try { - property.SetValue(input, this.RegisteredTypes.ResolveInternal(new TypeRegistration(property.PropertyType), resolveOptions), null); - } catch(DependencyContainerResolutionException) { - // Catch any resolution errors and ignore them - } - } - }*/ - #endregion #region Internal Methods @@ -537,44 +151,6 @@ namespace Swan.DependencyInjection { return true; } - /*private static Boolean IsIgnoredAssembly(Assembly assembly) { - // TODO - find a better way to remove "system" assemblies from the auto registration - List> ignoreChecks = new List> - { - asm => asm.FullName.StartsWith("Microsoft.", StringComparison.Ordinal), - asm => asm.FullName.StartsWith("System.", StringComparison.Ordinal), - asm => asm.FullName.StartsWith("System,", StringComparison.Ordinal), - asm => asm.FullName.StartsWith("CR_ExtUnitTest", StringComparison.Ordinal), - asm => asm.FullName.StartsWith("mscorlib,", StringComparison.Ordinal), - asm => asm.FullName.StartsWith("CR_VSTest", StringComparison.Ordinal), - asm => asm.FullName.StartsWith("DevExpress.CodeRush", StringComparison.Ordinal), - asm => asm.FullName.StartsWith("xunit.", StringComparison.Ordinal), - }; - - return ignoreChecks.Any(check => check(assembly)); - } - - private static Boolean IsIgnoredType(Type type, Func registrationPredicate) { - // TODO - find a better way to remove "system" types from the auto registration - List> ignoreChecks = new List>() - { - t => t.FullName?.StartsWith("System.", StringComparison.Ordinal) ?? false, - t => t.FullName?.StartsWith("Microsoft.", StringComparison.Ordinal) ?? false, - t => t.IsPrimitive, - t => t.IsGenericTypeDefinition, - t => t.GetConstructors(BindingFlags.Instance | BindingFlags.Public).Length == 0 && - !(t.IsInterface || t.IsAbstract), - }; - - if(registrationPredicate != null) { - ignoreChecks.Add(t => !registrationPredicate(t)); - } - - return ignoreChecks.Any(check => check(type)); - } - - private static ObjectFactoryBase GetDefaultObjectFactory(Type registerType, Type registerImplementation) => registerType.IsInterface || registerType.IsAbstract ? (ObjectFactoryBase)new SingletonFactory(registerType, registerImplementation) : new MultiInstanceFactory(registerType, registerImplementation);*/ - #endregion } } diff --git a/Swan.Tiny/DependencyInjection/DependencyContainerRegistrationException.cs b/Swan.Tiny/DependencyInjection/DependencyContainerRegistrationException.cs index 422a3e5..58aa519 100644 --- a/Swan.Tiny/DependencyInjection/DependencyContainerRegistrationException.cs +++ b/Swan.Tiny/DependencyInjection/DependencyContainerRegistrationException.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; namespace Swan.DependencyInjection { /// @@ -10,15 +8,6 @@ namespace Swan.DependencyInjection { public class DependencyContainerRegistrationException : Exception { private const String ConvertErrorText = "Cannot convert current registration of {0} to {1}"; private const String RegisterErrorText = "Cannot register type {0} - abstract classes or interfaces are not valid implementation types for {1}."; - /*private const String ErrorText = "Duplicate implementation of type {0} found ({1}).";*/ - - /*/// - /// Initializes a new instance of the class. - /// - /// Type of the register. - /// The types. - public DependencyContainerRegistrationException(Type registerType, IEnumerable types) : base(String.Format(ErrorText, registerType, GetTypesString(types))) { - }*/ /// /// Initializes a new instance of the class. @@ -28,7 +17,5 @@ namespace Swan.DependencyInjection { /// if set to true [is type factory]. public DependencyContainerRegistrationException(Type type, String method, Boolean isTypeFactory = false) : base(isTypeFactory ? String.Format(RegisterErrorText, type.FullName, method) : String.Format(ConvertErrorText, type.FullName, method)) { } - - /*private static String GetTypesString(IEnumerable types) => String.Join(",", types.Select(type => type.FullName));*/ } } \ No newline at end of file diff --git a/Swan.Tiny/DependencyInjection/DependencyContainerResolveOptions.cs b/Swan.Tiny/DependencyInjection/DependencyContainerResolveOptions.cs index 1d7fd6b..8c76670 100644 --- a/Swan.Tiny/DependencyInjection/DependencyContainerResolveOptions.cs +++ b/Swan.Tiny/DependencyInjection/DependencyContainerResolveOptions.cs @@ -82,25 +82,5 @@ namespace Swan.DependencyInjection { /// The fail /// Fail, - } - - /*/// - /// Enumerates duplicate definition actions. - /// - public enum DependencyContainerDuplicateImplementationAction { - /// - /// The register single - /// - RegisterSingle, - - /// - /// The register multiple - /// - RegisterMultiple, - - /// - /// The fail - /// - Fail, - }*/ + } } \ No newline at end of file diff --git a/Swan.Tiny/DependencyInjection/ObjectFactoryBase.cs b/Swan.Tiny/DependencyInjection/ObjectFactoryBase.cs index 89a43f1..00e8f17 100644 --- a/Swan.Tiny/DependencyInjection/ObjectFactoryBase.cs +++ b/Swan.Tiny/DependencyInjection/ObjectFactoryBase.cs @@ -107,7 +107,7 @@ namespace Swan.DependencyInjection { public override Type CreatesType => this._registerImplementation; - public override ObjectFactoryBase SingletonVariant => new SingletonFactory(this._registerType, this._registerImplementation); + public override ObjectFactoryBase SingletonVariant => new SingletonFactory(this._registerType, this._registerImplementation); public override ObjectFactoryBase MultiInstanceVariant => this; @@ -129,7 +129,7 @@ namespace Swan.DependencyInjection { private readonly Func, Object> _factory; - public DelegateFactory( Type registerType, Func, Object> factory) { + public DelegateFactory(Type registerType, Func, Object> factory) { this._factory = factory ?? throw new ArgumentNullException(nameof(factory)); this._registerType = registerType; @@ -313,9 +313,9 @@ namespace Swan.DependencyInjection { public override ObjectFactoryBase SingletonVariant => this; - public override ObjectFactoryBase MultiInstanceVariant => new MultiInstanceFactory(this._registerType, this._registerImplementation); + public override ObjectFactoryBase MultiInstanceVariant => new MultiInstanceFactory(this._registerType, this._registerImplementation); - public override Object GetObject( Type requestedType, DependencyContainer container, DependencyContainerResolveOptions options) { + public override Object GetObject(Type requestedType, DependencyContainer container, DependencyContainerResolveOptions options) { if(options.ConstructorParameters.Count != 0) { throw new ArgumentException("Cannot specify parameters for singleton types"); } @@ -329,7 +329,7 @@ namespace Swan.DependencyInjection { return this._current; } - public override ObjectFactoryBase GetFactoryForChildContainer( Type type, DependencyContainer parent, DependencyContainer child) { + public override ObjectFactoryBase GetFactoryForChildContainer(Type type, DependencyContainer parent, DependencyContainer child) { // We make sure that the singleton is constructed before the child container takes the factory. // Otherwise the results would vary depending on whether or not the parent container had resolved // the type before the child container does. diff --git a/Swan.Tiny/DependencyInjection/RegisterOptions.cs b/Swan.Tiny/DependencyInjection/RegisterOptions.cs index b54c378..676b589 100644 --- a/Swan.Tiny/DependencyInjection/RegisterOptions.cs +++ b/Swan.Tiny/DependencyInjection/RegisterOptions.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Swan.DependencyInjection { +namespace Swan.DependencyInjection { /// /// Registration options for "fluent" API. /// @@ -19,100 +15,5 @@ namespace Swan.DependencyInjection { this._registeredTypes = registeredTypes; this._registration = registration; } - - /*/// - /// Make registration a singleton (single instance) if possible. - /// - /// A registration options for fluent API. - /// Generic constraint registration exception. - public RegisterOptions AsSingleton() { - ObjectFactoryBase currentFactory = this._registeredTypes.GetCurrentFactory(this._registration); - - if(currentFactory == null) { - throw new DependencyContainerRegistrationException(this._registration.Type, "singleton"); - } - - return this._registeredTypes.AddUpdateRegistration(this._registration, currentFactory.SingletonVariant); - } - - /// - /// Make registration multi-instance if possible. - /// - /// A registration options for fluent API. - /// Generic constraint registration exception. - public RegisterOptions AsMultiInstance() { - ObjectFactoryBase currentFactory = this._registeredTypes.GetCurrentFactory(this._registration); - - if(currentFactory == null) { - throw new DependencyContainerRegistrationException(this._registration.Type, "multi-instance"); - } - - return this._registeredTypes.AddUpdateRegistration(this._registration, currentFactory.MultiInstanceVariant); - } - - /// - /// Make registration hold a weak reference if possible. - /// - /// A registration options for fluent API. - /// Generic constraint registration exception. - public RegisterOptions WithWeakReference() { - ObjectFactoryBase currentFactory = this._registeredTypes.GetCurrentFactory(this._registration); - - if(currentFactory == null) { - throw new DependencyContainerRegistrationException(this._registration.Type, "weak reference"); - } - - return this._registeredTypes.AddUpdateRegistration(this._registration, currentFactory.WeakReferenceVariant); - } - - /// - /// Make registration hold a strong reference if possible. - /// - /// A registration options for fluent API. - /// Generic constraint registration exception. - public RegisterOptions WithStrongReference() { - ObjectFactoryBase currentFactory = this._registeredTypes.GetCurrentFactory(this._registration); - - if(currentFactory == null) { - throw new DependencyContainerRegistrationException(this._registration.Type, "strong reference"); - } - - return this._registeredTypes.AddUpdateRegistration(this._registration, currentFactory.StrongReferenceVariant); - }*/ - } - - /*/// - /// Registration options for "fluent" API when registering multiple implementations. - /// - public sealed class MultiRegisterOptions { - /*private IEnumerable _registerOptions; - - /// - /// Initializes a new instance of the class. - /// - /// The register options. - public MultiRegisterOptions(IEnumerable registerOptions) => this._registerOptions = registerOptions; - - /// - /// Make registration a singleton (single instance) if possible. - /// - /// A registration multi-instance for fluent API. - /// Generic Constraint Registration Exception. - public MultiRegisterOptions AsSingleton() { - this._registerOptions = this.ExecuteOnAllRegisterOptions(ro => ro.AsSingleton()); - return this; - } - - /// - /// Make registration multi-instance if possible. - /// - /// A registration multi-instance for fluent API. - /// Generic Constraint Registration Exception. - public MultiRegisterOptions AsMultiInstance() { - this._registerOptions = this.ExecuteOnAllRegisterOptions(ro => ro.AsMultiInstance()); - return this; - } - - private IEnumerable ExecuteOnAllRegisterOptions( Func action) => this._registerOptions.Select(action).ToList(); - }*/ + } } \ No newline at end of file diff --git a/Swan.Tiny/Diagnostics/HighResolutionTimer.cs b/Swan.Tiny/Diagnostics/HighResolutionTimer.cs index ed6bb88..bb0425b 100644 --- a/Swan.Tiny/Diagnostics/HighResolutionTimer.cs +++ b/Swan.Tiny/Diagnostics/HighResolutionTimer.cs @@ -18,14 +18,9 @@ namespace Swan.Diagnostics { } } - /// + /*/// /// Gets the number of microseconds per timer tick. /// - public static Double MicrosecondsPerTick { get; } = 1000000d / Frequency; - - /*/// - /// Gets the elapsed microseconds. - /// - public Int64 ElapsedMicroseconds => (Int64)(this.ElapsedTicks * MicrosecondsPerTick);*/ + public static Double MicrosecondsPerTick { get; } = 1000000d / Frequency;*/ } } diff --git a/Swan.Tiny/Extensions.ByteArrays.cs b/Swan.Tiny/Extensions.ByteArrays.cs index 584e8b3..8d8a3bc 100644 --- a/Swan.Tiny/Extensions.ByteArrays.cs +++ b/Swan.Tiny/Extensions.ByteArrays.cs @@ -1,50 +1,11 @@ using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; namespace Swan { /// /// Provides various extension methods for byte arrays and streams. /// public static class ByteArrayExtensions { - /*/// - /// Converts an array of bytes to its lower-case, hexadecimal representation. - /// - /// The bytes. - /// if set to true add the 0x prefix tot he output. - /// - /// The specified string instance; no actual conversion is performed. - /// - /// bytes. - public static String ToLowerHex(this Byte[] bytes, Boolean addPrefix = false) => ToHex(bytes, addPrefix, "x2"); - - /// - /// Converts an array of bytes to its upper-case, hexadecimal representation. - /// - /// The bytes. - /// if set to true [add prefix]. - /// - /// The specified string instance; no actual conversion is performed. - /// - /// bytes. - public static String ToUpperHex(this Byte[] bytes, Boolean addPrefix = false) => ToHex(bytes, addPrefix, "X2"); - - /// - /// Converts an array of bytes to a sequence of dash-separated, hexadecimal, - /// uppercase characters. - /// - /// The bytes. - /// - /// A string of hexadecimal pairs separated by hyphens, where each pair represents - /// the corresponding element in value; for example, "7F-2C-4A-00". - /// - public static String ToDashedHex(this Byte[] bytes) => BitConverter.ToString(bytes);*/ - /// /// Converts an array of bytes to a base-64 encoded string. /// @@ -69,430 +30,5 @@ namespace Swan { return Enumerable.Range(0, @this.Length / 2).Select(x => Convert.ToByte(@this.Substring(x * 2, 2), 16)).ToArray(); } - - /*/// - /// Gets the bit value at the given offset. - /// - /// The b. - /// The offset. - /// The length. - /// - /// Bit value at the given offset. - /// - public static Byte GetBitValueAt(this Byte @this, Byte offset, Byte length = 1) => (Byte)((@this >> offset) & ~(0xff << length)); - - /// - /// Sets the bit value at the given offset. - /// - /// The b. - /// The offset. - /// The length. - /// The value. - /// Bit value at the given offset. - public static Byte SetBitValueAt(this Byte @this, Byte offset, Byte length, Byte value) { - Int32 mask = ~(0xff << length); - Byte valueAt = (Byte)(value & mask); - - return (Byte)((valueAt << offset) | (@this & ~(mask << offset))); - } - - /// - /// Sets the bit value at the given offset. - /// - /// The b. - /// The offset. - /// The value. - /// Bit value at the given offset. - public static Byte SetBitValueAt(this Byte @this, Byte offset, Byte value) => @this.SetBitValueAt(offset, 1, value); - - /// - /// Splits a byte array delimited by the specified sequence of bytes. - /// Each individual element in the result will contain the split sequence terminator if it is found to be delimited by it. - /// For example if you split [1,2,3,4] by a sequence of [2,3] this method will return a list with 2 byte arrays, one containing [1,2,3] and the - /// second one containing 4. Use the Trim extension methods to remove terminator sequences. - /// - /// The buffer. - /// The offset at which to start splitting bytes. Any bytes before this will be discarded. - /// The sequence. - /// - /// A byte array containing the results the specified sequence of bytes. - /// - /// - /// buffer - /// or - /// sequence. - /// - public static List Split(this Byte[] @this, Int32 offset, params Byte[] sequence) { - if(@this == null) { - throw new ArgumentNullException(nameof(@this)); - } - - if(sequence == null) { - throw new ArgumentNullException(nameof(sequence)); - } - - Int32 seqOffset = offset.Clamp(0, @this.Length - 1); - - List result = new List(); - - while(seqOffset < @this.Length) { - Int32 separatorStartIndex = @this.GetIndexOf(sequence, seqOffset); - - if(separatorStartIndex >= 0) { - Byte[] item = new Byte[separatorStartIndex - seqOffset + sequence.Length]; - Array.Copy(@this, seqOffset, item, 0, item.Length); - result.Add(item); - seqOffset += item.Length; - } else { - Byte[] item = new Byte[@this.Length - seqOffset]; - Array.Copy(@this, seqOffset, item, 0, item.Length); - result.Add(item); - break; - } - } - - return result; - } - - /// - /// Clones the specified buffer, byte by byte. - /// - /// The buffer. - /// - /// A byte array containing the results of encoding the specified set of characters. - /// - /// this - public static Byte[] DeepClone(this Byte[] @this) { - if(@this == null) { - throw new ArgumentNullException(nameof(@this)); - } - - Byte[] result = new Byte[@this.Length]; - Array.Copy(@this, result, @this.Length); - return result; - } - - /// - /// Removes the specified sequence from the start of the buffer if the buffer begins with such sequence. - /// - /// The buffer. - /// The sequence. - /// - /// A new trimmed byte array. - /// - /// buffer. - public static Byte[] TrimStart(this Byte[] buffer, params Byte[] sequence) { - if(buffer == null) { - throw new ArgumentNullException(nameof(buffer)); - } - - if(buffer.StartsWith(sequence) == false) { - return buffer.DeepClone(); - } - - Byte[] result = new Byte[buffer.Length - sequence.Length]; - Array.Copy(buffer, sequence.Length, result, 0, result.Length); - return result; - } - - /// - /// Removes the specified sequence from the end of the buffer if the buffer ends with such sequence. - /// - /// The buffer. - /// The sequence. - /// - /// A byte array containing the results of encoding the specified set of characters. - /// - /// buffer. - public static Byte[] TrimEnd(this Byte[] buffer, params Byte[] sequence) { - if(buffer == null) { - throw new ArgumentNullException(nameof(buffer)); - } - - if(buffer.EndsWith(sequence) == false) { - return buffer.DeepClone(); - } - - Byte[] result = new Byte[buffer.Length - sequence.Length]; - Array.Copy(buffer, 0, result, 0, result.Length); - return result; - } - - /// - /// Removes the specified sequence from the end and the start of the buffer - /// if the buffer ends and/or starts with such sequence. - /// - /// The buffer. - /// The sequence. - /// A byte array containing the results of encoding the specified set of characters. - public static Byte[] Trim(this Byte[] buffer, params Byte[] sequence) { - Byte[] trimStart = buffer.TrimStart(sequence); - return trimStart.TrimEnd(sequence); - } - - /// - /// Determines if the specified buffer ends with the given sequence of bytes. - /// - /// The buffer. - /// The sequence. - /// - /// True if the specified buffer is ends; otherwise, false. - /// - /// buffer. - public static Boolean EndsWith(this Byte[] buffer, params Byte[] sequence) { - if(buffer == null) { - throw new ArgumentNullException(nameof(buffer)); - } - - Int32 startIndex = buffer.Length - sequence.Length; - return buffer.GetIndexOf(sequence, startIndex) == startIndex; - } - - /// - /// Determines if the specified buffer starts with the given sequence of bytes. - /// - /// The buffer. - /// The sequence. - /// true if the specified buffer starts; otherwise, false. - public static Boolean StartsWith(this Byte[] buffer, params Byte[] sequence) => buffer.GetIndexOf(sequence) == 0; - - /// - /// Determines whether the buffer contains the specified sequence. - /// - /// The buffer. - /// The sequence. - /// - /// true if [contains] [the specified sequence]; otherwise, false. - /// - public static Boolean Contains(this Byte[] buffer, params Byte[] sequence) => buffer.GetIndexOf(sequence) >= 0; - - /// - /// Determines whether the buffer exactly matches, byte by byte the specified sequence. - /// - /// The buffer. - /// The sequence. - /// - /// true if [is equal to] [the specified sequence]; otherwise, false. - /// - /// buffer. - public static Boolean IsEqualTo(this Byte[] buffer, params Byte[] sequence) { - if(ReferenceEquals(buffer, sequence)) { - return true; - } - - if(buffer == null) { - throw new ArgumentNullException(nameof(buffer)); - } - - return buffer.Length == sequence.Length && buffer.GetIndexOf(sequence) == 0; - } - - /// - /// Returns the first instance of the matched sequence based on the given offset. - /// If no matches are found then this method returns -1. - /// - /// The buffer. - /// The sequence. - /// The offset. - /// The index of the sequence. - /// - /// buffer - /// or - /// sequence. - /// - public static Int32 GetIndexOf(this Byte[] buffer, Byte[] sequence, Int32 offset = 0) { - if(buffer == null) { - throw new ArgumentNullException(nameof(buffer)); - } - - if(sequence == null) { - throw new ArgumentNullException(nameof(sequence)); - } - - if(sequence.Length == 0) { - return -1; - } - - if(sequence.Length > buffer.Length) { - return -1; - } - - Int32 seqOffset = offset < 0 ? 0 : offset; - - Int32 matchedCount = 0; - for(Int32 i = seqOffset; i < buffer.Length; i++) { - if(buffer[i] == sequence[matchedCount]) { - matchedCount++; - } else { - matchedCount = 0; - } - - if(matchedCount == sequence.Length) { - return i - (matchedCount - 1); - } - } - - return -1; - } - - /// - /// Appends the Memory Stream with the specified buffer. - /// - /// The stream. - /// The buffer. - /// - /// The same MemoryStream instance. - /// - /// - /// stream - /// or - /// buffer. - /// - public static MemoryStream Append(this MemoryStream stream, Byte[] buffer) { - if(stream == null) { - throw new ArgumentNullException(nameof(stream)); - } - - if(buffer == null) { - throw new ArgumentNullException(nameof(buffer)); - } - - stream.Write(buffer, 0, buffer.Length); - return stream; - } - - /// - /// Appends the Memory Stream with the specified buffer. - /// - /// The stream. - /// The buffer. - /// - /// Block of bytes to the current stream using data read from a buffer. - /// - /// buffer. - public static MemoryStream Append(this MemoryStream stream, IEnumerable buffer) => Append(stream, buffer?.ToArray()); - - /// - /// Appends the Memory Stream with the specified set of buffers. - /// - /// The stream. - /// The buffers. - /// - /// Block of bytes to the current stream using data read from a buffer. - /// - /// buffers. - public static MemoryStream Append(this MemoryStream stream, IEnumerable buffers) { - if(buffers == null) { - throw new ArgumentNullException(nameof(buffers)); - } - - foreach(Byte[] buffer in buffers) { - _ = Append(stream, buffer); - } - - return stream; - } - - /// - /// Converts an array of bytes into text with the specified encoding. - /// - /// The buffer. - /// The encoding. - /// A that contains the results of decoding the specified sequence of bytes. - public static String ToText(this IEnumerable buffer, Encoding encoding) => encoding.GetString(buffer.ToArray()); - - /// - /// Converts an array of bytes into text with UTF8 encoding. - /// - /// The buffer. - /// A that contains the results of decoding the specified sequence of bytes. - public static String ToText(this IEnumerable buffer) => buffer.ToText(Encoding.UTF8); - - /// - /// Reads the bytes asynchronous. - /// - /// The stream. - /// The length. - /// Length of the buffer. - /// The cancellation token. - /// - /// A byte array containing the results of encoding the specified set of characters. - /// - /// stream. - public static async Task ReadBytesAsync(this Stream stream, Int64 length, Int32 bufferLength, CancellationToken cancellationToken = default) { - if(stream == null) { - throw new ArgumentNullException(nameof(stream)); - } - - using MemoryStream dest = new MemoryStream(); - try { - Byte[] buff = new Byte[bufferLength]; - while(length > 0) { - if(length < bufferLength) { - bufferLength = (Int32)length; - } - - Int32 nread = await stream.ReadAsync(buff, 0, bufferLength, cancellationToken).ConfigureAwait(false); - if(nread == 0) { - break; - } - - dest.Write(buff, 0, nread); - length -= nread; - } - } catch { - // ignored - } - - return dest.ToArray(); - } - - /// - /// Reads the bytes asynchronous. - /// - /// The stream. - /// The length. - /// The cancellation token. - /// - /// A byte array containing the results of encoding the specified set of characters. - /// - /// stream. - public static async Task ReadBytesAsync(this Stream stream, Int32 length, CancellationToken cancellationToken = default) { - if(stream == null) { - throw new ArgumentNullException(nameof(stream)); - } - - Byte[] buff = new Byte[length]; - Int32 offset = 0; - try { - while(length > 0) { - Int32 nread = await stream.ReadAsync(buff, offset, length, cancellationToken).ConfigureAwait(false); - if(nread == 0) { - break; - } - - offset += nread; - length -= nread; - } - } catch { - // ignored - } - - return new ArraySegment(buff, 0, offset).ToArray(); - } - - private static String ToHex(Byte[] bytes, Boolean addPrefix, String format) { - if(bytes == null) { - throw new ArgumentNullException(nameof(bytes)); - } - - StringBuilder sb = new StringBuilder(bytes.Length * 2); - - foreach(Byte item in bytes) { - _ = sb.Append(item.ToString(format, CultureInfo.InvariantCulture)); - } - - return $"{(addPrefix ? "0x" : String.Empty)}{sb}"; - }*/ } } diff --git a/Swan.Tiny/Extensions.Dictionaries.cs b/Swan.Tiny/Extensions.Dictionaries.cs index 7f3886c..24aa714 100644 --- a/Swan.Tiny/Extensions.Dictionaries.cs +++ b/Swan.Tiny/Extensions.Dictionaries.cs @@ -64,23 +64,5 @@ namespace Swan { return dict[key]; } - - /*/// - /// Executes the item action for each element in the Dictionary. - /// - /// The type of the key. - /// The type of the value. - /// The dictionary. - /// The item action. - /// dict. - public static void ForEach(this IDictionary dict, Action itemAction) { - if(dict == null) { - throw new ArgumentNullException(nameof(dict)); - } - - foreach(KeyValuePair kvp in dict) { - itemAction(kvp.Key, kvp.Value); - } - }*/ } } \ No newline at end of file diff --git a/Swan.Tiny/Extensions.Functional.cs b/Swan.Tiny/Extensions.Functional.cs index 76359ef..8a362fb 100644 --- a/Swan.Tiny/Extensions.Functional.cs +++ b/Swan.Tiny/Extensions.Functional.cs @@ -1,45 +1,11 @@ using System; using System.Collections.Generic; -using System.Linq; namespace Swan { /// /// Functional programming extension methods. /// public static class FunctionalExtensions { - /*/// - /// Whens the specified condition. - /// - /// The type of IQueryable. - /// The list. - /// The condition. - /// The function. - /// - /// The IQueryable. - /// - /// - /// this - /// or - /// condition - /// or - /// fn. - /// - public static IQueryable When(this IQueryable list, Func condition, Func, IQueryable> fn) { - if(list == null) { - throw new ArgumentNullException(nameof(list)); - } - - if(condition == null) { - throw new ArgumentNullException(nameof(condition)); - } - - if(fn == null) { - throw new ArgumentNullException(nameof(fn)); - } - - return condition() ? fn(list) : list; - }*/ - /// /// Whens the specified condition. /// @@ -72,102 +38,5 @@ namespace Swan { return condition() ? fn(list) : list; } - - /*/// - /// Adds the value when the condition is true. - /// - /// The type of IList element. - /// The list. - /// The condition. - /// The value. - /// - /// The IList. - /// - /// - /// this - /// or - /// condition - /// or - /// value. - /// - public static IList AddWhen(this IList list, Func condition, Func value) { - if(list == null) { - throw new ArgumentNullException(nameof(list)); - } - - if(condition == null) { - throw new ArgumentNullException(nameof(condition)); - } - - if(value == null) { - throw new ArgumentNullException(nameof(value)); - } - - if(condition()) { - list.Add(value()); - } - - return list; - } - - /// - /// Adds the value when the condition is true. - /// - /// The type of IList element. - /// The list. - /// if set to true [condition]. - /// The value. - /// - /// The IList. - /// - /// list. - public static IList AddWhen(this IList list, Boolean condition, T value) { - if(list == null) { - throw new ArgumentNullException(nameof(list)); - } - - if(condition) { - list.Add(value); - } - - return list; - } - - /// - /// Adds the range when the condition is true. - /// - /// The type of List element. - /// The list. - /// The condition. - /// The value. - /// - /// The List. - /// - /// - /// this - /// or - /// condition - /// or - /// value. - /// - public static List AddRangeWhen(this List list, Func condition, Func> value) { - if(list == null) { - throw new ArgumentNullException(nameof(list)); - } - - if(condition == null) { - throw new ArgumentNullException(nameof(condition)); - } - - if(value == null) { - throw new ArgumentNullException(nameof(value)); - } - - if(condition()) { - list.AddRange(value()); - } - - return list; - }*/ } } \ No newline at end of file diff --git a/Swan.Tiny/Extensions.Reflection.cs b/Swan.Tiny/Extensions.Reflection.cs index 262e711..65fde8a 100644 --- a/Swan.Tiny/Extensions.Reflection.cs +++ b/Swan.Tiny/Extensions.Reflection.cs @@ -1,14 +1,9 @@ #nullable enable using System; -using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Reflection; - -using Swan.Configuration; -using Swan.Reflection; namespace Swan { /// @@ -19,30 +14,6 @@ namespace Swan { private static readonly Lazy, Action>> CacheSetMethods = new Lazy, Action>>(() => new ConcurrentDictionary, Action>(), true); - #region Assembly Extensions - - /*/// - /// Gets all types within an assembly in a safe manner. - /// - /// The assembly. - /// - /// Array of Type objects representing the types specified by an assembly. - /// - /// assembly. - public static IEnumerable GetAllTypes(this Assembly assembly) { - if(assembly == null) { - throw new ArgumentNullException(nameof(assembly)); - } - - try { - return assembly.GetTypes(); - } catch(ReflectionTypeLoadException e) { - return e.Types.Where(t => t != null); - } - }*/ - - #endregion - #region Type Extensions /// @@ -61,64 +32,6 @@ namespace Swan { return type.IsValueType ? Activator.CreateInstance(type) : default; } - /*/// - /// Determines whether this type is compatible with ICollection. - /// - /// The type. - /// - /// true if the specified source type is collection; otherwise, false. - /// - /// sourceType. - public static Boolean IsCollection(this Type sourceType) { - if(sourceType == null) { - throw new ArgumentNullException(nameof(sourceType)); - } - - return sourceType != typeof(String) && typeof(IEnumerable).IsAssignableFrom(sourceType); - } - - /// - /// Gets a method from a type given the method name, binding flags, generic types and parameter types. - /// - /// Type of the source. - /// The binding flags. - /// Name of the method. - /// The generic types. - /// The parameter types. - /// - /// An object that represents the method with the specified name. - /// - /// - /// The exception that is thrown when binding to a member results in more than one member matching the - /// binding criteria. This class cannot be inherited. - /// - public static MethodInfo GetMethod(this Type type, BindingFlags bindingFlags, String methodName, Type[] genericTypes, Type[] parameterTypes) { - if(type == null) { - throw new ArgumentNullException(nameof(type)); - } - - if(methodName == null) { - throw new ArgumentNullException(nameof(methodName)); - } - - if(genericTypes == null) { - throw new ArgumentNullException(nameof(genericTypes)); - } - - if(parameterTypes == null) { - throw new ArgumentNullException(nameof(parameterTypes)); - } - - List methods = type.GetMethods(bindingFlags) - .Where(mi => String.Equals(methodName, mi.Name, StringComparison.Ordinal)) - .Where(mi => mi.ContainsGenericParameters) - .Where(mi => mi.GetGenericArguments().Length == genericTypes.Length) - .Where(mi => mi.GetParameters().Length == parameterTypes.Length).Select(mi => mi.MakeGenericMethod(genericTypes)) - .Where(mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)).ToList(); - - return methods.Count > 1 ? throw new AmbiguousMatchException() : methods.FirstOrDefault(); - }*/ - /// /// Determines whether [is i enumerable request]. /// @@ -281,39 +194,6 @@ namespace Swan { return true; } - /*/// - /// Gets property actual value or PropertyDisplayAttribute.DefaultValue if presented. - /// - /// If the PropertyDisplayAttribute.Format value is presented, the property value - /// will be formatted accordingly. - /// - /// If the object contains a null value, a empty string will be returned. - /// - /// The property information. - /// The object. - /// The property value or null. - /// propertyInfo. - public static String? ToFormattedString(this PropertyInfo propertyInfo, Object target) { - if(propertyInfo == null) { - throw new ArgumentNullException(nameof(propertyInfo)); - } - - try { - Object? value = propertyInfo.GetValue(target); - PropertyDisplayAttribute attr = AttributeCache.DefaultCache.Value.RetrieveOne(propertyInfo); - - if(attr == null) { - return value?.ToString() ?? String.Empty; - } - - Object valueToFormat = value ?? attr.DefaultValue; - - return String.IsNullOrEmpty(attr.Format) ? (valueToFormat?.ToString() ?? String.Empty) : ConvertObjectAndFormat(propertyInfo.PropertyType, valueToFormat, attr.Format); - } catch { - return null; - } - }*/ - /// /// Gets a MethodInfo from a Property Get method. /// @@ -368,24 +248,6 @@ namespace Swan { return false; } - /*/// - /// Creates a property proxy that stores getter and setter delegates. - /// - /// The property information. - /// - /// The property proxy. - /// - /// this. - public static IPropertyProxy? CreatePropertyProxy(this PropertyInfo @this) { - if(@this == null) { - throw new ArgumentNullException(nameof(@this)); - } - - Type genericType = typeof(PropertyProxy<,>).MakeGenericType(@this.DeclaringType!, @this.PropertyType); - - return Activator.CreateInstance(genericType, @this) as IPropertyProxy; - }*/ - /// /// Convert a object to a boolean. /// @@ -394,18 +256,5 @@ namespace Swan { /// true if the string represents a valid truly value, otherwise false. /// public static Boolean ToBoolean(this Object value) => value.ToStringInvariant().ToBoolean(); - - /*private static String ConvertObjectAndFormat(Type propertyType, Object value, String format) => - propertyType == typeof(DateTime) || propertyType == typeof(DateTime?) - ? Convert.ToDateTime(value, CultureInfo.InvariantCulture).ToString(format) - : propertyType == typeof(Int32) || propertyType == typeof(Int32?) - ? Convert.ToInt32(value, CultureInfo.InvariantCulture).ToString(format) - : propertyType == typeof(Decimal) || propertyType == typeof(Decimal?) - ? Convert.ToDecimal(value, CultureInfo.InvariantCulture).ToString(format) - : propertyType == typeof(Double) || propertyType == typeof(Double?) - ? Convert.ToDouble(value, CultureInfo.InvariantCulture).ToString(format) - : propertyType == typeof(Byte) || propertyType == typeof(Byte?) - ? Convert.ToByte(value, CultureInfo.InvariantCulture).ToString(format) - : value?.ToString() ?? String.Empty;*/ } } diff --git a/Swan.Tiny/Extensions.Strings.cs b/Swan.Tiny/Extensions.Strings.cs index 4773737..1359868 100644 --- a/Swan.Tiny/Extensions.Strings.cs +++ b/Swan.Tiny/Extensions.Strings.cs @@ -1,6 +1,5 @@ #nullable enable using System; -using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; @@ -16,21 +15,8 @@ namespace Swan { private const RegexOptions StandardRegexOptions = RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.CultureInvariant; - /*private static readonly String[] ByteSuffixes = { "B", "KB", "MB", "GB", "TB" };*/ - private static readonly Lazy SplitLinesRegex = new Lazy(() => new Regex("\r\n|\r|\n", StandardRegexOptions)); - /*private static readonly Lazy UnderscoreRegex = new Lazy(() => new Regex(@"_", StandardRegexOptions)); - - private static readonly Lazy CamelCaseRegEx = new Lazy(() => new Regex(@"[a-z][A-Z]", StandardRegexOptions)); - - private static readonly Lazy SplitCamelCaseString = new Lazy(() => m => { - String x = m.ToString(); - return x[0] + " " + x[1..]; - }); - - private static readonly Lazy InvalidFilenameChars = new Lazy(() => Path.GetInvalidFileNameChars().Select(c => c.ToString()).ToArray());*/ - #endregion /// @@ -82,22 +68,6 @@ namespace Swan { return new String(value.Where(c => Char.IsControl(c) == false || excludeChars.Contains(c)).ToArray()); } - /*/// - /// Removes all control characters from a string, including new line sequences. - /// - /// The input. - /// A that represents the current object. - /// input. - public static String RemoveControlChars(this String value) => value.RemoveControlCharsExcept(null); - - /// - /// Outputs JSON string representing this object. - /// - /// The object. - /// if set to true format the output. - /// A that represents the current object. - public static String ToJson(this Object @this, Boolean format = true) => @this == null ? String.Empty : Json.Serialize(@this, format);*/ - /// /// Returns text representing the properties of the specified object in a human-readable format. /// While this method is fairly expensive computationally speaking, it provides an easy way to @@ -171,43 +141,6 @@ namespace Swan { /// public static String[] ToLines(this String @this) => @this == null ? Array.Empty() : SplitLinesRegex.Value.Split(@this); - /*/// - /// Humanizes (make more human-readable) an identifier-style string - /// in either camel case or snake case. For example, CamelCase will be converted to - /// Camel Case and Snake_Case will be converted to Snake Case. - /// - /// The identifier-style string. - /// A humanized. - public static String Humanize(this String value) { - if(value == null) { - return String.Empty; - } - - String returnValue = UnderscoreRegex.Value.Replace(value, " "); - returnValue = CamelCaseRegEx.Value.Replace(returnValue, SplitCamelCaseString.Value); - return returnValue; - } - - /// - /// Humanizes (make more human-readable) an boolean. - /// - /// if set to true [value]. - /// A that represents the current boolean. - public static String Humanize(this Boolean value) => value ? "Yes" : "No"; - - /// - /// Humanizes (make more human-readable) the specified value. - /// - /// The value. - /// A that represents the current object. - public static String Humanize(this Object value) => - value switch - { - String stringValue => stringValue.Humanize(), - Boolean boolValue => boolValue.Humanize(), - _ => value.Stringify() - };*/ - /// /// Indents the specified multi-line text with the given amount of leading spaces /// per line. @@ -270,99 +203,5 @@ namespace Swan { return Tuple.Create(lineIndex + 1, colNumber); } - - /*/// - /// Makes the file name system safe. - /// - /// The s. - /// - /// A string with a safe file name. - /// - /// s. - public static String ToSafeFilename(this String value) => value == null ? throw new ArgumentNullException(nameof(value)) : InvalidFilenameChars.Value.Aggregate(value, (current, c) => current.Replace(c, String.Empty)).Slice(0, 220); - - /// - /// Formats a long into the closest bytes string. - /// - /// The bytes length. - /// - /// The string representation of the current Byte object, formatted as specified by the format parameter. - /// - public static String FormatBytes(this Int64 bytes) => ((UInt64)bytes).FormatBytes(); - - /// - /// Formats a long into the closest bytes string. - /// - /// The bytes length. - /// - /// A copy of format in which the format items have been replaced by the string - /// representations of the corresponding arguments. - /// - public static String FormatBytes(this UInt64 bytes) { - Int32 i; - Double dblSByte = bytes; - - for(i = 0; i < ByteSuffixes.Length && bytes >= 1024; i++, bytes /= 1024) { - dblSByte = bytes / 1024.0; - } - - return $"{dblSByte:0.##} {ByteSuffixes[i]}"; - } - - /// - /// Truncates the specified value. - /// - /// The value. - /// The maximum length. - /// - /// Retrieves a substring from this instance. - /// The substring starts at a specified character position and has a specified length. - /// - public static String? Truncate(this String value, Int32 maximumLength) => Truncate(value, maximumLength, String.Empty); - - /// - /// Truncates the specified value and append the omission last. - /// - /// The value. - /// The maximum length. - /// The omission. - /// - /// Retrieves a substring from this instance. - /// The substring starts at a specified character position and has a specified length. - /// - public static String? Truncate(this String value, Int32 maximumLength, String omission) => value == null ? null : value.Length > maximumLength ? value.Substring(0, maximumLength) + (omission ?? String.Empty) : value; - - /// - /// Determines whether the specified contains any of characters in - /// the specified array of . - /// - /// - /// true if contains any of ; - /// otherwise, false. - /// - /// - /// A to test. - /// - /// - /// An array of that contains characters to find. - /// - public static Boolean Contains(this String value, params Char[] chars) => chars?.Length == 0 || !String.IsNullOrEmpty(value) && chars != null && value.IndexOfAny(chars) > -1; - - /// - /// Replaces all chars in a string. - /// - /// The value. - /// The replace value. - /// The chars. - /// The string with the characters replaced. - public static String ReplaceAll(this String value, String replaceValue, params Char[] chars) => chars.Aggregate(value, (current, c) => current.Replace(new String(new[] { c }), replaceValue)); - - /// - /// Convert hex character to an integer. Return -1 if char is something - /// other than a hex char. - /// - /// The c. - /// Converted integer. - public static Int32 Hex2Int(this Char value) => value >= '0' && value <= '9' ? value - '0' : value >= 'A' && value <= 'F' ? value - 'A' + 10 : value >= 'a' && value <= 'f' ? value - 'a' + 10 : -1;*/ } } diff --git a/Swan.Tiny/Extensions.ValueTypes.cs b/Swan.Tiny/Extensions.ValueTypes.cs index 7c8be30..538139a 100644 --- a/Swan.Tiny/Extensions.ValueTypes.cs +++ b/Swan.Tiny/Extensions.ValueTypes.cs @@ -1,8 +1,4 @@ using System; -using System.Reflection; -using System.Runtime.InteropServices; - -using Swan.Reflection; namespace Swan { /// @@ -30,110 +26,5 @@ namespace Swan { /// A value that indicates the relative order of the objects being compared. // [Obsolete("NEED",false)] public static Int32 Clamp(this Int32 @this, Int32 min, Int32 max) => @this < min ? min : (@this > max ? max : @this); - /* - /// - /// Determines whether the specified value is between a minimum and a maximum value. - /// - /// The type of value to check. - /// The value. - /// The minimum. - /// The maximum. - /// - /// true if the specified minimum is between; otherwise, false. - /// - public static Boolean IsBetween(this T @this, T min, T max) where T : struct, IComparable => @this.CompareTo(min) >= 0 && @this.CompareTo(max) <= 0; - - /// - /// Converts an array of bytes into the given struct type. - /// - /// The type of structure to convert. - /// The data. - /// a struct type derived from convert an array of bytes ref=ToStruct". - public static T ToStruct(this Byte[] @this) where T : struct => @this == null ? throw new ArgumentNullException(nameof(@this)) : ToStruct(@this, 0, @this.Length); - - /// - /// Converts an array of bytes into the given struct type. - /// - /// The type of structure to convert. - /// The data. - /// The offset. - /// The length. - /// - /// A managed object containing the data pointed to by the ptr parameter. - /// - /// data. - public static T ToStruct(this Byte[] @this, Int32 offset, Int32 length) where T : struct { - if(@this == null) { - throw new ArgumentNullException(nameof(@this)); - } - - Byte[] buffer = new Byte[length]; - Array.Copy(@this, offset, buffer, 0, buffer.Length); - GCHandle handle = GCHandle.Alloc(GetStructBytes(buffer), GCHandleType.Pinned); - - try { - return Marshal.PtrToStructure(handle.AddrOfPinnedObject()); - } finally { - handle.Free(); - } - } - - /// - /// Converts a struct to an array of bytes. - /// - /// The type of structure to convert. - /// The object. - /// A byte array containing the results of encoding the specified set of characters. - public static Byte[] ToBytes(this T @this) where T : struct { - Byte[] data = new Byte[Marshal.SizeOf(@this)]; - GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned); - - try { - Marshal.StructureToPtr(@this, handle.AddrOfPinnedObject(), false); - return GetStructBytes(data); - } finally { - handle.Free(); - } - } - - /// - /// Swaps the endianness of an unsigned long to an unsigned integer. - /// - /// The bytes contained in a long. - /// - /// A 32-bit unsigned integer equivalent to the ulong - /// contained in longBytes. - /// - public static UInt32 SwapEndianness(this UInt64 @this) => (UInt32)(((@this & 0x000000ff) << 24) + ((@this & 0x0000ff00) << 8) + ((@this & 0x00ff0000) >> 8) + ((@this & 0xff000000) >> 24)); - - private static Byte[] GetStructBytes(Byte[] data) { - if(data == null) { - throw new ArgumentNullException(nameof(data)); - } - - FieldInfo[] fields = typeof(T).GetTypeInfo() - .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - - StructEndiannessAttribute endian = AttributeCache.DefaultCache.Value.RetrieveOne(); - - foreach(FieldInfo field in fields) { - if(endian == null && !field.IsDefined(typeof(StructEndiannessAttribute), false)) { - continue; - } - - Int32 offset = Marshal.OffsetOf(field.Name).ToInt32(); - Int32 length = Marshal.SizeOf(field.FieldType); - - endian ??= AttributeCache.DefaultCache.Value.RetrieveOne(field); - - if(endian != null && (endian.Endianness == Endianness.Big && BitConverter.IsLittleEndian || - endian.Endianness == Endianness.Little && !BitConverter.IsLittleEndian)) { - Array.Reverse(data, offset, length); - } - } - - return data; - } - */ } } \ No newline at end of file diff --git a/Swan.Tiny/Extensions.cs b/Swan.Tiny/Extensions.cs index 3e30c3c..9915b44 100644 --- a/Swan.Tiny/Extensions.cs +++ b/Swan.Tiny/Extensions.cs @@ -3,7 +3,6 @@ using System; using System.Collections; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using Swan.Lite.Reflection; using Swan.Mappers; @@ -27,18 +26,6 @@ namespace Swan { /// public static Int32 CopyPropertiesTo(this T source, Object? target, params String[]? ignoreProperties) where T : class => ObjectMapper.Copy(source, target, GetCopyableProperties(target), ignoreProperties); - /*/// - /// Iterates over the public, instance, readable properties of the source and - /// tries to write a compatible value to a public, instance, writable property in the destination. - /// - /// The source. - /// The destination. - /// Properties to copy. - /// - /// Number of properties that were successfully copied. - /// - public static Int32 CopyOnlyPropertiesTo(this Object source, Object target, params String[]? propertiesToCopy) => ObjectMapper.Copy(source, target, propertiesToCopy);*/ - /// /// Copies the properties to new instance of T. /// @@ -60,109 +47,6 @@ namespace Swan { return target; } - /*/// - /// Copies the only properties to new instance of T. - /// - /// Object Type. - /// The source. - /// The properties to copy. - /// - /// The specified type with properties copied. - /// - /// source. - public static T CopyOnlyPropertiesToNew(this Object source, params String[] propertiesToCopy) where T : class { - if(source == null) { - throw new ArgumentNullException(nameof(source)); - } - - T target = Activator.CreateInstance(); - _ = ObjectMapper.Copy(source, target, propertiesToCopy); - - return target; - } - - /// - /// Iterates over the keys of the source and tries to write a compatible value to a public, - /// instance, writable property in the destination. - /// - /// The source. - /// The target. - /// The ignore keys. - /// Number of properties that was copied successful. - public static Int32 CopyKeyValuePairTo(this IDictionary source, Object? target, params String[] ignoreKeys) => source == null ? throw new ArgumentNullException(nameof(source)) : ObjectMapper.Copy(source, target, null, ignoreKeys); - - /// - /// Iterates over the keys of the source and tries to write a compatible value to a public, - /// instance, writable property in the destination. - /// - /// Object Type. - /// The source. - /// The ignore keys. - /// - /// The specified type with properties copied. - /// - public static T CopyKeyValuePairToNew(this IDictionary source, params String[] ignoreKeys) { - if(source == null) { - throw new ArgumentNullException(nameof(source)); - } - - T target = Activator.CreateInstance(); - _ = source.CopyKeyValuePairTo(target, ignoreKeys); - return target; - } - - /// - /// Does the specified action. - /// - /// The action. - /// The retry interval. - /// The retry count. - public static void Retry(this Action action, TimeSpan retryInterval = default, Int32 retryCount = 3) { - if(action == null) { - throw new ArgumentNullException(nameof(action)); - } - - _ = Retry(() => { action(); return null; }, retryInterval, retryCount); - } - - /// - /// Does the specified action. - /// - /// The type of the source. - /// The action. - /// The retry interval. - /// The retry count. - /// - /// The return value of the method that this delegate encapsulates. - /// - /// action. - /// Represents one or many errors that occur during application execution. - public static T Retry(this Func action, TimeSpan retryInterval = default, Int32 retryCount = 3) { - if(action == null) { - throw new ArgumentNullException(nameof(action)); - } - - if(retryInterval == default) { - retryInterval = TimeSpan.FromSeconds(1); - } - - global::System.Collections.Generic.List exceptions = new List(); - - for(Int32 retry = 0; retry < retryCount; retry++) { - try { - if(retry > 0) { - Task.Delay(retryInterval).Wait(); - } - - return action(); - } catch(Exception ex) { - exceptions.Add(ex); - } - } - - throw new AggregateException(exceptions); - }*/ - /// /// Gets the copyable properties. /// diff --git a/Swan.Tiny/Formatters/Json.SerializerOptions.cs b/Swan.Tiny/Formatters/Json.SerializerOptions.cs index 91ba468..5a0c03a 100644 --- a/Swan.Tiny/Formatters/Json.SerializerOptions.cs +++ b/Swan.Tiny/Formatters/Json.SerializerOptions.cs @@ -124,7 +124,7 @@ namespace Swan.Formatters { Dictionary, MemberInfo> value = fields.ToDictionary(x => Tuple.Create(x.Name, x.GetCustomAttribute()?.PropertyName ?? x.Name.GetNameWithCase(this.JsonSerializerCase)), x => x); - TypeCache.TryAdd(targetType, value); + _ = TypeCache.TryAdd(targetType, value); return value; } diff --git a/Swan.Tiny/Formatters/Json.cs b/Swan.Tiny/Formatters/Json.cs index 9fad334..486215b 100644 --- a/Swan.Tiny/Formatters/Json.cs +++ b/Swan.Tiny/Formatters/Json.cs @@ -99,18 +99,6 @@ namespace Swan.Formatters { /// public static String Serialize(Object? obj, Boolean format = false, String? typeSpecifier = null, Boolean includeNonPublic = false, String[]? includedNames = null, params String[] excludedNames) => Serialize(obj, format, typeSpecifier, includeNonPublic, includedNames, excludedNames, null, JsonSerializerCase.None); - /*/// - /// Serializes the specified object into a JSON string. - /// - /// The object. - /// The json serializer case. - /// if set to true [format]. - /// The type specifier. - /// - /// A that represents the current object. - /// - public static String Serialize(Object? obj, JsonSerializerCase jsonSerializerCase, Boolean format = false, String? typeSpecifier = null) => Serialize(obj, format, typeSpecifier, false, null, null, null, jsonSerializerCase);*/ - /// /// Serializes the specified object into a JSON string. /// @@ -145,68 +133,6 @@ namespace Swan.Formatters { /// public static String Serialize(Object? obj, SerializerOptions options) => Serializer.Serialize(obj, 0, options); - /*/// - /// Serializes the specified object only including the specified property names. - /// - /// The object. - /// if set to true it formats and indents the output. - /// The include names. - /// A that represents the current object. - /// - /// The following example shows how to serialize a simple object including the specified properties. - /// - /// using Swan.Formatters; - /// - /// class Example - /// { - /// static void Main() - /// { - /// // object to serialize - /// var obj = new { One = "One", Two = "Two", Three = "Three" }; - /// - /// // the included names - /// var includedNames = new[] { "Two", "Three" }; - /// - /// // serialize only the included names - /// var data = Json.SerializeOnly(basicObject, true, includedNames); - /// // {"Two": "Two","Three": "Three" } - /// } - /// } - /// - /// - public static String SerializeOnly(Object? obj, Boolean format, params String[] includeNames) => Serialize(obj, new SerializerOptions(format, null, includeNames)); - - /// - /// Serializes the specified object excluding the specified property names. - /// - /// The object. - /// if set to true it formats and indents the output. - /// The exclude names. - /// A that represents the current object. - /// - /// The following code shows how to serialize a simple object excluding the specified properties. - /// - /// using Swan.Formatters; - /// - /// class Example - /// { - /// static void Main() - /// { - /// // object to serialize - /// var obj = new { One = "One", Two = "Two", Three = "Three" }; - /// - /// // the excluded names - /// var excludeNames = new[] { "Two", "Three" }; - /// - /// // serialize excluding - /// var data = Json.SerializeExcluding(basicObject, false, includedNames); - /// // {"One": "One"} - /// } - /// } - /// - /// - public static String SerializeExcluding(Object? obj, Boolean format, params String[] excludeNames) => Serialize(obj, new SerializerOptions(format, null, null, excludeNames));*/ - /// /// Deserializes the specified json string as either a Dictionary[string, object] or as a List[object] /// depending on the syntax of the JSON string. @@ -258,54 +184,6 @@ namespace Swan.Formatters { /// public static Object? Deserialize(String? json) => Deserialize(json, JsonSerializerCase.None); - /*/// - /// Deserializes the specified JSON string and converts it to the specified object type. - /// Non-public constructors and property setters are ignored. - /// - /// The type of object to deserialize. - /// The JSON string. - /// The JSON serializer case. - /// - /// The deserialized specified type object. - /// - /// - /// The following code describes how to deserialize a JSON string into an object of type T. - /// - /// using Swan.Formatters; - /// class Example - /// { - /// static void Main() - /// { - /// // json type BasicJson to serialize - /// var basicJson = "{\"One\":\"One\",\"Two\":\"Two\",\"Three\":\"Three\"}"; - /// // deserializes the specified string in a new instance of the type BasicJson. - /// var data = Json.Deserialize<BasicJson>(basicJson); - /// } - /// } - /// - public static T Deserialize(String json, JsonSerializerCase jsonSerializerCase = JsonSerializerCase.None) where T : notnull => (T)Deserialize(json, typeof(T), jsonSerializerCase: jsonSerializerCase)!; - - /// - /// Deserializes the specified JSON string and converts it to the specified object type. - /// - /// The type of object to deserialize. - /// The JSON string. - /// if set to true, it also uses the non-public constructors and property setters. - /// The deserialized specified type object. - public static T Deserialize(String json, Boolean includeNonPublic) where T : notnull => (T)Deserialize(json, typeof(T), includeNonPublic)!; - - /// - /// Deserializes the specified JSON string and converts it to the specified object type. - /// - /// The JSON string. - /// Type of the result. - /// if set to true, it also uses the non-public constructors and property setters. - /// The json serializer case. - /// - /// Type of the current conversion from json result. - /// - public static Object? Deserialize(String json, Type resultType, Boolean includeNonPublic = false, JsonSerializerCase jsonSerializerCase = JsonSerializerCase.None) => Converter.FromJsonResult(Deserializer.DeserializeInternal(json), jsonSerializerCase, resultType, includeNonPublic);*/ - #endregion #region Private API @@ -315,17 +193,9 @@ namespace Swan.Formatters { return excludedNames; } - global::System.Collections.Generic.IEnumerable excludedByAttr = IgnoredPropertiesCache.Retrieve(type, t => t.GetProperties() - .Where(x => AttributeCache.DefaultCache.Value.RetrieveOne(x)?.Ignored == true) - .Select(x => x.Name)); + IEnumerable excludedByAttr = IgnoredPropertiesCache.Retrieve(type, t => t.GetProperties().Where(x => AttributeCache.DefaultCache.Value.RetrieveOne(x)?.Ignored == true).Select(x => x.Name)); - if(excludedByAttr?.Any() != true) { - return excludedNames; - } - - return excludedNames?.Any(String.IsNullOrWhiteSpace) == true - ? excludedByAttr.Intersect(excludedNames.Where(y => !String.IsNullOrWhiteSpace(y))).ToArray() - : excludedByAttr.ToArray(); + return excludedByAttr?.Any() != true ? excludedNames : excludedNames?.Any(String.IsNullOrWhiteSpace) == true ? excludedByAttr.Intersect(excludedNames.Where(y => !String.IsNullOrWhiteSpace(y))).ToArray() : excludedByAttr.ToArray(); } private static String SerializePrimitiveValue(Object obj) => obj switch diff --git a/Swan.Tiny/Formatters/JsonPropertyAttribute.cs b/Swan.Tiny/Formatters/JsonPropertyAttribute.cs index 624b70f..c31108a 100644 --- a/Swan.Tiny/Formatters/JsonPropertyAttribute.cs +++ b/Swan.Tiny/Formatters/JsonPropertyAttribute.cs @@ -7,16 +7,6 @@ namespace Swan.Formatters { /// [AttributeUsage(AttributeTargets.Property)] public sealed class JsonPropertyAttribute : Attribute { - /*/// - /// Initializes a new instance of the class. - /// - /// Name of the property. - /// if set to true [ignored]. - public JsonPropertyAttribute(String propertyName, Boolean ignored = false) { - this.PropertyName = propertyName ?? throw new ArgumentNullException(nameof(propertyName)); - this.Ignored = ignored; - }*/ - /// /// Gets or sets the name of the property. /// diff --git a/Swan.Tiny/Logging/LogMessageReceivedEventArgs.cs b/Swan.Tiny/Logging/LogMessageReceivedEventArgs.cs index c8568ff..d141754 100644 --- a/Swan.Tiny/Logging/LogMessageReceivedEventArgs.cs +++ b/Swan.Tiny/Logging/LogMessageReceivedEventArgs.cs @@ -22,16 +22,7 @@ namespace Swan { /// Name of the caller member. /// The caller file path. /// The caller line number. - public LogMessageReceivedEventArgs( - UInt64 sequence, - LogLevel messageType, - DateTime utcDate, - String source, - String message, - Object? extendedData, - String callerMemberName, - String callerFilePath, - Int32 callerLineNumber) { + public LogMessageReceivedEventArgs(UInt64 sequence, LogLevel messageType, DateTime utcDate, String source, String message, Object? extendedData, String callerMemberName, String callerFilePath, Int32 callerLineNumber) { this.Sequence = sequence; this.MessageType = messageType; this.UtcDate = utcDate; diff --git a/Swan.Tiny/Logging/Logger.cs b/Swan.Tiny/Logging/Logger.cs index 1f9afe3..dd7399c 100644 --- a/Swan.Tiny/Logging/Logger.cs +++ b/Swan.Tiny/Logging/Logger.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; @@ -28,306 +27,7 @@ namespace Swan.Logging { } } - /*#region Standard Public API - - /// - /// Registers the logger. - /// - /// The type of logger to register. - /// There is already a logger with that class registered. - public static void RegisterLogger() where T : ILogger { - lock(SyncLock) { - ILogger loggerInstance = Loggers.FirstOrDefault(x => x.GetType() == typeof(T)); - - if(loggerInstance != null) { - throw new InvalidOperationException("There is already a logger with that class registered."); - } - - Loggers.Add(Activator.CreateInstance()); - } - } - - /// - /// Registers the logger. - /// - /// The logger. - public static void RegisterLogger(ILogger logger) { - lock(SyncLock) { - Loggers.Add(logger); - } - } - - /// - /// Unregisters the logger. - /// - /// The logger. - /// logger. - public static void UnregisterLogger(ILogger logger) => RemoveLogger(x => x == logger); - - /// - /// Unregisters the logger. - /// - /// The type of logger to unregister. - public static void UnregisterLogger() => RemoveLogger(x => x.GetType() == typeof(T)); - - /// - /// Remove all the loggers. - /// - public static void NoLogging() { - lock(SyncLock) { - Loggers.Clear(); - } - } - - #region Debug - - /// - /// Logs a debug message to the console. - /// - /// The message. - /// The source. - /// The extended data. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Debug(this String message, String source = null, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Debug, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs a debug message to the console. - /// - /// The message. - /// The source. - /// The extended data. - /// Name of the caller member. - /// The caller file path. - /// The caller line number. - public static void Debug(this String message, Type source, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Debug, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs a debug message to the console. - /// - /// The exception. - /// The source. - /// The message. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Debug(this Exception extendedData, String source, String message, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Debug, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - #endregion - - #region Trace - - /// - /// Logs a trace message to the console. - /// - /// The text. - /// The source. - /// The extended data. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Trace(this String message, String source = null, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Trace, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs a trace message to the console. - /// - /// The message. - /// The source. - /// The extended data. - /// Name of the caller member. - /// The caller file path. - /// The caller line number. - public static void Trace(this String message, Type source, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Trace, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs a trace message to the console. - /// - /// The extended data. - /// The source. - /// The message. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Trace(this Exception extendedData, String source, String message, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Trace, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - #endregion - - #region Warn - - /// - /// Logs a warning message to the console. - /// - /// The text. - /// The source. - /// The extended data. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Warn(this String message, String source = null, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Warning, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs a warning message to the console. - /// - /// The message. - /// The source. - /// The extended data. - /// Name of the caller member. - /// The caller file path. - /// The caller line number. - public static void Warn(this String message, Type source, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Warning, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs a warning message to the console. - /// - /// The extended data. - /// The source. - /// The message. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Warn(this Exception extendedData, String source, String message, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Warning, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - #endregion - - #region Fatal - - /// - /// Logs a warning message to the console. - /// - /// The text. - /// The source. - /// The extended data. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Fatal(this String message, String source = null, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Fatal, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs a warning message to the console. - /// - /// The message. - /// The source. - /// The extended data. - /// Name of the caller member. - /// The caller file path. - /// The caller line number. - public static void Fatal(this String message, Type source, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Fatal, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs a warning message to the console. - /// - /// The extended data. - /// The source. - /// The message. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Fatal(this Exception extendedData, String source, String message, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Fatal, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - #endregion - - #region Info - - /// - /// Logs an info message to the console. - /// - /// The text. - /// The source. - /// The extended data. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Info(this String message, String source = null, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Info, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs an info message to the console. - /// - /// The message. - /// The source. - /// The extended data. - /// Name of the caller member. - /// The caller file path. - /// The caller line number. - public static void Info(this String message, Type source, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Info, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs an info message to the console. - /// - /// The extended data. - /// The source. - /// The message. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Info(this Exception extendedData, String source, String message, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Info, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - #endregion - - #region Error - - /// - /// Logs an error message to the console's standard error. - /// - /// The text. - /// The source. - /// The extended data. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Error(this String message, String source = null, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Error, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs an error message to the console's standard error. - /// - /// The message. - /// The source. - /// The extended data. - /// Name of the caller member. - /// The caller file path. - /// The caller line number. - public static void Error(this String message, Type source, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Error, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs an error message to the console's standard error. - /// - /// The exception. - /// The source. - /// The message. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Error(this Exception ex, String source, String message, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Error, message, source, ex, callerMemberName, callerFilePath, callerLineNumber); - - #endregion - - #endregion*/ - - #region Extended Public API - - /*/// - /// Logs the specified message. - /// - /// The message. - /// The source. - /// Type of the message. - /// The extended data. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Log(this String message, String source, LogLevel messageType, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(messageType, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs the specified message. - /// - /// The message. - /// The source. - /// Type of the message. - /// The extended data. - /// Name of the caller member. - /// The caller file path. - /// The caller line number. - public static void Log(this String message, Type source, LogLevel messageType, Object extendedData = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(messageType, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber);*/ + #region Extended Public API /// /// Logs an error message to the console's standard error. @@ -341,70 +41,7 @@ namespace Swan.Logging { // [Obsolete("NEED", false)] public static void Log(this Exception ex, String source = null, String message = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Error, message ?? ex.Message, source ?? ex.Source, ex, callerMemberName, callerFilePath, callerLineNumber); - /*/// - /// Logs an error message to the console's standard error. - /// - /// The ex. - /// The source. - /// The message. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Log(this Exception ex, Type source = null, String message = null, [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) => LogMessage(LogLevel.Error, message ?? ex.Message, source?.FullName ?? ex.Source, ex, callerMemberName, callerFilePath, callerLineNumber); - - /// - /// Logs a trace message showing all possible non-null properties of the given object - /// This method is expensive as it uses Stringify internally. - /// - /// The object. - /// The source. - /// The title. - /// Name of the caller member. This is automatically populated. - /// The caller file path. This is automatically populated. - /// The caller line number. This is automatically populated. - public static void Dump(this Object obj, String source, String text = "Object Dump", [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) { - if(obj == null) { - return; - } - - String message = $"{text} ({obj.GetType()}): {Environment.NewLine}{obj.Stringify().Indent(5)}"; - LogMessage(LogLevel.Trace, message, source, obj, callerMemberName, callerFilePath, callerLineNumber); - } - - /// - /// Logs a trace message showing all possible non-null properties of the given object - /// This method is expensive as it uses Stringify internally. - /// - /// The object. - /// The source. - /// The text. - /// Name of the caller member. - /// The caller file path. - /// The caller line number. - public static void Dump(this Object obj, Type source, String text = "Object Dump", [CallerMemberName] String callerMemberName = "", [CallerFilePath] String callerFilePath = "", [CallerLineNumber] Int32 callerLineNumber = 0) { - if(obj == null) { - return; - } - - String message = $"{text} ({obj.GetType()}): {Environment.NewLine}{obj.Stringify().Indent(5)}"; - LogMessage(LogLevel.Trace, message, source?.FullName, obj, callerMemberName, callerFilePath, callerLineNumber); - }*/ - - #endregion - - /*private static void RemoveLogger(Func criteria) { - lock(SyncLock) { - ILogger loggerInstance = Loggers.FirstOrDefault(criteria); - - if(loggerInstance == null) { - throw new InvalidOperationException("The logger is not registered."); - } - - loggerInstance.Dispose(); - - _ = Loggers.Remove(loggerInstance); - } - }*/ + #endregion // [Obsolete("NEED", false)] private static void LogMessage(LogLevel logLevel, String message, String sourceName, Object extendedData, String callerMemberName, String callerFilePath, Int32 callerLineNumber) { diff --git a/Swan.Tiny/Mappers/ObjectMap.cs b/Swan.Tiny/Mappers/ObjectMap.cs index beacfc6..0272cba 100644 --- a/Swan.Tiny/Mappers/ObjectMap.cs +++ b/Swan.Tiny/Mappers/ObjectMap.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Linq.Expressions; using System.Reflection; namespace Swan.Mappers { @@ -32,78 +31,5 @@ namespace Swan.Mappers { public Type DestinationType { get; } - - /*/// - /// Maps the property. - /// - /// The type of the destination property. - /// The type of the source property. - /// The destination property. - /// The source property. - /// - /// An object map representation of type of the destination property - /// and type of the source property. - /// - public ObjectMap MapProperty(Expression> destinationProperty, Expression> sourceProperty) { - PropertyInfo propertyDestinationInfo = (destinationProperty.Body as MemberExpression)?.Member as PropertyInfo; - - if(propertyDestinationInfo == null) { - throw new ArgumentException("Invalid destination expression", nameof(destinationProperty)); - } - - List sourceMembers = GetSourceMembers(sourceProperty); - - if(sourceMembers.Any() == false) { - throw new ArgumentException("Invalid source expression", nameof(sourceProperty)); - } - - // reverse order - sourceMembers.Reverse(); - this.Map[propertyDestinationInfo] = sourceMembers; - - return this; - } - - /// - /// Removes the map property. - /// - /// The type of the destination property. - /// The destination property. - /// - /// An object map representation of type of the destination property - /// and type of the source property. - /// - /// Invalid destination expression. - public ObjectMap RemoveMapProperty(Expression> destinationProperty) { - PropertyInfo propertyDestinationInfo = (destinationProperty.Body as MemberExpression)?.Member as PropertyInfo; - - if(propertyDestinationInfo == null) { - throw new ArgumentException("Invalid destination expression", nameof(destinationProperty)); - } - - if(this.Map.ContainsKey(propertyDestinationInfo)) { - _ = this.Map.Remove(propertyDestinationInfo); - } - - return this; - } - - private static List GetSourceMembers(Expression> sourceProperty) { - List sourceMembers = new List(); - MemberExpression initialExpression = sourceProperty.Body as MemberExpression; - - while(true) { - PropertyInfo propertySourceInfo = initialExpression?.Member as PropertyInfo; - - if(propertySourceInfo == null) { - break; - } - - sourceMembers.Add(propertySourceInfo); - initialExpression = initialExpression.Expression as MemberExpression; - } - - return sourceMembers; - }*/ } } diff --git a/Swan.Tiny/Mappers/ObjectMapper.PropertyInfoComparer.cs b/Swan.Tiny/Mappers/ObjectMapper.PropertyInfoComparer.cs deleted file mode 100644 index 3f4ff3b..0000000 --- a/Swan.Tiny/Mappers/ObjectMapper.PropertyInfoComparer.cs +++ /dev/null @@ -1,20 +0,0 @@ -/*using System; -using System.Collections.Generic; -using System.Reflection; - -namespace Swan.Mappers { - /// - /// Represents an AutoMapper-like object to map from one object type - /// to another using defined properties map or using the default behaviour - /// to copy same named properties from one object to another. - /// - /// The extension methods like CopyPropertiesTo use the default behaviour. - /// - public partial class ObjectMapper { - internal class PropertyInfoComparer : IEqualityComparer { - public Boolean Equals(PropertyInfo x, PropertyInfo y) => x != null && y != null && x.Name == y.Name && x.PropertyType == y.PropertyType; - - public Int32 GetHashCode(PropertyInfo obj) => obj.Name.GetHashCode() + obj.PropertyType.Name.GetHashCode(); - } - } -}*/ \ No newline at end of file diff --git a/Swan.Tiny/Mappers/ObjectMapper.cs b/Swan.Tiny/Mappers/ObjectMapper.cs index a200c40..99c7659 100644 --- a/Swan.Tiny/Mappers/ObjectMapper.cs +++ b/Swan.Tiny/Mappers/ObjectMapper.cs @@ -79,18 +79,6 @@ namespace Swan.Mappers { /// /// public partial class ObjectMapper { - /*private static readonly Lazy LazyInstance = new Lazy(() => new ObjectMapper()); - - private readonly List _maps = new List();*/ - - /*/// - /// Gets the current. - /// - /// - /// The current. - /// - public static ObjectMapper Current => LazyInstance.Value;*/ - /// /// Copies the specified source. /// @@ -145,78 +133,6 @@ namespace Swan.Mappers { return CopyInternal(target, source.ToDictionary(x => x.Key.ToLowerInvariant(), x => Tuple.Create(typeof(Object), x.Value)), propertiesToCopy, ignoreProperties); } - /*/// - /// Creates the map. - /// - /// The type of the source. - /// The type of the destination. - /// - /// An object map representation of type of the destination property - /// and type of the source property. - /// - /// - /// You can't create an existing map - /// or - /// Types doesn't match. - /// - public ObjectMap CreateMap() { - if(this._maps.Any(x => x.SourceType == typeof(TSource) && x.DestinationType == typeof(TDestination))) { - throw new InvalidOperationException("You can't create an existing map"); - } - - IEnumerable sourceType = PropertyTypeCache.DefaultCache.Value.RetrieveAllProperties(true); - IEnumerable destinationType = PropertyTypeCache.DefaultCache.Value.RetrieveAllProperties(true); - - PropertyInfo[] intersect = sourceType.Intersect(destinationType, new PropertyInfoComparer()).ToArray(); - - if(!intersect.Any()) { - throw new InvalidOperationException("Types doesn't match"); - } - - ObjectMap map = new ObjectMap(intersect); - - this._maps.Add(map); - - return map; - } - - /// - /// Maps the specified source. - /// - /// The type of the destination. - /// The source. - /// if set to true [automatic resolve]. - /// - /// A new instance of the map. - /// - /// source. - /// You can't map from type {source.GetType().Name} to {typeof(TDestination).Name}. - public TDestination Map(Object source, Boolean autoResolve = true) { - if(source == null) { - throw new ArgumentNullException(nameof(source)); - } - - TDestination destination = Activator.CreateInstance(); - IObjectMap map = this._maps.FirstOrDefault(x => x.SourceType == source.GetType() && x.DestinationType == typeof(TDestination)); - - if(map != null) { - foreach(KeyValuePair> property in map.Map) { - Object finalSource = property.Value.Aggregate(source, (current, sourceProperty) => sourceProperty.GetValue(current)!); - - property.Key.SetValue(destination, finalSource); - } - } else { - if(!autoResolve) { - throw new InvalidOperationException($"You can't map from type {source.GetType().Name} to {typeof(TDestination).Name}"); - } - - // Missing mapping, try to use default behavior - _ = Copy(source, destination); - } - - return destination; - }*/ - private static Int32 CopyInternal(Object target, Dictionary> sourceProperties, IEnumerable? propertiesToCopy, IEnumerable? ignoreProperties) { // Filter properties IEnumerable? requiredProperties = propertiesToCopy?.Where(p => !String.IsNullOrWhiteSpace(p)).Select(p => p.ToLowerInvariant()); diff --git a/Swan.Tiny/Net/Dns/DnsClient.Interfaces.cs b/Swan.Tiny/Net/Dns/DnsClient.Interfaces.cs deleted file mode 100644 index 631fad5..0000000 --- a/Swan.Tiny/Net/Dns/DnsClient.Interfaces.cs +++ /dev/null @@ -1,96 +0,0 @@ -/*using System; -using System.Threading.Tasks; -using System.Collections.Generic; - -namespace Swan.Net.Dns { - /// - /// DnsClient public interfaces. - /// - internal partial class DnsClient { - public interface IDnsMessage { - IList Questions { - get; - } - - Int32 Size { - get; - } - Byte[] ToArray(); - } - - public interface IDnsMessageEntry { - DnsDomain Name { - get; - } - DnsRecordType Type { - get; - } - DnsRecordClass Class { - get; - } - - Int32 Size { - get; - } - Byte[] ToArray(); - } - - public interface IDnsResourceRecord : IDnsMessageEntry { - TimeSpan TimeToLive { - get; - } - Int32 DataLength { - get; - } - Byte[] Data { - get; - } - } - - public interface IDnsRequest : IDnsMessage { - Int32 Id { - get; set; - } - DnsOperationCode OperationCode { - get; set; - } - Boolean RecursionDesired { - get; set; - } - } - - public interface IDnsResponse : IDnsMessage { - Int32 Id { - get; set; - } - IList AnswerRecords { - get; - } - IList AuthorityRecords { - get; - } - IList AdditionalRecords { - get; - } - Boolean IsRecursionAvailable { - get; set; - } - Boolean IsAuthorativeServer { - get; set; - } - Boolean IsTruncated { - get; set; - } - DnsOperationCode OperationCode { - get; set; - } - DnsResponseCode ResponseCode { - get; set; - } - } - - public interface IDnsRequestResolver { - Task Request(DnsClientRequest request); - } - } -}*/ diff --git a/Swan.Tiny/Net/Dns/DnsClient.Request.cs b/Swan.Tiny/Net/Dns/DnsClient.Request.cs deleted file mode 100644 index 85e9607..0000000 --- a/Swan.Tiny/Net/Dns/DnsClient.Request.cs +++ /dev/null @@ -1,559 +0,0 @@ -/* -#nullable enable -using Swan.Formatters; -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Runtime.InteropServices; -using System.Text; - -namespace Swan.Net.Dns { - /// - /// DnsClient Request inner class. - /// - internal partial class DnsClient { - public class DnsClientRequest : IDnsRequest { - private readonly IDnsRequestResolver _resolver; - private readonly IDnsRequest _request; - - public DnsClientRequest(IPEndPoint dns, IDnsRequest? request = null, IDnsRequestResolver? resolver = null) { - this.Dns = dns; - this._request = request == null ? new DnsRequest() : new DnsRequest(request); - this._resolver = resolver ?? new DnsUdpRequestResolver(); - } - - public Int32 Id { - get => this._request.Id; - set => this._request.Id = value; - } - - public DnsOperationCode OperationCode { - get => this._request.OperationCode; - set => this._request.OperationCode = value; - } - - public Boolean RecursionDesired { - get => this._request.RecursionDesired; - set => this._request.RecursionDesired = value; - } - - public IList Questions => this._request.Questions; - - public Int32 Size => this._request.Size; - - public IPEndPoint Dns { - get; set; - } - - public Byte[] ToArray() => this._request.ToArray(); - - public override String ToString() => this._request.ToString()!; - - /// - /// Resolves this request into a response using the provided DNS information. The given - /// request strategy is used to retrieve the response. - /// - /// Throw if a malformed response is received from the server. - /// Thrown if a IO error occurs. - /// Thrown if a the reading or writing to the socket fails. - /// The response received from server. - public async Task Resolve() { - try { - DnsClientResponse response = await this._resolver.Request(this).ConfigureAwait(false); - - if(response.Id != this.Id) { - throw new DnsQueryException(response, "Mismatching request/response IDs"); - } - - if(response.ResponseCode != DnsResponseCode.NoError) { - throw new DnsQueryException(response); - } - - return response; - } catch(Exception e) { - if(e is ArgumentException || e is SocketException) { - throw new DnsQueryException("Invalid response", e); - } - - throw; - } - } - } - - public class DnsRequest : IDnsRequest { - private static readonly Random Random = new Random(); - - private DnsHeader header; - - public DnsRequest() { - this.Questions = new List(); - this.header = new DnsHeader { - OperationCode = DnsOperationCode.Query, - Response = false, - Id = Random.Next(UInt16.MaxValue), - }; - } - - public DnsRequest(IDnsRequest request) { - this.header = new DnsHeader(); - this.Questions = new List(request.Questions); - - this.header.Response = false; - - this.Id = request.Id; - this.OperationCode = request.OperationCode; - this.RecursionDesired = request.RecursionDesired; - } - - public IList Questions { - get; - } - - public Int32 Size => this.header.Size + this.Questions.Sum(q => q.Size); - - public Int32 Id { - get => this.header.Id; - set => this.header.Id = value; - } - - public DnsOperationCode OperationCode { - get => this.header.OperationCode; - set => this.header.OperationCode = value; - } - - public Boolean RecursionDesired { - get => this.header.RecursionDesired; - set => this.header.RecursionDesired = value; - } - - public Byte[] ToArray() { - this.UpdateHeader(); - using MemoryStream result = new MemoryStream(this.Size); - - return result.Append(this.header.ToArray()).Append(this.Questions.Select(q => q.ToArray())).ToArray(); - } - - public override String ToString() { - this.UpdateHeader(); - - return Json.Serialize(this, true); - } - - private void UpdateHeader() => this.header.QuestionCount = this.Questions.Count; - } - - public class DnsTcpRequestResolver : IDnsRequestResolver { - public async Task Request(DnsClientRequest request) { - TcpClient tcp = new TcpClient(); - - try { - await tcp.Client.ConnectAsync(request.Dns).ConfigureAwait(false); - - NetworkStream stream = tcp.GetStream(); - Byte[] buffer = request.ToArray(); - Byte[] length = BitConverter.GetBytes((UInt16)buffer.Length); - - if(BitConverter.IsLittleEndian) { - Array.Reverse(length); - } - - await stream.WriteAsync(length, 0, length.Length).ConfigureAwait(false); - await stream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false); - - buffer = new Byte[2]; - await Read(stream, buffer).ConfigureAwait(false); - - if(BitConverter.IsLittleEndian) { - Array.Reverse(buffer); - } - - buffer = new Byte[BitConverter.ToUInt16(buffer, 0)]; - await Read(stream, buffer).ConfigureAwait(false); - - DnsResponse response = DnsResponse.FromArray(buffer); - - return new DnsClientResponse(request, response, buffer); - } finally { - tcp.Dispose(); - } - } - - private static async Task Read(Stream stream, Byte[] buffer) { - Int32 length = buffer.Length; - Int32 offset = 0; - Int32 size; - - while(length > 0 && (size = await stream.ReadAsync(buffer, offset, length).ConfigureAwait(false)) > 0) { - offset += size; - length -= size; - } - - if(length > 0) { - throw new IOException("Unexpected end of stream"); - } - } - } - - public class DnsUdpRequestResolver : IDnsRequestResolver { - private readonly IDnsRequestResolver _fallback; - - public DnsUdpRequestResolver(IDnsRequestResolver fallback) => this._fallback = fallback; - - public DnsUdpRequestResolver() => this._fallback = new DnsNullRequestResolver(); - - public async Task Request(DnsClientRequest request) { - UdpClient udp = new UdpClient(); - IPEndPoint dns = request.Dns; - - try { - udp.Client.SendTimeout = 7000; - udp.Client.ReceiveTimeout = 7000; - - await udp.Client.ConnectAsync(dns).ConfigureAwait(false); - - - _ = await udp.SendAsync(request.ToArray(), request.Size).ConfigureAwait(false); - - List bufferList = new List(); - - do { - Byte[] tempBuffer = new Byte[1024]; - Int32 receiveCount = udp.Client.Receive(tempBuffer); - bufferList.AddRange(tempBuffer.Skip(0).Take(receiveCount)); - } - while(udp.Client.Available > 0 || bufferList.Count == 0); - - Byte[] buffer = bufferList.ToArray(); - DnsResponse response = DnsResponse.FromArray(buffer); - - return response.IsTruncated - ? await this._fallback.Request(request).ConfigureAwait(false) - : new DnsClientResponse(request, response, buffer); - } finally { - udp.Dispose(); - } - } - } - - public class DnsNullRequestResolver : IDnsRequestResolver { - public Task Request(DnsClientRequest request) => throw new DnsQueryException("Request failed"); - } - - // 12 bytes message header - [StructEndianness(Endianness.Big)] - [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct DnsHeader { - public const Int32 SIZE = 12; - - private UInt16 id; - - // Question count: number of questions in the Question section - private UInt16 questionCount; - - // Answer record count: number of records in the Answer section - private UInt16 answerCount; - - // Authority record count: number of records in the Authority section - private UInt16 authorityCount; - - // Additional record count: number of records in the Additional section - private UInt16 addtionalCount; - - public Int32 Id { - get => this.id; - set => this.id = (UInt16)value; - } - - public Int32 QuestionCount { - get => this.questionCount; - set => this.questionCount = (UInt16)value; - } - - public Int32 AnswerRecordCount { - get => this.answerCount; - set => this.answerCount = (UInt16)value; - } - - public Int32 AuthorityRecordCount { - get => this.authorityCount; - set => this.authorityCount = (UInt16)value; - } - - public Int32 AdditionalRecordCount { - get => this.addtionalCount; - set => this.addtionalCount = (UInt16)value; - } - - public Boolean Response { - get => this.Qr == 1; - set => this.Qr = Convert.ToByte(value); - } - - public DnsOperationCode OperationCode { - get => (DnsOperationCode)this.Opcode; - set => this.Opcode = (Byte)value; - } - - public Boolean AuthorativeServer { - get => this.Aa == 1; - set => this.Aa = Convert.ToByte(value); - } - - public Boolean Truncated { - get => this.Tc == 1; - set => this.Tc = Convert.ToByte(value); - } - - public Boolean RecursionDesired { - get => this.Rd == 1; - set => this.Rd = Convert.ToByte(value); - } - - public Boolean RecursionAvailable { - get => this.Ra == 1; - set => this.Ra = Convert.ToByte(value); - } - - public DnsResponseCode ResponseCode { - get => (DnsResponseCode)this.RCode; - set => this.RCode = (Byte)value; - } - - public Int32 Size => SIZE; - - // Query/Response Flag - private Byte Qr { - get => this.Flag0.GetBitValueAt(7); - set => this.Flag0 = this.Flag0.SetBitValueAt(7, 1, value); - } - - // Operation Code - private Byte Opcode { - get => this.Flag0.GetBitValueAt(3, 4); - set => this.Flag0 = this.Flag0.SetBitValueAt(3, 4, value); - } - - // Authorative Answer Flag - private Byte Aa { - get => this.Flag0.GetBitValueAt(2); - set => this.Flag0 = this.Flag0.SetBitValueAt(2, 1, value); - } - - // Truncation Flag - private Byte Tc { - get => this.Flag0.GetBitValueAt(1); - set => this.Flag0 = this.Flag0.SetBitValueAt(1, 1, value); - } - - // Recursion Desired - private Byte Rd { - get => this.Flag0.GetBitValueAt(0); - set => this.Flag0 = this.Flag0.SetBitValueAt(0, 1, value); - } - - // Recursion Available - private Byte Ra { - get => this.Flag1.GetBitValueAt(7); - set => this.Flag1 = this.Flag1.SetBitValueAt(7, 1, value); - } - - // Zero (Reserved) - private Byte Z { - get => this.Flag1.GetBitValueAt(4, 3); - set { - } - } - - // Response Code - private Byte RCode { - get => this.Flag1.GetBitValueAt(0, 4); - set => this.Flag1 = this.Flag1.SetBitValueAt(0, 4, value); - } - - private Byte Flag0 { - get; - set; - } - - private Byte Flag1 { - get; - set; - } - - public static DnsHeader FromArray(Byte[] header) => header.Length < SIZE ? throw new ArgumentException("Header length too small") : header.ToStruct(0, SIZE); - - public Byte[] ToArray() => this.ToBytes(); - - public override String ToString() => Json.SerializeExcluding(this, true, nameof(this.Size)); - } - - public class DnsDomain : IComparable { - private readonly String[] _labels; - - public DnsDomain(String domain) : this(domain.Split('.')) { - } - - public DnsDomain(String[] labels) => this._labels = labels; - - public Int32 Size => this._labels.Sum(l => l.Length) + this._labels.Length + 1; - - public static DnsDomain FromArray(Byte[] message, Int32 offset) => FromArray(message, offset, out _); - - public static DnsDomain FromArray(Byte[] message, Int32 offset, out Int32 endOffset) { - List labels = new List(); - Boolean endOffsetAssigned = false; - endOffset = 0; - Byte lengthOrPointer; - - while((lengthOrPointer = message[offset++]) > 0) { - // Two heighest bits are set (pointer) - if(lengthOrPointer.GetBitValueAt(6, 2) == 3) { - if(!endOffsetAssigned) { - endOffsetAssigned = true; - endOffset = offset + 1; - } - - UInt16 pointer = lengthOrPointer.GetBitValueAt(0, 6); - offset = (pointer << 8) | message[offset]; - - continue; - } - - if(lengthOrPointer.GetBitValueAt(6, 2) != 0) { - throw new ArgumentException("Unexpected bit pattern in label length"); - } - - Byte length = lengthOrPointer; - Byte[] label = new Byte[length]; - Array.Copy(message, offset, label, 0, length); - - labels.Add(label); - - offset += length; - } - - if(!endOffsetAssigned) { - endOffset = offset; - } - - return new DnsDomain(labels.Select(l => l.ToText(Encoding.ASCII)).ToArray()); - } - - public static DnsDomain PointerName(IPAddress ip) => new DnsDomain(FormatReverseIP(ip)); - - public Byte[] ToArray() { - Byte[] result = new Byte[this.Size]; - Int32 offset = 0; - - foreach(Byte[] l in this._labels.Select(label => Encoding.ASCII.GetBytes(label))) { - result[offset++] = (Byte)l.Length; - l.CopyTo(result, offset); - - offset += l.Length; - } - - result[offset] = 0; - - return result; - } - - public override String ToString() => String.Join(".", this._labels); - - public Int32 CompareTo(DnsDomain other) => String.Compare(this.ToString(), other.ToString(), StringComparison.Ordinal); - - public override Boolean Equals(Object? obj) => obj is DnsDomain domain && this.CompareTo(domain) == 0; - - public override Int32 GetHashCode() => this.ToString().GetHashCode(); - - private static String FormatReverseIP(IPAddress ip) { - Byte[] address = ip.GetAddressBytes(); - - if(address.Length == 4) { - return String.Join(".", address.Reverse().Select(b => b.ToString())) + ".in-addr.arpa"; - } - - Byte[] nibbles = new Byte[address.Length * 2]; - - for(Int32 i = 0, j = 0; i < address.Length; i++, j = 2 * i) { - Byte b = address[i]; - - nibbles[j] = b.GetBitValueAt(4, 4); - nibbles[j + 1] = b.GetBitValueAt(0, 4); - } - - return String.Join(".", nibbles.Reverse().Select(b => b.ToString("x"))) + ".ip6.arpa"; - } - } - - public class DnsQuestion : IDnsMessageEntry { - public static IList GetAllFromArray(Byte[] message, Int32 offset, Int32 questionCount) => GetAllFromArray(message, offset, questionCount, out _); - - public static IList GetAllFromArray(Byte[] message, Int32 offset, Int32 questionCount, out Int32 endOffset) { - IList questions = new List(questionCount); - - for(Int32 i = 0; i < questionCount; i++) { - questions.Add(FromArray(message, offset, out offset)); - } - - endOffset = offset; - return questions; - } - - public static DnsQuestion FromArray(Byte[] message, Int32 offset, out Int32 endOffset) { - DnsDomain domain = DnsDomain.FromArray(message, offset, out offset); - Tail tail = message.ToStruct(offset, Tail.SIZE); - - endOffset = offset + Tail.SIZE; - - return new DnsQuestion(domain, tail.Type, tail.Class); - } - - public DnsQuestion(DnsDomain domain, DnsRecordType type = DnsRecordType.A, DnsRecordClass klass = DnsRecordClass.IN) { - this.Name = domain; - this.Type = type; - this.Class = klass; - } - - public DnsDomain Name { - get; - } - - public DnsRecordType Type { - get; - } - - public DnsRecordClass Class { - get; - } - - public Int32 Size => this.Name.Size + Tail.SIZE; - - public Byte[] ToArray() => new MemoryStream(this.Size).Append(this.Name.ToArray()).Append(new Tail { Type = Type, Class = Class }.ToBytes()).ToArray(); - - public override String ToString() => Json.SerializeOnly(this, true, nameof(this.Name), nameof(this.Type), nameof(this.Class)); - - [StructEndianness(Endianness.Big)] - [StructLayout(LayoutKind.Sequential, Pack = 2)] - private struct Tail { - public const Int32 SIZE = 4; - - private UInt16 type; - private UInt16 klass; - - public DnsRecordType Type { - get => (DnsRecordType)this.type; - set => this.type = (UInt16)value; - } - - public DnsRecordClass Class { - get => (DnsRecordClass)this.klass; - set => this.klass = (UInt16)value; - } - } - } - } -}*/ diff --git a/Swan.Tiny/Net/Dns/DnsClient.ResourceRecords.cs b/Swan.Tiny/Net/Dns/DnsClient.ResourceRecords.cs deleted file mode 100644 index 6b61ed4..0000000 --- a/Swan.Tiny/Net/Dns/DnsClient.ResourceRecords.cs +++ /dev/null @@ -1,344 +0,0 @@ -/*using Swan.Formatters; -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Runtime.InteropServices; - -namespace Swan.Net.Dns { - /// - /// DnsClient public methods. - /// - internal partial class DnsClient { - public abstract class DnsResourceRecordBase : IDnsResourceRecord { - private readonly IDnsResourceRecord _record; - - protected DnsResourceRecordBase(IDnsResourceRecord record) => this._record = record; - - public DnsDomain Name => this._record.Name; - - public DnsRecordType Type => this._record.Type; - - public DnsRecordClass Class => this._record.Class; - - public TimeSpan TimeToLive => this._record.TimeToLive; - - public Int32 DataLength => this._record.DataLength; - - public Byte[] Data => this._record.Data; - - public Int32 Size => this._record.Size; - - protected virtual String[] IncludedProperties => new[] { nameof(this.Name), nameof(this.Type), nameof(this.Class), nameof(this.TimeToLive), nameof(this.DataLength) }; - - public Byte[] ToArray() => this._record.ToArray(); - - public override String ToString() => Json.SerializeOnly(this, true, this.IncludedProperties); - } - - public class DnsResourceRecord : IDnsResourceRecord { - public DnsResourceRecord(DnsDomain domain, Byte[] data, DnsRecordType type, DnsRecordClass klass = DnsRecordClass.IN, TimeSpan ttl = default) { - this.Name = domain; - this.Type = type; - this.Class = klass; - this.TimeToLive = ttl; - this.Data = data; - } - - public DnsDomain Name { - get; - } - - public DnsRecordType Type { - get; - } - - public DnsRecordClass Class { - get; - } - - public TimeSpan TimeToLive { - get; - } - - public Int32 DataLength => this.Data.Length; - - public Byte[] Data { - get; - } - - public Int32 Size => this.Name.Size + Tail.SIZE + this.Data.Length; - - public static DnsResourceRecord FromArray(Byte[] message, Int32 offset, out Int32 endOffset) { - DnsDomain domain = DnsDomain.FromArray(message, offset, out offset); - Tail tail = message.ToStruct(offset, Tail.SIZE); - - Byte[] data = new Byte[tail.DataLength]; - - offset += Tail.SIZE; - Array.Copy(message, offset, data, 0, data.Length); - - endOffset = offset + data.Length; - - return new DnsResourceRecord(domain, data, tail.Type, tail.Class, tail.TimeToLive); - } - - public Byte[] ToArray() => new MemoryStream(this.Size).Append(this.Name.ToArray()).Append(new Tail() { Type = Type, Class = Class, TimeToLive = TimeToLive, DataLength = this.Data.Length, }.ToBytes()).Append(this.Data).ToArray(); - - public override String ToString() => Json.SerializeOnly(this, true, nameof(this.Name), nameof(this.Type), nameof(this.Class), nameof(this.TimeToLive), nameof(this.DataLength)); - - [StructEndianness(Endianness.Big)] - [StructLayout(LayoutKind.Sequential, Pack = 2)] - private struct Tail { - public const Int32 SIZE = 10; - - private UInt16 type; - private UInt16 klass; - private UInt32 ttl; - private UInt16 dataLength; - - public DnsRecordType Type { - get => (DnsRecordType)this.type; - set => this.type = (UInt16)value; - } - - public DnsRecordClass Class { - get => (DnsRecordClass)this.klass; - set => this.klass = (UInt16)value; - } - - public TimeSpan TimeToLive { - get => TimeSpan.FromSeconds(this.ttl); - set => this.ttl = (UInt32)value.TotalSeconds; - } - - public Int32 DataLength { - get => this.dataLength; - set => this.dataLength = (UInt16)value; - } - } - } - - public class DnsPointerResourceRecord : DnsResourceRecordBase { - public DnsPointerResourceRecord(IDnsResourceRecord record, Byte[] message, Int32 dataOffset) : base(record) => this.PointerDomainName = DnsDomain.FromArray(message, dataOffset); - - public DnsDomain PointerDomainName { - get; - } - - protected override String[] IncludedProperties { - get { - List temp = new List(base.IncludedProperties) { nameof(this.PointerDomainName) }; - return temp.ToArray(); - } - } - } - - public class DnsIPAddressResourceRecord : DnsResourceRecordBase { - public DnsIPAddressResourceRecord(IDnsResourceRecord record) : base(record) => this.IPAddress = new IPAddress(this.Data); - - public IPAddress IPAddress { - get; - } - - protected override String[] IncludedProperties => new List(base.IncludedProperties) { nameof(this.IPAddress) }.ToArray(); - } - - public class DnsNameServerResourceRecord : DnsResourceRecordBase { - public DnsNameServerResourceRecord(IDnsResourceRecord record, Byte[] message, Int32 dataOffset) : base(record) => this.NSDomainName = DnsDomain.FromArray(message, dataOffset); - - public DnsDomain NSDomainName { - get; - } - - protected override String[] IncludedProperties => new List(base.IncludedProperties) { nameof(this.NSDomainName) }.ToArray(); - } - - public class DnsCanonicalNameResourceRecord : DnsResourceRecordBase { - public DnsCanonicalNameResourceRecord(IDnsResourceRecord record, Byte[] message, Int32 dataOffset) : base(record) => this.CanonicalDomainName = DnsDomain.FromArray(message, dataOffset); - - public DnsDomain CanonicalDomainName { - get; - } - - protected override String[] IncludedProperties => new List(base.IncludedProperties) { nameof(this.CanonicalDomainName) }.ToArray(); - } - - public class DnsMailExchangeResourceRecord : DnsResourceRecordBase { - private const Int32 PreferenceSize = 2; - - public DnsMailExchangeResourceRecord(IDnsResourceRecord record, Byte[] message, Int32 dataOffset) - : base(record) { - Byte[] preference = new Byte[PreferenceSize]; - Array.Copy(message, dataOffset, preference, 0, preference.Length); - - if(BitConverter.IsLittleEndian) { - Array.Reverse(preference); - } - - dataOffset += PreferenceSize; - - this.Preference = BitConverter.ToUInt16(preference, 0); - this.ExchangeDomainName = DnsDomain.FromArray(message, dataOffset); - } - - public Int32 Preference { - get; - } - - public DnsDomain ExchangeDomainName { - get; - } - - protected override String[] IncludedProperties => new List(base.IncludedProperties) - { - nameof(this.Preference), - nameof(this.ExchangeDomainName), - }.ToArray(); - } - - public class DnsStartOfAuthorityResourceRecord : DnsResourceRecordBase { - public DnsStartOfAuthorityResourceRecord(IDnsResourceRecord record, Byte[] message, Int32 dataOffset) : base(record) { - this.MasterDomainName = DnsDomain.FromArray(message, dataOffset, out dataOffset); - this.ResponsibleDomainName = DnsDomain.FromArray(message, dataOffset, out dataOffset); - - Options tail = message.ToStruct(dataOffset, Options.SIZE); - - this.SerialNumber = tail.SerialNumber; - this.RefreshInterval = tail.RefreshInterval; - this.RetryInterval = tail.RetryInterval; - this.ExpireInterval = tail.ExpireInterval; - this.MinimumTimeToLive = tail.MinimumTimeToLive; - } - - public DnsStartOfAuthorityResourceRecord(DnsDomain domain, DnsDomain master, DnsDomain responsible, Int64 serial, TimeSpan refresh, TimeSpan retry, TimeSpan expire, TimeSpan minTtl, TimeSpan ttl = default) - : base(Create(domain, master, responsible, serial, refresh, retry, expire, minTtl, ttl)) { - this.MasterDomainName = master; - this.ResponsibleDomainName = responsible; - - this.SerialNumber = serial; - this.RefreshInterval = refresh; - this.RetryInterval = retry; - this.ExpireInterval = expire; - this.MinimumTimeToLive = minTtl; - } - - public DnsDomain MasterDomainName { - get; - } - - public DnsDomain ResponsibleDomainName { - get; - } - - public Int64 SerialNumber { - get; - } - - public TimeSpan RefreshInterval { - get; - } - - public TimeSpan RetryInterval { - get; - } - - public TimeSpan ExpireInterval { - get; - } - - public TimeSpan MinimumTimeToLive { - get; - } - - protected override String[] IncludedProperties => new List(base.IncludedProperties) - { - nameof(this.MasterDomainName), - nameof(this.ResponsibleDomainName), - nameof(this.SerialNumber), - }.ToArray(); - - private static IDnsResourceRecord Create(DnsDomain domain, DnsDomain master, DnsDomain responsible, Int64 serial, TimeSpan refresh, TimeSpan retry, TimeSpan expire, TimeSpan minTtl, TimeSpan ttl) { - MemoryStream data = new MemoryStream(Options.SIZE + master.Size + responsible.Size); - Options tail = new Options { - SerialNumber = serial, - RefreshInterval = refresh, - RetryInterval = retry, - ExpireInterval = expire, - MinimumTimeToLive = minTtl, - }; - - _ = data.Append(master.ToArray()).Append(responsible.ToArray()).Append(tail.ToBytes()); - - return new DnsResourceRecord(domain, data.ToArray(), DnsRecordType.SOA, DnsRecordClass.IN, ttl); - } - - [StructEndianness(Endianness.Big)] - [StructLayout(LayoutKind.Sequential, Pack = 4)] - public struct Options { - public const Int32 SIZE = 20; - - private UInt32 serialNumber; - private UInt32 refreshInterval; - private UInt32 retryInterval; - private UInt32 expireInterval; - private UInt32 ttl; - - public Int64 SerialNumber { - get => this.serialNumber; - set => this.serialNumber = (UInt32)value; - } - - public TimeSpan RefreshInterval { - get => TimeSpan.FromSeconds(this.refreshInterval); - set => this.refreshInterval = (UInt32)value.TotalSeconds; - } - - public TimeSpan RetryInterval { - get => TimeSpan.FromSeconds(this.retryInterval); - set => this.retryInterval = (UInt32)value.TotalSeconds; - } - - public TimeSpan ExpireInterval { - get => TimeSpan.FromSeconds(this.expireInterval); - set => this.expireInterval = (UInt32)value.TotalSeconds; - } - - public TimeSpan MinimumTimeToLive { - get => TimeSpan.FromSeconds(this.ttl); - set => this.ttl = (UInt32)value.TotalSeconds; - } - } - } - - private static class DnsResourceRecordFactory { - public static IList GetAllFromArray(Byte[] message, Int32 offset, Int32 count, out Int32 endOffset) { - List result = new List(count); - - for(Int32 i = 0; i < count; i++) { - result.Add(GetFromArray(message, offset, out offset)); - } - - endOffset = offset; - return result; - } - - private static IDnsResourceRecord GetFromArray(Byte[] message, Int32 offset, out Int32 endOffset) { - DnsResourceRecord record = DnsResourceRecord.FromArray(message, offset, out endOffset); - Int32 dataOffset = endOffset - record.DataLength; - - return record.Type switch - { - DnsRecordType.A => (new DnsIPAddressResourceRecord(record)), - DnsRecordType.AAAA => new DnsIPAddressResourceRecord(record), - DnsRecordType.NS => new DnsNameServerResourceRecord(record, message, dataOffset), - DnsRecordType.CNAME => new DnsCanonicalNameResourceRecord(record, message, dataOffset), - DnsRecordType.SOA => new DnsStartOfAuthorityResourceRecord(record, message, dataOffset), - DnsRecordType.PTR => new DnsPointerResourceRecord(record, message, dataOffset), - DnsRecordType.MX => new DnsMailExchangeResourceRecord(record, message, dataOffset), - _ => record - }; - } - } - } -}*/ diff --git a/Swan.Tiny/Net/Dns/DnsClient.Response.cs b/Swan.Tiny/Net/Dns/DnsClient.Response.cs deleted file mode 100644 index 28dd312..0000000 --- a/Swan.Tiny/Net/Dns/DnsClient.Response.cs +++ /dev/null @@ -1,174 +0,0 @@ -/*using Swan.Formatters; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.IO; -using System.Linq; - -namespace Swan.Net.Dns { - /// - /// DnsClient Response inner class. - /// - internal partial class DnsClient { - public class DnsClientResponse : IDnsResponse { - private readonly DnsResponse _response; - private readonly Byte[] _message; - - internal DnsClientResponse(DnsClientRequest request, DnsResponse response, Byte[] message) { - this.Request = request; - - this._message = message; - this._response = response; - } - - public DnsClientRequest Request { - get; - } - - public Int32 Id { - get => this._response.Id; - set { - } - } - - public IList AnswerRecords => this._response.AnswerRecords; - - public IList AuthorityRecords => new ReadOnlyCollection(this._response.AuthorityRecords); - - public IList AdditionalRecords => new ReadOnlyCollection(this._response.AdditionalRecords); - - public Boolean IsRecursionAvailable { - get => this._response.IsRecursionAvailable; - set { - } - } - - public Boolean IsAuthorativeServer { - get => this._response.IsAuthorativeServer; - set { - } - } - - public Boolean IsTruncated { - get => this._response.IsTruncated; - set { - } - } - - public DnsOperationCode OperationCode { - get => this._response.OperationCode; - set { - } - } - - public DnsResponseCode ResponseCode { - get => this._response.ResponseCode; - set { - } - } - - public IList Questions => new ReadOnlyCollection(this._response.Questions); - - public Int32 Size => this._message.Length; - - public Byte[] ToArray() => this._message; - - public override String ToString() => this._response.ToString(); - } - - public class DnsResponse : IDnsResponse { - private DnsHeader _header; - - public DnsResponse(DnsHeader header, IList questions, IList answers, IList authority, IList additional) { - this._header = header; - this.Questions = questions; - this.AnswerRecords = answers; - this.AuthorityRecords = authority; - this.AdditionalRecords = additional; - } - - public IList Questions { - get; - } - - public IList AnswerRecords { - get; - } - - public IList AuthorityRecords { - get; - } - - public IList AdditionalRecords { - get; - } - - public Int32 Id { - get => this._header.Id; - set => this._header.Id = value; - } - - public Boolean IsRecursionAvailable { - get => this._header.RecursionAvailable; - set => this._header.RecursionAvailable = value; - } - - public Boolean IsAuthorativeServer { - get => this._header.AuthorativeServer; - set => this._header.AuthorativeServer = value; - } - - public Boolean IsTruncated { - get => this._header.Truncated; - set => this._header.Truncated = value; - } - - public DnsOperationCode OperationCode { - get => this._header.OperationCode; - set => this._header.OperationCode = value; - } - - public DnsResponseCode ResponseCode { - get => this._header.ResponseCode; - set => this._header.ResponseCode = value; - } - - public Int32 Size => this._header.Size + this.Questions.Sum(q => q.Size) + this.AnswerRecords.Sum(a => a.Size) + this.AuthorityRecords.Sum(a => a.Size) + this.AdditionalRecords.Sum(a => a.Size); - - public static DnsResponse FromArray(Byte[] message) { - DnsHeader header = DnsHeader.FromArray(message); - Int32 offset = header.Size; - - if(!header.Response || header.QuestionCount == 0) { - throw new ArgumentException("Invalid response message"); - } - - return header.Truncated - ? new DnsResponse(header, DnsQuestion.GetAllFromArray(message, offset, header.QuestionCount), new List(), new List(), new List()) - : new DnsResponse(header, DnsQuestion.GetAllFromArray(message, offset, header.QuestionCount, out offset), DnsResourceRecordFactory.GetAllFromArray(message, offset, header.AnswerRecordCount, out offset), DnsResourceRecordFactory.GetAllFromArray(message, offset, header.AuthorityRecordCount, out offset), DnsResourceRecordFactory.GetAllFromArray(message, offset, header.AdditionalRecordCount, out _)); - } - - public Byte[] ToArray() { - this.UpdateHeader(); - MemoryStream result = new MemoryStream(this.Size); - - _ = result.Append(this._header.ToArray()).Append(this.Questions.Select(q => q.ToArray())).Append(this.AnswerRecords.Select(a => a.ToArray())).Append(this.AuthorityRecords.Select(a => a.ToArray())).Append(this.AdditionalRecords.Select(a => a.ToArray())); - - return result.ToArray(); - } - - public override String ToString() { - this.UpdateHeader(); - - return Json.SerializeOnly(this, true, nameof(this.Questions), nameof(this.AnswerRecords), nameof(this.AuthorityRecords), nameof(this.AdditionalRecords)); - } - - private void UpdateHeader() { - this._header.QuestionCount = this.Questions.Count; - this._header.AnswerRecordCount = this.AnswerRecords.Count; - this._header.AuthorityRecordCount = this.AuthorityRecords.Count; - this._header.AdditionalRecordCount = this.AdditionalRecords.Count; - } - } - } -}*/ \ No newline at end of file diff --git a/Swan.Tiny/Net/Dns/DnsClient.cs b/Swan.Tiny/Net/Dns/DnsClient.cs deleted file mode 100644 index cad4a0c..0000000 --- a/Swan.Tiny/Net/Dns/DnsClient.cs +++ /dev/null @@ -1,65 +0,0 @@ -/*using System; -using System.Collections.Generic; -using System.Linq; -#nullable enable -using System.Net; -using System.Threading.Tasks; - -namespace Swan.Net.Dns { - /// - /// DnsClient public methods. - /// - internal partial class DnsClient { - private readonly IPEndPoint _dns; - private readonly IDnsRequestResolver _resolver; - - public DnsClient(IPEndPoint dns, IDnsRequestResolver? resolver = null) { - this._dns = dns; - this._resolver = resolver ?? new DnsUdpRequestResolver(new DnsTcpRequestResolver()); - } - - public DnsClient(IPAddress ip, Int32 port = Network.DnsDefaultPort, IDnsRequestResolver? resolver = null) : this(new IPEndPoint(ip, port), resolver) { - } - - public DnsClientRequest Create(IDnsRequest? request = null) => new DnsClientRequest(this._dns, request, this._resolver); - - public async Task> Lookup(String domain, DnsRecordType type = DnsRecordType.A) { - if(String.IsNullOrWhiteSpace(domain)) { - throw new ArgumentNullException(nameof(domain)); - } - - if(type != DnsRecordType.A && type != DnsRecordType.AAAA) { - throw new ArgumentException("Invalid record type " + type); - } - - DnsClientResponse response = await this.Resolve(domain, type).ConfigureAwait(false); - List ips = response.AnswerRecords.Where(r => r.Type == type).Cast().Select(r => r.IPAddress).ToList(); - - return ips.Count == 0 ? throw new DnsQueryException(response, "No matching records") : ips; - } - - public async Task Reverse(IPAddress ip) { - if(ip == null) { - throw new ArgumentNullException(nameof(ip)); - } - - DnsClientResponse response = await this.Resolve(DnsDomain.PointerName(ip), DnsRecordType.PTR); - IDnsResourceRecord ptr = response.AnswerRecords.FirstOrDefault(r => r.Type == DnsRecordType.PTR); - - return ptr == null ? throw new DnsQueryException(response, "No matching records") : ((DnsPointerResourceRecord)ptr).PointerDomainName.ToString(); - } - - public Task Resolve(String domain, DnsRecordType type) => this.Resolve(new DnsDomain(domain), type); - - public Task Resolve(DnsDomain domain, DnsRecordType type) { - DnsClientRequest request = this.Create(); - DnsQuestion question = new DnsQuestion(domain, type); - - request.Questions.Add(question); - request.OperationCode = DnsOperationCode.Query; - request.RecursionDesired = true; - - return request.Resolve(); - } - } -}*/ diff --git a/Swan.Tiny/Net/Dns/DnsQueryException.cs b/Swan.Tiny/Net/Dns/DnsQueryException.cs deleted file mode 100644 index 37a4bf7..0000000 --- a/Swan.Tiny/Net/Dns/DnsQueryException.cs +++ /dev/null @@ -1,29 +0,0 @@ -/*#nullable enable -using System; - -namespace Swan.Net.Dns { - /// - /// An exception thrown when the DNS query fails. - /// - /// - [Serializable] - public class DnsQueryException : Exception { - internal DnsQueryException(String message) : base(message) { - } - - internal DnsQueryException(String message, Exception e) : base(message, e) { - } - - internal DnsQueryException(DnsClient.IDnsResponse response) : this(response, Format(response)) { - } - - internal DnsQueryException(DnsClient.IDnsResponse response, String message) : base(message) => this.Response = response; - - internal DnsClient.IDnsResponse? Response { - get; - } - - private static String Format(DnsClient.IDnsResponse response) => $"Invalid response received with code {response.ResponseCode}"; - } -} -*/ \ No newline at end of file diff --git a/Swan.Tiny/Net/Dns/DnsQueryResult.cs b/Swan.Tiny/Net/Dns/DnsQueryResult.cs deleted file mode 100644 index ca953cc..0000000 --- a/Swan.Tiny/Net/Dns/DnsQueryResult.cs +++ /dev/null @@ -1,131 +0,0 @@ -/*namespace Swan.Net.Dns { - using System.Collections.Generic; - - /// - /// Represents a response from a DNS server. - /// - public class DnsQueryResult { - private readonly List _mAnswerRecords = new List(); - private readonly List _mAdditionalRecords = new List(); - private readonly List _mAuthorityRecords = new List(); - - /// - /// Initializes a new instance of the class. - /// - /// The response. - internal DnsQueryResult(DnsClient.IDnsResponse response) : this() { - this.Id = response.Id; - this.IsAuthoritativeServer = response.IsAuthorativeServer; - this.IsRecursionAvailable = response.IsRecursionAvailable; - this.IsTruncated = response.IsTruncated; - this.OperationCode = response.OperationCode; - this.ResponseCode = response.ResponseCode; - - if(response.AnswerRecords != null) { - foreach(DnsClient.IDnsResourceRecord record in response.AnswerRecords) { - this.AnswerRecords.Add(new DnsRecord(record)); - } - } - - if(response.AuthorityRecords != null) { - foreach(DnsClient.IDnsResourceRecord record in response.AuthorityRecords) { - this.AuthorityRecords.Add(new DnsRecord(record)); - } - } - - if(response.AdditionalRecords != null) { - foreach(DnsClient.IDnsResourceRecord record in response.AdditionalRecords) { - this.AdditionalRecords.Add(new DnsRecord(record)); - } - } - } - - private DnsQueryResult() { - } - - /// - /// Gets the identifier. - /// - /// - /// The identifier. - /// - public System.Int32 Id { - get; - } - - /// - /// Gets a value indicating whether this instance is authoritative server. - /// - /// - /// true if this instance is authoritative server; otherwise, false. - /// - public System.Boolean IsAuthoritativeServer { - get; - } - - /// - /// Gets a value indicating whether this instance is truncated. - /// - /// - /// true if this instance is truncated; otherwise, false. - /// - public System.Boolean IsTruncated { - get; - } - - /// - /// Gets a value indicating whether this instance is recursion available. - /// - /// - /// true if this instance is recursion available; otherwise, false. - /// - public System.Boolean IsRecursionAvailable { - get; - } - - /// - /// Gets the operation code. - /// - /// - /// The operation code. - /// - public DnsOperationCode OperationCode { - get; - } - - /// - /// Gets the response code. - /// - /// - /// The response code. - /// - public DnsResponseCode ResponseCode { - get; - } - - /// - /// Gets the answer records. - /// - /// - /// The answer records. - /// - public IList AnswerRecords => this._mAnswerRecords; - - /// - /// Gets the additional records. - /// - /// - /// The additional records. - /// - public IList AdditionalRecords => this._mAdditionalRecords; - - /// - /// Gets the authority records. - /// - /// - /// The authority records. - /// - public IList AuthorityRecords => this._mAuthorityRecords; - } -} -*/ \ No newline at end of file diff --git a/Swan.Tiny/Net/Dns/DnsRecord.cs b/Swan.Tiny/Net/Dns/DnsRecord.cs deleted file mode 100644 index 8ed1f45..0000000 --- a/Swan.Tiny/Net/Dns/DnsRecord.cs +++ /dev/null @@ -1,240 +0,0 @@ -/*using System; -using System.Net; -using System.Text; - -namespace Swan.Net.Dns { - /// - /// Represents a DNS record entry. - /// - public class DnsRecord { - /// - /// Initializes a new instance of the class. - /// - /// The record. - internal DnsRecord(DnsClient.IDnsResourceRecord record) : this() { - this.Name = record.Name.ToString(); - this.Type = record.Type; - this.Class = record.Class; - this.TimeToLive = record.TimeToLive; - this.Data = record.Data; - - // PTR - this.PointerDomainName = (record as DnsClient.DnsPointerResourceRecord)?.PointerDomainName?.ToString(); - - // A - this.IPAddress = (record as DnsClient.DnsIPAddressResourceRecord)?.IPAddress; - - // NS - this.NameServerDomainName = (record as DnsClient.DnsNameServerResourceRecord)?.NSDomainName?.ToString(); - - // CNAME - this.CanonicalDomainName = (record as DnsClient.DnsCanonicalNameResourceRecord)?.CanonicalDomainName.ToString(); - - // MX - this.MailExchangerDomainName = (record as DnsClient.DnsMailExchangeResourceRecord)?.ExchangeDomainName.ToString(); - this.MailExchangerPreference = (record as DnsClient.DnsMailExchangeResourceRecord)?.Preference; - - // SOA - this.SoaMasterDomainName = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.MasterDomainName.ToString(); - this.SoaResponsibleDomainName = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.ResponsibleDomainName.ToString(); - this.SoaSerialNumber = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.SerialNumber; - this.SoaRefreshInterval = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.RefreshInterval; - this.SoaRetryInterval = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.RetryInterval; - this.SoaExpireInterval = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.ExpireInterval; - this.SoaMinimumTimeToLive = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.MinimumTimeToLive; - } - - private DnsRecord() { - // placeholder - } - - /// - /// Gets the name. - /// - /// - /// The name. - /// - public String Name { - get; - } - - /// - /// Gets the type. - /// - /// - /// The type. - /// - public DnsRecordType Type { - get; - } - - /// - /// Gets the class. - /// - /// - /// The class. - /// - public DnsRecordClass Class { - get; - } - - /// - /// Gets the time to live. - /// - /// - /// The time to live. - /// - public TimeSpan TimeToLive { - get; - } - - /// - /// Gets the raw data of the record. - /// - /// - /// The data. - /// - public Byte[] Data { - get; - } - - /// - /// Gets the data text bytes in ASCII encoding. - /// - /// - /// The data text. - /// - public String DataText => this.Data == null ? String.Empty : Encoding.ASCII.GetString(this.Data); - - /// - /// Gets the name of the pointer domain. - /// - /// - /// The name of the pointer domain. - /// - public String PointerDomainName { - get; - } - - /// - /// Gets the ip address. - /// - /// - /// The ip address. - /// - public IPAddress IPAddress { - get; - } - - /// - /// Gets the name of the name server domain. - /// - /// - /// The name of the name server domain. - /// - public String NameServerDomainName { - get; - } - - /// - /// Gets the name of the canonical domain. - /// - /// - /// The name of the canonical domain. - /// - public String CanonicalDomainName { - get; - } - - /// - /// Gets the mail exchanger preference. - /// - /// - /// The mail exchanger preference. - /// - public Int32? MailExchangerPreference { - get; - } - - /// - /// Gets the name of the mail exchanger domain. - /// - /// - /// The name of the mail exchanger domain. - /// - public String MailExchangerDomainName { - get; - } - - /// - /// Gets the name of the soa master domain. - /// - /// - /// The name of the soa master domain. - /// - public String SoaMasterDomainName { - get; - } - - /// - /// Gets the name of the soa responsible domain. - /// - /// - /// The name of the soa responsible domain. - /// - public String SoaResponsibleDomainName { - get; - } - - /// - /// Gets the soa serial number. - /// - /// - /// The soa serial number. - /// - public Int64? SoaSerialNumber { - get; - } - - /// - /// Gets the soa refresh interval. - /// - /// - /// The soa refresh interval. - /// - public TimeSpan? SoaRefreshInterval { - get; - } - - /// - /// Gets the soa retry interval. - /// - /// - /// The soa retry interval. - /// - public TimeSpan? SoaRetryInterval { - get; - } - - /// - /// Gets the soa expire interval. - /// - /// - /// The soa expire interval. - /// - public TimeSpan? SoaExpireInterval { - get; - } - - /// - /// Gets the soa minimum time to live. - /// - /// - /// The soa minimum time to live. - /// - public TimeSpan? SoaMinimumTimeToLive { - get; - } - } -} -*/ \ No newline at end of file diff --git a/Swan.Tiny/Net/Dns/Enums.Dns.cs b/Swan.Tiny/Net/Dns/Enums.Dns.cs deleted file mode 100644 index 1d3a842..0000000 --- a/Swan.Tiny/Net/Dns/Enums.Dns.cs +++ /dev/null @@ -1,168 +0,0 @@ -/*// ReSharper disable InconsistentNaming -namespace Swan.Net.Dns { - /// - /// Enumerates the different DNS record types. - /// - public enum DnsRecordType { - /// - /// A records - /// - A = 1, - - /// - /// Nameserver records - /// - NS = 2, - - /// - /// CNAME records - /// - CNAME = 5, - - /// - /// SOA records - /// - SOA = 6, - - /// - /// WKS records - /// - WKS = 11, - - /// - /// PTR records - /// - PTR = 12, - - /// - /// MX records - /// - MX = 15, - - /// - /// TXT records - /// - TXT = 16, - - /// - /// A records fot IPv6 - /// - AAAA = 28, - - /// - /// SRV records - /// - SRV = 33, - - /// - /// ANY records - /// - ANY = 255, - } - - /// - /// Enumerates the different DNS record classes. - /// - public enum DnsRecordClass { - /// - /// IN records - /// - IN = 1, - - /// - /// ANY records - /// - ANY = 255, - } - - /// - /// Enumerates the different DNS operation codes. - /// - public enum DnsOperationCode { - /// - /// Query operation - /// - Query = 0, - - /// - /// IQuery operation - /// - IQuery, - - /// - /// Status operation - /// - Status, - - /// - /// Notify operation - /// - Notify = 4, - - /// - /// Update operation - /// - Update, - } - - /// - /// Enumerates the different DNS query response codes. - /// - public enum DnsResponseCode { - /// - /// No error - /// - NoError = 0, - - /// - /// No error - /// - FormatError, - - /// - /// Format error - /// - ServerFailure, - - /// - /// Server failure error - /// - NameError, - - /// - /// Name error - /// - NotImplemented, - - /// - /// Not implemented error - /// - Refused, - - /// - /// Refused error - /// - YXDomain, - - /// - /// YXRR error - /// - YXRRSet, - - /// - /// NXRR Set error - /// - NXRRSet, - - /// - /// Not authorized error - /// - NotAuth, - - /// - /// Not zone error - /// - NotZone, - } -} -*/ \ No newline at end of file diff --git a/Swan.Tiny/Net/Network.cs b/Swan.Tiny/Net/Network.cs index 55016ec..9c4e266 100644 --- a/Swan.Tiny/Net/Network.cs +++ b/Swan.Tiny/Net/Network.cs @@ -1,13 +1,5 @@ -//using Swan.Net.Dns; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; +using System; using System.Net.NetworkInformation; -using System.Net.Sockets; -using System.Threading; -using System.Threading.Tasks; namespace Swan.Net { /// @@ -15,16 +7,6 @@ namespace Swan.Net { /// a DNS client to query DNS records of any kind, and an NTP client. /// public static class Network { - /*/// - /// The DNS default port. - /// - public const Int32 DnsDefaultPort = 53; - - /// - /// The NTP default port. - /// - public const Int32 NtpDefaultPort = 123;*/ - /// /// Gets the name of the host. /// @@ -32,259 +14,6 @@ namespace Swan.Net { /// The name of the host. /// // [Obsolete("NEED", false)] - public static String HostName => IPGlobalProperties.GetIPGlobalProperties().HostName; - - /*/// - /// Gets the name of the network domain. - /// - /// - /// The name of the network domain. - /// - public static String DomainName => IPGlobalProperties.GetIPGlobalProperties().DomainName; - - #region IP Addresses and Adapters Information Methods - - /// - /// Gets the active IPv4 interfaces. - /// Only those interfaces with a valid unicast address and a valid gateway will be returned in the collection. - /// - /// - /// A collection of NetworkInterface/IPInterfaceProperties pairs - /// that represents the active IPv4 interfaces. - /// - public static Dictionary GetIPv4Interfaces() { - // zero conf ip address - IPAddress zeroConf = new IPAddress(0); - - NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces().Where(network => network.OperationalStatus == OperationalStatus.Up && network.NetworkInterfaceType != NetworkInterfaceType.Unknown && network.NetworkInterfaceType != NetworkInterfaceType.Loopback).ToArray(); - - Dictionary result = new Dictionary(); - - foreach(NetworkInterface adapter in adapters) { - IPInterfaceProperties properties = adapter.GetIPProperties(); - if(properties == null || properties.GatewayAddresses.Count == 0 || properties.GatewayAddresses.All(gateway => Equals(gateway.Address, zeroConf)) || properties.UnicastAddresses.Count == 0 || properties.GatewayAddresses.All(address => Equals(address.Address, zeroConf)) || properties.UnicastAddresses.Any(a => a.Address.AddressFamily == AddressFamily.InterNetwork) == false) { - continue; - } - - result[adapter] = properties; - } - - return result; - } - - /// - /// Retrieves the local ip addresses. - /// - /// if set to true [include loopback]. - /// An array of local ip addresses. - public static IPAddress[] GetIPv4Addresses(Boolean includeLoopback = true) => GetIPv4Addresses(NetworkInterfaceType.Unknown, true, includeLoopback); - - /// - /// Retrieves the local ip addresses. - /// - /// Type of the interface. - /// if set to true [skip type filter]. - /// if set to true [include loopback]. - /// An array of local ip addresses. - public static IPAddress[] GetIPv4Addresses(NetworkInterfaceType interfaceType, Boolean skipTypeFilter = false, Boolean includeLoopback = false) { - List addressList = new List(); - NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces() - .Where(ni => (skipTypeFilter || ni.NetworkInterfaceType == interfaceType) && ni.OperationalStatus == OperationalStatus.Up).ToArray(); - - foreach(NetworkInterface networkInterface in interfaces) { - IPInterfaceProperties properties = networkInterface.GetIPProperties(); - - if(properties.GatewayAddresses.All(g => g.Address.AddressFamily != AddressFamily.InterNetwork)) { - continue; - } - - addressList.AddRange(properties.UnicastAddresses.Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork).Select(i => i.Address)); - } - - if(includeLoopback || interfaceType == NetworkInterfaceType.Loopback) { - addressList.Add(IPAddress.Loopback); - } - - return addressList.ToArray(); - } - - /// - /// Gets the public IP address using ipify.org. - /// - /// The cancellation token. - /// A public IP address of the result produced by this Task. - public static async Task GetPublicIPAddressAsync(CancellationToken cancellationToken = default) { - using HttpClient client = new HttpClient(); - HttpResponseMessage response = await client.GetAsync("https://api.ipify.org", cancellationToken).ConfigureAwait(false); - return IPAddress.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); - } - - /// - /// Gets the configured IPv4 DNS servers for the active network interfaces. - /// - /// - /// A collection of NetworkInterface/IPInterfaceProperties pairs - /// that represents the active IPv4 interfaces. - /// - public static IPAddress[] GetIPv4DnsServers() => GetIPv4Interfaces().Select(a => a.Value.DnsAddresses.Where(d => d.AddressFamily == AddressFamily.InterNetwork)).SelectMany(d => d).ToArray(); - - #endregion - - #region DNS and NTP Clients - - /// - /// Gets the DNS host entry (a list of IP addresses) for the domain name. - /// - /// The FQDN. - /// An array of local ip addresses of the result produced by this task. - public static Task GetDnsHostEntryAsync(String fqdn) { - IPAddress dnsServer = GetIPv4DnsServers().FirstOrDefault() ?? IPAddress.Parse("8.8.8.8"); - return GetDnsHostEntryAsync(fqdn, dnsServer, DnsDefaultPort); - } - - /// - /// Gets the DNS host entry (a list of IP addresses) for the domain name. - /// - /// The FQDN. - /// The DNS server. - /// The port. - /// - /// An array of local ip addresses of the result produced by this task. - /// - /// fqdn. - public static async Task GetDnsHostEntryAsync(String fqdn, IPAddress dnsServer, Int32 port) { - if(fqdn == null) { - throw new ArgumentNullException(nameof(fqdn)); - } - - if(fqdn.IndexOf(".", StringComparison.Ordinal) == -1) { - fqdn += "." + IPGlobalProperties.GetIPGlobalProperties().DomainName; - } - - while(true) { - if(!fqdn.EndsWith(".", StringComparison.OrdinalIgnoreCase)) { - break; - } - - fqdn = fqdn[0..^1]; - } - - DnsClient client = new DnsClient(dnsServer, port); - IList result = await client.Lookup(fqdn).ConfigureAwait(false); - return result.ToArray(); - } - - /// - /// Gets the reverse lookup FQDN of the given IP Address. - /// - /// The query. - /// The DNS server. - /// The port. - /// A that represents the current object. - public static Task GetDnsPointerEntryAsync(IPAddress query, IPAddress dnsServer, Int32 port) { - DnsClient client = new DnsClient(dnsServer, port); - return client.Reverse(query); - } - - /// - /// Gets the reverse lookup FQDN of the given IP Address. - /// - /// The query. - /// A that represents the current object. - public static Task GetDnsPointerEntryAsync(IPAddress query) { - DnsClient client = new DnsClient(GetIPv4DnsServers().FirstOrDefault()); - return client.Reverse(query); - } - - /// - /// Queries the DNS server for the specified record type. - /// - /// The query. - /// Type of the record. - /// The DNS server. - /// The port. - /// Queries the DNS server for the specified record type of the result produced by this Task. - public static async Task QueryDnsAsync(String query, DnsRecordType recordType, IPAddress dnsServer, Int32 port) { - if(query == null) { - throw new ArgumentNullException(nameof(query)); - } - - DnsClient client = new DnsClient(dnsServer, port); - DnsClient.DnsClientResponse response = await client.Resolve(query, recordType).ConfigureAwait(false); - return new DnsQueryResult(response); - } - - /// - /// Queries the DNS server for the specified record type. - /// - /// The query. - /// Type of the record. - /// Queries the DNS server for the specified record type of the result produced by this Task. - public static Task QueryDnsAsync(String query, DnsRecordType recordType) => QueryDnsAsync(query, recordType, GetIPv4DnsServers().FirstOrDefault(), DnsDefaultPort); - - /// - /// Gets the UTC time by querying from an NTP server. - /// - /// The NTP server address. - /// The port. - /// The UTC time by querying from an NTP server of the result produced by this Task. - public static async Task GetNetworkTimeUtcAsync(IPAddress ntpServerAddress, Int32 port = NtpDefaultPort) { - if(ntpServerAddress == null) { - throw new ArgumentNullException(nameof(ntpServerAddress)); - } - - // NTP message size - 16 bytes of the digest (RFC 2030) - Byte[] ntpData = new Byte[48]; - - // Setting the Leap Indicator, Version Number and Mode values - ntpData[0] = 0x1B; // LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode) - - // The UDP port number assigned to NTP is 123 - IPEndPoint endPoint = new IPEndPoint(ntpServerAddress, port); - Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - - - await socket.ConnectAsync(endPoint).ConfigureAwait(false); - - - socket.ReceiveTimeout = 3000; // Stops code hang if NTP is blocked - _ = socket.Send(ntpData); - _ = socket.Receive(ntpData); - socket.Dispose(); - - // Offset to get to the "Transmit Timestamp" field (time at which the reply - // departed the server for the client, in 64-bit timestamp format." - const Byte serverReplyTime = 40; - - // Get the seconds part - UInt64 intPart = BitConverter.ToUInt32(ntpData, serverReplyTime); - - // Get the seconds fraction - UInt64 fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4); - - // Convert From big-endian to little-endian to match the platform - if(BitConverter.IsLittleEndian) { - intPart = intPart.SwapEndianness(); - fractPart = intPart.SwapEndianness(); - } - - UInt64 milliseconds = intPart * 1000 + fractPart * 1000 / 0x100000000L; - - // The time is given in UTC - return new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((Int64)milliseconds); - } - - /// - /// Gets the UTC time by querying from an NTP server. - /// - /// The NTP server, by default pool.ntp.org. - /// The port, by default NTP 123. - /// The UTC time by querying from an NTP server of the result produced by this Task. - public static async Task GetNetworkTimeUtcAsync(String ntpServerName = "pool.ntp.org", Int32 port = NtpDefaultPort) { - IPAddress[] addresses = await GetDnsHostEntryAsync(ntpServerName).ConfigureAwait(false); - return await GetNetworkTimeUtcAsync(addresses.First(), port).ConfigureAwait(false); - } - - #endregion*/ + public static String HostName => IPGlobalProperties.GetIPGlobalProperties().HostName; } } diff --git a/Swan.Tiny/ProcessRunner.cs b/Swan.Tiny/ProcessRunner.cs index 22d4a95..832593e 100644 --- a/Swan.Tiny/ProcessRunner.cs +++ b/Swan.Tiny/ProcessRunner.cs @@ -60,25 +60,6 @@ namespace Swan { return result.ExitCode == 0 ? result.StandardOutput : result.StandardError; } - /*/// - /// Runs the process asynchronously and if the exit code is 0, - /// returns all of the standard output text. If the exit code is something other than 0 - /// it returns the contents of standard error. - /// This method is meant to be used for programs that output a relatively small amount - /// of text using a different encoder. - /// - /// The filename. - /// The arguments. - /// The encoding. - /// The cancellation token. - /// - /// The type of the result produced by this Task. - /// - public static async Task GetProcessEncodedOutputAsync(String filename, String arguments = "", Encoding? encoding = null, CancellationToken cancellationToken = default) { - ProcessResult result = await GetProcessResultAsync(filename, arguments, null, encoding, cancellationToken).ConfigureAwait(false); - return result.ExitCode == 0 ? result.StandardOutput : result.StandardError; - }*/ - /// /// Executes a process asynchronously and returns the text of the standard output and standard error streams /// along with the exit code. This method is meant to be used for programs that output a relatively small diff --git a/Swan.Tiny/Reflection/AttributeCache.cs b/Swan.Tiny/Reflection/AttributeCache.cs index ccb82ab..82b5874 100644 --- a/Swan.Tiny/Reflection/AttributeCache.cs +++ b/Swan.Tiny/Reflection/AttributeCache.cs @@ -37,50 +37,6 @@ namespace Swan.Reflection { get; } - /*/// - /// Determines whether [contains] [the specified member]. - /// - /// The type of the attribute to be retrieved. - /// The member. - /// - /// true if [contains] [the specified member]; otherwise, false. - /// - public Boolean Contains(MemberInfo member) => this._data.Value.ContainsKey(new Tuple(member, typeof(T))); - - /// - /// Gets specific attributes from a member constrained to an attribute. - /// - /// The type of the attribute to be retrieved. - /// The member. - /// true to inspect the ancestors of element; otherwise, false. - /// An array of the attributes stored for the specified type. - public IEnumerable Retrieve(MemberInfo member, Boolean inherit = false) where T : Attribute { - if(member == null) { - throw new ArgumentNullException(nameof(member)); - } - - return this.Retrieve(new Tuple(member, typeof(T)), t => member.GetCustomAttributes(inherit)); - } - - /// - /// Gets all attributes of a specific type from a member. - /// - /// The member. - /// The attribute type. - /// true to inspect the ancestors of element; otherwise, false. - /// An array of the attributes stored for the specified type. - public IEnumerable Retrieve(MemberInfo member, Type type, Boolean inherit = false) { - if(member == null) { - throw new ArgumentNullException(nameof(member)); - } - - if(type == null) { - throw new ArgumentNullException(nameof(type)); - } - - return this.Retrieve(new Tuple(member, type), t => member.GetCustomAttributes(type, inherit)); - }*/ - /// /// Gets one attribute of a specific type from a member. /// @@ -98,56 +54,6 @@ namespace Swan.Reflection { return ConvertToAttribute(attr); } - /*/// - /// Gets one attribute of a specific type from a generic type. - /// - /// The type of the attribute. - /// The type to retrieve the attribute. - /// if set to true [inherit]. - /// An attribute stored for the specified type. - public TAttribute RetrieveOne(Boolean inherit = false) where TAttribute : Attribute { - IEnumerable attr = this.Retrieve(new Tuple(typeof(T), typeof(TAttribute)), t => typeof(T).GetCustomAttributes(typeof(TAttribute), inherit)); - - return ConvertToAttribute(attr); - } - - /// - /// Gets all properties an their attributes of a given type constrained to only attributes. - /// - /// The type of the attribute to retrieve. - /// The type of the object. - /// true to inspect the ancestors of element; otherwise, false. - /// A dictionary of the properties and their attributes stored for the specified type. - public Dictionary> Retrieve(Type type, Boolean inherit = false) where T : Attribute => this.PropertyTypeCache.RetrieveAllProperties(type, true).ToDictionary(x => x, x => this.Retrieve(x, inherit)); - - /// - /// Gets all properties and their attributes of a given type. - /// - /// The object type used to extract the properties from. - /// The type of the attribute. - /// true to inspect the ancestors of element; otherwise, false. - /// - /// A dictionary of the properties and their attributes stored for the specified type. - /// - public Dictionary> RetrieveFromType(Boolean inherit = false) => this.RetrieveFromType(typeof(TAttribute), inherit); - - /// - /// Gets all properties and their attributes of a given type. - /// - /// The object type used to extract the properties from. - /// Type of the attribute. - /// true to inspect the ancestors of element; otherwise, false. - /// - /// A dictionary of the properties and their attributes stored for the specified type. - /// - public Dictionary> RetrieveFromType(Type attributeType, Boolean inherit = false) { - if(attributeType == null) { - throw new ArgumentNullException(nameof(attributeType)); - } - - return this.PropertyTypeCache.RetrieveAllProperties(true).ToDictionary(x => x, x => this.Retrieve(x, attributeType, inherit)); - }*/ - private static T ConvertToAttribute(IEnumerable attr) where T : Attribute => attr?.Any() != true ? (default!) : attr.Count() == 1 ? (T)Convert.ChangeType(attr.First(), typeof(T)) : throw new AmbiguousMatchException("Multiple custom attributes of the same type found."); private IEnumerable Retrieve(Tuple key, Func, IEnumerable> factory) { diff --git a/Swan.Tiny/Reflection/ConstructorTypeCache.cs b/Swan.Tiny/Reflection/ConstructorTypeCache.cs index 5627478..e25df0e 100644 --- a/Swan.Tiny/Reflection/ConstructorTypeCache.cs +++ b/Swan.Tiny/Reflection/ConstructorTypeCache.cs @@ -17,16 +17,6 @@ namespace Swan.Lite.Reflection { /// public static Lazy DefaultCache { get; } = new Lazy(() => new ConstructorTypeCache()); - /*/// - /// Retrieves all constructors order by the number of parameters ascending. - /// - /// The type to inspect. - /// if set to true [include non public]. - /// - /// A collection with all the constructors in the given type. - /// - public IEnumerable> RetrieveAllConstructors(Boolean includeNonPublic = false) => this.Retrieve(GetConstructors(includeNonPublic));*/ - /// /// Retrieves all constructors order by the number of parameters ascending. /// diff --git a/Swan.Tiny/Reflection/ExtendedTypeInfo.cs b/Swan.Tiny/Reflection/ExtendedTypeInfo.cs index c544177..c8d4bd3 100644 --- a/Swan.Tiny/Reflection/ExtendedTypeInfo.cs +++ b/Swan.Tiny/Reflection/ExtendedTypeInfo.cs @@ -234,14 +234,5 @@ namespace Swan.Reflection { public ExtendedTypeInfo() : base(typeof(T)) { // placeholder } - - /*/// - /// Converts this instance to its string representation, - /// trying to use the CultureInfo.InvariantCulture - /// IFormat provider if the overload is available. - /// - /// The instance. - /// A that represents the current object. - public String ToStringInvariant(T instance) => base.ToStringInvariant(instance);*/ } } diff --git a/Swan.Tiny/Reflection/IPropertyProxy.cs b/Swan.Tiny/Reflection/IPropertyProxy.cs deleted file mode 100644 index 9a0080b..0000000 --- a/Swan.Tiny/Reflection/IPropertyProxy.cs +++ /dev/null @@ -1,22 +0,0 @@ -/*using System; - -namespace Swan.Reflection { - /// - /// Represents a generic interface to store getters and setters. - /// - public interface IPropertyProxy { - /// - /// Gets the property value via a stored delegate. - /// - /// The instance. - /// The property value. - Object GetValue(Object instance); - - /// - /// Sets the property value via a stored delegate. - /// - /// The instance. - /// The value. - void SetValue(Object instance, Object value); - } -}*/ \ No newline at end of file diff --git a/Swan.Tiny/Reflection/PropertyProxy.cs b/Swan.Tiny/Reflection/PropertyProxy.cs deleted file mode 100644 index 5976ba9..0000000 --- a/Swan.Tiny/Reflection/PropertyProxy.cs +++ /dev/null @@ -1,44 +0,0 @@ -/*using System; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Swan.Reflection { - /// - /// Represents a generic class to store getters and setters. - /// - /// The type of the class. - /// The type of the property. - /// - public sealed class PropertyProxy : IPropertyProxy where TClass : class { - private readonly Func _getter; - private readonly Action _setter; - - /// - /// Initializes a new instance of the class. - /// - /// The property. - public PropertyProxy(PropertyInfo property) { - if(property == null) { - throw new ArgumentNullException(nameof(property)); - } - - MethodInfo getterInfo = property.GetGetMethod(false); - if(getterInfo != null) { - this._getter = (Func)Delegate.CreateDelegate(typeof(Func), getterInfo); - } - - MethodInfo setterInfo = property.GetSetMethod(false); - if(setterInfo != null) { - this._setter = (Action)Delegate.CreateDelegate(typeof(Action), setterInfo); - } - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - Object IPropertyProxy.GetValue(Object instance) => this._getter(instance as TClass); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - void IPropertyProxy.SetValue(Object instance, Object value) => this._setter(instance as TClass, (TProperty)value); - } -}*/ \ No newline at end of file diff --git a/Swan.Tiny/Reflection/PropertyTypeCache.cs b/Swan.Tiny/Reflection/PropertyTypeCache.cs index 6cfb4eb..7e69ca3 100644 --- a/Swan.Tiny/Reflection/PropertyTypeCache.cs +++ b/Swan.Tiny/Reflection/PropertyTypeCache.cs @@ -16,16 +16,6 @@ namespace Swan.Reflection { /// public static Lazy DefaultCache { get; } = new Lazy(() => new PropertyTypeCache()); - /*/// - /// Retrieves all properties. - /// - /// The type to inspect. - /// if set to true [only public]. - /// - /// A collection with all the properties in the given type. - /// - public IEnumerable RetrieveAllProperties(Boolean onlyPublic = false) => this.Retrieve(onlyPublic ? GetAllPublicPropertiesFunc() : GetAllPropertiesFunc());*/ - /// /// Retrieves all properties. /// diff --git a/Swan.Tiny/Reflection/TypeCache.cs b/Swan.Tiny/Reflection/TypeCache.cs index 1577cb5..ef18d60 100644 --- a/Swan.Tiny/Reflection/TypeCache.cs +++ b/Swan.Tiny/Reflection/TypeCache.cs @@ -13,24 +13,7 @@ namespace Swan.Reflection { /// /// The type of Member to be cached. public abstract class TypeCache : CollectionCacheRepository { - /*/// - /// Determines whether the cache contains the specified type. - /// - /// The type of the out. - /// - /// true if [contains]; otherwise, false. - /// - public Boolean Contains() => this.ContainsKey(typeof(TOut)); - /// - /// Retrieves the properties stored for the specified type. - /// If the properties are not available, it calls the factory method to retrieve them - /// and returns them as an array of PropertyInfo. - /// - /// The type of the out. - /// The factory. - /// An array of the properties stored for the specified type. - public IEnumerable Retrieve(Func> factory) => this.Retrieve(typeof(TOut), factory);*/ } /// @@ -48,15 +31,6 @@ namespace Swan.Reflection { /// public static Lazy DefaultCache { get; } = new Lazy(() => new FieldTypeCache()); - /*/// - /// Retrieves all fields. - /// - /// The type to inspect. - /// - /// A collection with all the fields in the given type. - /// - public IEnumerable RetrieveAllFields() => this.Retrieve(GetAllFieldsFunc());*/ - /// /// Retrieves all fields. /// diff --git a/Swan.Tiny/StructEndiannessAttribute.cs b/Swan.Tiny/StructEndiannessAttribute.cs deleted file mode 100644 index 7fc58d1..0000000 --- a/Swan.Tiny/StructEndiannessAttribute.cs +++ /dev/null @@ -1,27 +0,0 @@ -/*using System; - -namespace Swan { - /// - /// An attribute used to help conversion structs back and forth into arrays of bytes via - /// extension methods included in this library ToStruct and ToBytes. - /// - /// - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Struct)] - public class StructEndiannessAttribute : Attribute { - /// - /// Initializes a new instance of the class. - /// - /// The endianness. - public StructEndiannessAttribute(Endianness endianness) => this.Endianness = endianness; - - /// - /// Gets the endianness. - /// - /// - /// The endianness. - /// - public Endianness Endianness { - get; - } - } -}*/ \ No newline at end of file diff --git a/Swan.Tiny/SwanRuntime.cs b/Swan.Tiny/SwanRuntime.cs index 6e9dfb6..da79e38 100644 --- a/Swan.Tiny/SwanRuntime.cs +++ b/Swan.Tiny/SwanRuntime.cs @@ -1,35 +1,11 @@ -using Swan.Logging; -using System; +using System; using System.IO; -using System.Reflection; -using System.Threading; namespace Swan { /// /// Provides utility methods to retrieve information about the current application. /// public static class SwanRuntime { - /*private static readonly Lazy EntryAssemblyLazy = new Lazy(Assembly.GetEntryAssembly); - - private static readonly Lazy CompanyNameLazy = new Lazy(() => { - AssemblyCompanyAttribute attribute = EntryAssembly.GetCustomAttribute(typeof(AssemblyCompanyAttribute)) as AssemblyCompanyAttribute; - return attribute?.Company ?? String.Empty; - }); - - private static readonly Lazy ProductNameLazy = new Lazy(() => { - AssemblyProductAttribute attribute = EntryAssembly.GetCustomAttribute(typeof(AssemblyProductAttribute)) as AssemblyProductAttribute; - return attribute?.Product ?? String.Empty; - }); - - private static readonly Lazy ProductTrademarkLazy = new Lazy(() => { - AssemblyTrademarkAttribute attribute = EntryAssembly.GetCustomAttribute(typeof(AssemblyTrademarkAttribute)) as AssemblyTrademarkAttribute; - return attribute?.Trademark ?? String.Empty; - }); - - private static readonly String ApplicationMutexName = "Global\\{{" + EntryAssembly.FullName + "}}"; - - private static readonly Object SyncLock = new Object();*/ - // [Obsolete("NEED", false)] private static OperatingSystem? _oS; @@ -54,148 +30,6 @@ namespace Swan { } } - - /*/// - /// Checks if this application (including version number) is the only instance currently running. - /// - /// - /// true if this instance is the only instance; otherwise, false. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Codequalität", "IDE0067:Objekte verwerfen, bevor Bereich verloren geht", Justification = "")] - public static Boolean IsTheOnlyInstance { - get { - lock(SyncLock) { - try { - // Try to open existing mutex. - _ = Mutex.OpenExisting(ApplicationMutexName); - } catch { - try { - // If exception occurred, there is no such mutex. - Mutex appMutex = new Mutex(true, ApplicationMutexName); - $"Application Mutex created {appMutex} named '{ApplicationMutexName}'".Debug(typeof(SwanRuntime)); - - // Only one instance. - return true; - } catch { - // Sometimes the user can't create the Global Mutex - } - } - - // More than one instance. - return false; - } - } - } - - /// - /// Gets a value indicating whether this application instance is using the MONO runtime. - /// - /// - /// true if this instance is using MONO runtime; otherwise, false. - /// - public static Boolean IsUsingMonoRuntime => Type.GetType("Mono.Runtime") != null; - - /// - /// Gets the assembly that started the application. - /// - /// - /// The entry assembly. - /// - public static Assembly EntryAssembly => EntryAssemblyLazy.Value; - - /// - /// Gets the name of the entry assembly. - /// - /// - /// The name of the entry assembly. - /// - public static AssemblyName EntryAssemblyName => EntryAssemblyLazy.Value.GetName(); - - /// - /// Gets the entry assembly version. - /// - public static Version EntryAssemblyVersion => EntryAssemblyName.Version; - - /// - /// Gets the full path to the folder containing the assembly that started the application. - /// - /// - /// The entry assembly directory. - /// - public static String EntryAssemblyDirectory { - get { - UriBuilder uri = new UriBuilder(EntryAssembly.CodeBase); - String path = Uri.UnescapeDataString(uri.Path); - return Path.GetDirectoryName(path); - } - } - - /// - /// Gets the name of the company. - /// - /// - /// The name of the company. - /// - public static String CompanyName => CompanyNameLazy.Value; - - /// - /// Gets the name of the product. - /// - /// - /// The name of the product. - /// - public static String ProductName => ProductNameLazy.Value; - - /// - /// Gets the trademark. - /// - /// - /// The product trademark. - /// - public static String ProductTrademark => ProductTrademarkLazy.Value; - - /// - /// Gets a local storage path with a version. - /// - /// - /// The local storage path. - /// - public static String LocalStoragePath { - get { - String localAppDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), EntryAssemblyName.Name); - - String returnPath = Path.Combine(localAppDataPath, EntryAssemblyVersion.ToString()); - - if(!Directory.Exists(returnPath)) { - _ = Directory.CreateDirectory(returnPath); - } - - return returnPath; - } - }*/ - #endregion - - /*#region Methods - - /// - /// Build a full path pointing to the current user's desktop with the given filename. - /// - /// The filename. - /// - /// The fully qualified location of path, such as "C:\MyFile.txt". - /// - /// filename. - public static String GetDesktopFilePath(String filename) { - if(String.IsNullOrWhiteSpace(filename)) { - throw new ArgumentNullException(nameof(filename)); - } - - String pathWithFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), filename); - - return Path.GetFullPath(pathWithFilename); - } - - #endregion*/ } } diff --git a/Swan.Tiny/Terminal.Output.cs b/Swan.Tiny/Terminal.Output.cs index a66beb3..dae1d85 100644 --- a/Swan.Tiny/Terminal.Output.cs +++ b/Swan.Tiny/Terminal.Output.cs @@ -7,33 +7,6 @@ namespace Swan { /// This class is thread-safe :). /// public static partial class Terminal { - /*/// - /// Writes a character a number of times, optionally adding a new line at the end. - /// - /// The character code. - /// The color. - /// The count. - /// if set to true [new line]. - /// The writer flags. - public static void Write(Char charCode, ConsoleColor? color = null, Int32 count = 1, Boolean newLine = false, TerminalWriters writerFlags = TerminalWriters.StandardOutput) { - lock(SyncLock) { - String text = new String(charCode, count); - - if(newLine) { - text += Environment.NewLine; - } - - Byte[] buffer = OutputEncoding.GetBytes(text); - OutputContext context = new OutputContext { - OutputColor = color ?? Settings.DefaultColor, - OutputText = OutputEncoding.GetChars(buffer), - OutputWriters = writerFlags, - }; - - EnqueueOutput(context); - } - }*/ - /// /// Writes the specified text in the given color. /// @@ -57,33 +30,5 @@ namespace Swan { EnqueueOutput(context); } } - - /*/// - /// Writes a New Line Sequence to the standard output. - /// - /// The writer flags. - public static void WriteLine(TerminalWriters writerFlags = TerminalWriters.StandardOutput) => Write(Environment.NewLine, Settings.DefaultColor, writerFlags); - - /// - /// Writes a line of text in the current console foreground color - /// to the standard output. - /// - /// The text. - /// The color. - /// The writer flags. - public static void WriteLine(String text, ConsoleColor? color = null, TerminalWriters writerFlags = TerminalWriters.StandardOutput) => Write($"{text ?? String.Empty}{Environment.NewLine}", color, writerFlags); - - /// - /// As opposed to WriteLine methods, it prepends a Carriage Return character to the text - /// so that the console moves the cursor one position up after the text has been written out. - /// - /// The text. - /// The color. - /// The writer flags. - public static void OverwriteLine(String text, ConsoleColor? color = null, TerminalWriters writerFlags = TerminalWriters.StandardOutput) { - Write($"\r{text ?? String.Empty}", color, writerFlags); - Flush(); - CursorLeft = 0; - }*/ } } diff --git a/Swan.Tiny/Terminal.Settings.cs b/Swan.Tiny/Terminal.Settings.cs index fae3b3a..670578d 100644 --- a/Swan.Tiny/Terminal.Settings.cs +++ b/Swan.Tiny/Terminal.Settings.cs @@ -17,30 +17,6 @@ namespace Swan { /// The default color. /// public static ConsoleColor DefaultColor { get; set; } = Console.ForegroundColor; - - /*/// - /// Gets the color of the border. - /// - /// - /// The color of the border. - /// - public static ConsoleColor BorderColor { get; } = ConsoleColor.DarkGreen; - - /// - /// Gets or sets the user input prefix. - /// - /// - /// The user input prefix. - /// - public static String UserInputPrefix { get; set; } = "USR"; - - /// - /// Gets or sets the user option text. - /// - /// - /// The user option text. - /// - public static String UserOptionText { get; set; } = " Option: ";*/ } } } diff --git a/Swan.Tiny/Terminal.cs b/Swan.Tiny/Terminal.cs index c10e8f5..829dbc9 100644 --- a/Swan.Tiny/Terminal.cs +++ b/Swan.Tiny/Terminal.cs @@ -50,73 +50,7 @@ namespace Swan { DequeueOutputTimer = new ExclusiveTimer(DequeueOutputCycle); DequeueOutputTimer.Resume(OutputFlushInterval); } - } - - #endregion - - /*#region Synchronized Cursor Movement - - /// - /// Gets or sets the cursor left position. - /// - /// - /// The cursor left. - /// - public static Int32 CursorLeft { - get { - if(IsConsolePresent == false) { - return -1; - } - - lock(SyncLock) { - Flush(); - return Console.CursorLeft; - } - } - set { - if(IsConsolePresent == false) { - return; - } - - lock(SyncLock) { - Flush(); - Console.CursorLeft = value; - } - } - } - - /// - /// Gets or sets the cursor top position. - /// - /// - /// The cursor top. - /// - public static Int32 CursorTop { - get { - if(IsConsolePresent == false) { - return -1; - } - - lock(SyncLock) { - Flush(); - return Console.CursorTop; - } - } - set { - if(IsConsolePresent == false) { - return; - } - - lock(SyncLock) { - Flush(); - Console.CursorTop = value; - } - } - } - - #endregion*/ - - #region Properties + } /// /// Gets a value indicating whether the Console is present. @@ -166,75 +100,6 @@ namespace Swan { #region Methods - /*/// - /// Waits for all of the queued output messages to be written out to the console. - /// Call this method if it is important to display console text before - /// quitting the application such as showing usage or help. - /// Set the timeout to null or TimeSpan.Zero to wait indefinitely. - /// - /// The timeout. Set the amount of time to black before this method exits. - public static void Flush(TimeSpan? timeout = null) { - if(timeout == null) { - timeout = TimeSpan.Zero; - } - - DateTime startTime = DateTime.UtcNow; - - while(OutputQueue.Count > 0) { - // Manually trigger a timer cycle to run immediately - DequeueOutputTimer.Change(0, OutputFlushInterval); - - // Wait for the output to finish - if(OutputDone.Wait(OutputFlushInterval)) { - break; - } - - // infinite timeout - if(timeout.Value == TimeSpan.Zero) { - continue; - } - - // break if we have reached a timeout condition - if(DateTime.UtcNow.Subtract(startTime) >= timeout.Value) { - break; - } - } - } - - /// - /// Sets the cursor position. - /// - /// The left. - /// The top. - public static void SetCursorPosition(Int32 left, Int32 top) { - if(!IsConsolePresent) { - return; - } - - lock(SyncLock) { - Flush(); - Console.SetCursorPosition(left.Clamp(0, left), top.Clamp(0, top)); - } - } - - /// - /// Moves the output cursor one line up starting at left position 0 - /// Please note that backlining the cursor does not clear the contents of the - /// previous line so you might need to clear it by writing an empty string the - /// length of the console width. - /// - public static void BacklineCursor() => SetCursorPosition(0, CursorTop - 1); - - /// - /// Writes a standard banner to the standard output - /// containing the company name, product name, assembly version and trademark. - /// - /// The color. - public static void WriteWelcomeBanner(ConsoleColor color = ConsoleColor.Gray) { - WriteLine($"{SwanRuntime.CompanyName} {SwanRuntime.ProductName} [Version {SwanRuntime.EntryAssemblyVersion}]", color); - WriteLine($"{SwanRuntime.ProductTrademark}", color); - }*/ - /// /// Enqueues the output to be written to the console /// This is the only method that should enqueue to the output diff --git a/Swan.Tiny/Threading/AtomicTypeBase.cs b/Swan.Tiny/Threading/AtomicTypeBase.cs index 8deb770..4acc07c 100644 --- a/Swan.Tiny/Threading/AtomicTypeBase.cs +++ b/Swan.Tiny/Threading/AtomicTypeBase.cs @@ -54,96 +54,6 @@ namespace Swan.Threading { /// public static Boolean operator !=(AtomicTypeBase a, T b) => a?.Equals(b) == false; - /*/// - /// Implements the operator >. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Boolean operator >(AtomicTypeBase a, T b) => a.CompareTo(b) > 0; - - /// - /// Implements the operator <. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Boolean operator <(AtomicTypeBase a, T b) => a.CompareTo(b) < 0; - - /// - /// Implements the operator >=. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Boolean operator >=(AtomicTypeBase a, T b) => a.CompareTo(b) >= 0; - - /// - /// Implements the operator <=. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Boolean operator <=(AtomicTypeBase a, T b) => a.CompareTo(b) <= 0; - - /// - /// Implements the operator ++. - /// - /// The instance. - /// - /// The result of the operator. - /// - public static AtomicTypeBase operator ++(AtomicTypeBase instance) { - _ = Interlocked.Increment(ref instance._backingValue); - return instance; - } - - /// - /// Implements the operator --. - /// - /// The instance. - /// - /// The result of the operator. - /// - public static AtomicTypeBase operator --(AtomicTypeBase instance) { - _ = Interlocked.Decrement(ref instance._backingValue); - return instance; - } - - /// - /// Implements the operator -<. - /// - /// The instance. - /// The operand. - /// - /// The result of the operator. - /// - public static AtomicTypeBase operator +(AtomicTypeBase instance, Int64 operand) { - instance.BackingValue += operand; - return instance; - } - - /// - /// Implements the operator -. - /// - /// The instance. - /// The operand. - /// - /// The result of the operator. - /// - public static AtomicTypeBase operator -(AtomicTypeBase instance, Int64 operand) { - instance.BackingValue -= operand; - return instance; - }*/ - /// /// Compares the value to the other instance. /// diff --git a/Swan.Tiny/Threading/ExclusiveTimer.cs b/Swan.Tiny/Threading/ExclusiveTimer.cs index e242eb4..0f9b2bb 100644 --- a/Swan.Tiny/Threading/ExclusiveTimer.cs +++ b/Swan.Tiny/Threading/ExclusiveTimer.cs @@ -29,25 +29,6 @@ namespace Swan.Threading { this._backingTimer = new Timer(this.InternalCallback, state ?? this, dueTime, Timeout.Infinite); } - /*/// - /// Initializes a new instance of the class. - /// - /// The timer callback. - /// The state. - /// The due time. - /// The period. - public ExclusiveTimer(TimerCallback timerCallback, Object state, TimeSpan dueTime, TimeSpan period) : this(timerCallback, state, Convert.ToInt32(dueTime.TotalMilliseconds), Convert.ToInt32(period.TotalMilliseconds)) { - // placeholder - }*/ - - /*/// - /// Initializes a new instance of the class. - /// - /// The timer callback. - public ExclusiveTimer(TimerCallback timerCallback) : this(timerCallback, null, Timeout.Infinite, Timeout.Infinite) { - // placeholder - }*/ - /// /// Initializes a new instance of the class. /// @@ -58,16 +39,6 @@ namespace Swan.Threading { // placeholder } - /*/// - /// Initializes a new instance of the class. - /// - /// The timer callback. - /// The due time. - /// The period. - public ExclusiveTimer(Action timerCallback, TimeSpan dueTime, TimeSpan period) : this(s => timerCallback?.Invoke(), null, dueTime, period) { - // placeholder - }*/ - /// /// Initializes a new instance of the class. /// @@ -93,36 +64,6 @@ namespace Swan.Threading { /// public Boolean IsDisposed => this._isDisposed.Value; - /*/// - /// Waits until the time is elapsed. - /// - /// The until date. - /// The cancellation token. - public static void WaitUntil(DateTime untilDate, CancellationToken cancellationToken = default) { - static void Callback(IWaitEvent waitEvent) { - try { - waitEvent.Complete(); - waitEvent.Begin(); - } catch { - // ignore - } - } - - using IWaitEvent delayLock = WaitEventFactory.Create(true); - using ExclusiveTimer _ = new ExclusiveTimer(() => Callback(delayLock), 0, 15); - while(!cancellationToken.IsCancellationRequested && DateTime.UtcNow < untilDate) { - delayLock.Wait(); - } - }*/ - - /*/// - /// Waits the specified wait time. - /// - /// The wait time. - /// The cancellation token. - public static void Wait(TimeSpan waitTime, CancellationToken cancellationToken = default) => - WaitUntil(DateTime.UtcNow.Add(waitTime), cancellationToken);*/ - /// /// Changes the start time and the interval between method invocations for the internal timer. /// @@ -134,13 +75,6 @@ namespace Swan.Threading { _ = this._backingTimer.Change(dueTime, Timeout.Infinite); } - /*/// - /// Changes the start time and the interval between method invocations for the internal timer. - /// - /// The due time. - /// The period. - public void Change(TimeSpan dueTime, TimeSpan period) => this.Change(Convert.ToInt32(dueTime.TotalMilliseconds), Convert.ToInt32(period.TotalMilliseconds));*/ - /// /// Changes the interval between method invocations for the internal timer. /// @@ -148,12 +82,6 @@ namespace Swan.Threading { // [Obsolete("NEED", false)] public void Resume(Int32 period) => this.Change(0, period); - /*/// - /// Changes the interval between method invocations for the internal timer. - /// - /// The period. - public void Resume(TimeSpan period) => this.Change(TimeSpan.Zero, period);*/ - /// /// Pauses this instance. /// diff --git a/Swan.Tiny/Threading/WaitEventFactory.cs b/Swan.Tiny/Threading/WaitEventFactory.cs index a303fe9..fb0d564 100644 --- a/Swan.Tiny/Threading/WaitEventFactory.cs +++ b/Swan.Tiny/Threading/WaitEventFactory.cs @@ -67,14 +67,6 @@ namespace Swan.Threading { /// The Wait Event. public static IWaitEvent CreateSlim(Boolean isCompleted) => new WaitEventSlim(isCompleted); - /*/// - /// Creates a Wait Event backed by a ManualResetEventSlim. - /// - /// if initially set to completed. Generally true. - /// if set to true creates a slim version of the wait event. - /// The Wait Event. - public static IWaitEvent Create(Boolean isCompleted, Boolean useSlim) => useSlim ? CreateSlim(isCompleted) : Create(isCompleted);*/ - #endregion #region Backing Classes