### HTTP GET Request Example (http) Source: https://github.com/digvijay/sannr/blob/main/samples/README.md An example of an HTTP GET request to the '/weatherforecast' endpoint. This demonstrates how parameters like 'days', 'location', 'units', and 'includeDetails' are used and validated. ```http GET /weatherforecast?days=7&location=NewYork&units=fahrenheit&includeDetails=true ``` -------------------------------- ### Install Sannr NuGet Package Source: https://github.com/digvijay/sannr/blob/main/docs/GETTING_STARTED.md Add the Sannr NuGet package to your .NET project using the dotnet CLI. This is the first step to enable compile-time validation and sanitization. ```bash dotnet add package Sannr ``` -------------------------------- ### FluentValidation to Sannr Migration Example Source: https://github.com/digvijay/sannr/blob/main/docs/guide/migration.md Illustrates the conversion process from a FluentValidation validator class to Sannr attributes placed directly on model properties. It shows the generated guidance comments and TODO items. ```csharp using Sannr; // TODO: Convert to Sannr attributes on model properties // Original FluentValidation: RuleFor(x => x.Name).NotEmpty().Length(2, 50); /* * MIGRATION NOTES: * 1. Move validation rules from validator classes to model properties as attributes * 2. Remove this validator class after migrating all rules */ ``` -------------------------------- ### Migration Tools CLI - Installation & Execution Source: https://github.com/digvijay/sannr/blob/main/docs/MIGRATION_TOOLS.md Instructions on how to install and execute the Sannr Migration Tools CLI. ```APIDOC ## Installation & Execution The migration CLI is available as a dotnet global tool. Install it using: ```bash dotnet tool install -g Sannr.Cli ``` Once installed, you can run it using the `sannr` command: ```bash sannr [command] [options] ``` Alternatively, you can run it without installing from the repository root: ```bash dotnet run --project src/Sannr.Cli -- [command] [options] ``` ``` -------------------------------- ### FluentValidation to Sannr Migration Guidance Example C# Source: https://github.com/digvijay/sannr/blob/main/docs/MIGRATION_TOOLS.md This C# code illustrates the output of the `fluentvalidation` command, showing how original FluentValidation rules are commented out and replaced with migration guidance. It includes TODO comments and links to migration guides, facilitating the manual conversion process. ```csharp public class UserValidator : AbstractValidator { public UserValidator() { RuleFor(x => x.Name) .NotEmpty() .Length(2, 50); RuleFor(x => x.Email) .NotEmpty() .EmailAddress(); RuleFor(x => x.Age) .GreaterThan(0) .LessThan(150); } } ``` ```csharp using Sannr; // TODO: Convert to Sannr attributes on model properties // Original FluentValidation: RuleFor(x => x.Name).NotEmpty().Length(2, 50); // Original FluentValidation: RuleFor(x => x.Email).NotEmpty().EmailAddress(); // Original FluentValidation: RuleFor(x => x.Age).GreaterThan(0).LessThan(150); // See migration guide: https://github.com/your-repo/sannr/migration /* * MIGRATION NOTES: * 1. Move validation rules from validator classes to model properties as attributes * 2. Convert RuleFor(x => x.Name).NotEmpty() to [Required] on Name property * 3. Convert RuleFor(x => x.Name).Length(2, 50) to [StringLength(50)] on Name property * 4. Convert RuleFor(x => x.Email).EmailAddress() to [EmailAddress] on Email property * 5. Convert RuleFor(x => x.Age).GreaterThan(0) to [Range(1, int.MaxValue)] on Age property * 6. Remove this validator class after migrating all rules */ ``` -------------------------------- ### Run Complete Sannr Demo Suite (Bash) Source: https://github.com/digvijay/sannr/blob/main/samples/README.md Executes the entire Sannr demo suite using the .NET CLI. This command launches the AppHost, which in turn starts all associated services. ```bash dotnet run --project Sannr.Demo.AppHost ``` -------------------------------- ### Install Sannr Migration CLI Source: https://github.com/digvijay/sannr/blob/main/docs/MIGRATION_TOOLS.md Installs the Sannr CLI as a global dotnet tool, enabling the use of the 'sannr' command for migration tasks. This is the primary method for making the CLI readily available. ```bash dotnet tool install -g Sannr.Cli ``` -------------------------------- ### Complete Example: User Registration API Source: https://github.com/digvijay/sannr/blob/main/docs/MINIMAL_API_INTEGRATION.md A full ASP.NET Core Minimal API example demonstrating user registration with Sannr validation. It includes service registration, model definition with attributes, and an endpoint that uses Validated for request validation. ```csharp using Sannr.AspNetCore; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSannr(); var app = builder.Build(); public class UserRegistration { [Required, EmailAddress] public string? Email { get; set; } [Required, StringLength(100, MinimumLength = 8)] public string? Password { get; set; } [Required, Compare("Password")] public string? ConfirmPassword { get; set; } [Range(13, 120)] public int Age { get; set; } } app.MapPost("/register", async (Validated registration) => { if (!registration.IsValid) { return registration.ToBadRequestResult("Registration failed due to invalid data"); } var user = registration.Value; // Create user account... var userId = await userService.CreateUserAsync(user); return Results.Created($"/users/{userId}", new { UserId = userId }); }); app.Run(); ``` -------------------------------- ### Sannr Sanitization Example Source: https://github.com/digvijay/sannr/blob/main/docs/GETTING_STARTED.md Apply Sannr's `Sanitize` attribute to properties to automatically clean data. Options include trimming whitespace and converting to uppercase. ```csharp [Sanitize(Trim = true, ToUpper = true)] public string ProductCode { get; set; } ``` -------------------------------- ### DataAnnotations to Sannr Migration Example (C#) Source: https://github.com/digvijay/sannr/blob/main/src/Sannr.Cli/README.md Illustrates the transformation of a C# class using DataAnnotations to an equivalent structure using Sannr attributes. ```csharp using System.ComponentModel.DataAnnotations; public class User { [Required] [StringLength(100, MinimumLength = 2)] public string Name { get; set; } [EmailAddress] public string Email { get; set; } } ``` ```csharp using Sannr; public class User { [Required] [StringLength(100, MinimumLength = 2)] public string Name { get; set; } [EmailAddress] public string Email { get; set; } } ``` -------------------------------- ### Sannr CLI Usage Examples Source: https://github.com/digvijay/sannr/blob/main/src/Sannr.Cli/README.md Demonstrates common Sannr CLI commands for analyzing existing validation code and migrating from DataAnnotations or FluentValidation to Sannr attributes or fluent API. ```bash # Analyze your existing validation code sannr analyze --input ./src # Migrate from DataAnnotations sannr dataannotations --input ./Models --output ./Models # Migrate from FluentValidation (to attributes) sannr fluentvalidation --input ./Validators --output ./Models --target attribute # Migrate from FluentValidation (to Sannr fluent API) sannr fluentvalidation --input ./Validators --output ./Validators --target fluent ``` -------------------------------- ### Install Swashbuckle.AspNetCore Dependency Source: https://github.com/digvijay/sannr/blob/main/docs/OPENAPI_INTEGRATION.md This command installs the Swashbuckle.AspNetCore NuGet package, which is required for Swagger integration in ASP.NET Core applications. ```bash dotnet add package Swashbuckle.AspNetCore ``` -------------------------------- ### FluentValidation to Sannr Attribute Migration Example (C#) Source: https://github.com/digvijay/sannr/blob/main/src/Sannr.Cli/README.md Shows how FluentValidation rules in a validator class are converted into Sannr attributes applied directly to the model properties. ```csharp public class UserValidator : AbstractValidator { public UserValidator() { RuleFor(x => x.Name).NotEmpty().Length(2, 100); RuleFor(x => x.Email).EmailAddress(); } } ``` ```csharp using Sannr; public partial class User { [Required] [StringLength(100, MinimumLength = 2)] public string Name { get; set; } [EmailAddress] public string Email { get; set; } } ``` -------------------------------- ### FluentValidation to Sannr Fluent API Migration Example (C#) Source: https://github.com/digvijay/sannr/blob/main/src/Sannr.Cli/README.md Demonstrates migrating FluentValidation rules to Sannr's fluent API structure, maintaining a separate validator configuration class. ```csharp public class UserValidator : AbstractValidator { public UserValidator() { RuleFor(x => x.Name).NotEmpty().Length(2, 100); RuleFor(x => x.Email).EmailAddress(); } } ``` ```csharp using Sannr; public partial class UserValidator : ValidatorConfig { public override void Configure() { RuleFor(x => x.Name).NotEmpty().Length(2, 100); RuleFor(x => x.Email).Email(); } } ``` -------------------------------- ### Run Sannr CLI Without Installation Source: https://github.com/digvijay/sannr/blob/main/docs/MIGRATION_TOOLS.md Executes Sannr migration commands directly from the repository root without global installation. This is useful for testing or when global installation is not desired. ```bash dotnet run --project src/Sannr.Cli -- [command] [options] ``` -------------------------------- ### Run Sannr CLI Commands Source: https://github.com/digvijay/sannr/blob/main/docs/MIGRATION_TOOLS.md Executes Sannr migration commands using the globally installed tool. Replace '[command]' with 'analyze', 'dataannotations', or 'fluentvalidation' and '[options]' with specific parameters for the chosen command. ```bash sannr [command] [options] ``` -------------------------------- ### Sannr CLI General Options Source: https://github.com/digvijay/sannr/blob/main/docs/guide/migration.md Provides an overview of common Sannr CLI commands for analyzing validation code and migrating DataAnnotations, including optional parameters like output directory and dry-run. ```bash # Analyze validation code dotnet run --project Sannr.Cli -- analyze --input [--type auto|fluentvalidation|dataannotations] # Migrate DataAnnotations dotnet run --project Sannr.Cli -- dataannotations --input --output [--overwrite] [--dry-run] ``` -------------------------------- ### C# Metric Prefix Configuration Example Source: https://github.com/digvijay/sannr/blob/main/docs/PERFORMANCE_MONITORING.md This C# code snippet demonstrates how to configure a descriptive prefix for metrics in the Sannr options. Using a descriptive prefix helps in organizing and identifying metrics in monitoring systems. ```csharp // Good options.MetricsPrefix = "ecommerce_user_validation"; // Avoid options.MetricsPrefix = "metrics"; ``` -------------------------------- ### Project File Configuration for Native AOT (XML) Source: https://github.com/digvijay/sannr/blob/main/docs/TECHNICAL_SUMMARY.md An example of a .NET project file (`.csproj`) configured for Native AOT compilation. It includes setting the target framework and enabling AOT compatibility. ```xml net8.0 true ``` -------------------------------- ### Sannr Client-Side Validation Generation Source: https://github.com/digvijay/sannr/blob/main/docs/GETTING_STARTED.md Generate client-side validation rules, for example, in TypeScript, by decorating a model with `GenerateClientValidators`. The rules can be accessed as static properties. ```csharp [GenerateClientValidators(Language = ClientValidationLanguage.TypeScript)] public partial class LoginForm { ... } ``` -------------------------------- ### Sannr Conditional Validation Example Source: https://github.com/digvijay/sannr/blob/main/docs/GETTING_STARTED.md Implement conditional validation using the `RequiredIf` attribute. This makes a property required only when a specified condition on another property is met. ```csharp public bool HasCustomShipping { get; set; } [RequiredIf(nameof(HasCustomShipping), true)] public string? ShippingAddress { get; set; } ``` -------------------------------- ### Running the Sannr API Demo Source: https://github.com/digvijay/sannr/blob/main/samples/Sannr.ConsoleDemo/README.md Instructions to run the Sannr API demo, which includes all Sannr features and serves as a fully working example without web dependencies. This command navigates to the AppHost directory and executes the .NET application. ```bash cd ../Sannr.Demo.AppHost dotnet run ``` -------------------------------- ### Navigate to Demo Directory (Bash) Source: https://github.com/digvijay/sannr/blob/main/samples/README.md Changes the current directory to the 'samples' folder where the Sannr demo resides. This is a prerequisite for running the demo. ```bash cd samples ``` -------------------------------- ### Customize Sannr Options in Program.cs Source: https://github.com/digvijay/sannr/blob/main/docs/GETTING_STARTED.md Configure Sannr's behavior, such as enabling performance metrics or enhanced error responses, by passing an options action to the `AddSannr()` method in Program.cs. ```csharp builder.Services.AddSannr(options => { // 1. Performance Monitoring options.EnableMetrics = true; // Enables System.Diagnostics.Metrics options.MetricsPrefix = "myapp_sannr"; // Custom prefix for metric names // 2. Enhanced Error Responses // Returns detailed error objects including correlation IDs and timing metadata options.EnableEnhancedErrorResponses = true; // 3. Metadata Control options.IncludeValidationRuleMetadata = true; // Includes which rule failed in the response options.IncludeValidationDuration = true; // Includes 'durationMs' in the response }); ``` -------------------------------- ### Phased Migration Example Bash Source: https://github.com/digvijay/sannr/blob/main/docs/MIGRATION_TOOLS.md This bash script demonstrates a phased migration approach for large codebases using the Sannr CLI. It shows how to migrate DataAnnotations and FluentValidation for a specific module, such as user management, in separate steps. ```bash # Phase 1: User management sannr dataannotations --input ./UserModels --output ./UserModels sannr fluentvalidation --input ./UserValidators --output ./UserValidators --target attribute ``` -------------------------------- ### Configure Sannr in Program.cs Source: https://github.com/digvijay/sannr/blob/main/docs/GETTING_STARTED.md Register Sannr services and enable validation for API routes in your ASP.NET Core application's Program.cs file. This sets up automatic request validation and sanitization. ```csharp using Sannr; using Sannr.AspNetCore; var builder = WebApplication.CreateBuilder(args); // 1. Register Sannr - this finds and registers all generated validators builder.Services.AddSannr(); var app = builder.Build(); // 2. Enable Sannr validation for your API group or specific endpoints // This automatically validates and sanitizes incoming requests var api = app.MapGroup("/api").WithSannrValidation(); api.MapPost("/users", (UserDto user) => { // If you reach here, 'user' is already validated and sanitized! return Results.Ok(user); }); app.Run(); ``` -------------------------------- ### Define User DTO with Sannr Attributes Source: https://github.com/digvijay/sannr/blob/main/docs/GETTING_STARTED.md Create a partial class for your data transfer object (DTO) and decorate its properties with Sannr validation and sanitization attributes. Ensure the class is marked as `partial` for source generation. ```csharp using Sannr; namespace MyApp.Models; public partial class UserDto { [Required(ErrorMessage = "Username is mandatory")] [StringLength(50, MinimumLength = 3)] [Sanitize(Trim = true)] public string Username { get; set; } = string.Empty; [Required] [EmailAddress] [Sanitize(ToLower = true)] public string Email { get; set; } = string.Empty; [Range(18, 99)] public int Age { get; set; } } ``` -------------------------------- ### Migration from Custom Validators to Sannr Attributes Source: https://github.com/digvijay/sannr/blob/main/docs/BUSINESS_RULE_VALIDATORS.md Provides a clear before-and-after example of migrating from custom validation methods to Sannr's declarative attributes. It shows how a custom validator for future dates can be replaced by the simpler `[FutureDate]` attribute, streamlining the validation setup. ```csharp **Before:** ```csharp [CustomValidator(typeof(MyValidators), nameof(MyValidators.ValidateFutureDate))] public DateTime DeliveryDate { get; set; } public static class MyValidators { public static ValidationResult ValidateFutureDate(DateTime date) { return date > DateTime.Now ? ValidationResult.Success() : ValidationResult.Error("Date must be in the future"); } } ``` **After:** ```csharp [FutureDate] public DateTime DeliveryDate { get; set; } ``` ``` -------------------------------- ### Product Creation API Source: https://github.com/digvijay/sannr/blob/main/samples/README.md Creates a new product with specified details. Validates file extensions, decimal ranges, and business rules. ```APIDOC ## POST /api/products ### Description Creates a new product with specified details. Validates file extensions, decimal ranges, and business rules. ### Method POST ### Endpoint /api/products ### Parameters #### Request Body - **name** (string) - Required - The name of the product. - **description** (string) - Optional - A description of the product. - **price** (number) - Required - The price of the product. - **stockQuantity** (integer) - Required - The current stock quantity of the product. - **category** (string) - Optional - The category the product belongs to. - **imageFileName** (string) - Optional - The filename of the product image. - **isFeatured** (boolean) - Optional - Indicates if the product is featured. ### Request Example ```json { "name": "Wireless Headphones", "description": "High-quality wireless headphones", "price": 199.99, "stockQuantity": 50, "category": "Electronics", "imageFileName": "headphones.jpg", "isFeatured": true } ``` ### Response #### Success Response (201 Created) - **productId** (string) - The unique identifier of the newly created product. - **message** (string) - Indicates successful product creation. #### Response Example ```json { "productId": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "message": "Product created successfully" } ``` ``` -------------------------------- ### Generated Shadow Type Example (C#) Source: https://github.com/digvijay/sannr/blob/main/docs/STATIC_REFLECTION.md Illustrates the C# code generated by Sannr for a shadow type, demonstrating direct property accessors, PII flags, and optimized deep cloning logic. ```csharp // Generated by Sannr public static class UserShadow { public static int GetId(User instance) => instance.Id; public static void SetId(User instance, int value) => instance.Id = value; public static bool IsEmailPii => true; public static User DeepClone(User source) { if (source == null) return null; var clone = new User { Id = source.Id, Email = source.Email }; if (source.Addresses != null) { clone.Addresses = new List
(source.Addresses.Count); foreach (var item in source.Addresses) { clone.Addresses.Add(AddressShadow.DeepClone(item)); } } return clone; } } ``` -------------------------------- ### Example Enhanced Error Response (JSON) Source: https://github.com/digvijay/sannr/blob/main/README.md An example of an enhanced error response adhering to RFC 7807 Problem Details. This response includes correlation IDs, validation rule metadata, model type, timestamps, and performance metrics. ```json { "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "correlationId": "550e8400-e29b-41d4-a716-446655440000", "modelType": "UserRegistration", "timestamp": "2024-01-15T10:30:00.0000000Z", "validationDurationMs": 15.5, "errors": { "Email": ["The Email field is required."], "Age": ["The Age must be between 18 and 120."] }, "validationRules": { "Email": { "required": true, "email": true }, "Age": { "range": { "min": 18, "max": 120 } } } } ``` -------------------------------- ### Implement Range Attribute for Numeric Validation Source: https://context7.com/digvijay/sannr/llms.txt Illustrates how to use the `[Range]` attribute to validate that numeric properties fall within a specified minimum and maximum range. This example covers integer and double types, and includes an example of how validation errors are returned. ```csharp using Sannr; public partial class ValidationTestModel { [Range(18, 99, ErrorMessage = "Age must be between 18 and 99")] public int? Age { get; set; } [Range(0.01, 1000.00, ErrorMessage = "Price must be between $0.01 and $1000.00")] public double? Price { get; set; } [Display(Name = "Security Code")] [Range(1000, 9999, ErrorMessage = "Security code must be 4 digits")] public int? SecurityCode { get; set; } } // POST /api/test/validation // Request: { "age": 15, "price": 5000.00 } // Response 400: { "errors": { "Age": ["Age must be between 18 and 99"], "Price": ["Price must be between $0.01 and $1000.00"] } } ``` -------------------------------- ### Product Creation API Endpoint Source: https://github.com/digvijay/sannr/blob/main/samples/README.md Handles the creation of new products, accepting detailed product information in JSON format. Validates file extensions, decimal ranges, and business rules. ```http POST /api/products Content-Type: application/json { "name": "Wireless Headphones", "description": "High-quality wireless headphones", "price": 199.99, "stockQuantity": 50, "category": "Electronics", "imageFileName": "headphones.jpg", "isFeatured": true } ``` -------------------------------- ### Trigger Specific Validation Groups (C#) Source: https://github.com/digvijay/sannr/blob/main/docs/features/validation-groups.md Shows how to trigger specific validation groups when executing validation in C#. The example demonstrates validating a model with the 'Creation' group and default rules. It also includes an integration example with Minimal APIs using a `Validated` wrapper. ```csharp // Evaluate only the "Creation" rules AND default rules var result = validator.ValidateAsync(model, group: "Creation"); // Integration with Minimal APIs Wrapper: app.MapPost("/product", async (Validated request) => { // Evaluates with full group scoping automatically defined by your extension setup }); ``` -------------------------------- ### Sannr Generated Validation Code Example (C#) Source: https://github.com/digvijay/sannr/blob/main/samples/Sannr.ConsoleDemo/README.md Illustrates how Sannr generates validation rules directly from C# model attributes. The example shows a UserRegistration model with [Required] and [StringLength] attributes, and how properties like ValidationRulesTypeScript, ValidationRulesJavaScript, and ValidationRulesJson become automatically available at compile time. ```csharp // Your model with attributes public partial class UserRegistration { [Required] [StringLength(50, MinimumLength = 3)] public string? Username { get; set; } } // Automatically available at compile-time: var typescript = UserRegistration.ValidationRulesTypeScript; var javascript = UserRegistration.ValidationRulesJavaScript; var json = UserRegistration.ValidationRulesJson; ``` -------------------------------- ### Run Individual Sannr Services (Bash) Source: https://github.com/digvijay/sannr/blob/main/samples/README.md Provides commands to run individual services of the Sannr demo suite in separate terminals. This allows for focused testing or development of specific components. ```bash # Terminal 1: API Service dotnet run --project Sannr.Demo.ApiService # Terminal 2: Web Frontend dotnet run --project Sannr.Demo.Web # Terminal 3: App Host (Dashboard) dotnet run --project Sannr.Demo.AppHost ``` -------------------------------- ### Generic PII Extraction using Sannr Shadow Type Visitor in C# Source: https://github.com/digvijay/sannr/blob/main/docs/features/pii.md This C# example shows how to use the `Visit()` method provided by Sannr Shadow Types for dynamic PII extraction. This approach is suitable for scenarios like database insert mappers or log dump frameworks, automatically identifying PII with zero memory allocations during iteration. ```csharp UserShadow.Visit(user, (propertyName, value, isPii) => { if (isPii) { Console.WriteLine($"{propertyName}: [REDACTED]"); } else { Console.WriteLine($"{propertyName}: {value}"); } }); ``` -------------------------------- ### Custom Metrics Endpoint Source: https://github.com/digvijay/sannr/blob/main/samples/README.md Provides real-time validation statistics and performance data via a GET request. This endpoint is crucial for monitoring and observability. ```http GET /metrics/validation ``` -------------------------------- ### Url Attribute - C# Source: https://github.com/digvijay/sannr/blob/main/docs/features/validation-attributes.md Ensures that a string property is a well-formed URL. It specifically checks if the URL starts with 'http://' or 'https://'. ```csharp using Sannr; public class WebsiteInfo { [Url] public string PortfolioUrl { get; set; } } ``` -------------------------------- ### Supported Validation Attributes Overview Source: https://github.com/digvijay/sannr/blob/main/README.md Provides a summary of common validation attributes supported by Sannr, including their purpose and an example of their usage. ```markdown | Attribute | Description | |-----------|-------------| | `[Required]` | Ensures field is not null/empty | `[Required(ErrorMessage = "Name is required")]` | | `[StringLength]` | Validates string length | `[StringLength(50, MinimumLength = 2)]` | | `[Range]` | Numeric range validation | `[Range(18, 65)]` | | `[EmailAddress]` | Email format validation | `[EmailAddress]` | | `[Url]` | URL format validation | `[Url]` | | `[Phone]` | Phone number validation | `[Phone]` | | `[CreditCard]` | Credit card format | `[CreditCard]` | | `[FileExtensions]` | File extension validation | `[FileExtensions(Extensions = "pdf,docx")]` | | `[FutureDate]` | Date must be in future | `[FutureDate]` | | `[AllowedValues]` | Whitelist validation | `[AllowedValues("Active", "Inactive")]` | | `[RequiredIf]` | Conditional required | `[RequiredIf("IsEmployed", true)]` | | `[ConditionalRange]` | Conditional range | `[ConditionalRange("MinValue", "MaxValue")]` | ``` -------------------------------- ### CI/CD Integration for Sannr Validation Analysis Source: https://github.com/digvijay/sannr/blob/main/docs/MIGRATION_TOOLS.md Example GitHub Actions workflow for automating Sannr validation analysis as part of a CI/CD pipeline. This workflow checks out code, sets up .NET, runs the Sannr analysis, and comments on the Pull Request with results. ```yaml # .github/workflows/migrate-validation.yml name: Migrate Validation on: [push] jobs: analyze: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup .NET uses: actions/setup-dotnet@v3 with: dotnet-version: 8.0.x - name: Analyze Validation run: dotnet run --project src/Sannr.Cli -- analyze --input ./src - name: Comment PR uses: actions/github-script@v6 with: script: | // Post analysis results as PR comment ``` -------------------------------- ### URL Format Validation (C#) Source: https://github.com/digvijay/sannr/blob/main/docs/ATTRIBUTES.md The [Url] attribute validates that a string property is a well-formed URL, requiring it to start with 'http://' or 'https://'. ```csharp [Url] public string PortfolioUrl { get; set; } ``` -------------------------------- ### Migration Tools CLI - Overview Source: https://github.com/digvijay/sannr/blob/main/docs/MIGRATION_TOOLS.md Overview of the Sannr Migration Tools CLI, its purpose, and available commands. ```APIDOC ## Sannr Migration Tools CLI Sannr provides powerful CLI tools to help you migrate from other validation libraries to Sannr. The migration tools support both automated conversion (for DataAnnotations) and guided migration (for FluentValidation). ### Available Commands: - `analyze`: Analyze existing validation code to understand migration complexity. - `dataannotations`: Automatically migrate from DataAnnotations to Sannr. - `fluentvalidation`: Generate migration guidance for FluentValidation code. ``` -------------------------------- ### Profile and Optimize in C# Source: https://github.com/digvijay/sannr/blob/main/docs/PERFORMANCE_MONITORING.md This snippet provides guidance on how to profile and optimize a C# application. Performance profiling tools can identify bottlenecks in the application. This is a crucial step to avoid performance degradation. ```csharp // 3. Profile and optimize // Use performance profiling tools to identify bottlenecks ``` -------------------------------- ### GET /weatherforecast Source: https://github.com/digvijay/sannr/blob/main/samples/README.md Retrieves weather forecast data. Supports filtering by number of days, location, units, and inclusion of details. Validates input parameters for range, required fields, and enum types. ```APIDOC ## GET /weatherforecast ### Description Retrieves weather forecast data for a specified location and duration. This endpoint includes validation for the `days` parameter (1-14 days), ensures the `location` is provided, and supports different `units` (e.g., fahrenheit, celsius). ### Method GET ### Endpoint /weatherforecast ### Parameters #### Query Parameters - **days** (integer) - Required - The number of days for the forecast (1-14). - **location** (string) - Required - The location for which to retrieve the weather forecast. - **units** (string) - Optional - The units for temperature (e.g., 'fahrenheit', 'celsius'). Defaults to 'fahrenheit'. - **includeDetails** (boolean) - Optional - Whether to include detailed forecast information. Defaults to 'false'. ### Request Example ```http GET /weatherforecast?days=7&location=NewYork&units=fahrenheit&includeDetails=true ``` ### Response #### Success Response (200) - **date** (string) - The date of the forecast. - **temperatureC** (integer) - The temperature in Celsius. - **temperatureF** (integer) - The temperature in Fahrenheit. - **summary** (string) - A summary of the weather conditions. - **details** (object) - Additional detailed forecast information (if `includeDetails` is true). #### Response Example ```json [ { "date": "2023-10-27T10:00:00Z", "temperatureC": 15, "temperatureF": 59, "summary": "Partly cloudy", "details": { "precipitation": "0.1 inches", "wind": "10 mph" } } ] ``` ``` -------------------------------- ### C# Enable Metrics Configuration Example Source: https://github.com/digvijay/sannr/blob/main/docs/PERFORMANCE_MONITORING.md This C# code snippet shows how to conditionally enable metrics based on the application's environment. It's recommended to enable metrics in production and potentially disable them in development for performance reasons. ```csharp options.EnableMetrics = !builder.Environment.IsDevelopment(); ``` -------------------------------- ### Analyze Project for Trimming Boundaries with Sannr CLI Source: https://github.com/digvijay/sannr/blob/main/docs/api/cli.md The 'analyze' command scans your project to discover reflection boundaries that hinder comprehensive trimming. It requires the input path to your project's models. ```bash dotnet run --project Sannr.Cli -- analyze --input ./MyProject/Models ```