CSharpEssentials.RequestResponseLogging 1.0.3

dotnet add package CSharpEssentials.RequestResponseLogging --version 1.0.3                
NuGet\Install-Package CSharpEssentials.RequestResponseLogging -Version 1.0.3                
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.RequestResponseLogging" Version="1.0.3" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add CSharpEssentials.RequestResponseLogging --version 1.0.3                
#r "nuget: CSharpEssentials.RequestResponseLogging, 1.0.3"                
#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.
// Install CSharpEssentials.RequestResponseLogging as a Cake Addin
#addin nuget:?package=CSharpEssentials.RequestResponseLogging&version=1.0.3

// Install CSharpEssentials.RequestResponseLogging as a Cake Tool
#tool nuget:?package=CSharpEssentials.RequestResponseLogging&version=1.0.3                

CSharpEssentials

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();
}

πŸš€ Getting Started

Installation

Choose the packages you need:

Core Package

NuGet

dotnet add package CSharpEssentials
Entity Framework Core Integration

NuGet

dotnet add package CSharpEssentials.EntityFrameworkCore
ASP.NET Core Integration

NuGet

dotnet add package CSharpEssentials.AspNetCore
Request Response Logging

NuGet

dotnet add package CSharpEssentials.RequestResponseLogging

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
Domain Modeling
Infrastructure

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

πŸ”§ 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

🀝 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.3 35 12/27/2024
1.0.2 90 12/4/2024
1.0.1 83 12/4/2024
1.0.0 94 12/4/2024