diff --git a/DevBase.Net/DevBase.Net.csproj b/DevBase.Net/DevBase.Net.csproj index c7460b0..6e7e938 100644 --- a/DevBase.Net/DevBase.Net.csproj +++ b/DevBase.Net/DevBase.Net.csproj @@ -15,7 +15,7 @@ https://github.com/AlexanderDotH/DevBase.git https://github.com/AlexanderDotH/DevBase.git git - 1.4.6 + 1.4.8 MIT false http;client;requests;proxy;socks5;jwt;authentication;fluent-api;async;retry;rate-limiting;json;html-parsing diff --git a/DevBase.Net/Proxy/ProxyInfo.cs b/DevBase.Net/Proxy/ProxyInfo.cs index f992dc2..5ab66b2 100644 --- a/DevBase.Net/Proxy/ProxyInfo.cs +++ b/DevBase.Net/Proxy/ProxyInfo.cs @@ -9,10 +9,38 @@ public sealed class ProxyInfo { private static readonly ConcurrentDictionary ProxyCache = new(); - public string Host { get; } - public int Port { get; } - public EnumProxyType Type { get; } - public NetworkCredential? Credentials { get; } + public string Host { get; set; } = string.Empty; + public int Port { get; set; } + public EnumProxyType Type { get; set; } = EnumProxyType.Http; + public NetworkCredential? Credentials { get; set; } + + public string? Username + { + get => Credentials?.UserName; + set + { + if (value != null) + { + Credentials = new NetworkCredential(value, Credentials?.Password ?? string.Empty); + } + } + } + + public string? Password + { + get => Credentials?.Password; + set + { + if (Credentials != null) + { + Credentials = new NetworkCredential(Credentials.UserName, value ?? string.Empty); + } + else if (value != null) + { + Credentials = new NetworkCredential(string.Empty, value); + } + } + } public bool BypassLocalAddresses { get; init; } public string[]? BypassList { get; init; } @@ -22,7 +50,11 @@ public sealed class ProxyInfo public int InternalServerPort { get; init; } public string Key => $"{this.Type}://{this.Host}:{this.Port}"; - public bool HasAuthentication => Credentials != null; + public bool HasAuthentication => Credentials != null && !string.IsNullOrEmpty(Credentials.UserName); + + public ProxyInfo() + { + } public ProxyInfo(string host, int port, EnumProxyType type = EnumProxyType.Http, NetworkCredential? credentials = null) { diff --git a/DevBase.Net/Proxy/TrackedProxyInfo.cs b/DevBase.Net/Proxy/TrackedProxyInfo.cs index fc492ed..e85bf69 100644 --- a/DevBase.Net/Proxy/TrackedProxyInfo.cs +++ b/DevBase.Net/Proxy/TrackedProxyInfo.cs @@ -2,16 +2,16 @@ namespace DevBase.Net.Proxy; -public sealed class TrackedProxyInfo +public class TrackedProxyInfo { private readonly object _lock = new(); public ProxyInfo Proxy { get; } - public int FailureCount { get; private set; } - public DateTime? LastFailure { get; private set; } - public bool IsTimedOut { get; private set; } - public DateTime? TimeoutUntil { get; private set; } - public int TotalTimeouts { get; private set; } + public int FailureCount { get; protected set; } + public DateTime? LastFailure { get; protected set; } + public bool IsTimedOut { get; protected set; } + public DateTime? TimeoutUntil { get; protected set; } + public int TotalTimeouts { get; protected set; } public int MaxFailures { get; } public TimeSpan TimeoutDuration { get; } @@ -41,7 +41,7 @@ public TrackedProxyInfo(ProxyInfo proxy, int maxFailures = 3, TimeSpan? timeoutD IsTimedOut = false; } - public bool ReportFailure() + public virtual bool ReportFailure() { lock (_lock) { @@ -60,7 +60,7 @@ public bool ReportFailure() } } - public void ReportSuccess() + public virtual void ReportSuccess() { lock (_lock) { @@ -69,7 +69,7 @@ public void ReportSuccess() } } - public bool IsAvailable() + public virtual bool IsAvailable() { lock (_lock) { @@ -86,7 +86,7 @@ public bool IsAvailable() } } - public void ResetTimeout() + public virtual void ResetTimeout() { lock (_lock) { @@ -96,7 +96,7 @@ public void ResetTimeout() } } - public IWebProxy ToWebProxy() => Proxy.ToWebProxy(); + public virtual IWebProxy ToWebProxy() => Proxy.ToWebProxy(); public override string ToString() => $"{Key} [Failures: {FailureCount}/{MaxFailures}, TimedOut: {IsTimedOut}]"; diff --git a/DevBase.Test/DevBase/Async/TaskRegisterTests.cs b/DevBase.Test/DevBase/Async/TaskRegisterTests.cs new file mode 100644 index 0000000..4cca5b5 --- /dev/null +++ b/DevBase.Test/DevBase/Async/TaskRegisterTests.cs @@ -0,0 +1,203 @@ +using DevBase.Async.Task; + +namespace DevBase.Test.DevBase.Async; + +/// +/// Tests for the TaskRegister class. +/// Verifies task registration, suspension, resumption, and token management. +/// +public class TaskRegisterTests +{ + /// + /// Tests that GenerateNewToken creates a valid token for a type. + /// + [Test] + public void GenerateNewToken_CreatesValidToken() + { + var register = new TaskRegister(); + + var token = register.GenerateNewToken("TestType"); + + Assert.That(token, Is.Not.Null); + Assert.That(token, Is.InstanceOf()); + } + + /// + /// Tests that GenerateNewToken returns the same token for the same type. + /// + [Test] + public void GenerateNewToken_ReturnsSameTokenForSameType() + { + var register = new TaskRegister(); + + var token1 = register.GenerateNewToken("TestType"); + var token2 = register.GenerateNewToken("TestType"); + + Assert.That(token1, Is.SameAs(token2)); + } + + /// + /// Tests that GenerateNewToken returns different tokens for different types. + /// + [Test] + public void GenerateNewToken_ReturnsDifferentTokensForDifferentTypes() + { + var register = new TaskRegister(); + + var token1 = register.GenerateNewToken("Type1"); + var token2 = register.GenerateNewToken("Type2"); + + Assert.That(token1, Is.Not.SameAs(token2)); + } + + /// + /// Tests that GetTokenByType returns the correct token. + /// + [Test] + public void GetTokenByType_ReturnsCorrectToken() + { + var register = new TaskRegister(); + var generatedToken = register.GenerateNewToken("TestType"); + + var retrievedToken = register.GetTokenByType("TestType"); + + Assert.That(retrievedToken, Is.SameAs(generatedToken)); + } + + /// + /// Tests that Suspend suspends the token for a type. + /// + [Test] + public void Suspend_SuspendsToken() + { + var register = new TaskRegister(); + var token = register.GenerateNewToken("TestType"); + + register.Suspend("TestType"); + + Assert.That(token.IsSuspended, Is.True); + } + + /// + /// Tests that Resume resumes a suspended token. + /// + [Test] + public void Resume_ResumesToken() + { + var register = new TaskRegister(); + var token = register.GenerateNewToken("TestType"); + + register.Suspend("TestType"); + Assert.That(token.IsSuspended, Is.True); + + register.Resume("TestType"); + Assert.That(token.IsSuspended, Is.False); + } + + /// + /// Tests that Suspend with multiple types suspends all of them. + /// + [Test] + public void Suspend_MultipleTypes_SuspendsAll() + { + var register = new TaskRegister(); + var token1 = register.GenerateNewToken("Type1"); + var token2 = register.GenerateNewToken("Type2"); + var token3 = register.GenerateNewToken("Type3"); + + register.Suspend("Type1", "Type2", "Type3"); + + Assert.That(token1.IsSuspended, Is.True); + Assert.That(token2.IsSuspended, Is.True); + Assert.That(token3.IsSuspended, Is.True); + } + + /// + /// Tests that RegisterTask with action creates and starts a task. + /// + [Test] + public async Task RegisterTask_WithAction_CreatesAndStartsTask() + { + var register = new TaskRegister(); + var executed = false; + + register.RegisterTask(() => { executed = true; }, "TestTask", startAfterCreation: true); + + // Wait for task to execute + await Task.Delay(100); + + Assert.That(executed, Is.True); + } + + /// + /// Tests that RegisterTask with startAfterCreation=false does not start immediately. + /// + [Test] + public async Task RegisterTask_WithStartAfterCreationFalse_DoesNotStartImmediately() + { + var register = new TaskRegister(); + var executed = false; + var task = new Task(() => { executed = true; }); + + register.RegisterTask(task, "TestTask", startAfterCreation: false); + + await Task.Delay(100); + + Assert.That(executed, Is.False); + } + + /// + /// Tests that tokens work with integer type identifiers. + /// + [Test] + public void GenerateNewToken_WorksWithIntegerTypes() + { + var register = new TaskRegister(); + + var token1 = register.GenerateNewToken(1); + var token2 = register.GenerateNewToken(2); + var token1Again = register.GenerateNewToken(1); + + Assert.That(token1, Is.Not.SameAs(token2)); + Assert.That(token1, Is.SameAs(token1Again)); + } + + /// + /// Tests that tokens work with custom object type identifiers. + /// + [Test] + public void GenerateNewToken_WorksWithCustomObjects() + { + var register = new TaskRegister(); + var key1 = new TestKey("key1"); + var key2 = new TestKey("key2"); + var key1Duplicate = new TestKey("key1"); + + var token1 = register.GenerateNewToken(key1); + var token2 = register.GenerateNewToken(key2); + var token1Again = register.GenerateNewToken(key1Duplicate); + + Assert.That(token1, Is.Not.SameAs(token2)); + Assert.That(token1, Is.SameAs(token1Again)); // Same because Equals returns true + } + + private class TestKey + { + private readonly string _value; + + public TestKey(string value) + { + _value = value; + } + + public override bool Equals(object? obj) + { + return obj is TestKey other && _value == other._value; + } + + public override int GetHashCode() + { + return _value.GetHashCode(); + } + } +} diff --git a/DevBase/Async/Task/TaskSuspensionToken.cs b/DevBase/Async/Task/TaskSuspensionToken.cs index 2cfda84..9b76af4 100644 --- a/DevBase/Async/Task/TaskSuspensionToken.cs +++ b/DevBase/Async/Task/TaskSuspensionToken.cs @@ -16,6 +16,11 @@ public class TaskSuspensionToken private bool _suspended; private TaskCompletionSource _resumeRequestTcs; + /// + /// Gets whether the token is currently suspended. + /// + public bool IsSuspended => _suspended; + /// /// Initializes a new instance of the class. /// diff --git a/DevBase/DevBase.csproj b/DevBase/DevBase.csproj index a01d7ea..8a01266 100644 --- a/DevBase/DevBase.csproj +++ b/DevBase/DevBase.csproj @@ -11,7 +11,9 @@ https://github.com/AlexanderDotH/DevBase.git https://github.com/AlexanderDotH/DevBase.git Public - 1.3.5 + 1.4.1 + 1.4.1.0 + 1.4.1.0 MIT false Key.snk diff --git a/DevBase/Globals.cs b/DevBase/Globals.cs index 14001b8..72e8ba1 100644 --- a/DevBase/Globals.cs +++ b/DevBase/Globals.cs @@ -2,5 +2,10 @@ public class Globals { - public static bool ALLOW_SERIALIZATION { get; set; } = true; -} \ No newline at end of file + /// + /// Controls whether BinaryFormatter serialization is allowed for size measurement. + /// Disabled by default for .NET 9+ compatibility where BinaryFormatter is removed. + /// When disabled, object size estimation uses reflection-based calculation. + /// + public static bool AllowSerialization { get; set; } = false; +} \ No newline at end of file diff --git a/DevBase/Utilities/MemoryUtils.cs b/DevBase/Utilities/MemoryUtils.cs index 40c25df..2bb14ea 100644 --- a/DevBase/Utilities/MemoryUtils.cs +++ b/DevBase/Utilities/MemoryUtils.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Runtime.InteropServices; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; @@ -15,28 +14,102 @@ namespace DevBase.Utilities /// public class MemoryUtils { - - #pragma warning disable SYSLIB0011 /// - /// Calculates the approximate size of an object in bytes using serialization. - /// Returns 0 if serialization is not allowed or object is null. + /// Estimates the approximate size of an object in bytes using reflection. + /// For primitive types and structs, uses Marshal.SizeOf when possible. + /// For reference types, estimates based on field types. /// /// The object to measure. - /// The size in bytes. + /// The estimated size in bytes, or 0 if measurement fails. public static long GetSize(Object obj) { - if (!Globals.ALLOW_SERIALIZATION) + if (obj == null) return 0; - + + try + { + return EstimateSize(obj, obj.GetType()); + } + catch + { + return 0; + } + } + + private static long EstimateSize(object obj, Type type) + { if (obj == null) return 0; + + // Primitives and value types with known sizes + if (type == typeof(bool)) return 1; + if (type == typeof(byte) || type == typeof(sbyte)) return 1; + if (type == typeof(char)) return 2; + if (type == typeof(short) || type == typeof(ushort)) return 2; + if (type == typeof(int) || type == typeof(uint)) return 4; + if (type == typeof(long) || type == typeof(ulong)) return 8; + if (type == typeof(float)) return 4; + if (type == typeof(double)) return 8; + if (type == typeof(decimal)) return 16; + if (type == typeof(IntPtr) || type == typeof(UIntPtr)) return IntPtr.Size; + + // String: 2 bytes per character + overhead + if (type == typeof(string)) + { + var str = (string)obj; + return str.Length * 2 + IntPtr.Size; + } + + // Arrays + if (type.IsArray) + { + var array = (Array)obj; + var elementType = type.GetElementType(); + long elementSize = elementType != null ? GetPrimitiveSize(elementType) : IntPtr.Size; + return array.Length * elementSize + IntPtr.Size; + } + + // Try Marshal.SizeOf for blittable structs + if (type.IsValueType && !type.IsEnum) + { + try + { + return Marshal.SizeOf(type); + } + catch + { + // Not a blittable type, estimate via reflection + } + } + + // Reference types: estimate based on fields + long size = IntPtr.Size; // Object header + var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - using (Stream s = new MemoryStream()) + foreach (var field in fields) + { + size += GetPrimitiveSize(field.FieldType); + } + + return size; + } + + private static long GetPrimitiveSize(Type type) + { + if (type == typeof(bool)) return 1; + if (type == typeof(byte) || type == typeof(sbyte)) return 1; + if (type == typeof(char)) return 2; + if (type == typeof(short) || type == typeof(ushort)) return 2; + if (type == typeof(int) || type == typeof(uint)) return 4; + if (type == typeof(long) || type == typeof(ulong)) return 8; + if (type == typeof(float)) return 4; + if (type == typeof(double)) return 8; + if (type == typeof(decimal)) return 16; + if (type.IsValueType) { - BinaryFormatter formatter = new BinaryFormatter(); - formatter.Serialize(s, obj); - return s.Length; + try { return Marshal.SizeOf(type); } catch { } } + return IntPtr.Size; // Reference type pointer } ///