Hexalith.Commons.Configurations 2.7.0

dotnet add package Hexalith.Commons.Configurations --version 2.7.0
                    
NuGet\Install-Package Hexalith.Commons.Configurations -Version 2.7.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Hexalith.Commons.Configurations" Version="2.7.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hexalith.Commons.Configurations" Version="2.7.0" />
                    
Directory.Packages.props
<PackageReference Include="Hexalith.Commons.Configurations" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Hexalith.Commons.Configurations --version 2.7.0
                    
#r "nuget: Hexalith.Commons.Configurations, 2.7.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Hexalith.Commons.Configurations@2.7.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Hexalith.Commons.Configurations&version=2.7.0
                    
Install as a Cake Addin
#tool nuget:?package=Hexalith.Commons.Configurations&version=2.7.0
                    
Install as a Cake Tool

Hexalith.Commons

A modular .NET utility library providing essential building blocks for enterprise applications.

License: MIT Discord Build status NuGet


Overview

Hexalith.Commons is a collection of focused .NET libraries that provide reusable utilities for common programming tasks. Each package is lightweight, well-tested, and easy to integrate.

Key Capabilities

Package Purpose Key Features
Hexalith.Commons Core utilities String helpers, error handling, reflection, logging
Hexalith.Commons.Configurations Configuration management Type-safe settings, FluentValidation integration
Hexalith.Commons.StringEncoders String encoding RFC1123 encoding/decoding for restricted contexts
Hexalith.Commons.UniqueIds ID generation DateTime-based and GUID-based unique identifiers
Hexalith.Commons.Metadatas Message metadata Context tracking for distributed systems

Requirements

  • .NET 10.0 or later
  • Compatible with ASP.NET Core, Console, Worker Services, and library projects

Installation

Install packages via NuGet:

# Core utilities
dotnet add package Hexalith.Commons

# Configuration management
dotnet add package Hexalith.Commons.Configurations

# String encoding
dotnet add package Hexalith.Commons.StringEncoders

# Unique ID generation
dotnet add package Hexalith.Commons.UniqueIds

# Message metadata
dotnet add package Hexalith.Commons.Metadatas

Hexalith.Commons (Core)

The core library provides essential utilities organized into focused namespaces.

String Utilities

Namespace: Hexalith.Extensions.Helpers

using Hexalith.Extensions.Helpers;

// Format strings with named placeholders
string template = "Hello {name}, your order #{orderId} is ready";
string result = template.FormatWithNamedPlaceholders(
    new Dictionary<string, object> { ["name"] = "John", ["orderId"] = 12345 }
);
// Result: "Hello John, your order #12345 is ready"

// Culture-invariant number conversions
string number = "42.5";
decimal value = number.ToDecimal();  // Works regardless of system culture

// RFC1123 hostname validation
bool isValid = "my-server.example.com".IsRfc1123Compliant();  // true
bool isInvalid = "my_server".IsRfc1123Compliant();            // false

Error Handling

Namespace: Hexalith.Commons.Errors

Structured error handling with railway-oriented programming support.

using Hexalith.Commons.Errors;

// Create structured errors
var error = new ApplicationError
{
    Title = "Validation Failed",
    Detail = "The field {fieldName} is required",
    Category = ErrorCategory.Validation,
    Arguments = new object[] { "Email" }
};

string message = error.GetDetailMessage();
// Result: "The field Email is required"

// Railway-oriented error handling with ValueOrError<T>
ValueOrError<User> result = await GetUserAsync(userId);

if (result.HasError)
{
    // Handle error
    logger.LogError(result.Error.GetDetailMessage());
}
else
{
    // Use the value
    User user = result.Value;
}

Object Utilities

Namespace: Hexalith.Commons.Objects

Deep equality comparison and object introspection.

using Hexalith.Commons.Objects;

// Deep equality comparison (supports nested objects, collections, dictionaries)
bool areEqual = EquatableHelper.AreSame(object1, object2);

// Attribute-based object description
var description = ObjectDescriptionHelper.Describe(typeof(MyClass));
// Returns: Name, DisplayName, Description from attributes

// Implement custom equality
public class Order : IEquatableObject
{
    public string Id { get; set; }
    public decimal Total { get; set; }

    public IEnumerable<object?> GetEqualityComponents()
    {
        yield return Id;
        yield return Total;
    }
}

Reflection Utilities

Namespace: Hexalith.Commons.Reflections

Type discovery and mapping utilities.

using Hexalith.Commons.Reflections;

// Find all implementations of an interface
IEnumerable<Type> handlers = ReflectionHelper.GetInstantiableTypesOf<ICommandHandler>();

// Create instances of discovered types
IEnumerable<ICommandHandler> instances = ReflectionHelper.GetInstantiableObjectsOf<ICommandHandler>();

// Type name mapping
var mapper = new TypeMapper();
mapper.Register<OrderCreatedEvent>("order-created");
Type eventType = mapper.GetType("order-created");

Date Utilities

Namespace: Hexalith.Commons.Dates

Timezone-aware date operations.

using Hexalith.Commons.Dates;

// Convert DateOnly to DateTimeOffset with timezone
DateOnly date = new(2024, 1, 15);
TimeSpan offset = TimeSpan.FromHours(-5); // EST
DateTimeOffset result = DateHelper.ToLocalTime(date, offset);

// Convert to UTC
DateTimeOffset utc = DateHelper.ToUniversalTime(date);

// Calculate wait time between dates
TimeSpan waitTime = DateHelper.WaitTime(targetDate, currentDate);

Assembly Utilities

Namespace: Hexalith.Commons.Assemblies

Version information retrieval.

using Hexalith.Commons.Assemblies;

// Get entry assembly version
string? version = VersionHelper.EntryProductVersion();

// Get version from specific assembly
string? assemblyVersion = typeof(MyClass).Assembly.GetAssemblyVersion();

Logging Helpers

Namespace: Hexalith.Commons.Helpers

Structured logging for application errors.

using Hexalith.Commons.Helpers;

// Log application errors with full context
logger.LogApplicationError(applicationError);

Hexalith.Commons.Configurations

Type-safe configuration management with validation support.

Defining Settings

using Hexalith.Commons.Configurations;

public class DatabaseSettings : ISettings
{
    public string ConnectionString { get; set; } = string.Empty;
    public int CommandTimeout { get; set; } = 30;
    public int MaxRetryCount { get; set; } = 3;

    // Configuration section name in appsettings.json
    public static string ConfigurationName() => "Database";
}

appsettings.json:

{
  "Database": {
    "ConnectionString": "Server=localhost;Database=MyApp",
    "CommandTimeout": 60,
    "MaxRetryCount": 5
  }
}

Registration and Usage

// Program.cs - Register settings
builder.Services.ConfigureSettings<DatabaseSettings>(builder.Configuration);

// Service class - Inject and use
public class DataService
{
    private readonly DatabaseSettings _settings;

    public DataService(IOptions<DatabaseSettings> options)
    {
        _settings = options.Value;

        // Validate required settings
        SettingsException<DatabaseSettings>.ThrowIfUndefined(_settings.ConnectionString);
    }
}

FluentValidation Integration

using FluentValidation;

public class DatabaseSettingsValidator : AbstractValidator<DatabaseSettings>
{
    public DatabaseSettingsValidator()
    {
        RuleFor(x => x.ConnectionString)
            .NotEmpty()
            .WithMessage("Database connection string is required");

        RuleFor(x => x.CommandTimeout)
            .InclusiveBetween(1, 300)
            .WithMessage("Command timeout must be between 1 and 300 seconds");
    }
}

// Registration with validation
services.ConfigureSettings<DatabaseSettings>(configuration);
services.AddValidatorsFromAssemblyContaining<DatabaseSettingsValidator>();

Hexalith.Commons.StringEncoders

Reversible string encoding for RFC1123-compliant contexts.

Encoding Rules

Character Encoded Form Description
A-Z, a-z, 0-9, -, . Unchanged Allowed characters
_ (underscore) __ Escaped as double underscore
Space _20 UTF-8 hex encoding
Other characters _XX UTF-8 byte hex encoding

Usage Examples

using Hexalith.Commons.StringEncoders;

// Basic encoding
string encoded = "Hello World!".ToRFC1123();
// Result: "Hello_20World_21"

// Unicode support
string chinese = "δ½ ε₯½".ToRFC1123();
// Result: "_E4_BD_A0_E5_A5_BD"

// Email addresses
string email = "user@example.com".ToRFC1123();
// Result: "user_40example.com"

// Decoding
string original = "Hello_20World_21".FromRFC1123();
// Result: "Hello World!"

// Round-trip guarantee
string input = "Any string with Γ©mojis πŸŽ‰!";
string roundTrip = input.ToRFC1123().FromRFC1123();
Assert.Equal(input, roundTrip);  // Always true

Use Cases

  • File system paths: Generate safe filenames from user input
  • URL identifiers: Create URL-safe slugs from arbitrary text
  • Message headers: Encode values for protocols with character restrictions
  • Database keys: Create compliant identifiers from any string

Hexalith.Commons.UniqueIds

Unique identifier generation for different scenarios.

DateTime-Based IDs

17-character identifiers based on UTC timestamp. Useful for sortable, human-readable IDs.

using Hexalith.Commons.UniqueIds;

string id = UniqueIdHelper.GenerateDateTimeId();
// Example: "20240115143052789"
// Format: yyyyMMddHHmmssfff

// Thread-safe - automatically increments for same-millisecond calls
string id1 = UniqueIdHelper.GenerateDateTimeId();
string id2 = UniqueIdHelper.GenerateDateTimeId();
// id2 will be greater than id1 even if called in same millisecond

Characteristics:

  • Length: 17 characters
  • Format: yyyyMMddHHmmssfff
  • Thread-safe with automatic increment
  • Sortable chronologically
  • One unique ID per millisecond maximum

GUID-Based IDs

22-character URL-safe identifiers derived from GUIDs. Ideal for distributed systems.

string id = UniqueIdHelper.GenerateUniqueStringId();
// Example: "gZOW2EgVrEq5SBJLegYcVA"

Characteristics:

  • Length: 22 characters
  • Characters: A-Z, a-z, 0-9, _, -
  • URL-safe (no encoding needed)
  • Globally unique (GUID-based)
  • Suitable for distributed systems

Comparison

Feature GenerateDateTimeId GenerateUniqueStringId
Length 17 chars 22 chars
Sortable Yes (chronological) No
Rate limit 1 per millisecond Unlimited
Distributed No Yes
Human readable Yes (datetime) No

Hexalith.Commons.Metadatas

Metadata structures for message tracking in distributed systems.

Metadata Structure

Metadata
β”œβ”€β”€ MessageMetadata
β”‚   β”œβ”€β”€ Id          (string)    - Unique message identifier
β”‚   β”œβ”€β”€ Name        (string)    - Message type name
β”‚   β”œβ”€β”€ Version     (int)       - Message schema version
β”‚   β”œβ”€β”€ CreatedDate (DateTimeOffset)
β”‚   └── Domain      (DomainMetadata)
β”‚       β”œβ”€β”€ Id      (string)    - Aggregate identifier
β”‚       └── Name    (string)    - Aggregate type name
└── ContextMetadata
    β”œβ”€β”€ CorrelationId  (string) - Request correlation
    β”œβ”€β”€ UserId         (string) - User performing action
    β”œβ”€β”€ PartitionId    (string) - Partition for distribution
    β”œβ”€β”€ SessionId      (string) - User session
    β”œβ”€β”€ SequenceNumber (long)   - Message ordering
    β”œβ”€β”€ ReceivedDate   (DateTimeOffset)
    └── Scopes         (IEnumerable<string>)

Usage Example

using Hexalith.Commons.Metadatas;

// Create message metadata
var messageMetadata = new MessageMetadata(
    Id: UniqueIdHelper.GenerateUniqueStringId(),
    Name: "OrderCreated",
    Version: 1,
    Domain: new DomainMetadata(Id: "ORD-12345", Name: "Order"),
    CreatedDate: DateTimeOffset.UtcNow
);

// Create context metadata
var contextMetadata = new ContextMetadata(
    CorrelationId: correlationId,
    UserId: currentUser.Id,
    PartitionId: tenantId,
    SessionId: sessionId,
    SequenceNumber: 1,
    ReceivedDate: DateTimeOffset.UtcNow,
    Scopes: new[] { "orders", "write" }
);

// Combine into complete metadata
var metadata = new Metadata(messageMetadata, contextMetadata);

// Generate domain global identifier
string globalId = metadata.DomainGlobalId;
// Format: "{partitionId}-{aggregateName}-{aggregateId}"

// Logging-friendly representation
string logEntry = metadata.ToLogString();

Use Cases

  • Event sourcing: Track event origin and context
  • Message routing: Route messages based on partition and domain
  • Audit trails: Complete traceability of all operations
  • Correlation: Link related messages across services
  • Ordering: Maintain message sequence within partitions

Quality Metrics

Coverity Scan Build Status Codacy Badge Quality Gate Status Security Rating Maintainability Rating Reliability Rating


Building from Source

# Clone the repository
git clone https://github.com/Hexalith/Hexalith.Commons.git
cd Hexalith.Commons

# Build
dotnet build

# Run tests
dotnet test

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License. See the LICENSE file for details.


Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on Hexalith.Commons.Configurations:

Package Downloads
Hexalith.Security.Application

Hexalith is a set of libraries to build an application with micro-service architecture.

Hexalith.IdentityStores.Abstractions

Hexalith is a set of libraries to build an application with micro-service architecture.

Hexalith.DaprIdentityStore.Abstractions

Hexalith is a set of libraries to build a micro-service architecture.

Hexalith.KeyValueStorages.Abstractions

Hexalith KeyValueStorages utilities and helpers

Hexalith.KeyValueStorages.Files

Hexalith KeyValueStorages utilities and helpers

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.7.0 218 12/23/2025
2.6.1 168 12/23/2025
2.6.0 259 12/22/2025
2.5.0 145 12/21/2025
2.4.1 154 12/21/2025
2.4.0 147 12/21/2025
2.3.0 148 12/21/2025
2.2.2 602 12/6/2025
2.2.1 349 11/30/2025
2.2.0 629 11/13/2025
2.1.9 182 10/14/2025
2.1.8 178 10/13/2025
2.1.7 579 9/20/2025
2.1.6 326 8/10/2025
2.1.5 265 8/5/2025
2.1.4 1,213 7/24/2025
2.1.3 1,556 7/9/2025
2.1.2 834 7/6/2025
2.1.1 586 7/6/2025
2.1.0 183 7/6/2025
2.0.6 183 7/6/2025
2.0.5 702 7/4/2025
2.0.4 201 7/4/2025
2.0.3 630 6/29/2025
2.0.2 2,234 6/24/2025
2.0.1 1,802 6/13/2025
2.0.0 304 6/13/2025
1.66.5 1,681 4/11/2025
1.66.4 248 4/10/2025
1.66.3 507 4/9/2025
1.66.2 242 4/8/2025
1.66.1 184 4/8/2025
1.66.0 191 4/7/2025
1.65.1 188 4/6/2025
1.65.0 193 4/6/2025
1.64.0 604 4/2/2025
1.0.0 201 4/2/2025