### Create and Validate Tokens in C# Source: https://context7.com/codebeltnet/shared-kernel/llms.txt Shows how to create Token objects with default and custom validation options for length and character frequency. It also includes examples of validation failures due to unmet length or character frequency requirements, and disallows whitespace. ```csharp using Codebelt.SharedKernel; // Create with default options (32-128 chars, 4+ distinct chars required) var token = new Token("1acb4e4928a64206b22b2392ffd4e605"); Console.WriteLine(token.Value); // Output: 1acb4e4928a64206b22b2392ffd4e605 // Create with custom options var customToken = new Token("shorttoken12345", options => { options.MinimumLength = 10; // Allow shorter tokens options.MaximumLength = 50; // Restrict maximum length options.MaximumCharacterFrequency = 2; // Require more distinct characters }); // Allow very short tokens var shortToken = new Token("abc123def456ghij", options => { options.MinimumLength = 0; // No minimum length }); // Allow very long tokens var longToken = new Token(new string('x', 200) + "abc123", options => { options.MaximumLength = 0; // No maximum length options.MaximumCharacterFrequency = 0; // No frequency check }); // Validation failures (throws ArgumentOutOfRangeException) try { new Token("short"); // Less than 32 characters } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); // "The minimum length of value was not meet. 32 characters are required." } try { new Token("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); // Too few distinct characters } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); // "Value suggest to high frequency of repeated characters." } // Whitespace not allowed try { new Token("1acb4e4928a64206 b22b2392ffd4e605"); // Contains space } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); // "White-space characters are not allowed inside value." } ``` -------------------------------- ### CorrelationId: Create and Use in C# Source: https://context7.com/codebeltnet/shared-kernel/llms.txt Demonstrates how to create and use the CorrelationId value object in C#. It covers creation from GUID and string, implicit conversions, and usage in HTTP contexts and inter-service communication for distributed tracing. ```csharp using Codebelt.SharedKernel; // Create from GUID CorrelationId fromGuid = new CorrelationId(Guid.NewGuid()); Console.WriteLine(fromGuid.Value); // Output: e.g., 1acb4e4928a64206b22b2392ffd4e605 // Create from string (32-128 chars, must have unique characters) CorrelationId fromString = new CorrelationId("request-trace-id-abc123def456ghi"); Console.WriteLine(fromString.Value); // Output: request-trace-id-abc123def456ghi // Implicit conversions for easy assignment CorrelationId implicitFromGuid = Guid.NewGuid(); // Guid -> CorrelationId CorrelationId implicitFromString = "correlation-123-abc-def-456-ghi"; // string -> CorrelationId // Use in HTTP context (pseudo-code) // httpContext.Items["CorrelationId"] = new CorrelationId(Guid.NewGuid()); // var correlationId = httpContext.Request.Headers["X-Correlation-ID"]; // CorrelationId parsed = correlationId; // Pass between services void ProcessRequest(CorrelationId correlationId) { Console.WriteLine($"Processing request with correlation: {correlationId.Value}"); // Log with correlation ID for distributed tracing } ProcessRequest(Guid.NewGuid()); ``` -------------------------------- ### Create and Use Secrets in C# Source: https://context7.com/codebeltnet/shared-kernel/llms.txt Illustrates creating Secret objects from GUIDs and strings, supporting implicit conversions from these types. It also shows how to convert secrets to byte arrays with customizable encoding options and access the underlying string value. ```csharp using Codebelt.SharedKernel.Security; // Create from GUID (converted to N format - 32 hex chars) Secret fromGuid = new Secret(Guid.NewGuid()); Console.WriteLine(fromGuid); // Output: e.g., 1acb4e4928a64206b22b2392ffd4e605 // Create from string (minimum 32 characters with sufficient entropy) Secret fromString = new Secret("mysecretthatisatleastthirtytwocharacterslong"); Console.WriteLine(fromString); // Output: mysecretthatisatleastthirtytwocharacterslong // Implicit conversions Secret implicitFromGuid = Guid.NewGuid(); // Guid -> Secret Secret implicitFromString = "bae9d2e09c9b5f65f9a7a3c5a55748b180ee65c1"; // string -> Secret // Convert to byte array for cryptographic operations byte[] secretBytes = fromString.ToByteArray(); Console.WriteLine(secretBytes.Length); // Output: varies based on string length // With encoding options byte[] utf32Bytes = fromString.ToByteArray(options => { options.Encoding = System.Text.Encoding.UTF32; }); // Access underlying value string secretValue = fromGuid.Value; ``` -------------------------------- ### AccessKey: Create and Validate in C# Source: https://context7.com/codebeltnet/shared-kernel/llms.txt Illustrates the creation and validation of the AccessKey value object in C#. It shows how to create keys with default and custom options, issue temporary keys, and validate their authenticity using current or specific times. ```csharp using Codebelt.SharedKernel; using Codebelt.SharedKernel.Security; // Create with default options (no expiration, 30 second tolerance) var accessKey = new AccessKey(Guid.NewGuid()); Console.WriteLine(accessKey.Secret); // Output: e.g., 1acb4e4928a64206b22b2392ffd4e605 Console.WriteLine(accessKey.ValidFrom); // Output: 0001-01-01T00:00:00.0000000Z Console.WriteLine(accessKey.Expires); // Output: 9999-12-31T22:59:59.9999999Z Console.WriteLine(accessKey.DesiredTolerance); // Output: 00:00:30 // Create with custom secret string var customKey = new AccessKey("mysecretthatisatleastthirtytwocharacterslong"); // Issue with lifespan using factory method Secret secret = "bae9d2e09c9b5f65f9a7a3c5a55748b180ee65c1"; AccessKey temporaryKey = AccessKey.Issue(secret, TimeToLive.FromYears(1)); Console.WriteLine($"Valid from: {temporaryKey.ValidFrom}"); Console.WriteLine($"Expires: {temporaryKey.Expires}"); // ~1 year from now // Issue with shorter lifespan AccessKey shortLived = AccessKey.Issue(Guid.NewGuid(), TimeToLive.FromHours(24)); AccessKey veryShort = AccessKey.Issue(Guid.NewGuid(), TimeToLive.FromMinutes(30)); // Create with custom options var configuredKey = new AccessKey(Guid.NewGuid(), options => { options.ValidFrom = DateTime.UtcNow; options.Expires = DateTime.UtcNow.AddDays(30); options.DesiredTolerance = ClockSkew.FromMinutes(5); // 5 minute tolerance }); // Validate access key bool isValid = configuredKey.IsValid(); // Uses current UTC time bool wasValidAtTime = configuredKey.IsValid(CoordinatedUniversalTime.FromString("2024-06-01T12:00:00Z")); // JSON serialization output // {"secret":"1acb4e4928a64206b22b2392ffd4e605","validFrom":"0001-01-01T00:00:00.0000000Z","expires":"9999-12-31T22:59:59.9999999Z","desiredTolerance":"00:00:30"} ``` -------------------------------- ### Create and Use TimeToLive Durations in C# Source: https://context7.com/codebeltnet/shared-kernel/llms.txt Demonstrates creating TimeToLive durations from various time units (minutes, hours, days, months, years) and TimeSpans. It also covers implicit conversions, comparison operations, and accessing the underlying TimeSpan value. ```csharp using Codebelt.SharedKernel; // Create from various time units TimeToLive fiveMinutes = TimeToLive.FromMinutes(5); Console.WriteLine(fiveMinutes); // Output: 00:05:00 TimeToLive twoHours = TimeToLive.FromHours(2); Console.WriteLine(twoHours); // Output: 02:00:00 TimeToLive oneDay = TimeToLive.FromDays(1); Console.WriteLine(oneDay); // Output: 1.00:00:00 TimeToLive sixMonths = TimeToLive.FromMonths(6); Console.WriteLine(sixMonths); // Output varies based on current date TimeToLive oneYear = TimeToLive.FromYears(1); Console.WriteLine(oneYear); // Output varies based on current date (365 or 366 days) // Create from TimeSpan TimeToLive custom = new TimeToLive(TimeSpan.FromHours(12)); // Implicit conversions TimeSpan span = fiveMinutes; // TimeToLive -> TimeSpan TimeToLive fromSpan = TimeSpan.FromMinutes(30); // TimeSpan -> TimeToLive // Comparison operations TimeToLive shorter = TimeToLive.FromMinutes(5); TimeToLive longer = TimeToLive.FromHours(1); bool isLonger = longer > shorter; // true bool isShorterOrEqual = shorter <= longer; // true // Access underlying value TimeSpan underlyingSpan = oneDay.Value; Console.WriteLine(underlyingSpan.TotalHours); // Output: 24 ``` -------------------------------- ### Create Comparable Value Objects with Built-in Comparison Operators Source: https://context7.com/codebeltnet/shared-kernel/llms.txt Illustrates creating custom comparable value objects using the abstract base record ComparableValueObject. This C# code demonstrates defining Money and Temperature value objects with implicit conversions and comparison operators. ```csharp using Codebelt.SharedKernel; using Savvyio.Domain; // Example: Creating a custom comparable value object for Money public record Money : ComparableValueObject { public static Money Zero => new Money(0m); public static implicit operator Money(decimal value) => new Money(value); public static implicit operator decimal(Money value) => value.Value; public Money(decimal value) : base(value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), "Money cannot be negative"); } public override string ToString() => $"{Value:N2}"; } // Usage Money price1 = 19.99m; Money price2 = 29.99m; Money price3 = new Money(19.99m); // Comparison operators work out of the box bool isMoreExpensive = price2 > price1; // true bool isLessExpensive = price1 < price2; // true bool isEqual = price1 == price3; // true bool isGreaterOrEqual = price2 >= price1; // true bool isLessOrEqual = price1 <= price2; // true Console.WriteLine($"{price1} < {price2}: {isMoreExpensive}"); // Output: $19.99 < $29.99: true // Example: Creating a custom Temperature value object public record Temperature : ComparableValueObject { public static Temperature AbsoluteZero => new Temperature(-273.15); public Temperature(double celsius) : base(celsius) { if (celsius < -273.15) throw new ArgumentOutOfRangeException(nameof(celsius), "Temperature cannot be below absolute zero"); } public double ToFahrenheit() => (Value * 9 / 5) + 32; public override string ToString() => $"{Value:F1}°C"; } // Usage var freezing = new Temperature(0); var boiling = new Temperature(100); bool isHotter = boiling > freezing; // true ``` -------------------------------- ### Validate AccessKey Validity Period and Clock Skew Tolerance Source: https://context7.com/codebeltnet/shared-kernel/llms.txt Demonstrates how to validate an AccessKey using its validity period and clock skew tolerance. This C# code shows issuing keys, checking current validity, validating against specific times, and handling expired keys with tolerance. ```csharp using Codebelt.SharedKernel; using Codebelt.SharedKernel.Security; // Create access key with 24-hour lifespan Secret secret = Guid.NewGuid(); AccessKey key = AccessKey.Issue(secret, TimeToLive.FromHours(24)); // Validate using current time bool currentlyValid = key.IsValid(); Console.WriteLine($"Key is valid: {currentlyValid}"); // Output: Key is valid: True // Validate against specific time CoordinatedUniversalTime futureTime = CoordinatedUniversalTime.Now(); // Note: To test expiration, you'd need a time beyond the expiry bool validAtFuture = key.IsValid(futureTime); // Example: Authentication middleware pattern public class ApiKeyMiddleware { public bool ValidateApiKey(string apiKeyHeader, AccessKey storedKey) { // Check if the provided key matches and is still valid if (apiKeyHeader == storedKey.Secret && storedKey.IsValid()) { return true; } return false; } } // Create expired key for testing var expiredKey = new AccessKey(Guid.NewGuid(), options => { options.ValidFrom = DateTime.UtcNow.AddDays(-2); options.Expires = DateTime.UtcNow.AddDays(-1); options.DesiredTolerance = ClockSkew.FromSeconds(30); }); bool isExpiredKeyValid = expiredKey.IsValid(); Console.WriteLine($"Expired key is valid: {isExpiredKeyValid}"); // Output: Expired key is valid: False // Clock skew tolerance example - key tolerates 30 seconds past expiry by default var keyWithTolerance = AccessKey.Issue(Guid.NewGuid(), TimeToLive.FromMinutes(1)); // Even if checked 30 seconds after expiry, still valid due to tolerance ``` -------------------------------- ### ClockSkew Value Object in C# Source: https://context7.com/codebeltnet/shared-kernel/llms.txt Illustrates the use of the ClockSkew value object for managing clock skew tolerance, with values constrained between 0 and 4 hours. It shows creation from seconds, minutes, and TimeSpan, along with implicit conversions and boundary value access. Invalid values outside the allowed range will throw an ArgumentOutOfRangeException. ```csharp using Codebelt.SharedKernel; // Create from seconds (0-65535) ClockSkew thirtySeconds = ClockSkew.FromSeconds(30); Console.WriteLine(thirtySeconds); // Output: 00:00:30 // Create from minutes (0-255) ClockSkew fifteenMinutes = ClockSkew.FromMinutes(15); Console.WriteLine(fifteenMinutes); // Output: 00:15:00 // Create from TimeSpan directly ClockSkew oneHour = new ClockSkew(TimeSpan.FromHours(1)); Console.WriteLine(oneHour); // Output: 01:00:00 // Implicit conversion to/from TimeSpan TimeSpan span = thirtySeconds; // ClockSkew -> TimeSpan ClockSkew fromSpan = TimeSpan.FromMinutes(5); // TimeSpan -> ClockSkew // Use boundaries Console.WriteLine(ClockSkew.MinValue); // Output: 00:00:00 Console.WriteLine(ClockSkew.MaxValue); // Output: 04:00:00 // Comparison operations ClockSkew small = ClockSkew.FromSeconds(30); ClockSkew large = ClockSkew.FromMinutes(5); bool isGreater = large > small; // true // Invalid: throws ArgumentOutOfRangeException // ClockSkew invalid = new ClockSkew(TimeSpan.FromHours(5)); // Exceeds MaxValue // ClockSkew negative = new ClockSkew(TimeSpan.FromSeconds(-1)); // Below MinValue ``` -------------------------------- ### CoordinatedUniversalTime Value Object in C# Source: https://context7.com/codebeltnet/shared-kernel/llms.txt Demonstrates the usage of the CoordinatedUniversalTime value object for handling UTC timestamps. It covers creation from current time, strings, DateTime, and DateTimeOffset, along with comparison operations and accessing the underlying DateTime value. Ensure DateTime objects are UTC kind when converting. ```csharp using Codebelt.SharedKernel; // Create from current time CoordinatedUniversalTime now = CoordinatedUniversalTime.Now(); Console.WriteLine(now); // Output: 2024-03-17T07:27:30.0000000Z // Create from string (ISO 8601) CoordinatedUniversalTime parsed = CoordinatedUniversalTime.FromString("2024-03-17T15:27:30.0000000+08:00"); Console.WriteLine(parsed); // Output: 2024-03-17T07:27:30.0000000Z (converted to UTC) // Implicit conversion from DateTime (must be UTC kind) DateTime utcDateTime = DateTime.UtcNow; CoordinatedUniversalTime fromDateTime = utcDateTime; // Implicit conversion from DateTimeOffset DateTimeOffset offset = DateTimeOffset.Parse("2024-03-17T15:27:30.0000000+08:00"); CoordinatedUniversalTime fromOffset = offset; // Comparison operations CoordinatedUniversalTime earlier = CoordinatedUniversalTime.MinValue; CoordinatedUniversalTime later = CoordinatedUniversalTime.MaxValue; bool isAfter = later > earlier; // true bool isBefore = earlier < later; // true bool isEqual = now == CoordinatedUniversalTime.Now(); // depends on timing // Access underlying DateTime DateTime underlying = now.Value; Console.WriteLine(underlying.Kind); // Output: Utc ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.