CSharpEssentials.RequestResponseLogging
1.0.3
dotnet add package CSharpEssentials.RequestResponseLogging --version 1.0.3
NuGet\Install-Package CSharpEssentials.RequestResponseLogging -Version 1.0.3
<PackageReference Include="CSharpEssentials.RequestResponseLogging" Version="1.0.3" />
paket add CSharpEssentials.RequestResponseLogging --version 1.0.3
#r "nuget: CSharpEssentials.RequestResponseLogging, 1.0.3"
// 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
- NuGet Package: CSharpEssentials
- NuGet Package EntityFrameworkCore: CSharpEssentials.EntityFrameworkCore
- NuGet Package AspNetCore: CSharpEssentials.AspNetCore
- NuGet Package RequestResponseLogging: CSharpEssentials.RequestResponseLogging
- GitHub Repository: SenRecep/CSharpEssentials
- Author: Recep Εen
π 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
dotnet add package CSharpEssentials
Entity Framework Core Integration
dotnet add package CSharpEssentials.EntityFrameworkCore
ASP.NET Core Integration
dotnet add package CSharpEssentials.AspNetCore
Request Response Logging
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
- Maybe Monad - Null-safe programming with Maybe pattern
- Result Pattern - Railway-oriented programming with Result types
- Any Type (Discriminated Unions) - Type-safe union types for C#
- Extensions - Functional programming extension methods
Domain Modeling
- Rule Engine - Business rule validation and processing
- Error Types - Structured error handling system
- Entity Base - Base classes and patterns for domain entities
Infrastructure
- JSON Utilities - Enhanced JSON serialization and handling
- Time Management - Testable datetime operations
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
- Entity Framework Core Integration
- Soft delete support
- Audit logging
- Query interceptors
- Domain events
- Optimistic concurrency
- Entity configurations
Logging and Monitoring
- Request Response Logging
- HTTP traffic monitoring
- Request/Response logging
- Performance tracking
- Custom log writers
π§ 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:
- ErrorOr - A simple, fluent discriminated union of an error or a result
- CSharpFunctionalExtensions - Functional extensions for C#
- OneOf - Easy to use F#-like discriminated unions for C#
- TechBuddySolution - The foundation for our Request Response Logging module
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.
π Related Projects
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 | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. |
-
net9.0
- Microsoft.IO.RecyclableMemoryStream (>= 3.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.