### Install FormCraft NuGet Packages Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md Instructions to add FormCraft and FormCraft.ForMudBlazor NuGet packages to a Blazor project using the .NET CLI. These packages provide the core library and MudBlazor integration respectively. ```bash dotnet add package FormCraft dotnet add package FormCraft.ForMudBlazor ``` -------------------------------- ### Configure FormCraft Services in Program.cs Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md Add required MudBlazor and FormCraft services to the Blazor application's service collection in `Program.cs`. This step is crucial for dependency injection and making FormCraft functionalities available throughout the application. ```csharp // Add MudBlazor services builder.Services.AddMudServices(); // Add FormCraft services builder.Services.AddFormCraft(); builder.Services.AddFormCraftMudBlazor(); ``` -------------------------------- ### Installing git-cliff for Local Development Source: https://github.com/phmatray/formcraft/blob/main/build/README.md Provides instructions for manually installing `git-cliff` on Windows (using Scoop) and macOS (using Homebrew) for local changelog generation, in cases where automatic installation is not feasible. ```powershell # Windows (using Scoop) scoop install git-cliff # Or download from GitHub releases # https://github.com/orhun/git-cliff/releases ``` ```bash # macOS brew install git-cliff ``` -------------------------------- ### Include MudBlazor CSS and JS in HTML Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md Add MudBlazor stylesheet and JavaScript references to the main HTML file (e.g., `index.html` for WebAssembly or `_Host.cshtml` for Server-side Blazor). This ensures proper styling and interactive functionality for MudBlazor components used by FormCraft. ```html ``` -------------------------------- ### FormCraft Validation with FluentValidation Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md Demonstrates how to apply custom validation rules to form fields using FormCraft's integration with FluentValidation. This example shows setting minimum length and adding a custom predicate validator for a password field. ```csharp .AddField(x => x.Password, field => field .WithLabel("Password") .Required("Password is required") .WithMinLength(8, "Password must be at least 8 characters") .WithValidator(value => value.Any(char.IsDigit), "Password must contain a number")) ``` -------------------------------- ### FormCraft Fluent API: Common Field Extension Methods Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md Lists convenience extension methods provided by FormCraft for quickly adding common field types with built-in validation. These methods simplify form configuration by abstracting common patterns. ```APIDOC - AddRequiredTextField() - Text input with required validation - AddEmailField() - Email input with format validation - AddNumericField() - Number input with range validation - AddDropdownField() - Select dropdown with options - AddPasswordField() - Password input with strength validation - AddPhoneField() - Phone number input with format validation - AddDateField() - Date picker - AddCheckboxField() - Boolean checkbox - AddFileUploadField() - File upload control ``` -------------------------------- ### Implement Custom Field Renderers in FormCraft Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md This C# example shows how to integrate a custom renderer for a field in FormCraft. It uses the `WithCustomRenderer` method to apply a `ColorPickerRenderer` to the 'Color' field, allowing for specialized UI components beyond standard input types. ```csharp .AddField(x => x.Color, field => field .WithLabel("Favorite Color") .WithCustomRenderer(new ColorPickerRenderer())) ``` -------------------------------- ### Define a Data Model for FormCraft Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md Create a simple C# class to serve as the data model for the form. The properties of this model will correspond to the fields in your FormCraft form, enabling type-safe data binding. ```csharp public class ContactModel { public string FirstName { get; set; } = ""; public string LastName { get; set; } = ""; public string Email { get; set; } = ""; public int Age { get; set; }; public string Country { get; set; } = ""; public string Message { get; set; } = ""; } ``` -------------------------------- ### Add FormCraft and MudBlazor References to _Imports.razor Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md Include necessary `using` directives for FormCraft and MudBlazor namespaces in `_Imports.razor`. This makes their components and types globally available in all Blazor components without needing explicit `using` statements in each file. ```razor @using FormCraft @using FormCraft.ForMudBlazor @using MudBlazor ``` -------------------------------- ### Running the FormCraft Demo Application Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md Instructions to navigate to the FormCraft demo Blazor application directory and launch it locally, typically accessible via a secure HTTPS endpoint. ```bash cd FormCraft.DemoBlazorApp dotnet run ``` -------------------------------- ### Display FormCraft Component in Blazor Page Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md Integrate the configured FormCraft form into a Blazor page using the `FormCraftComponent`. This component binds the model, applies the defined configuration, and handles form submission via the `OnValidSubmit` event. ```razor @page "/contact" Contact Form ``` -------------------------------- ### Build FormCraft Configuration with Fluent API Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md Demonstrates how to use FormCraft's fluent API (`FormBuilder`) to define form fields, their labels, types, and validation rules for a given model. This code snippet shows how to set up various field types including text, email, numeric, dropdown, and textarea. ```csharp @code { private ContactModel model = new(); private IFormConfiguration formConfig; protected override void OnInitialized() { formConfig = FormBuilder .Create() .AddRequiredTextField(x => x.FirstName, "First Name", minLength: 2) .AddRequiredTextField(x => x.LastName, "Last Name", minLength: 2) .AddEmailField(x => x.Email) .AddNumericField(x => x.Age, "Age", min: 18, max: 100) .AddDropdownField(x => x.Country, "Country", ("US", "United States"), ("CA", "Canada"), ("UK", "United Kingdom")) .AddField(x => x.Message, field => field .WithLabel("Message") .AsTextArea(lines: 5) .Required("Please enter a message")) .Build(); } private async Task HandleSubmit(ContactModel submittedModel) { // Handle form submission await Task.CompletedTask; } } ``` -------------------------------- ### FormCraft Fluent API: AddField with Lambda Configuration Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md Illustrates the generic `AddField` method for configuring form fields with custom labels, validation rules, placeholders, and help text using a lambda expression. This provides fine-grained control over individual field properties. ```APIDOC .AddField(x => x.PropertyName, field => field .WithLabel("Display Label") .Required("Custom error message") .WithPlaceholder("Placeholder text") .WithHelpText("Help text for users")) ``` -------------------------------- ### Setup Git Hook for Automatic Changelog Generation Source: https://github.com/phmatray/formcraft/blob/main/CONTRIBUTING.md Commands to install a pre-commit Git hook that automatically generates and stages the CHANGELOG.md file before each commit. This ensures the changelog is always up-to-date with commit history. ```bash ./setup-hooks.sh ``` ```powershell ./setup-hooks.ps1 ``` -------------------------------- ### Quick Start: Running FormCraft Build Targets Source: https://github.com/phmatray/formcraft/blob/main/build/README.md Provides basic `bash` commands to run the FormCraft build system's default target (Compile), execute tests, create NuGet packages, and generate the changelog. ```bash # Run default target (Compile) ./build.sh # Run tests ./build.sh Test # Create NuGet packages ./build.sh Pack # Generate changelog ./build.sh Changelog ``` -------------------------------- ### Set Up EditForm for FormCraft Validation Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Illustrates the correct setup of a Blazor `EditForm` component, including `DataAnnotationsValidator` and `DynamicFormValidator`, to enable comprehensive form validation. ```html ``` -------------------------------- ### Building FormCraft Projects Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md Provides commands for restoring dependencies, building the FormCraft project in various configurations (debug, release), and packaging it into local NuGet packages for distribution or testing. ```bash dotnet restore dotnet build dotnet build --configuration Release ./pack-local.sh # macOS/Linux ./pack-local.ps1 # Windows ``` -------------------------------- ### Verify Git-Cliff Installation Source: https://github.com/phmatray/formcraft/blob/main/build/README.md Executes the installed git-cliff command with the '--version' flag to confirm that the executable is correctly installed, accessible in the system's PATH, and to display its current version number. ```bash git-cliff --version ``` -------------------------------- ### Adding a Custom Field Renderer in FormCraft Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md Example C# code demonstrating how to implement a custom field renderer by inheriting from `CustomFieldRendererBase` and registering it, enabling the rendering of custom data types or UI components within FormCraft. ```csharp public class MyCustomRenderer : CustomFieldRendererBase { protected override RenderFragment RenderField(IFieldRenderContext context) { // Return RenderFragment with MudBlazor components } } // Register in DI or use inline: .WithCustomRenderer(new MyCustomRenderer()) ``` -------------------------------- ### Creating Reusable FormCraft Field Configurations Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md C# example illustrating the creation of reusable field configurations using extension methods on `FormBuilder`, allowing for consistent and concise definition of common form fields across multiple forms. ```csharp public static class MyFormExtensions { public static FormBuilder AddCustomField( this FormBuilder builder, Expression> propertyExpression) where TModel : new() { return builder.AddField(propertyExpression, field => field .WithLabel("Custom Label") .WithPlaceholder("Enter value...") .Required()); } } ``` -------------------------------- ### Add Parameterless Constructor for FormCraft Models Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Explains that FormCraft's `FormBuilder` often requires a parameterless constructor (`new()`) for models, and provides an example of how to add one if necessary. ```csharp public class MyModel // Add parameterless constructor if needed { public MyModel() { } } ``` -------------------------------- ### Install Git-Cliff on Linux Source: https://github.com/phmatray/formcraft/blob/main/build/README.md Downloads the latest git-cliff release for Linux x86_64, extracts the executable from the tarball, and moves it to a common system-wide binary directory (/usr/local/bin) to make it accessible from any location in the terminal. ```bash wget -qO- https://github.com/orhun/git-cliff/releases/latest/download/git-cliff-x86_64-unknown-linux-gnu.tar.gz | tar -xz sudo mv git-cliff /usr/local/bin/ ``` -------------------------------- ### Install FormCraft.ForMudBlazor via .NET CLI Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.ForMudBlazor/README.md This command adds the FormCraft.ForMudBlazor NuGet package to your project, enabling MudBlazor integration for dynamic forms. ```bash dotnet add package FormCraft.ForMudBlazor ``` -------------------------------- ### Create a User Registration Form with FormCraft in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/examples.md Illustrates building a user registration form with FormCraft, showcasing features like username validation (no spaces), email, password with confirmation, date of birth validation (age check), and required terms acceptance. ```csharp public class RegistrationModel { public string Username { get; set; } = ""; public string Email { get; set; } = ""; public string Password { get; set; } = ""; public string ConfirmPassword { get; set; } = ""; public DateTime DateOfBirth { get; set; } public bool AcceptTerms { get; set; } } var config = FormBuilder .Create() .AddRequiredTextField(x => x.Username, "Username", minLength: 3, maxLength: 20) .WithValidator(value => !value.Contains(" "), "Username cannot contain spaces") .AddEmailField(x => x.Email) .AddPasswordField(x => x.Password, "Password", 8, true) .AddField(x => x.ConfirmPassword, field => field .WithLabel("Confirm Password") .Required("Please confirm your password") .WithValidator((value, model) => value == model.Password, "Passwords must match")) .AddDateField(x => x.DateOfBirth, "Date of Birth") .WithValidator(value => value < DateTime.Now.AddYears(-13), "Must be at least 13 years old") .AddCheckboxField(x => x.AcceptTerms, "I accept the terms and conditions") .Required("You must accept the terms") .Build(); ``` -------------------------------- ### Inspect FormCraft Field Configuration at Runtime Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Provides an example of how to inspect the FormCraft field configuration programmatically within a Blazor component's `OnParametersSet` method, useful for debugging field properties and counts. ```csharp protected override void OnParametersSet() { Console.WriteLine($"Form has {Configuration.Fields.Count} fields"); foreach (var field in Configuration.Fields) { Console.WriteLine($"Field: {field.FieldName}, Type: {field.GetType()}"); } } ``` -------------------------------- ### Creating a Version Tag for Automated Release Trigger Source: https://github.com/phmatray/formcraft/blob/main/BUILD_RELEASE_SETUP.md This command sequence creates a lightweight Git tag with a specified version (e.g., `v1.0.0`) and pushes it to the remote `origin` repository. Pushing a version tag to the main branch is the trigger for the automated CI/CD pipeline to build, test, publish NuGet packages, and create a GitHub release. ```bash git tag v1.0.0 git push origin v1.0.0 ``` -------------------------------- ### Integrate MudBlazor theming and custom CSS with FormCraft Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md Configures MudBlazor services and defines a custom theme to apply consistent styling across FormCraft components. It also shows how to apply custom CSS classes to individual fields and provides an example CSS definition. ```csharp // In Program.cs builder.Services.AddMudServices(config => { config.SnackbarConfiguration.PositionClass = Defaults.Classes.Position.BottomLeft; }); // Custom theme var theme = new MudTheme() { Palette = new PaletteLight() { Primary = "#1976d2", Secondary = "#dc004e", // ... other colors } }; ``` ```csharp .AddField(x => x.SpecialField, field => field .WithCssClass("my-special-field")) ``` ```css .my-special-field { background: linear-gradient(45deg, #f0f0f0, #ffffff); border-radius: 8px; padding: 1rem; } ``` -------------------------------- ### Extend FormCraft's FormBuilder with custom methods in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md Shows how to create extension methods for the `FormBuilder` class, allowing developers to add custom field types or pre-configured field setups, thereby enhancing the form building API and promoting reusability. ```csharp public static class MyFormBuilderExtensions { public static FormBuilder AddCurrencyField( this FormBuilder builder, Expression> expression, string label, string currency = "USD") where TModel : new() { return builder.AddField(expression, field => field .WithLabel(label) .WithAttribute("currency", currency) .WithValidator(value => value >= 0, "Amount must be positive")); } } ``` -------------------------------- ### Install FormCraft NuGet Package Source: https://github.com/phmatray/formcraft/blob/main/FormCraft/README.md This command installs the FormCraft NuGet package into your .NET project, making the library available for use in your Blazor application. ```bash dotnet add package FormCraft ``` -------------------------------- ### Conventional Git Commit Message Examples Source: https://github.com/phmatray/formcraft/blob/main/CONTRIBUTING.md Illustrates examples of commit messages adhering to the Conventional Commits specification. These examples demonstrate how to categorize changes like new features, bug fixes, and documentation updates for automated changelog generation. ```git feat: add field groups layout support fix: resolve null reference in field renderer docs: update API documentation ``` -------------------------------- ### Define Field Dependencies in FormCraft Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/getting-started.md This C# code demonstrates how to create a field dependency in FormCraft. The 'State' field is made visible only when the 'Country' field is 'US', and its value is cleared if the country changes from 'US', ensuring data consistency based on user input. ```csharp .AddField(x => x.State, field => field .WithLabel("State") .VisibleWhen(model => model.Country == "US") .DependsOn(x => x.Country, (model, country) => { if (country != "US") model.State = ""; })) ``` -------------------------------- ### Run Blazor WebAssembly Application Locally Source: https://github.com/phmatray/formcraft/blob/main/BLAZOR_WASM_CONVERSION.md Instructions to run the converted Blazor WebAssembly application on a local development machine using the .NET CLI. This command navigates to the application directory and starts the development server. ```bash cd FormCraft.DemoBlazorApp dotnet run ``` -------------------------------- ### Enable Detailed Logging in FormCraft Applications Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Shows how to configure logging in `Program.cs` to a `LogLevel.Debug` level, providing more detailed output for troubleshooting FormCraft application behavior. ```csharp // In Program.cs builder.Logging.SetMinimumLevel(LogLevel.Debug); ``` -------------------------------- ### Running FormCraft Tests Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md Commands to execute unit and integration tests for the FormCraft project, including options to run all tests, specific test projects, with code coverage, or filter tests by class or method name. ```bash dotnet test dotnet test FormCraft.UnitTests/FormCraft.UnitTests.csproj dotnet test --collect:"XPlat Code Coverage" dotnet test --filter "FullyQualifiedName~FormBuilderTests" dotnet test --filter "DisplayName~Should_Build_Valid_Configuration" ``` -------------------------------- ### Testing FormCraft Build Targets Locally Source: https://github.com/phmatray/formcraft/blob/main/BUILD_RELEASE_SETUP.md These commands allow developers to execute specific build targets of the FormCraft project locally using the `build.sh` script. `Compile` builds the project, `Test` runs the unit tests, and `Pack` creates the NuGet packages. This is useful for verifying changes before committing and pushing to the remote repository. ```bash ./build.sh Compile ./build.sh Test ./build.sh Pack ``` -------------------------------- ### Configure global FormCraft options in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md Demonstrates how to configure global default behaviors for FormCraft, such as the default layout, visibility of required indicators, and validation settings, using the options pattern in `Program.cs`. ```csharp builder.Services.Configure(options => { options.DefaultLayout = FormLayout.Horizontal; options.ShowRequiredIndicator = true; options.RequiredIndicator = "*"; options.ValidateOnFieldChanged = true; }); ``` -------------------------------- ### Install FormCraft NuGet Packages Source: https://github.com/phmatray/formcraft/blob/main/README.md This snippet provides the `dotnet add package` commands required to install the core FormCraft library and its specific integration package for MudBlazor. Installing these packages is the initial step to incorporate FormCraft into a .NET Blazor project. ```bash dotnet add package FormCraft dotnet add package FormCraft.ForMudBlazor ``` -------------------------------- ### FormCraft Contributor Quick Start Commands (Bash) Source: https://github.com/phmatray/formcraft/blob/main/README.md Provides essential Git and .NET CLI commands for contributors to quickly set up, build, test, and package the FormCraft project locally. This includes cloning the repository, building the solution, running unit tests, and creating a local NuGet package. ```bash # Clone the repository git clone https://github.com/phmatray/FormCraft.git # Build the project dotnet build # Run tests dotnet test # Create a local NuGet package ./pack-local.sh # or pack-local.ps1 on Windows ``` -------------------------------- ### Handle Type Expressions in FormCraft Fields Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Provides examples of correct and incorrect type expressions when defining FormCraft fields, emphasizing the need to match the field's type with the model property's type to avoid casting errors. ```csharp // Correct .AddField(x => x.Age, field => field) // where Age is int // Incorrect - mixing types .AddField(x => x.Age.ToString(), field => field) // This creates expression issues ``` -------------------------------- ### Executing FormCraft NUKE Build System Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md Commands to invoke the NUKE build automation system for the FormCraft project, supporting both macOS/Linux and Windows environments for streamlined build processes. ```bash ./build.sh ./build.ps1 ``` -------------------------------- ### Design a Multi-Section Survey Form with FormCraft in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/examples.md Shows how to construct a survey form using FormCraft, featuring numeric fields, checkboxes, text areas, and conditional display of improvement suggestions based on satisfaction level. ```csharp public class SurveyModel { public string Name { get; set; } = ""; public int Satisfaction { get; set; } public bool WouldRecommend { get; set; } public string Feedback { get; set; } = ""; public string ImprovementSuggestions { get; set; } = ""; } var config = FormBuilder .Create() .AddRequiredTextField(x => x.Name, "Your Name") .AddNumericField(x => x.Satisfaction, "Satisfaction (1-10)", 1, 10) .AddCheckboxField(x => x.WouldRecommend, "Would you recommend us to others?") .AddField(x => x.Feedback, field => field .WithLabel("Additional Feedback") .WithPlaceholder("Tell us about your experience...") .AsTextArea(rows: 4)) .AddField(x => x.ImprovementSuggestions, field => field .WithLabel("Suggestions for Improvement") .AsTextArea(rows: 3) .VisibleWhen(m => m.Satisfaction < 8)) .Build(); ``` -------------------------------- ### Implement a Custom FormCraft UI Framework Adapter in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft/Forms/Rendering/README.md This C# example illustrates the basic structure for creating a custom UI framework adapter for FormCraft. It shows how to implement the IUIFrameworkAdapter interface, defining the framework name and providing specific renderers for different field types, along with methods for rendering form elements. ```C# public class MyFrameworkAdapter : IUIFrameworkAdapter { public string FrameworkName => "MyFramework"; public IFieldRenderer TextFieldRenderer => new MyTextFieldRenderer(); // ... implement other properties public RenderFragment RenderForm(RenderFragment content, string? cssClass = null) { // Framework-specific form rendering } // ... implement other methods } ``` -------------------------------- ### Implement Custom Asynchronous Validation in FormCraft C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/examples.md Provides an example of implementing a custom asynchronous field validator in FormCraft using C#. It demonstrates how to check username availability against a service and integrate this custom validator into a form field. ```csharp public class AccountModel { public string Username { get; set; } = ""; public string Email { get; set; } = ""; } // Custom async validator public class UsernameAvailabilityValidator : IFieldValidator { private readonly IUserService _userService; public UsernameAvailabilityValidator(IUserService userService) { _userService = userService; } public async Task ValidateAsync(AccountModel model, string value, IServiceProvider services) { if (string.IsNullOrEmpty(value)) return ValidationResult.Success(); var isAvailable = await _userService.IsUsernameAvailableAsync(value); return isAvailable ? ValidationResult.Success() : ValidationResult.Error("Username is already taken"); } } // Usage var config = FormBuilder .Create() .AddField(x => x.Username, field => field .WithLabel("Username") .Required() .WithAsyncValidator()) .Build(); ``` -------------------------------- ### C# Form Configuration with FormBuilder Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Illustrates how to configure forms using a fluent FormBuilder pattern. This approach promotes readable configuration by grouping related fields, adding clear labels and help text, and defining meaningful validation messages for user input. ```csharp // Keep configuration readable var config = FormBuilder .Create() // Group related fields .AddRequiredTextField(x => x.FirstName, "First Name") .AddRequiredTextField(x => x.LastName, "Last Name") // Add clear labels and help text .AddEmailField(x => x.Email) .WithHelpText("We'll never share your email") // Use meaningful validation messages .AddField(x => x.Password, field => field .Required("Password is required for security") .WithMinLength(8, "Password must be at least 8 characters")) .Build(); ``` -------------------------------- ### Implement Async Validation for FormCraft Performance Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Illustrates how to implement asynchronous validation (`ValidateAsync`) for expensive operations in FormCraft, suggesting techniques like caching or debouncing to improve form responsiveness. ```csharp public class ExpensiveValidator : IFieldValidator { public async Task ValidateAsync(MyModel model, string value, IServiceProvider services) { // Use caching, debouncing, or other optimization techniques return await SomeExpensiveValidation(value); } } ``` -------------------------------- ### FormCraft Core Architecture and Design Patterns Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md Overview of the fundamental design patterns and architectural components within the FormCraft library, including the Fluent Builder for API chaining, the Rendering Pipeline for UI generation, the Pluggable Validation system, and the Reactive Dependency system for field interactions. ```APIDOC Fluent Builder Pattern: - Entry point: FormBuilder.Create() - Field configuration: .AddField(x => x.Property, field => field.WithLabel("Label")) - Group management: .AddFieldGroup(group => group.AddField(...)) Rendering Pipeline: - IFieldRendererService: Manages renderer registry - IFieldRenderer: Interface for each supported type - Custom renderers can be registered via DI Validation Architecture: - Built-in validators: RequiredValidator, CustomValidator, AsyncValidator - Integration with FluentValidation via DynamicFormValidator - IFieldValidator: Interface for custom validators Dependency System: - Fields can depend on other fields via DependsOn() - Dependencies trigger visibility/value updates - Managed through IFieldDependency ``` -------------------------------- ### Group FormCraft fields logically in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md Demonstrates how to organize form fields into logical groups using the `WithGroup` extension method, which helps in structuring complex forms and improving user experience. ```csharp .AddField(x => x.PersonalInfo, field => field .WithGroup("Personal Information")) .AddField(x => x.ContactInfo, field => field .WithGroup("Contact Details")) ``` -------------------------------- ### Register Default FormCraft Renderers Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Explains the importance of calling `builder.Services.AddFormCraft()` in `Program.cs` to register the default field renderers, which are essential for fields to display correctly. ```csharp // In Program.cs builder.Services.AddFormCraft(); ``` -------------------------------- ### C# Model Design Best Practices Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Demonstrates best practices for C# model design, including the use of descriptive names, proper initialization of collections, appropriate nullability for optional fields, and the application of validation attributes for data integrity. ```csharp public class WellDesignedModel { // Use descriptive names public string CustomerName { get; set; } = ""; // Initialize collections public List Tags { get; set; } = new(); // Use appropriate nullability public DateTime? OptionalDate { get; set; } // Add validation attributes as backup [Required] [EmailAddress] public string Email { get; set; } = ""; } ``` -------------------------------- ### Optimize Field Dependencies in FormCraft Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Advises on keeping logic simple and fast within `DependsOn` callbacks to prevent performance bottlenecks, especially in forms with complex field interdependencies. ```csharp // Avoid complex dependency chains .DependsOn(x => x.Field1, (model, value) => { // Keep logic simple and fast }) ``` -------------------------------- ### Build a Contact Form with FormCraft in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/examples.md Demonstrates how to create a contact form using FormCraft, including defining the model, setting up a horizontal layout, adding required text fields, email, phone, dropdowns, and conditional visibility for the city field based on country selection. ```csharp public class ContactModel { public string FirstName { get; set; } = ""; public string LastName { get; set; } = ""; public string Email { get; set; } = ""; public string Phone { get; set; } = ""; public string Country { get; set; } = ""; public string City { get; set; } = ""; public bool SubscribeToNewsletter { get; set; } } // Form configuration var config = FormBuilder .Create() .WithLayout(FormLayout.Horizontal) .AddRequiredTextField(x => x.FirstName, "First Name", minLength: 2) .AddRequiredTextField(x => x.LastName, "Last Name", minLength: 2) .AddEmailField(x => x.Email) .AddField(x => x.Phone, field => field .WithLabel("Phone") .WithPlaceholder("(555) 123-4567")) .AddDropdownField(x => x.Country, "Country", ("US", "United States"), ("CA", "Canada"), ("UK", "United Kingdom")) .AddField(x => x.City, field => field .WithLabel("City") .VisibleWhen(m => !string.IsNullOrEmpty(m.Country)) .DependsOn(x => x.Country, (model, country) => { if (string.IsNullOrEmpty(country)) { model.City = ""; } })) .AddCheckboxField(x => x.SubscribeToNewsletter, "Subscribe to newsletter") .Build(); ``` -------------------------------- ### Virtualize Large Forms with FormCraft Grouping Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Suggests using field grouping (`WithGroup`) and conditional visibility (`VisibleWhen`) to virtualize large forms, rendering only visible sections to improve performance. ```csharp // Group fields and render only visible sections .AddField(x => x.Section1Field, field => field .WithGroup("Section 1") .VisibleWhen(model => model.CurrentSection == 1)) ``` -------------------------------- ### Enforcing FormCraft Code Quality and Linting Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md Command to build the FormCraft project with strict code quality checks, treating all compiler warnings as errors to ensure adherence to C# conventions and analyzer rules. ```bash dotnet build /p:TreatWarningsAsErrors=true ``` -------------------------------- ### FormCraft Migration: New Framework-Agnostic Renderer in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft/Forms/Rendering/README.md This C# example demonstrates the new framework-agnostic approach for a field renderer in FormCraft. Instead of directly referencing UI framework components, it specifies a ComponentType which is resolved at runtime based on the configured UI framework, promoting loose coupling and extensibility. ```C# public class StringFieldRenderer : FieldRendererBase { protected override Type ComponentType => typeof(StringFieldComponent<>); } ``` -------------------------------- ### Implement Custom Rate Limiting Service in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/security.md Provides an example of the `IRateLimitService` interface for implementing a custom rate limiting mechanism, such as one backed by Redis, for distributed environments. This allows for flexible and scalable rate limiting solutions. ```csharp public class RedisRateLimitService : IRateLimitService { private readonly IConnectionMultiplexer _redis; public async Task CheckRateLimitAsync( string identifier, int maxAttempts, TimeSpan timeWindow) { // Redis implementation } } ``` -------------------------------- ### Implement and register a custom FormCraft field renderer in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md Defines a custom field renderer by implementing the `IFieldRenderer` interface to handle specialized input types, and registers it with the dependency injection container for FormCraft to utilize. ```csharp public class CustomFieldRenderer : IFieldRenderer { public bool CanRender(Type fieldType, string? fieldSubType = null) { return fieldType == typeof(MyCustomType); } public void RenderField( RenderTreeBuilder builder, object model, IFieldConfiguration field, EventCallback onValueChanged, EventCallback onDependencyChanged) { // Your custom rendering logic here builder.OpenComponent(0); builder.AddAttribute(1, "Value", field.GetValue(model)); builder.AddAttribute(2, "ValueChanged", onValueChanged); builder.CloseComponent(); } } ``` ```csharp builder.Services.AddScoped(); ``` -------------------------------- ### Implement Custom Field Renderers in Formcraft Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/api-reference.md Provides an example of creating a custom field renderer by implementing the `IFieldRenderer` interface. This allows integration of custom UI components (e.g., a MudBlazor ColorPicker) for rendering specific field types. ```csharp public class ColorPickerRenderer : CustomFieldRendererBase { protected override RenderFragment RenderField(IFieldRenderContext context) { return builder => { builder.OpenComponent(0); builder.AddAttribute(1, "Label", context.Field.Label); builder.AddAttribute(2, "Value", context.CurrentValue); builder.AddAttribute(3, "ValueChanged", context.OnValueChanged); builder.CloseComponent(); }; } } ``` -------------------------------- ### Implement Custom Encryption Service in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/security.md Provides an example of implementing a custom `IEncryptionService` to integrate bespoke encryption logic with FormCraft. This allows developers to use their preferred encryption algorithms or integrate with existing security infrastructure, and register it with the dependency injection container. ```csharp public class CustomEncryptionService : IEncryptionService { public string? Encrypt(string? value) { // Your encryption logic } public string? Decrypt(string? encryptedValue) { // Your decryption logic } } // Register in DI services.AddScoped(); ``` -------------------------------- ### Build a User Registration Form with FormCraft and MudBlazor Source: https://github.com/phmatray/formcraft/blob/main/README.md Demonstrates how to construct a user registration form using FormCraft components within a Blazor application, leveraging MudBlazor for UI elements. This example illustrates the process of defining various form fields, applying validation rules, and handling the form submission logic. ```csharp @page "/register" @using FormCraft @using FormCraft.ForMudBlazor

User Registration

@code { private UserRegistration model = new(); private IFormConfiguration formConfig; protected override void OnInitialized() { formConfig = FormBuilder.Create() .AddRequiredTextField(x => x.FirstName, "First Name") .AddRequiredTextField(x => x.LastName, "Last Name") .AddEmailField(x => x.Email) .AddNumericField(x => x.Age, "Age", min: 18, max: 120) .AddSelectField(x => x.Country, "Country", GetCountries()) .AddCheckboxField(x => x.AcceptTerms, "I accept the terms and conditions") .IsRequired("You must accept the terms") .Build(); } private async Task HandleSubmit(UserRegistration model) { // Handle form submission await UserService.RegisterAsync(model); } private List> GetCountries() => new() { new("us", "United States"), new("uk", "United Kingdom"), new("ca", "Canada"), new("au", "Australia") }; } ``` -------------------------------- ### FormCraft Key Extension Points Source: https://github.com/phmatray/formcraft/blob/main/CLAUDE.md Defines the primary interfaces and classes that serve as extension points for customizing FormCraft's behavior, such as creating custom field renderers, validators, and form templates, allowing developers to tailor the library to specific needs. ```APIDOC Custom field renderers: Implement IFieldRenderer or extend CustomFieldRendererBase Custom validators: Implement IFieldValidator Form templates: Extend FormTemplates class Field types: Add new renderers to FieldRendererService ``` -------------------------------- ### Registering FluentValidation Validators in Dependency Injection Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/fluent-validation.md Illustrates the proper methods for registering FluentValidation validators with a dependency injection container. It provides examples for both stateless validators, which should be registered as Singletons, and validators with dependencies, typically registered as Scoped. ```csharp // For stateless validators services.AddSingleton, CustomerValidator>(); // For validators with dependencies services.AddScoped, UserValidator>(); ``` -------------------------------- ### Localizing Form Fields in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md Demonstrates how to apply localization to form fields using resource files in a C# application. It shows setting a label and a required message using a `Localizer` object, which typically resolves strings from `.resx` files based on the current culture. ```csharp // Resource files: Resources/FormLabels.en.resx, Resources/FormLabels.fr.resx .AddField(x => x.Name, field => field .WithLabel(Localizer["NameLabel"]) .Required(Localizer["NameRequired"])) ``` -------------------------------- ### Use Specific FluentValidation Instance in FormCraft Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/fluent-validation.md This example shows an alternative approach to integrating FluentValidation by directly providing an instance of the validator to FormCraft's WithFluentValidator method, rather than relying on dependency injection for resolution. ```csharp var customerValidator = new CustomerValidator(); var formConfig = FormBuilder .Create() .AddField(x => x.Name, field => field .WithLabel("Customer Name") .WithFluentValidator(customerValidator, x => x.Name)) .Build(); ``` -------------------------------- ### C# Asynchronous Form Submission Error Handling Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/troubleshooting.md Presents a robust error handling pattern for asynchronous form submissions. It demonstrates how to catch and differentiate between specific validation exceptions and general application errors, providing appropriate user feedback and logging for each scenario. ```csharp private async Task HandleValidSubmit(MyModel model) { try { await SaveModel(model); ShowSuccessMessage(); } catch (ValidationException ex) { // Handle validation errors ShowValidationErrors(ex.Errors); } catch (Exception ex) { // Handle general errors ShowErrorMessage("An unexpected error occurred. Please try again."); Logger.LogError(ex, "Form submission failed"); } } ``` -------------------------------- ### Viewing FormCraft Build Execution Plan Source: https://github.com/phmatray/formcraft/blob/main/build/README.md Demonstrates how to generate and view the build system's execution plan in HTML format, useful for understanding the sequence of operations. ```bash # Show execution plan in HTML ./build.sh --plan ``` -------------------------------- ### Configure FormCraft Security Features in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/security.md Demonstrates how to quickly configure multiple security features like field encryption, CSRF protection, rate limiting, and audit logging using the FormCraft fluent API. This provides a comprehensive setup for a form model. ```csharp var config = FormBuilder.Create() .AddField(x => x.Name, field => field .WithLabel("Name") .Required()) .AddField(x => x.SSN, field => field .WithLabel("Social Security Number") .Required()) .WithSecurity(security => security .EncryptField(x => x.SSN) .EnableCsrfProtection() .WithRateLimit(5, TimeSpan.FromMinutes(1)) .EnableAuditLogging()) .Build(); ``` -------------------------------- ### Create and apply a custom FormCraft field validator in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md Implements a custom asynchronous field validator by inheriting from `IFieldValidator` to enforce specific business rules, and demonstrates how to apply this validator to a form field using the `WithValidator` extension method. ```csharp public class BusinessRuleValidator : IFieldValidator { public async Task ValidateAsync(TModel model, string value, IServiceProvider services) { // Your validation logic if (await IsValidBusinessRule(value)) { return ValidationResult.Success(); } return ValidationResult.Error("Value violates business rule"); } private async Task IsValidBusinessRule(string value) { // Implement your business logic return await Task.FromResult(true); } } ``` ```csharp .AddField(x => x.BusinessCode, field => field .WithValidator>()) ``` -------------------------------- ### Define custom FormCraft layout enums and logic in C# Source: https://github.com/phmatray/formcraft/blob/main/FormCraft.DemoBlazorApp/wwwroot/docs/customization.md Illustrates how to define a custom enum for various form layouts and a corresponding helper method to map these layouts to specific CSS classes, enabling dynamic form presentation based on custom layout types. ```csharp public enum MyCustomLayout { Sidebar, Wizard, Accordion } // Custom layout logic public static string GetCustomLayoutClass(MyCustomLayout layout) { return layout switch { MyCustomLayout.Sidebar => "d-flex", MyCustomLayout.Wizard => "wizard-container", MyCustomLayout.Accordion => "accordion-form", _ => "" }; } ``` -------------------------------- ### Create and Use Custom Field Renderers in FormCraft (C#) Source: https://github.com/phmatray/formcraft/blob/main/README.md Provides an example of creating a custom field renderer by extending `CustomFieldRendererBase` to implement specialized input controls. It demonstrates how to define the rendering logic using `RenderFragment`, integrate the custom renderer into a form configuration, and optionally register it with a dependency injection container. ```csharp // Create a custom renderer public class ColorPickerRenderer : CustomFieldRendererBase { public override RenderFragment Render(IFieldRenderContext context) { return builder => { var value = GetValue(context) ?? "#000000"; builder.OpenElement(0, "input"); builder.AddAttribute(1, "type", "color"); builder.AddAttribute(2, "value", value); builder.AddAttribute(3, "onchange", EventCallback.Factory.CreateBinder( this, async (newValue) => await SetValue(context, newValue), value)); builder.CloseElement(); }; } } // Use in your form configuration .AddField(x => x.Color, field => field .WithLabel("Product Color") .WithCustomRenderer() .WithHelpText("Select the primary color")) // Register custom renderers (optional for DI) services.AddScoped(); services.AddScoped(); ``` -------------------------------- ### FormCraft Build System Configuration and Parameters Source: https://github.com/phmatray/formcraft/blob/main/build/README.md Documents the environment variables and command-line parameters used to configure and control the FormCraft build process, including specifying build configuration, running specific targets, and skipping steps. ```APIDOC Environment Variables: - `NUGET_API_KEY`: Required for publishing to NuGet.org Parameters: # Specify configuration ./build.sh --configuration Release # Run specific targets ./build.sh Test Pack --skip Restore ``` -------------------------------- ### Build FormCraft Project Source: https://github.com/phmatray/formcraft/blob/main/CONTRIBUTING.md Provides commands to set up the FormCraft development environment. This includes cloning the repository, restoring .NET dependencies, building the solution, and running unit tests to ensure everything is working correctly. ```bash git clone https://github.com/phmatray/DynamicFormBlazor.git cd DynamicFormBlazor dotnet restore dotnet build dotnet test ```