### Running the Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Results/README.md Navigate to the example directory and run the dotnet application. ```bash cd examples/Examples.Results dotnet run ``` -------------------------------- ### Run Maybe Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Maybe/README.md Navigate to the example directory and run the .NET application. ```bash cd examples/Examples.Maybe dotnet run ``` -------------------------------- ### Run CSharpEssentials.Any Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Any/README.md Navigate to the example directory and run the console application using the .NET CLI. ```bash cd examples/Examples.Any dotnet run ``` -------------------------------- ### Example Usage of Guider Class Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Core/Guids/Readme.MD Demonstrates a typical workflow: generating a new GUID, converting it to a URL-safe string for use in URLs, and converting it back to a GUID. ```csharp // Generate a new GUID Guid newId = Guider.NewGuid(); // Convert to URL-safe string string urlSafe = Guider.ToStringFromGuid(newId); // Use in URLs var url = $"https://api.example.com/resources/{urlSafe}"; // Convert back to GUID Guid originalId = Guider.ToGuidFromString(urlSafe); ``` -------------------------------- ### Run CSharpEssentials.Rules Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Rules/README.md Navigate to the example directory and run the console application using the .NET CLI. ```bash cd examples/Examples.Rules dotnet run ``` -------------------------------- ### Run CSharpEssentials.Errors Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Errors/README.md Navigate to the example directory and run the console application using .NET. ```bash cd examples/Examples.Errors dotnet run ``` -------------------------------- ### Run CSharpEssentials.Core Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Core/README.md Navigate to the example directory and run the console application using the dotnet CLI. ```bash cd examples/Examples.Core dotnet run ``` -------------------------------- ### Run Entity Examples Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Entity/README.md Navigate to the example directory and run the console application using the .NET CLI. ```bash cd examples/Examples.Entity dotnet run ``` -------------------------------- ### Run CSharpEssentials.Json Examples Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Json/README.md Navigate to the example directory and execute the console application using the .NET CLI. ```bash cd examples/Examples.Json dotnet run ``` -------------------------------- ### Run CSharpEssentials.Time Examples Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Time/README.md Navigate to the example directory and run the console application using dotnet run. ```bash cd examples/Examples.Time dotnet run ``` -------------------------------- ### Run Clone Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Clone/README.md Navigate to the example directory and run the .NET application to see the cloning features in action. ```bash cd examples/Examples.Clone dotnet run ``` -------------------------------- ### Run CSharpEssentials Main Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Main/README.md Navigate to the example directory and run the console application using the .NET CLI. ```bash cd examples/Examples.Main dotnet run ``` -------------------------------- ### Run Enum Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.Enums/README.md Navigate to the example directory and run the console application using the dotnet CLI. ```bash cd examples/Examples.Enums dotnet run ``` -------------------------------- ### Run C# GCP Secret Manager Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.GcpSecretManager/README.md Navigate to the example directory and run the console application using the .NET CLI. ```bash cd examples/Examples.GcpSecretManager dotnet run ``` -------------------------------- ### Install CSharpEssentials.Any Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Any/Readme.MD Use the dotnet CLI to add the CSharpEssentials.Any package to your project. ```bash dotnet add package CSharpEssentials.Any ``` -------------------------------- ### GUID Utilities in C# Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Core/README.MD Generate Version 7 GUIDs (on .NET 9+) and perform URL-safe Base64 encoding/decoding for GUIDs. Use Guider for generation and extension methods for string conversions. ```csharp Guid id = Guider.NewGuid(); // Version 7 on .NET 9+ string shortId = id.ToStringFromGuid(); // URL-safe Base64 (22 chars) Guid parsed = shortId.ToGuidFromString(); ``` -------------------------------- ### Install CSharpEssentials.Rules Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD Add the CSharpEssentials.Rules package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.Rules ``` -------------------------------- ### Install AI Skills for CSharpEssentials Source: https://github.com/senrecep/csharpessentials/blob/main/README.MD Installs AI skills for various agents to understand and utilize the CSharpEssentials library. ```bash npx skills add senrecep/CSharpEssentials ``` -------------------------------- ### Install CSharpEssentials.Http Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Http/Readme.MD Add the CSharpEssentials.Http package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.Http ``` -------------------------------- ### Install EntityFrameworkCore Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.EntityFrameworkCore/Readme.MD Add the CSharpEssentials.EntityFrameworkCore package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.EntityFrameworkCore ``` -------------------------------- ### Install CSharpEssentials Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials/Readme.MD Use this command to add the CSharpEssentials meta-package to your project. ```bash dotnet add package CSharpEssentials ``` -------------------------------- ### Install CSharpEssentials.Results Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Results/Readme.MD Add the CSharpEssentials.Results package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.Results ``` -------------------------------- ### Install CSharpEssentials.Entity Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Entity/Readme.MD Use the dotnet CLI to add the CSharpEssentials.Entity package to your project. ```bash dotnet add package CSharpEssentials.Entity ``` -------------------------------- ### Install CSharpEssentials.Core Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Core/README.MD Add the CSharpEssentials.Core NuGet package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.Core ``` -------------------------------- ### Install CSharpEssentials.Time Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Time/Readme.MD Add the CSharpEssentials.Time package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.Time ``` -------------------------------- ### Install CSharpEssentials.AspNetCore Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.AspNetCore/Readme.MD Add the CSharpEssentials.AspNetCore package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.AspNetCore ``` -------------------------------- ### Install CSharpEssentials.Errors Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Errors/Readme.MD Use the dotnet CLI to add the CSharpEssentials.Errors package to your project. ```bash dotnet add package CSharpEssentials.Errors ``` -------------------------------- ### Install RequestResponseLogging Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.RequestResponseLogging/Readme.MD Add the CSharpEssentials.RequestResponseLogging package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.RequestResponseLogging ``` -------------------------------- ### Install CSharpEssentials.Maybe Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Maybe/Readme.MD Add the CSharpEssentials.Maybe NuGet package to your project using the dotnet CLI. ```bash dotnet add package CSharpEssentials.Maybe ``` -------------------------------- ### Install CSharpEssentials.Clone Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Clone/Readme.MD Add the CSharpEssentials.Clone NuGet package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.Clone ``` -------------------------------- ### Install CSharpEssentials.Enums Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Enums/Readme.MD Add the CSharpEssentials.Enums package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.Enums ``` -------------------------------- ### Test Simple GET Endpoint Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.RequestResponseLogging/README.md Use curl to send a GET request to a simple endpoint and observe the log output. ```bash curl -s https://localhost:5001/api/demo/hello ``` -------------------------------- ### Install CSharpEssentials.Json Package Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Json/Readme.MD Add the CSharpEssentials.Json NuGet package to your project using the .NET CLI. ```bash dotnet add package CSharpEssentials.Json ``` -------------------------------- ### Setup Swagger with Versioning in ASP.NET Core Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.AspNetCore/Readme.MD Add Swagger services with versioning support and security schemes, then enable versionable Swagger UI. ```csharp builder.Services.AddSwagger(securityScheme: SecuritySchemes.Bearer); var app = builder.Build(); app.UseVersionableSwagger(); ``` -------------------------------- ### Sample Log Output Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.RequestResponseLogging/README.md Example of a structured JSON log entry capturing request and response details. ```json { "timestamp": "2025-01-15T10:30:45.123Z", "traceId": "0HMP3...", "durationMs": 12.45, "request": { "method": "POST", "path": "/api/demo/echo", "queryString": "", "headers": { "content-type": "application/json", "authorization": "Bear****1234" }, "body": "{\"message\":\"Hello\",\"repeatCount\":3}" }, "response": { "statusCode": 200, "headers": { "content-type": "application/json; charset=utf-8" }, "body": "{\"received\":{...},\"serverTime\":\"2025-01-15T10:30:45.135Z\"}" } } ``` -------------------------------- ### Add CSharpEssentials NuGet Packages Source: https://github.com/senrecep/csharpessentials/blob/main/README.MD Installs the core functional modules or individual packages for CSharpEssentials. ```bash # Core functional modules dotnet add package CSharpEssentials # Individual packages dotnet add package CSharpEssentials.Rules dotnet add package CSharpEssentials.Mediator ``` -------------------------------- ### URL-Safe GUID Utilities with CSharpEssentials.Core Source: https://context7.com/senrecep/csharpessentials/llms.txt Generate and parse GUIDs using URL-safe Base64 encoding for shorter string representations. Requires CSharpEssentials.Core. ```csharp // GUID utilities (Version 7 on .NET 9+, URL-safe Base64) Guid id = Guider.NewGuid(); string shortId = id.ToStringFromGuid(); // 22-char URL-safe Base64 Guid parsed = shortId.ToGuidFromString(); ``` -------------------------------- ### Structured Error Response Example Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.AspNetCore/Readme.MD An example of a structured ProblemDetails response conforming to RFC 9110, including detailed error information. ```json { "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1", "title": "Bad Request", "status": 400, "errors": [ { "code": "User.InvalidEmail", "description": "Email format is incorrect.", "type": "Validation" } ] } ``` -------------------------------- ### ASP.NET Core Application Setup with Versioned Endpoints Source: https://context7.com/senrecep/csharpessentials/llms.txt Builds the ASP.NET Core application, enables the exception handler, and sets up versioned endpoint groups. The `ResultEndpointFilter` is applied to specific routes. ```csharp var app = builder.Build(); app.UseExceptionHandler(); app.UseVersionableSwagger(); // Versioned endpoint group var usersGroup = app.CreateVersionedGroup("users", version: 1); usersGroup .MapGet("/{id}", (int id) => GetUser(id)) .AddEndpointFilter(); // On success → 200 OK { value } // On failure → 400 Bad Request: // { // "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1", // "title": "Bad Request", // "status": 400, // "errors": [ // { "code": "User.NotFound", "description": "User not found.", "type": "NotFound" } // ] // } ``` -------------------------------- ### ASP.NET Core API Versioning Setup Source: https://context7.com/senrecep/csharpessentials/llms.txt Configures API versioning for the ASP.NET Core application. This allows for managing multiple versions of your API endpoints. ```csharp // API versioning builder.Services.AddAndConfigureApiVersioning(); ``` -------------------------------- ### Use Pre-Configured JSON Options Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Json/Readme.MD Utilize the default pre-configured options for enhanced JSON serialization with System.Text.Json. This setup includes common configurations like camel casing and ignoring cycles. ```csharp using CSharpEssentials.Json; using System.Text.Json; var options = EnhancedJsonSerializerOptions.DefaultOptions; string json = JsonSerializer.Serialize(myObject, options); ``` -------------------------------- ### Combine Rules Using And - Func Array Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD This 'And' composition example uses an array of Func delegates, demonstrating direct usage without conversion. ```csharp // Using Func array — no .ToRule() needed at all Result andResult2 = RuleEngine.Evaluate( new Func[] { regionRule, CheckEmail }.And(), ctx); ``` -------------------------------- ### Configure Custom Logging Fields Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.RequestResponseLogging/Readme.MD Customize the logging behavior by specifying which fields to include in the logs. This example logs only the method, path, and response timing. ```csharp opt.LoggingOptions.LoggingFields = [ LogFields.Method, LogFields.Path, LogFields.ResponseTiming ]; ``` -------------------------------- ### Combine Rules Using Linear - Class Instances Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD The 'Linear' composition executes rules sequentially and stops on the first failure. This example uses an array of class instances. ```csharp // Class instances Result linear = RuleEngine.Evaluate( new IRule[] { new AgeRule(), new LicenseRule(repo) }.Linear(), ctx); ``` -------------------------------- ### Domain Exception Example: ProcessOrder Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Errors/Exceptions/Readme.MD Demonstrates using DomainException for single business rule violations like an empty order or invalid total amount. ```csharp public void ProcessOrder(Order order) { if (order.Items.Count == 0) { var error = Error.Validation( code: "ORDER_EMPTY", description: "Order must contain at least one item" ); throw new DomainException(error); } if (order.TotalAmount <= 0) { var error = Error.Validation( code: "INVALID_AMOUNT", description: "Order total amount must be greater than zero" ); throw new DomainException(error); } } ``` -------------------------------- ### Union with Three Types and Switch Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Any/Readme.MD Example of a union with three possible types (string, int, Exception) and using Switch for handling each case. ```csharp Any response = GetData(5); response.Switch( first: s => Console.WriteLine($"Success: {s}"), second: i => Console.WriteLine($"NotFound: {i}"), third: e => Console.WriteLine($"Error: {e.Message}")); ``` -------------------------------- ### NewGuid() Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Core/Guids/Readme.MD Generates a new GUID using .NET's Version 7 algorithm, optimized for database performance and sequential generation. ```APIDOC ## NewGuid() ### Description Creates a new GUID using .NET's Version 7 algorithm, which is optimized for database performance and sequential generation. ### Method ```csharp Guid newId = Guider.NewGuid(); ``` ``` -------------------------------- ### Combine Rules Using And - Class Instances Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD Compose rules using the 'And' operator to ensure all rules pass. This example uses an array of class instances. ```csharp // Using class instances Result andResult = RuleEngine.Evaluate( new IRuleBase[] { new AgeRule(), new LicenseRule(repo) }.And(), ctx); ``` -------------------------------- ### EF Core Domain Event Interceptor Setup Source: https://context7.com/senrecep/csharpessentials/llms.txt Registers a domain event publisher and the domain event interceptor. This allows for dispatching domain events automatically when entities are saved. ```csharp // Domain event interceptor services.AddSingleton(); services.AddSingleton(); ``` -------------------------------- ### ToStringFromGuid(Guid) Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Core/Guids/Readme.MD Converts a GUID to a URL-safe string format that is shorter and uses safe characters for URLs. ```APIDOC ## ToStringFromGuid(Guid) ### Description Converts a GUID to a URL-safe string format. The output is shorter than the standard GUID string (22 characters vs 36), URL-safe (uses '-' and '_' instead of '/' and '+'), has no padding characters, and is memory efficient using stack allocation. ### Method ```csharp Guid id = Guider.NewGuid(); string urlSafeString = Guider.ToStringFromGuid(id); // Example output: "Yx7A9bx0T0y2zKl3mN8pQw" ``` ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/senrecep/csharpessentials/blob/main/CONTRIBUTING.md Clone your fork of the repository and navigate into the project directory. ```bash git clone https://github.com/senrecep/CSharpEssentials.git cd CSharpEssentials ``` -------------------------------- ### Run Project Command Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.RequestResponseLogging/README.md Navigate to the project directory and run the .NET application. ```bash cd examples/Examples.RequestResponseLogging dotnet run ``` -------------------------------- ### Generate New Version 7 GUID Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Core/Guids/Readme.MD Creates a new GUID using .NET's Version 7 algorithm, optimized for database performance and sequential generation. ```csharp Guid newId = Guider.NewGuid(); ``` -------------------------------- ### Convert URL-Safe String to GUID Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Core/Guids/Readme.MD Converts a custom URL-safe string back to a GUID. This method handles the custom format efficiently using stack allocation and without heap allocations. ```csharp string urlSafeString = "Yx7A9bx0T0y2zKl3mN8pQw"; Guid id = Guider.ToGuidFromString(urlSafeString); ``` -------------------------------- ### Convert GUID to URL-Safe String Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Core/Guids/Readme.MD Converts a GUID to a URL-safe string format that is shorter (22 characters), URL-safe, and memory efficient using stack allocation. Avoids heap allocations. ```csharp Guid id = Guider.NewGuid(); string urlSafeString = Guider.ToStringFromGuid(id); // Example output: "Yx7A9bx0T0y2zKl3mN8pQw" ``` -------------------------------- ### Running the ASP.NET Core Project Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.AspNetCore/README.md Navigate to the project directory and run the application using the .NET CLI. Access the API documentation via Swagger UI. ```bash cd examples/Examples.AspNetCore dotnet run ``` -------------------------------- ### ToGuidFromString(string) Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Core/Guids/Readme.MD Converts a URL-safe string representation back into a GUID. ```APIDOC ## ToGuidFromString(string) ### Description Converts a URL-safe string back to a GUID. This method handles the custom URL-safe format, uses stack allocation for better performance, and efficiently processes the input without heap allocations. ### Method ```csharp string urlSafeString = "Yx7A9bx0T0y2zKl3mN8pQw"; Guid id = Guider.ToGuidFromString(urlSafeString); ``` ``` -------------------------------- ### Pattern Matching with Match and Switch Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Any/Readme.MD Shows how to use Match for returning a value and Switch for executing actions based on the union's active type. ```csharp Any result = ParseInput("123"); string output = result.Match( first: str => $"String: {str}", second: num => $"Number: {num}"); result.Switch( first: str => Console.WriteLine("It's a string"), second: num => Console.WriteLine("It's a number")); ``` -------------------------------- ### Create Generic and Non-Generic Results Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Results/Readme.MD Demonstrates how to create successful results with and without a value. Implicit conversions from values and errors are supported. ```csharp using CSharpEssentials.ResultPattern; using CSharpEssentials.Errors; public Result GetUser(int id) { if (id <= 0) return Error.Validation("Id.Invalid", "ID must be positive."); return 42; // implicit conversion to Result } public Result DeleteUser(int id) { if (id <= 0) return Error.Validation("Id.Invalid", "ID must be positive."); return Result.Success(); } ``` -------------------------------- ### Stage and Commit Changes Source: https://github.com/senrecep/csharpessentials/blob/main/CONTRIBUTING.md Stage all your changes and commit them with a descriptive message. ```bash git add . git commit -m "Description of your changes" ``` -------------------------------- ### DI Registration for Testable DateTime with CSharpEssentials.Time Source: https://context7.com/senrecep/csharpessentials/llms.txt Register `TimeProvider` and `IDateTimeProvider` for dependency injection. Use `TimeProvider.System` for production. ```csharp using CSharpEssentials.Time; using Microsoft.Extensions.Time.Testing; using FluentAssertions; // DI registration builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddSingleton(); ``` -------------------------------- ### Enhanced Validation Example: ValidateUser Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Errors/Exceptions/Readme.MD Illustrates using EnhancedValidationException to collect and report multiple validation errors for a UserDto. ```csharp public void ValidateUser(UserDto user) { var errors = new List(); if (string.IsNullOrEmpty(user.Email)) { errors.Add(Error.Validation( code: "EMAIL_REQUIRED", description: "Email is required" )); } if (user.Password?.Length < 8) { errors.Add(Error.Validation( code: "PASSWORD_TOO_SHORT", description: "Password must be at least 8 characters" )); } if (errors.Any()) { throw new EnhancedValidationException(errors.ToArray()); } } ``` -------------------------------- ### Define Rule Using Class - LicenseRule Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD This class-based rule demonstrates dependency injection by requiring an ILicenseRepository to validate a license ID. ```csharp public sealed class LicenseRule : IRule { private readonly ILicenseRepository _repo; public LicenseRule(ILicenseRepository repo) => _repo = repo; public Result Evaluate(UserContext ctx, CancellationToken ct = default) => _repo.IsValid(ctx.LicenseId) ? Result.Success() : Error.Validation("License.Invalid", "License not found."); } ``` -------------------------------- ### String Enum Serialization Example Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Json/Readme.MD Serialize enums as strings using the `[StringEnum]` attribute. Enums without this attribute will serialize as integers. ```csharp using CSharpEssentials.Enums; [StringEnum] public enum Status { Active, Inactive } public enum Level { Low, High } var data = new { S = Status.Active, L = Level.High }; string json = data.ConvertToJson(); // {"s":"active","l":1} ``` -------------------------------- ### Chain Operations with Then Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Results/Readme.MD Illustrates chaining operations using the `Then` extension method. This allows sequential execution of functions where each step can return a Result. ```csharp Result Parse(string input) { if (int.TryParse(input, out int n)) return n; return Error.Validation("Parse", "Not a number."); } Result result = Parse("5") .Then(n => n * 2) .Then(n => n + 10); ``` -------------------------------- ### Combine Multiple Results with And Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Results/Readme.MD Shows how to combine multiple Results using `Result.And`. The combined result is successful only if all input results are successful. ```csharp var r1 = Result.Success(); var r2 = Result.Success(); var r3 = Result.Failure(Error.NotFound()); Result combined = Result.And(r1, r2, r3); // Failure ``` -------------------------------- ### Conditional Branching with Rules Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD Demonstrates different ways to implement conditional logic using the RuleEngine.If method. Supports class instances, lambda expressions, and boolean properties for conditions. ```csharp Result conditional = RuleEngine.If( new AgeRule(), success: new GrantAccessRule(), failure: new DenyAccessRule(), ctx); ``` ```csharp Result conditional2 = RuleEngine.If( (UserContext c) => c.Age >= 18 ? Result.Success() : Error.Validation("Age.Underage", "Must be at least 18."), success: c => Result.Success(), failure: c => Error.Forbidden("Access.Denied", "Access denied."), ctx); ``` ```csharp Result conditional3 = RuleEngine.If( condition: ctx.IsAllowedRegion, success: new GrantAccessRule(), failure: new DenyAccessRule(), ctx); ``` -------------------------------- ### Cursor-Based Pagination with PaginateAsync Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.EntityFrameworkCore/README.md Demonstrates high-performance cursor-based pagination suitable for large datasets or infinite scrolling. The `PaginateAsync` method uses a cursor to efficiently retrieve the next set of items. ```csharp var request = new CursorPaginationRequest { Limit = 20, Cursor = lastSeenDate }; var response = await _dbContext.Logs .PaginateAsync(request, cursorSelector: x => x.CreatedAt); // response.NextCursor -> Continue from here ``` -------------------------------- ### Result Pattern for Product Retrieval Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.AspNetCore/README.md Demonstrates returning a Result to represent success or failure, avoiding exceptions for expected outcomes like a missing product. ```csharp public Result GetById(Guid id) { var product = _products.FirstOrDefault(p => p.Id == id); if (product is null) return Error.NotFound($"Product with id '{id}' was not found."); // Expected failure return Result.Success(product); } ``` -------------------------------- ### Result Chaining for Business Rule Composition Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.AspNetCore/README.md Illustrates composing multiple validation and business logic steps using the `Then()` extension method on Result. The chain short-circuits on the first failure. ```csharp return _productService.GetById(productId) .Then(product => ValidateQuantity(product, quantity)) // Must have stock .Then(product => ReserveStock(product, quantity)) // Must be under $10k .Then(product => CreateOrder(product, quantity)); // Persist order ``` -------------------------------- ### Define Rule Using Func Field - Region Rule Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD Define reusable rules as Func delegates. This example creates a rule to check if the user is in an allowed region. ```csharp // Defined once, reused anywhere Func regionRule = ctx => ctx.IsAllowedRegion ? Result.Success() : Error.Forbidden("Region.Blocked", "Not available in your region."); ``` -------------------------------- ### Enum to String Conversion Example Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.EntityFrameworkCore/README.md Illustrates how enum values are stored as human-readable snake_case strings in the database, making the schema self-documenting and avoiding the use of magic numbers. ```plaintext Enum Value | Stored in DB ------------|-------------- `ProductCategory.Electronics` | `"electronics"` `ProductCategory.Clothing` | `"clothing"` `ProductCategory.Food` | `"food"` ``` -------------------------------- ### Pattern Matching with Maybe Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Maybe/Readme.MD Demonstrates using the Match method to handle both the 'some' (value present) and 'none' (value absent) cases of a Maybe instance. This provides a clear way to execute different logic based on the presence of a value. ```csharp FindUser(1).Match( some: user => Console.WriteLine($"Found: {user.Name}"), none: () => Console.WriteLine("Not found")); ``` -------------------------------- ### Define Rule Using Inline Lambda Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD For simple, one-off checks, define rules directly as inline lambdas at the call site. This example checks the user's age. ```csharp Result result = RuleEngine.Evaluate( (UserContext ctx) => ctx.Age >= 18 ? Result.Success() : Error.Validation("Age.Underage", "Must be at least 18."), userCtx); ``` -------------------------------- ### Traditional Exception-Based Product Retrieval Source: https://github.com/senrecep/csharpessentials/blob/main/examples/Examples.AspNetCore/README.md Illustrates a conventional approach to data retrieval where exceptions are thrown for expected error conditions like a missing resource. ```csharp public Product GetById(Guid id) { var product = _db.Products.Find(id); if (product == null) throw new NotFoundException($ ``` -------------------------------- ### Combine Rules Using Linear - Func Chaining with Next Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD Chain Func delegates using the '.Next()' extension method to create a linear execution pipeline that stops on the first failure. ```csharp // Func chaining with .Next() — reads like a pipeline Result pipeline = RuleEngine.Evaluate( ((Func)CheckEmail) .Next(regionRule) .Next(c => c.Age >= 18 ? Result.Success() : Error.Validation("Age.Underage", "Must be at least 18.")), ctx); ``` -------------------------------- ### Skip Request Logging with Attribute Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.RequestResponseLogging/Readme.MD Use the `[SkipRequestLogging]` attribute on an endpoint to prevent request logging for that specific endpoint, for example, to avoid logging sensitive data like passwords. ```csharp using CSharpEssentials.RequestResponseLogging.Attributes; [HttpPost("login")] [SkipRequestLogging] // Don't log passwords public IActionResult Login(LoginRequest request) { /* ... */ } ``` -------------------------------- ### Source-Generated Enum Extensions Source: https://context7.com/senrecep/csharpessentials/llms.txt Annotate enums with [StringEnum] to get compile-time generated extension methods for string conversion, casing, parsing, and metadata access. These are used by CSharpEssentials.Json and CSharpEssentials.EntityFrameworkCore. ```csharp using CSharpEssentials.Enums; [StringEnum] public enum UserStatus { Active, Inactive, Suspended } UserStatus s = UserStatus.Active; // Generated instance methods s.ToOptimizedString(); // "Active" s.ToSnakeCase(); // "active" s.ToKebabCase(); // "active" s.ToLowerCase(); // "active" s.ToUpperCase(); // "ACTIVE" s.AsUnderlyingType(); // 0 // Generated constants UserStatusExtensions.ActiveSnakeCase; // "active" UserStatusExtensions.ActiveKebabCase; // "active" // Lookup helpers UserStatusExtensions.IsDefined("Active"); // true UserStatusExtensions.TryParse("Inactive", out var v); // true, v = Inactive UserStatus parsed = UserStatusExtensions.Parse("Suspended"); // UserStatus.Suspended // Metadata string[] names = UserStatusExtensions.GetNames(); // ["Active", "Inactive", "Suspended"] UserStatus[] vs = UserStatusExtensions.GetValues(); // [Active, Inactive, Suspended] ``` -------------------------------- ### Convert Maybe to Result and Vice Versa Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Maybe/Readme.MD Illustrates converting a Maybe to a Result with a specified error, and converting a Result back to a Maybe. This facilitates interoperability between the two types. ```csharp Maybe order = FindOrder(1); Result result = order.ToResult(Error.NotFound("Order.Missing", "Order not found.")); // Result -> Maybe Result result2 = Result.Success(new Order()); Maybe maybe = result2.AsMaybe(); ``` -------------------------------- ### Perform HTTP Requests as Result Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Http/Readme.MD Use extension methods like GetFromJsonAsResultAsync and PostAsJsonAsResultAsync to perform HTTP requests and get results as a Result type, avoiding exceptions for HTTP errors. ```csharp using CSharpEssentials.Http; using CSharpEssentials.ResultPattern; HttpClient client = new() { BaseAddress = new Uri("https://api.example.com") }; Result user = await client.GetFromJsonAsResultAsync(new Uri("/users/1", UriKind.Relative)); Result created = await client.PostAsJsonAsResultAsync( new Uri("/users", UriKind.Relative), new { Name = "Alice", Age = 30 }); Result deleted = await client.DeleteAsResultAsync(new Uri("/users/1", UriKind.Relative)); ``` -------------------------------- ### Quick JSON Extension Methods Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Json/Readme.MD Leverage extension methods for quick JSON serialization and deserialization. These methods simplify common JSON operations. ```csharp var user = new { Name = "Alice", Age = 30 }; string json = user.ConvertToJson(); var parsed = json.ConvertFromJson(); JsonDocument doc = json.ConvertToJsonDocument(); ``` -------------------------------- ### Integrate Polly for Resilience Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Http/Readme.MD Apply Polly resilience policies like retries and timeouts to HTTP requests by creating a pipeline and executing requests through it. ```csharp var pipeline = HttpClientResilienceExtensions.CreateResiliencePipeline( maxRetryAttempts: 3, timeout: TimeSpan.FromSeconds(30)); Result result = await pipeline.ExecuteAsResultAsync(async token => await client.GetFromJsonAsResultAsync(new Uri("/users/1"), cancellationToken: token)); ``` -------------------------------- ### Define Rule Using Class - AgeRule Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD Implement IRule for rules requiring dependencies, state, or clear naming. This example defines a rule to check if a user's age is at least 18. ```csharp public sealed class AgeRule : IRule { public Result Evaluate(UserContext ctx, CancellationToken ct = default) => ctx.Age >= 18 ? Result.Success() : Error.Validation("Age.Underage", "Must be at least 18."); } ``` -------------------------------- ### Convert Maybe to Result in C# Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials/Readme.MD Demonstrates converting a Maybe to a Result with a NotFound error if the user is missing. Ensure CSharpEssentials.Maybe and CSharpEssentials.ResultPattern are imported. ```csharp using CSharpEssentials.Maybe; using CSharpEssentials.ResultPattern; Maybe maybe = FindUser(1); Result result = maybe.ToResult(Error.NotFound("User.Missing", "User not found.")); ``` -------------------------------- ### LINQ Queries with Maybe Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Maybe/Readme.MD Shows how to use LINQ query syntax with Maybe for complex filtering and selection. This enables expressive data retrieval, similar to querying collections. ```csharp Maybe tracking = from user in FindUser(1) from order in FindOrder(user.Id) where order.Amount > 100 select order.TrackingNumber; ``` -------------------------------- ### Match Result for Success or Error Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Results/Readme.MD Demonstrates using the `Match` method to handle both the success and error cases of a Result, providing specific actions for each. ```csharp string message = GetUser(10).Match( onSuccess: user => $ ``` -------------------------------- ### Implement OrderService with IDateTimeProvider Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Time/Readme.MD Inject IDateTimeProvider into your service to access current time properties for creating domain objects. ```csharp using CSharpEssentials.Time; public class OrderService(IDateTimeProvider time) { public Order CreateOrder() { return new Order { CreatedAt = time.UtcNow, CreatedDate = time.UtcNowDate }; } } ``` -------------------------------- ### Combine Rules Using And - Mixed Types Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Rules/Readme.MD Demonstrates composing rules using a mix of class instances, Func variables, and lambdas with the 'And' operator. ```csharp // Mixed: class + lambda Result andResult3 = RuleEngine.Evaluate( new IRuleBase[] { new AgeRule(), regionRule.ToRule(), ((Func)(c => c.HasLicense ? Result.Success() : Error.Validation("License.Missing", "License required."))).ToRule() }.And(), ctx); ``` -------------------------------- ### Clone Collections using Extension Methods Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Clone/Readme.MD Clone all items in an IEnumerable or IQueryable collection using the provided extension methods. The Clone() method on collections creates a new collection with cloned items. ```csharp var users = new List { new() { Name = "Alice" }, new() { Name = "Bob" } }; // Clone all items var cloned = users.Clone().ToList(); // Clone from IQueryable IQueryable query = users.AsQueryable(); var clonedQuery = query.Clone(); ``` -------------------------------- ### Task Helpers with CSharpEssentials.Core Source: https://context7.com/senrecep/csharpessentials/llms.txt Simplify asynchronous operations with cancellation support and easy conversion of values to tasks. Requires CSharpEssentials.Core. ```csharp // Task helpers await SomeTask().WithCancellation(cts.Token); Task task = "hello".AsTask(); ValueTask vt = "hello".AsValueTask(); ``` -------------------------------- ### Configure Dependency Injection for TimeProvider Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Time/Readme.MD Register TimeProvider and IDateTimeProvider as singletons in your application's service collection. ```csharp builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddSingleton(); ``` -------------------------------- ### Create a Union with Implicit Conversion Source: https://github.com/senrecep/csharpessentials/blob/main/CSharpEssentials.Any/Readme.MD Demonstrates creating a union of string and int. Values can be implicitly converted to the union type. ```csharp using CSharpEssentials.Any; Any ParseInput(string input) { if (int.TryParse(input, out int n)) return n; // implicit to Any return input; } ```