CSharpEssentials.Enums 2.0.9

dotnet add package CSharpEssentials.Enums --version 2.0.9
                    
NuGet\Install-Package CSharpEssentials.Enums -Version 2.0.9
                    
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="CSharpEssentials.Enums" Version="2.0.9" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CSharpEssentials.Enums" Version="2.0.9" />
                    
Directory.Packages.props
<PackageReference Include="CSharpEssentials.Enums" />
                    
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 CSharpEssentials.Enums --version 2.0.9
                    
#r "nuget: CSharpEssentials.Enums, 2.0.9"
                    
#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 CSharpEssentials.Enums@2.0.9
                    
#: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=CSharpEssentials.Enums&version=2.0.9
                    
Install as a Cake Addin
#tool nuget:?package=CSharpEssentials.Enums&version=2.0.9
                    
Install as a Cake Tool

CSharpEssentials

NuGet NuGet GitHub

CSharpEssentials is a comprehensive library that enhances C#'s functional programming capabilities. It provides a robust set of tools and utilities designed to make your C# applications more maintainable, testable, and aligned with functional programming principles.

🌟 Package Information

🌟 Key Features

  • Functional Programming Support: Enhanced functional programming capabilities for C#
  • Type Safety: Strong type safety across all modules
  • Error Handling: Comprehensive error handling with Result pattern
  • Domain-Driven Design: Support for DDD patterns and practices
  • Performance: Optimized for high performance with modern C# features
  • Testing: Built with testability in mind

πŸ“¦ Core Modules

Maybe Monad

Maybe<T> - Safe handling of nullable values:

Maybe<string> someValue = Maybe.From("Hello");
Maybe<string> noValue = Maybe.None;

// LINQ support
var result = someValue
    .Select(str => str.ToUpper())
    .Where(str => str.Length > 5);

Result Pattern

Result<T> - Functional approach to error handling:

public Result<User> CreateUser(UserDto dto)
{
    if (string.IsNullOrEmpty(dto.Email))
        return Error.Validation("EMAIL_REQUIRED", "Email is required");

    var user = new User(dto);
    return Result<User>.Success(user);
}

Rule Engine

RuleEngine - Complex business rule management:

public class EmailValidationRule : IRule<string>
{
    public Result Evaluate(string email, CancellationToken cancellationToken = default)
    {
        return email.Contains("@")
            ? Result.Success()
            : Error.Validation("INVALID_EMAIL", "Email must contain @");
    }
}

Error Types

Error - Structured error handling:

var error = Error.Validation(
    code: "USER_INVALID_AGE",
    description: "User age must be greater than 18"
);

Discriminated Unions

Any<T0,T1,...> - Type-safe union types:

public Any<string, int> ParseOrKeepAsString(string input)
{
    return int.TryParse(input, out int number)
        ? number
        : input;
}

Entity Framework Support

EntityFrameworkCore - Enhanced EF Core support with functional patterns:

public class Product : SoftDeletableEntityBase<Guid>
{
    private Product(string name, decimal price)
    {
        Id = Guid.NewGuid();
        Name = name;
        Price = price;
    }

    public static Product Create(string name, decimal price)
    {
        var product = new Product(name, price);
        product.Raise(new ProductCreatedEvent(product.Id));
        return product;
    }
}

// Configure in DbContext
public void Configure(EntityTypeBuilder<Product> builder)
{
    builder.SoftDeletableEntityBaseGuidIdMap();
    builder.OptimisticConcurrencyVersionMap();
}

Time Management

DateTimeProvider - Testable datetime handling:

public class OrderService
{
    private readonly IDateTimeProvider _dateTimeProvider;

    public Order CreateOrder()
    {
        return new Order { CreatedAt = _dateTimeProvider.UtcNow };
    }
}

JSON Utilities

JSON - Enhanced JSON capabilities:

var options = EnhancedJsonSerializerOptions.DefaultOptions;
string json = myObject.ConvertToJson(options);

Extensions

Extensions - Useful extension methods:

// String transformations
"helloWorld".ToPascalCase();  // => "HelloWorld"
"hello_world".ToCamelCase();  // => "helloWorld"

// Collection operations
var randomItem = list.GetRandomItem();

Request Response Logging

RequestResponseLogging - Comprehensive HTTP traffic monitoring:

public void Configure(IApplicationBuilder app)
{
    app.AddRequestResponseLogging(opt =>
    {
        // Configure logging options
        var loggingOptions = LoggingOptions.CreateAllFields();
        loggingOptions.HeaderKeys.Add("X-Correlation-Id");

        // Use the configured logger
        opt.UseLogger(app.Services.GetRequiredService<ILoggerFactory>(), loggingOptions);
    });
}

ASP.NET Core Integration

AspNetCore - Enhanced ASP.NET Core capabilities:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddExceptionHandler<GlobalExceptionHandler>()
        .ConfigureModelValidatorResponse()
        .ConfigureSystemTextJson()
        .AddEnhancedProblemDetails()
        .AddAndConfigureApiVersioning()
        .AddSwagger<DefaultConfigureSwaggerOptions>(
            SecuritySchemes.JwtBearerTokenSecurity,
            Assembly.GetExecutingAssembly()
        );
}

public void Configure(IApplicationBuilder app)
{
    app.UseVersionableSwagger();
    app.UseExceptionHandler();
    app.UseStatusCodePages();
}

Google Cloud Secret Manager Integration

GcpSecretManager - Seamless integration with Google Cloud Secret Manager:

// Basic configuration in Program.cs or Startup.cs
builder.Configuration.AddGcpSecretManager();

// Advanced configuration with options
builder.Configuration.AddGcpSecretManager(options =>
{
    options.CredentialsPath = "/path/to/credentials.json";
    options.AddProject(new ProjectSecretConfiguration
    {
        ProjectId = "your-gcp-project-id",
        Region = "europe-west1",
        PrefixFilters = ["app_", "service_"],
        SecretIds = ["specific-secret1"],
        RawSecretIds = ["config-json"],      // Skip JSON parsing for these secrets
        RawSecretPrefixes = ["raw_"]         // Skip JSON parsing for secrets with these prefixes
    });
});

// Configuration in appsettings.json
{
  "GoogleSecretManager": {
    "Projects": [
      {
        "ProjectId": "your-gcp-project-id",
        "Region": "europe-west1",
        "PrefixFilters": ["app_"],
        "SecretIds": ["specific-secret1"],
        "RawSecretIds": ["config-json"],
        "RawSecretPrefixes": ["raw_"]
      }
    ]
  }
}

Key features:

  • Seamless integration with .NET configuration system
  • Region-specific secret management
  • Flexible secret filtering with prefix and exact matches
  • JSON value flattening with control over parsing behavior
  • Batch processing for optimal performance
  • Automatic secret rotation support
  • Built-in retry policies for resilience

Secret Management

  • Use region-specific endpoints for better latency
  • Implement proper credentials management
  • Use prefix filters to limit secret access
  • Configure appropriate batch sizes
  • Monitor secret loading performance
  • Implement proper error handling
  • Use JSON flattening for complex values with control over parsing behavior
  • Configure proper retry policies
  • Use RawSecretIds and RawSecretPrefixes to control JSON parsing behavior

πŸš€ Getting Started

Installation

Choose the packages you need:

Core Package

NuGet

dotnet add package CSharpEssentials
Core Utilities

NuGet

dotnet add package CSharpEssentials.Core
Functional Programming

NuGet

dotnet add package CSharpEssentials.Maybe

NuGet

dotnet add package CSharpEssentials.Results

NuGet

dotnet add package CSharpEssentials.Any
Error Handling & Validation

NuGet

dotnet add package CSharpEssentials.Errors

NuGet

dotnet add package CSharpEssentials.Rules
Domain Modeling

NuGet

dotnet add package CSharpEssentials.Entity
Entity Framework Core Integration

NuGet

dotnet add package CSharpEssentials.EntityFrameworkCore
ASP.NET Core Integration

NuGet

dotnet add package CSharpEssentials.AspNetCore
JSON Utilities

NuGet

dotnet add package CSharpEssentials.Json
Time Management

NuGet

dotnet add package CSharpEssentials.Time
Object Cloning

NuGet

dotnet add package CSharpEssentials.Clone
Enum Utilities

NuGet

dotnet add package CSharpEssentials.Enums
Request Response Logging

NuGet

dotnet add package CSharpEssentials.RequestResponseLogging
Google Cloud Secret Manager Integration

NuGet

dotnet add package CSharpEssentials.GcpSecretManager

You can also install the packages directly from the NuGet Gallery.

Basic Setup

Import the required namespaces based on your needs:

// Core functionality
using CSharpEssentials;

// Entity Framework Core integration
using CSharpEssentials.EntityFrameworkCore;

// ASP.NET Core integration
using CSharpEssentials.AspNetCore;

// Request Response Logging
using CSharpEssentials.RequestResponseLogging;

πŸ“š Documentation

Core Modules Documentation

Functional Programming Essentials
Error Handling & Validation
Domain Modeling
Infrastructure & Utilities

Integration Modules Documentation

Web Development
  • ASP.NET Core Integration
    • Global exception handling
    • API versioning
    • Swagger integration
    • Problem Details support
    • Model validation
    • Security configurations
Data Access
Logging and Monitoring
Secret Management
  • Google Cloud Secret Manager Integration
    • Configuration provider integration
    • Region-specific secret management
    • Flexible secret filtering
    • Batch processing support
    • JSON value flattening
    • Automatic secret rotation
    • Built-in retry policies

Package-Specific Documentation

Core Packages
Functional Programming
Error Handling
Domain & Infrastructure
Integration Packages

Getting Help

  • GitHub Issues: Report bugs or request features at GitHub Issues
  • Documentation: Each package has its own detailed README with examples
  • NuGet Packages: All packages are available on NuGet Gallery
  • Source Code: Browse the source code at GitHub Repository

πŸ”§ Best Practices

Error Handling

  • Use Result<T> for operations that can fail
  • Prefer Maybe<T> over null values for optional values
  • Use structured Error types for domain errors
  • Chain operations with LINQ-style methods on Result<T>
  • Handle validation errors separately from domain errors
  • Use Error.Validation() for input validation failures
  • Use Error.NotFound() for resource not found scenarios
  • Use Error.Unauthorized() for authentication/authorization failures

Domain Modeling

  • Extend EntityBase for domain entities
  • Use RuleEngine for complex validations
  • Implement domain events for state changes
  • Keep entities immutable where possible
  • Use static factory methods for entity creation
  • Encapsulate business rules within the domain model
  • Use value objects for complex value types
  • Implement IRule<T> for reusable business rules

Functional Programming

  • Use Any<T0,T1> for type-safe union types
  • Leverage extension methods for fluent interfaces
  • Use pure functions where possible
  • Avoid side effects in business logic
  • Use immutable collections when appropriate
  • Chain operations using LINQ and functional extensions
  • Use pattern matching with discriminated unions

ASP.NET Core Integration

  • Use global exception handling middleware
  • Configure proper API versioning
  • Implement proper request/response logging
  • Use problem details for error responses
  • Configure Swagger documentation properly
  • Use proper security headers
  • Implement proper model validation
  • Use proper HTTP status codes

Entity Framework Core

  • Use SoftDeletableEntityBase for soft delete support
  • Configure proper entity type configurations
  • Use optimistic concurrency where needed
  • Implement proper audit logging
  • Use proper indexing strategies
  • Configure proper lazy loading settings
  • Use proper query tracking behavior
  • Monitor slow queries with interceptors

Testing

  • Use DateTimeProvider for time-dependent tests
  • Mock interfaces instead of concrete implementations
  • Utilize Result<T> for predictable error scenarios
  • Write unit tests for business rules
  • Test error scenarios thoroughly
  • Use proper test data builders
  • Implement integration tests for critical paths
  • Test validation rules independently

Performance

  • Use proper caching strategies
  • Implement proper database indexing
  • Use async/await properly
  • Avoid N+1 query problems
  • Use proper connection pooling
  • Implement proper response compression
  • Monitor and log performance metrics
  • Use proper batch operations

Secret Management

  • Use region-specific endpoints for better latency
  • Implement proper credentials management
  • Use prefix filters to limit secret access
  • Configure appropriate batch sizes
  • Monitor secret loading performance
  • Implement proper error handling
  • Use JSON flattening for complex values with control over parsing behavior
  • Configure proper retry policies
  • Use RawSecretIds and RawSecretPrefixes to control JSON parsing behavior

πŸ”§ Development

Building and Publishing NuGet Packages

This repository includes an optimized build and publish script that handles all CSharpEssentials packages with proper dependency order management.

Script: build-and-publish-nugets.sh - Cross-platform script for Linux, macOS, and Windows (Git Bash/WSL)

Features
  • Smart Dependency Management: Automatically packages and publishes in correct dependency order
  • Parallel Processing: Optional parallel build/publish for same-level packages (--parallel)
  • Comprehensive Validation: Environment, API key, and project validation
  • Multiple Modes: Build-only, dry-run, verbose logging, skip-build options
  • Error Handling: Robust error handling with colored output and proper cleanup
  • Cross-Platform: Works on Windows (Git Bash/WSL), Linux, and macOS
Usage Examples
# Basic build and package (no publishing)
./build-and-publish-nugets.sh

# Build, package and publish to NuGet.org
./build-and-publish-nugets.sh YOUR_API_KEY

# Use parallel processing for faster builds
./build-and-publish-nugets.sh --parallel YOUR_API_KEY

# Preview what would happen (dry run)
./build-and-publish-nugets.sh --dry-run --verbose YOUR_API_KEY

# Skip build and only package existing builds
./build-and-publish-nugets.sh --skip-build YOUR_API_KEY

# Force package even with warnings (for NU5017 errors)
./build-and-publish-nugets.sh --force-pack YOUR_API_KEY

# Show help
./build-and-publish-nugets.sh --help
Package Dependency Levels
  • Level 0: Core, Enums, Time, Clone, AspNetCore, GcpSecretManager, RequestResponseLogging
  • Level 1: Errors, Json
  • Level 2: Results
  • Level 3: Any, Maybe, Rules, Entity, EntityFrameworkCore
  • Level 4: CSharpEssentials (meta-package)
Script Options
  • --parallel: Enable parallel processing for same-level packages
  • --verbose: Enable detailed logging
  • --dry-run: Show what would be executed without doing it
  • --skip-build: Skip build step and only package/publish
  • --force-pack: Force packaging even with NU5017 warnings
  • --help, -h: Show usage information

Development Workflow

# Clone the repository
git clone https://github.com/senrecep/CSharpEssentials.git
cd CSharpEssentials

# Build all packages
./build-and-publish-nugets.sh

# Run tests (if available)
dotnet test

# Build and publish with API key
./build-and-publish-nugets.sh --parallel YOUR_NUGET_API_KEY

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

πŸ“„ License

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

πŸ™ Acknowledgments

This library was inspired by and builds upon the work of several excellent open-source projects:

Special thanks to all contributors who have helped shape this library and to the maintainers of these inspiring projects.

πŸ“¬ Support

For support, please open an issue in the GitHub repository or contact the maintainers.

Take a look at senrecep.Aspire, a modern microservices template built with .NET Aspire 9.0. The template provides a robust foundation for building scalable, maintainable, and cloud-ready microservices applications. Check out the GitHub repository for more details.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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.
  • net9.0

    • No dependencies.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on CSharpEssentials.Enums:

Package Downloads
CSharpEssentials

A comprehensive C# library enhancing functional programming capabilities with type-safe monads (Maybe, Result), discriminated unions (Any), and robust error handling. Features include: domain-driven design support, enhanced Entity Framework integration, testable time management, JSON utilities, and LINQ extensions. Built for modern C# development with focus on maintainability, testability, and functional programming principles.

CSharpEssentials.EntityFrameworkCore

Enhances Entity Framework Core with functional programming patterns and DDD-friendly features. Includes base entity classes, soft delete support, audit trails, query filters, optimistic concurrency, PostgreSQL integration, query performance monitoring, and domain event handling. Perfect for building maintainable and scalable data access layers in modern .NET applications.

CSharpEssentials.Errors

Comprehensive error handling system for functional programming in C#. Provides Error types, ErrorMetadata, ErrorType enums, and extensions for robust error management. Foundation for Result pattern and functional error handling.

CSharpEssentials.Json

JSON utilities and custom converters for System.Text.Json in C#. Includes MultiFormatDateTimeConverter, ConditionalStringEnumConverter, PolymorphicJsonConverterFactory, and JsonOptions. Essential for advanced JSON serialization scenarios.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.9 19 9/30/2025
2.0.8 82 9/29/2025
2.0.7 81 9/29/2025
2.0.6 91 9/29/2025
2.0.5 80 9/29/2025
2.0.4 97 9/28/2025
2.0.3 87 9/28/2025
2.0.2 86 9/28/2025
2.0.1 88 9/28/2025
2.0.0 97 9/28/2025