### Install Rizzy.Htmx via NuGet Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy.Htmx/README.md This command installs the Rizzy.Htmx library into your .NET project using the NuGet package manager. Ensure you have the .NET CLI installed and are in your project directory. ```bash dotnet add package Rizzy.Htmx ``` -------------------------------- ### Install Rizzy Client Source: https://github.com/jalexsocial/rizzy/blob/main/packages/rizzy/README.md Installs the Rizzy client package using npm. This command should be executed in your project's terminal. ```bash npm install rizzy ``` -------------------------------- ### C# Get Antiforgery JavaScript Method Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Retrieves either the minified or non-minified antiforgery JavaScript based on a boolean parameter. This method simplifies selecting the correct script version for use. ```csharp /// /// Retrieves either the minified or non-minified antiforgery JavaScript, based on the parameter. /// /// True to load the minified resource; otherwise, false. /// The antiforgery JavaScript snippet. public string GetAntiforgeryJavaScript(bool minified) => minified ? AntiforgeryJavaScriptMinified : AntiforgeryJavaScript; ``` -------------------------------- ### Use Rizzy.Htmx in Controllers Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy.Htmx/README.md This C# example shows how to use Rizzy.Htmx within a controller to manage htmx responses. It includes returning a view with htmx enhancements and setting multiple htmx response operations like PushUrl and Reswap. ```csharp using Rizzy.Htmx; using Rizzy.Framework.Mvc; public class HomeController : RzController { public IResult Index() { // Return a view with htmx enhancements: return View(new { message = "Hello HTMX!" }); } public IResult Update() { // Set multiple htmx response operations using the Response.Htmx action method: HttpContext.Response.Htmx(response => { response.PushUrl("/new-url") .Reswap("outerHTML"); }); return Results.Ok("Update succeeded."); } } ``` -------------------------------- ### C# Antiforgery JavaScript Resource Access Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Provides properties to get the standard and minified antiforgery JavaScript resource contents. It relies on an internal `GetString` method to load embedded resources from the assembly. ```csharp /// /// Gets the standard (non-minified) antiforgery JavaScript resource contents. /// public string AntiforgeryJavaScript => GetString(nameof(AntiforgeryJavaScript)); /// /// Gets the minified antiforgery JavaScript resource contents. /// public string AntiforgeryJavaScriptMinified => GetString(nameof(AntiforgeryJavaScriptMinified)); ``` -------------------------------- ### Get Nonce from HttpContext Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Retrieves a nonce value from the HttpContext by utilizing an IRizzyNonceProvider registered in the service collection. This is typically used for security or state management purposes. ```C# using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Rizzy.Htmx; using System.Reflection; namespace Rizzy; public static class HttpContextExtensions { public static string GetNonce(this HttpContext context) { var provider = context.RequestServices.GetRequiredService(); return provider.GetNonce(); } ``` -------------------------------- ### Configure Rizzy.Htmx in Program.cs Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy.Htmx/README.md This C# code snippet demonstrates how to register and configure the Rizzy.Htmx services in your application's startup file. It shows enabling history features and setting default swap delays. ```csharp using Rizzy.Htmx; using Rizzy.Configuration; var builder = WebApplication.CreateBuilder(args); builder.Services.AddHtmx(options => { // Enable browser history, define default swap delays, and more: options.HistoryEnabled = true; options.RefreshOnHistoryMiss = true; options.DefaultSwapDelay = TimeSpan.FromMilliseconds(250); // Additional configuration properties... }); var app = builder.Build(); // ... rest of the application setup ``` -------------------------------- ### HtmxSwapService Implementation Methods Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Provides the C# implementation for the IHtmxSwapService interface. These methods handle the logic for adding and rendering swappable components, fragments, and raw HTML content, integrating with Htmx for dynamic updates. ```csharp public void AddSwappableComponent(string targetId, object? parameters = null, SwapStyle swapStyle = SwapStyle.outerHTML, string? selector = null) where TComponent : IComponent => AddSwappableComponent(targetId, parameters?.ToDictionary(), swapStyle, selector); public void AddSwappableFragment(string targetId, RenderFragment renderFragment, SwapStyle swapStyle = SwapStyle.outerHTML, string? selector = null) { _contentItems.Add(new ContentItem(RzContentType.Swappable, targetId, swapStyle, selector ?? string.Empty, renderFragment)); OnContentItemsUpdated(); } public void AddSwappableContent(string targetId, string content, SwapStyle swapStyle = SwapStyle.outerHTML, string? selector = null) { var contentFragment = new RenderFragment(builder => builder.AddMarkupContent(1, content)); _contentItems.Add(new ContentItem(RzContentType.Swappable, targetId, swapStyle, selector ?? string.Empty, contentFragment)); OnContentItemsUpdated(); } public void AddRawContent(string content) { var contentFragment = new RenderFragment(builder => builder.AddMarkupContent(2, content)); _contentItems.Add(new ContentItem(RzContentType.RawHtml, string.Empty, SwapStyle.none, string.Empty, contentFragment)); OnContentItemsUpdated(); } public RenderFragment RenderToFragment() { var isHtmx = new HtmxRequest(_httpContext).IsHtmx; return builder => { foreach (var item in _contentItems) { if (item.ContentType == RzContentType.RawHtml) { builder.AddContent(3, item.Content); } else if (item.ContentType == RzContentType.Swappable && isHtmx) { builder.OpenComponent(3, typeof(HtmxSwappable)); builder.AddAttribute(4, "TargetId", item.TargetId); builder.AddAttribute(5, "SwapStyle", item.SwapStyle); builder.AddAttribute(6, "Selector", item.Selector); builder.AddAttribute(7, "ChildContent", item.Content); builder.CloseComponent(); } } }; } public async Task RenderToString() { var content = string.Empty; if (ContentAvailable) { ILoggerFactory loggerFactory = _serviceProvider.GetRequiredService(); await using var renderer = new HtmlRenderer(_serviceProvider, loggerFactory); content = await renderer.Dispatcher.InvokeAsync(async () => { var output = await renderer.RenderComponentAsync(); return output.ToHtmlString(); }); } return content; } public void Clear() { _contentItems.Clear(); } public bool ContentAvailable => _contentItems.Count > 0; ``` -------------------------------- ### Activate HTMX Extensions with Rizzy Source: https://github.com/jalexsocial/rizzy/blob/main/packages/rizzy/README.md Shows how to activate Rizzy's specific HTMX extensions, such as `rizzy-streaming` for handling Blazor streaming rendering and `rizzy-nonce` for CSP nonces, using the `hx-ext` attribute on HTMX elements. ```html
``` -------------------------------- ### Get Current Action URL (C#) Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Retrieves the encoded path and query string of the current HTTP request. This property relies on `IHttpContextAccessor` being correctly registered and accessible within the request scope. ```C# public string CurrentActionUrl => _currentActionUrl ??= HttpContextSafe.Request.GetEncodedPathAndQuery(); ``` -------------------------------- ### RizzyComponentParameterBuilder: Build and Validation Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Finalizes the component parameter construction by building a dictionary of parameters. Includes validation to ensure all required parameters marked with [EditorRequired] have been provided. ```csharp public Dictionary Build() { foreach (var meta in _componentParameterMetadata) { if (meta.IsEditorRequired && !_parameters.ContainsKey(meta.Name)) { throw new ArgumentException($"Required parameter '{meta.Name}' for component '{ComponentTypeStatic.FullName}' was not provided. Ensure all parameters marked with [EditorRequired] are set using the builder."); } } return new Dictionary(_parameters, StringComparer.Ordinal); } ``` -------------------------------- ### Rizzy Service Registration Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Demonstrates common service registration patterns using dependency injection in C#. It shows how to register scoped services for HTMX swap functionality and nonce provision. ```csharp services.AddScoped(); services.TryAddScoped(); return services; ``` -------------------------------- ### Rizzy View and PartialView Methods Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Provides methods for rendering components as views or partial views within the Rizzy framework. Supports various overloads for passing data and configuring component parameters. ```csharp public virtual IResult View(Action> parameterBuilderAction, ModelStateDictionary? modelState = null) where TComponent : IComponent => Rizzy.View(parameterBuilderAction, modelState); public virtual IResult View(object? data = null, ModelStateDictionary? modelState = null) where TComponent : IComponent => Rizzy.View(data, modelState); public virtual IResult View(Dictionary data, ModelStateDictionary? modelState = null) where TComponent : IComponent => Rizzy.View(data, modelState); public virtual IResult PartialView(Action> parameterBuilderAction, ModelStateDictionary? modelState = null) where TComponent : IComponent => Rizzy.PartialView(parameterBuilderAction, modelState); public virtual IResult PartialView(object? data = null, ModelStateDictionary? modelState = null) where TComponent : IComponent => Rizzy.PartialView(data, modelState); public virtual IResult PartialView(Dictionary data, ModelStateDictionary? modelState = null) where TComponent : IComponent => Rizzy.PartialView(data, modelState); public virtual IResult PartialView(RenderFragment fragment) => Rizzy.PartialView(fragment); public virtual IResult PartialView(params RenderFragment[] fragments) => Rizzy.PartialView(fragments); ``` -------------------------------- ### Rizzy Component Parameter Builder Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt A generic builder for constructing parameters for Blazor-like components. It validates that properties exist and are marked with [Parameter] using cached metadata. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Microsoft.AspNetCore.Components; using Rizzy.Internal; namespace Rizzy; public class RizzyComponentParameterBuilder where TComponent : IComponent { private readonly Dictionary _parameters = new(StringComparer.Ordinal); private static readonly Type ComponentTypeStatic = typeof(TComponent); private readonly IReadOnlyList _componentParameterMetadata; public RizzyComponentParameterBuilder() { _componentParameterMetadata = ComponentMetadataCache.GetParameterMetadata(ComponentTypeStatic); } public RizzyComponentParameterBuilder Add( Expression> parameterSelector, TValue value) { ArgumentNullException.ThrowIfNull(parameterSelector); if (parameterSelector.Body is not MemberExpression memberExpression || memberExpression.Member is not PropertyInfo selectedPropertyInfo) { throw new ArgumentException( "The parameter selector must be a simple property access expression (e.g., p => p.MyProperty).", nameof(parameterSelector)); } string propertyName = selectedPropertyInfo.Name; var parameterMeta = _componentParameterMetadata.FirstOrDefault(p => p.Name.Equals(propertyName, StringComparison.Ordinal)); if (parameterMeta is null) { throw new ArgumentException($"Property '{propertyName}' is not a recognized [Parameter] on component '{ComponentTypeStatic.FullName}'. Ensure the property is public, on the component or a qualifying base class, and decorated with [Parameter].", nameof(parameterSelector)); } // Further validation could be added here, e.g., checking TValue against parameterMeta.ParameterType _parameters[propertyName] = value; return this; } // Method to build and return the parameters dictionary would typically follow // public IReadOnlyDictionary Build() => _parameters; } ``` -------------------------------- ### ReverseStringBuilder InsertFront Methods Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Provides methods to insert character spans or formatted values at the beginning of a buffer. It utilizes ArrayPool for efficient memory management and handles buffer resizing when necessary. Supports insertion of ReadOnlySpan, ISpanFormattable, and IFormattable types. ```C# internal ref struct ReverseStringBuilder { // ... other members ... public void InsertFront(scoped ReadOnlySpan span) { var startIndex = _nextEndIndex - span.Length; if (startIndex >= 0) { span.CopyTo(_currentBuffer[startIndex..]); _nextEndIndex = startIndex; return; } // ... buffer resizing logic ... } public void InsertFront(T value) where T : ISpanFormattable { Span result = stackalloc char[11]; if (value.TryFormat(result, out var charsWritten, format: default, CultureInfo.InvariantCulture)) { InsertFront(result[..charsWritten]); } else { InsertFront((IFormattable)value); } } public void InsertFront(IFormattable formattable) => InsertFront(formattable.ToString(null, CultureInfo.InvariantCulture)); } ``` -------------------------------- ### Rizzy Configuration Options Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Defines configuration settings for the Rizzy framework, including the default layout component and the root application component. It enforces type constraints for layout components. ```csharp using Microsoft.AspNetCore.Components; using Rizzy.Htmx; namespace Rizzy.Configuration; public class RizzyConfig { private Type? _defaultLayout = null; private Type? _rootComponent = typeof(HtmxApp); public AntiforgeryStrategy AntiforgeryStrategy { get; set; } = AntiforgeryStrategy.GenerateTokensPerPage; public Type? DefaultLayout { get => _defaultLayout; set { if (value != null && !typeof(LayoutComponentBase).IsAssignableFrom(value)) throw new Exception($"{nameof(value)} is not a Razor layout component"); _defaultLayout = value; } } public Type? RootComponent { get => _rootComponent; set { if (value != null) { if (!value.IsGenericType || value.GetGenericTypeDefinition() != typeof(HtmxApp<>)) { // Error handling for invalid root component type } } } } } ``` -------------------------------- ### Convert Blazor RenderFragment to Markup String in C# Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Extension methods for Blazor's RenderFragment. `AsMarkupString` converts a RenderFragment into its HTML string representation by rendering it. `RenderHtmlAsync` renders a RenderFragment using an `HtmlRenderer` for asynchronous HTML output. ```csharp using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.Extensions.DependencyInjection; #pragma warning disable BL0006 namespace Rizzy.Utility; public static class RenderFragmentExtensions { public static string AsMarkupString(this RenderFragment? fragment) { if (fragment == null) { return string.Empty; } var builder = new RenderTreeBuilder(); fragment.Invoke(builder); var frames = builder.GetFrames(); var markupContentList = new List(); for (int i = 0; i < frames.Count; i++) { var frame = frames.Array[i]; if (frame is { FrameType: RenderTreeFrameType.Markup, MarkupContent: not null }) { markupContentList.Add(frame.MarkupContent); } } if (markupContentList.Count > 0 && string.IsNullOrWhiteSpace(markupContentList[0])) { markupContentList.RemoveAt(0); } if (markupContentList.Count > 0 && string.IsNullOrWhiteSpace(markupContentList[^1])) { markupContentList.RemoveAt(markupContentList.Count - 1); } return string.Join("\n", markupContentList); } public static async Task RenderHtmlAsync(this RenderFragment? fragment, IServiceProvider serviceProvider) { if (fragment is null) return string.Empty; ILoggerFactory loggerFactory = serviceProvider.GetRequiredService(); await using var htmlRenderer = new HtmlRenderer(serviceProvider, loggerFactory); var html = await htmlRenderer.Dispatcher.InvokeAsync(async () => { var dictionary = new Dictionary { { "Fragment", fragment } }; var parameters = ParameterView.FromDictionary(dictionary); var output = await htmlRenderer.RenderComponentAsync(parameters); return output.ToHtmlString(); }); return html; } } ``` -------------------------------- ### Render Razor Partial Components (C#) Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Methods for rendering Razor partial components, allowing for dynamic content injection. Supports parameter building and direct `RenderFragment` execution. These methods are designed to work with HTMX, returning `NoContent` if an empty response is requested. ```C# public IResult PartialView(Action> parameterBuilderAction, ModelStateDictionary? modelState = null) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(parameterBuilderAction); if (HttpContextSafe.Response.Htmx().EmptyResponseBodyRequested) return Results.NoContent(); var builderInstance = new RizzyComponentParameterBuilder(); parameterBuilderAction(builderInstance); var parametersDictionary = builderInstance.Build(); return PartialView(parametersDictionary, modelState); } public IResult PartialView(object? data = null, ModelStateDictionary? modelState = null) where TComponent : IComponent => PartialView(data.ToDictionary(), modelState); public IResult PartialView(Dictionary data, ModelStateDictionary? modelState = null) where TComponent : IComponent { if (HttpContextSafe.Response.Htmx().EmptyResponseBodyRequested) return Results.NoContent(); var parameters = new Dictionary(StringComparer.Ordinal) { { "ComponentType", typeof(TComponent) }, { "ComponentParameters", data }, { "ModelState", modelState } }; return new RazorComponentResult(parameters) { PreventStreamingRendering = false }; } public IResult PartialView(RenderFragment fragment) { ArgumentNullException.ThrowIfNull(fragment); if (HttpContextSafe.Response.Htmx().EmptyResponseBodyRequested) return Results.NoContent(); return new RazorComponentResult(new { Fragment = fragment }); } public IResult PartialView(params RenderFragment[] fragments) { ArgumentNullException.ThrowIfNull(fragments); if (HttpContextSafe.Response.Htmx().EmptyResponseBodyRequested) return Results.NoContent(); return new RazorComponentResult(new { Fragments = fragments }); } ``` -------------------------------- ### RzPartial Component Implementation Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt The RzPartial component is a Blazor ComponentBase designed for rendering partial content. It utilizes a fixed EmptyLayout and a DynamicComponent to display specified component types and their parameters. ```csharp using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.CompilerServices; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace Rizzy; [RizzyParameterize] public partial class RzPartial : ComponentBase { public static void CreateCascadingValue(RenderTreeBuilder builder, TValue value, RenderFragment fragment) { builder.OpenComponent>(0); builder.AddComponentParameter(1, "Value", value); builder.AddComponentParameter(2, "ChildContent", fragment); builder.CloseComponent(); } protected override void BuildRenderTree(RenderTreeBuilder builder) { CreateCascadingValue(builder, ModelState, builder2 => { builder2.OpenComponent(4); builder2.AddComponentParameter(5, "Layout", typeof(EmptyLayout)); builder2.AddAttribute(6, "ChildContent", (RenderFragment)((builder3) => { builder3.OpenComponent(7); builder3.AddComponentParameter(8, "Type", RuntimeHelpers.TypeCheck(ComponentType)); ``` -------------------------------- ### Render Razor Components with Data (C#) Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Methods for rendering Razor components, supporting data binding and model state. These methods abstract the creation of `RazorComponentResult` for both full views and partial views. They handle HTMX requests for empty responses and accept parameters via dictionaries or builder patterns. ```C# public IResult View(Action> parameterBuilderAction, ModelStateDictionary? modelState = null) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(parameterBuilderAction); if (HttpContextSafe.Response.Htmx().EmptyResponseBodyRequested) return Results.NoContent(); var builderInstance = new RizzyComponentParameterBuilder(); parameterBuilderAction(builderInstance); var parametersDictionary = builderInstance.Build(); return View(parametersDictionary, modelState); } public IResult View(object? data = null, ModelStateDictionary? modelState = null) where TComponent : IComponent => View(data.ToDictionary(), modelState); public IResult View(Dictionary data, ModelStateDictionary? modelState = null) where TComponent : IComponent { if (HttpContextSafe.Response.Htmx().EmptyResponseBodyRequested) return Results.NoContent(); var parameters = new Dictionary(StringComparer.Ordinal) { { "ComponentType", typeof(TComponent) }, { "ComponentParameters", data }, { "ModelState", modelState } }; return new RazorComponentResult(parameters) { PreventStreamingRendering = false }; } ``` -------------------------------- ### RzPage Component Implementation Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt The RzPage component is a Blazor ComponentBase that handles rendering dynamic components with optional layouts. It resolves layouts based on attributes or configuration and injects necessary services like RizzyConfig. ```csharp using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.CompilerServices; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Options; using Rizzy.Configuration; using System.Reflection; namespace Rizzy; [RizzyParameterize] public partial class RzPage : ComponentBase { private static readonly System.Collections.Concurrent.ConcurrentDictionary LayoutAttributeCache = new(); private Type? _layout = null; [Inject] public IOptions RizzyConfig { get; set; } = default!; public static void CreateCascadingValue(RenderTreeBuilder builder, TValue value, RenderFragment fragment) { builder.OpenComponent>(0); builder.AddComponentParameter(1, "Value", value); builder.AddComponentParameter(2, "ChildContent", fragment); builder.CloseComponent(); } protected override void BuildRenderTree(RenderTreeBuilder builder) { CreateCascadingValue(builder, ModelState, builderPage => { builderPage.OpenComponent(4, RizzyConfig.Value.RootComponent ?? typeof(EmptyRootComponent)); builderPage.AddAttribute(5, "ChildContent", (RenderFragment)(builder3 => { if (_layout != null) { builder3.OpenComponent(6); builder3.AddComponentParameter(7, "Layout", RuntimeHelpers.TypeCheck(_layout)); builder3.AddAttribute(8, "ChildContent", (RenderFragment)((builder4) => { builder4.OpenComponent(9); builder4.AddComponentParameter(10, "Type", RuntimeHelpers.TypeCheck(ComponentType)); builder4.AddComponentParameter(11, "Parameters", RuntimeHelpers.TypeCheck>(ComponentParameters)); builder4.CloseComponent(); })); builder3.CloseComponent(); } else { builder3.OpenComponent(12); builder3.AddComponentParameter(13, "Type", RuntimeHelpers.TypeCheck(ComponentType)); builder3.AddComponentParameter(14, "Parameters", RuntimeHelpers.TypeCheck>(ComponentParameters)); builder3.CloseComponent(); } })); builderPage.OpenComponent(15); builderPage.CloseComponent(); builderPage.CloseComponent(); }); } [Parameter, EditorRequired] public required Type ComponentType { get; set; } = default!; [Parameter, EditorRequired] public required Dictionary ComponentParameters { get; set; } = default!; [Parameter] public ModelStateDictionary? ModelState { get; set; } protected override void OnParametersSet() { if (!LayoutAttributeCache.TryGetValue(ComponentType, out _layout)) { _layout = ComponentType.GetCustomAttribute()?.LayoutType; LayoutAttributeCache.TryAdd(ComponentType, _layout); } if (_layout == null) { var config = RizzyConfig; if (config?.Value.DefaultLayout != null) _layout = config?.Value.DefaultLayout; } } } ``` -------------------------------- ### EmptyRootComponent Component (C#) Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt A root Blazor component that renders the basic HTML structure (`` and `` tags). It's designed to wrap application content, providing a minimal HTML document structure. ```csharp using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; namespace Rizzy; internal class EmptyRootComponent : ComponentBase { [Parameter] public RenderFragment ChildContent { get; set; } = default!; protected override void BuildRenderTree(RenderTreeBuilder builder) { builder.OpenElement(0, "html"); builder.OpenElement(1, "body"); builder.AddContent(2, ChildContent); builder.CloseElement(); builder.CloseElement(); } } ``` -------------------------------- ### Initialize Blazor Form Data from HttpContext Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Processes incoming form data and files from an HttpContext to initialize Blazor's form data provider. It dynamically loads necessary types and methods from ASP.NET Core Components assemblies. ```C# internal static void InitializeBlazorFormData(this HttpContext context) { if (!context.Request.HasFormContentType) return; var form = context.Request.Form; var formFiles = context.Request.Form.Files; string? handlerValue = form["_handler"].FirstOrDefault(); if (handlerValue is null) return; var types = Assembly.Load("Microsoft.AspNetCore.Components.Endpoints").GetTypes(); var providerType = types.First(t => t.Name == "HttpContextFormDataProvider"); var formDictType = types.First(t => t.Name == "FormCollectionReadOnlyDictionary"); object formDataProvider = context.RequestServices.GetRequiredService(providerType) ?? throw new Exception("HttpContextFormDataProvider is not registered."); object formDictInstance = Activator.CreateInstance(formDictType, form) ?? throw new Exception("Unable to create an instance of FormCollectionReadOnlyDictionary."); MethodInfo setFormDataMethod = providerType.GetMethod("SetFormData", BindingFlags.Public | BindingFlags.Instance) ?? throw new Exception("SetFormData method not found."); setFormDataMethod.Invoke(formDataProvider, [handlerValue, formDictInstance, formFiles]); } } ``` -------------------------------- ### RizzyComponentParameterBuilder: Add Event Callbacks Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Enables adding EventCallback parameters to a component builder using lambda expressions. Supports both synchronous and asynchronous callbacks, with and without arguments, ensuring proper callback creation and assignment. ```csharp public RizzyComponentParameterBuilder Add(Expression> selector, Action? callback) { return Add(selector, EventCallback.Factory.Create(callback?.Target!, callback ?? (() => { }))); } public RizzyComponentParameterBuilder Add(Expression> selector, Func? callback) { return Add(selector, EventCallback.Factory.Create(callback?.Target!, callback ?? (() => Task.CompletedTask))); } public RizzyComponentParameterBuilder Add(Expression>> selector, Action? callback) { return Add(selector, EventCallback.Factory.Create(callback?.Target!, callback ?? ((TArg _) => { }))); } public RizzyComponentParameterBuilder Add(Expression>> selector, Func? callback) { return Add(selector, EventCallback.Factory.Create(callback?.Target!, callback ?? ((TArg _) => Task.CompletedTask))); } ``` -------------------------------- ### MinimalLayout Component (C#) Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt A Blazor LayoutComponentBase that renders a minimal HTML document structure, including `` and `` tags, and places its Body content within the body. This is often used for HTMX-rendered fragments that need a basic HTML wrapper. ```csharp using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; namespace Rizzy; internal class MinimalLayout : LayoutComponentBase { protected override void BuildRenderTree(RenderTreeBuilder builder) { builder.OpenElement(0, "html"); builder.OpenElement(1, "body"); builder.AddContent(2, Body); builder.CloseElement(); builder.CloseElement(); } } ``` -------------------------------- ### Include Rizzy Client Script in Layout Source: https://github.com/jalexsocial/rizzy/blob/main/packages/rizzy/README.md Demonstrates how to include the Rizzy client script in a Blazor layout file (e.g., `_Layout.cshtml` or `App.razor`). It's crucial to load HTMX before the Rizzy client script. ```html ``` -------------------------------- ### C# Antiforgery Minified Property Configuration Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Configures whether to use the minified antiforgery JavaScript resource based on the build configuration (DEBUG vs. Release). The property's default value is set conditionally. ```csharp /// /// Determines whether to use the minified antiforgery JavaScript resource. /// #if DEBUG public bool Minified { get; set; } = false; #else public bool Minified { get; set; } = true; #endif ``` -------------------------------- ### RizzyToastService - Success and Warning Notifications Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Implements the RizzyToastService to manage and display toast notifications. This snippet includes the public methods for showing success and warning toasts, which internally use a helper method to add messages to a list. ```csharp using System; using System.Collections.Generic; namespace Rizzy; public class RizzyToastService : IRizzyToastService { private readonly List _notifications = new(); public RizzyToastService() { } private static string GetDefaultTitle(ToastStatus status) { return status switch { ToastStatus.Success => "Success", ToastStatus.Error => "Error", ToastStatus.Warning => "Warning", ToastStatus.Info => "Info", _ => "Notification", }; } private void AddToast(ToastStatus status, string title, string text, ToastMessageOptions? options) { var message = new ToastMessage { Status = status, Title = title, Text = text }; if (options != null) { message = message with { CustomIcon = options.CustomIcon ?? message.CustomIcon, CustomClass = options.CustomClass ?? message.CustomClass, Effect = options.Effect ?? message.Effect, Speed = options.Speed ?? message.Speed, ShowIcon = options.ShowIcon ?? message.ShowIcon, ShowCloseButton = options.ShowCloseButton ?? message.ShowCloseButton, AutoClose = options.AutoClose ?? message.AutoClose, AutoTimeout = options.AutoTimeout ?? message.AutoTimeout, Position = options.Position ?? message.Position, Gap = options.Gap ?? message.Gap, Distance = options.Distance ?? message.Distance, Type = options.Type ?? message.Type }; } _notifications.Add(message); } public void Success(string text, string? title = null, ToastMessageOptions? options = null) => AddToast(ToastStatus.Success, title ?? GetDefaultTitle(ToastStatus.Success), text, options); public void Warning(string text, string? title = null, ToastMessageOptions? options = null) => ``` -------------------------------- ### Rizzy.Htmx Response Operations Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy.Htmx/README.md This C# code demonstrates the fluent API for composing multiple htmx response operations. It shows how to chain methods like PushUrl and Reswap on the HtmxResponse object. ```csharp HttpContext.Response.Htmx(response => { response.PushUrl("/new-url") .Reswap("outerHTML"); }); ``` -------------------------------- ### IHtmxSwapService Interface Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Defines the contract for managing swappable content and Htmx interactions within the Rizzy framework. It includes methods for adding various content types, rendering, and clearing the service's state. ```csharp using Microsoft.AspNetCore.Components; using Rizzy.Htmx; namespace Rizzy; public interface IHtmxSwapService { event EventHandler? ContentItemsUpdated; void AddSwappableComponent(string targetId, Dictionary? parameters = null, SwapStyle swapStyle = SwapStyle.outerHTML, string? selector = null) where TComponent : IComponent; void AddSwappableComponent(string targetId, object? parameters = null, SwapStyle swapStyle = SwapStyle.outerHTML, string? selector = null) where TComponent : IComponent; void AddSwappableFragment(string targetId, RenderFragment renderFragment, SwapStyle swapStyle = SwapStyle.outerHTML, string? selector = null); void AddSwappableContent(string targetId, string content, SwapStyle swapStyle = SwapStyle.outerHTML, string? selector = null); void AddRawContent(string content); RenderFragment RenderToFragment(); Task RenderToString(); void Clear(); bool ContentAvailable { get; } } ``` -------------------------------- ### Format Lambda Expression to String in C# Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt This C# method formats a LambdaExpression into a human-readable string representation. It traverses the expression tree, handling member access, indexers, and calls to format the output. It supports an optional prefix and uses a ReverseStringBuilder for efficient string construction. ```csharp public static string FormatLambda(LambdaExpression expression) { return FormatLambda(expression, prefix: null); } public static string FormatLambda(LambdaExpression expression, string? prefix = null) { var builder = new ReverseStringBuilder(stackalloc char[StackAllocBufferSize]); var node = expression.Body; var wasLastExpressionMemberAccess = false; var wasLastExpressionIndexer = false; while (node is not null) { switch (node.NodeType) { case ExpressionType.Constant: var constantExpression = (ConstantExpression)node; node = null; break; case ExpressionType.Call: var methodCallExpression = (MethodCallExpression)node; if (!IsSingleArgumentIndexer(methodCallExpression)) { throw new InvalidOperationException("Method calls cannot be formatted."); } node = methodCallExpression.Object; if (prefix != null && node is ConstantExpression) { break; } if (wasLastExpressionMemberAccess) { wasLastExpressionMemberAccess = false; builder.InsertFront("."); } wasLastExpressionIndexer = true; builder.InsertFront("]"); FormatIndexArgument(methodCallExpression.Arguments[0], ref builder); builder.InsertFront("["); break; case ExpressionType.ArrayIndex: var binaryExpression = (BinaryExpression)node; node = binaryExpression.Left; if (prefix != null && node is ConstantExpression) { break; } if (wasLastExpressionMemberAccess) { wasLastExpressionMemberAccess = false; builder.InsertFront("."); } builder.InsertFront("]"); FormatIndexArgument(binaryExpression.Right, ref builder); builder.InsertFront("["); wasLastExpressionIndexer = true; break; case ExpressionType.MemberAccess: var memberExpression = (MemberExpression)node; node = memberExpression.Expression; if (prefix != null && node is ConstantExpression) { break; } if (wasLastExpressionMemberAccess) { builder.InsertFront("."); } wasLastExpressionMemberAccess = true; wasLastExpressionIndexer = false; var name = memberExpression.Member.GetCustomAttribute()?.Name ?? memberExpression.Member.Name; builder.InsertFront(name); break; default: node = null; break; } } if (prefix != null) { if (!builder.Empty && !wasLastExpressionIndexer) { builder.InsertFront("."); } builder.InsertFront(prefix); } return builder.ToString(); } ``` -------------------------------- ### Use Rizzy Middleware for ASP.NET Core Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt An extension method for IApplicationBuilder to easily integrate the RizzyMiddleware into the ASP.NET Core request pipeline. This middleware is essential for processing Rizzy-specific requests and features. ```C# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; namespace Rizzy; public static class AppBuilderExtensions { public static IApplicationBuilder UseRizzy(this IApplicationBuilder builder) { builder.UseMiddleware(); return builder; } } ``` -------------------------------- ### C# Utility: Create Nonce Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Generates a cryptographically secure random nonce. It creates 32 random bytes and encodes them using Base64UrlTextEncoder, suitable for security-sensitive operations. ```C# private static string CreateNonce() { byte[] randomBytes = new byte[32]; RandomNumberGenerator.Fill(randomBytes); return Base64UrlTextEncoder.Encode(randomBytes); } ``` -------------------------------- ### Define Rizzy Application Constants Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Provides constant string values used throughout the Rizzy application. These include HTTP headers like 'HX-Nonce', broadcast event names such as 'rz:toast-broadcast', and internal HttpContext keys. ```C# namespace Rizzy; internal class Constants { public const string NonceResponseHeader = "HX-Nonce"; public const string ToastBroadcastEventName = "rz:toast-broadcast"; internal static class HttpContextKeys { public const string NonceKey = "RizzyNonce"; } } ``` -------------------------------- ### C# GetString Embedded Resource Loader Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Loads the specified embedded resource from the assembly as a string. It handles resource lookup and throws an `ArgumentException` if the resource is not found. ```csharp /// /// Loads the specified embedded resource from the assembly as a . /// /// The resource name to retrieve. /// The embedded resource contents as a string. /// Thrown if the resource could not be found. private static string GetString(string name) { var assembly = typeof(HtmxAntiforgeryScript).Assembly; using var resource = assembly.GetManifestResourceStream(name); if (resource == null) throw new ArgumentException($"Resource \"{name}\" was not found.", nameof(name)); using var reader = new StreamReader(resource); var response = reader.ReadToEnd(); return response; } ``` -------------------------------- ### EmptyLayout Component (C#) Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt A minimal Blazor LayoutComponentBase that simply renders its Body content. It's used when no specific layout structure is required, providing a blank canvas for content. ```csharp using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; namespace Rizzy; internal class EmptyLayout : LayoutComponentBase { protected override void BuildRenderTree(RenderTreeBuilder builder) { builder.AddContent(0, Body); } } ``` -------------------------------- ### Add Rizzy Services to ServiceCollection Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt Configures the application's service collection by adding Rizzy-specific services, including HttpContextAccessor, form value providers, configuration, a DataAnnotationsProcessor, and the core IRizzyService. ```C# using Microsoft.AspNetCore.Components.Forms.Mapping; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Rizzy.Configuration; using Rizzy.Htmx; namespace Rizzy; public static class ServiceCollectionExtensions { public static IServiceCollection AddRizzy(this IServiceCollection services, Action? configBuilder = null) { services = services ?? throw new ArgumentNullException(nameof(services)); services.AddHttpContextAccessor(); services.AddSupplyValueFromFormProvider(); services.Configure(configBuilder ?? (cfg => { })); services.AddSingleton(); services.AddScoped(); ``` -------------------------------- ### Blazor Head Content Outlet Component Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt This Blazor component acts as an outlet for head content, rendering sections for both title and general head elements. It uses `SectionOutlet` to define where content injected by `RzHeadContent` will be rendered, and includes logic for a default title. ```csharp using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.Sections; namespace Rizzy; public sealed class RzHeadOutlet : ComponentBase { internal static readonly object HeadSectionId = new(); internal static readonly object TitleSectionId = new(); private readonly string? _defaultTitle = null; protected override void BuildRenderTree(RenderTreeBuilder builder) { builder.OpenComponent(0); builder.AddComponentParameter(1, nameof(SectionOutlet.SectionId), TitleSectionId); builder.CloseComponent(); if (!string.IsNullOrEmpty(_defaultTitle)) { builder.OpenComponent(2); builder.AddComponentParameter(3, nameof(SectionContent.SectionId), TitleSectionId); builder.AddComponentParameter(4, "IsDefaultContent", true); builder.AddComponentParameter(5, nameof(SectionContent.ChildContent), (RenderFragment)BuildDefaultTitleRenderTree); builder.CloseComponent(); } builder.OpenComponent(6); builder.AddComponentParameter(7, nameof(SectionOutlet.SectionId), HeadSectionId); builder.CloseComponent(); } private void BuildDefaultTitleRenderTree(RenderTreeBuilder builder) { builder.OpenElement(0, "title"); ``` -------------------------------- ### C# FragmentComponent Blazor Component Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt A Blazor component designed to render `RenderFragment` content. It supports rendering a single fragment or an enumerable collection of fragments, allowing for flexible content composition. ```csharp using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; using Rizzy.Framework.Mvc; namespace Rizzy; [RizzyParameterize] public partial class FragmentComponent : ComponentBase { [Parameter] public RenderFragment? Fragment { get; set; } [Parameter] public IEnumerable? Fragments { get; set; } protected override void BuildRenderTree(RenderTreeBuilder builder) { if (Fragment != null) { builder.AddContent(0, Fragment); } if (Fragments != null) { foreach (var fragment in Fragments) { if (fragment != null) { builder.AddContent(1, fragment); } } } } } ``` -------------------------------- ### HtmxLayout Component (C#) Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt A Blazor layout component that adapts rendering based on HTMX requests. It applies specific layouts (MinimalLayout for root, EmptyLayout otherwise) for HTMX requests and falls back to a provided generic layout (T) for standard browser requests. ```csharp using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Http; using Rizzy.Htmx; namespace Rizzy; public sealed class HtmxLayout : LayoutComponentBase where T : LayoutComponentBase { [CascadingParameter] public HttpContext? HttpContext { get; set; } [Parameter] public bool IsRootComponent { get; set; } = false; protected override void BuildRenderTree(RenderTreeBuilder builder) { if (HttpContext?.Request.IsHtmx() == true) { HttpContext?.Response.Headers.TryAdd("Vary", HtmxRequestHeaderNames.HtmxRequest); if (IsRootComponent) { builder.OpenComponent(0); } else { builder.OpenComponent(0); } } else { builder.OpenComponent(0); } builder.AddComponentParameter(1, "Body", Body); builder.CloseComponent(); } } ``` -------------------------------- ### Generate Unique IDs with Sqids in C# Source: https://github.com/jalexsocial/rizzy/blob/main/src/Rizzy/llmquery.txt A utility class for generating unique, short, and URL-friendly IDs using the Sqids library. It uses a counter and a randomly generated alphabet for encoding, allowing for prefixed IDs. ```csharp using Sqids; namespace Rizzy.Utility; public static class IdGenerator { private static Random _random = new(System.Environment.TickCount); private static long _counter = DateTime.UtcNow.Ticks; private static SqidsEncoder _encoder = new(new SqidsOptions() { Alphabet = new string("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".OrderBy(x => _random.Next()).ToArray()), }); public static string UniqueId(string prefix) { long uniqueNumber = Interlocked.Increment(ref _counter); var encodedNumber = _encoder.Encode(uniqueNumber); string finalPrefix = string.IsNullOrWhiteSpace(prefix) ? "id" : prefix; return $"{finalPrefix}{encodedNumber}"; } } ```