Showing posts with label WASM. Show all posts
Showing posts with label WASM. Show all posts

Blazor QuickGrid using a Remote DataSource

And thou shalt make for it a grating of network of brass; and upon the net shalt thou make four brazen rings in the four corners thereof.
וְעָשִׂיתָ לּוֹ מִכְבָּר מַעֲשֵׂה רֶשֶׁת נְחֹשֶׁת וְעָשִׂיתָ עַל-הָרֶשֶׁת אַרְבַּע טַבְּעֹת נְחֹשֶׁת עַל אַרְבַּע קְצוֹתָיו

I really had to stretch my imagination a bit searching for a reference to a grid in the Torah. The closest word I could find was רשת which usually relates to a network. Exodus 27:4 provided the quote above. I'm guessing that most Hebrew speaking coders use the English word "grid" but part of the reason I spend time on this blog is to expand my knowledge of Biblical Hebrew so there you go.

As of .NET 8, the new QuickGrid Blazor component is officially supported. This grid is intended as a simple, flexible grid for general purpose use. It lacks a lot of features like nested grids and drag to reorder columns that are found in some commercial grid components, but it supplies enough basic functionality to make it the grid of choice in a lot of applications.

While studying the documentation found here, I didn't see code for an end-to-end sample application that leveraged a remote datasource linked to a database. There is an example that leverages a publicly available API from the US FDA Food Enforcement database, but this API seems to lack a few features that I wanted to play with that would demonstrate data sorting and filtering in addition to pagination. As such, I decided to put together a simple demo project on my own that could demonstrate a number of the features you can leverage with this simple grid component.

Source for this example can be found at https://github.com/rlebowitz/Finaltouch.QuickGrid

The Microsoft documentation recommends leveraging the QuickGrid component's ItemProvider attribute. ItemProvider is simply a delegate for a callback method that GridItemsProvider type, where TGridItem is the type of data displayed in the grid. The callback you provide must have a parameter of type GridItemsProviderRequest which specifies the start index, maximum row count, and sort order of data to return. If the grid employs paging or virtualization, your data source also needs to provide a total item count as well.

The Backend

For purposes of this demonstration, I downloaded a public SQLite database containing census information on the most popular male and female baby names grouped by US state. I constructed a pretty simple REST API that retrieves some of the records based on metadata indicating a starting index value, the maximum number of rows to retrieve, the sort order of the data as well as certain kinds of filter data. The metadata class is seen below. The SortProperty enumeration is part of the QuickGrid component library. The Filter class is I created a simple repository class that processes metadata posted to an API controller and returns a result containing a list of records matching the filter criteria.

  
 public class GridMetaData
    {
        public int StartIndex { get; set; }
        public int? Count { get; set; }
        public ICollection? SortProperties { get; set; }
        public Filter? Filter { get; set; }
    }
    

    
    public class Filter
    {
        public string? Field { get; set; }
        public string? Value { get; set; }
        public Operator Operator { get; set; } = Operator.Equals;
        public bool IsValid => Field != null && Value != null;

    }


public enum Operator
    {
        Equals,
        NotEquals,
        GreaterThan,
        LessThan,
        Contains
    }

If the metadata syntax seems a bit odd, it's because I am using the System.Linq.Dynamic.Core library to create LINQ queries dynamically from string fragments. Dynamic LINQ is worth taking a look at if like me, you want to generate filters that can be changed by controls within the grid. I couple Dynamic LINQ with some IQueryable extension methods to make it easier to construct the necessary queries based on the filter criteria.

  
        public class NamesRepository : INamesRepository
    {
        private ILogger Logger { get; set; }
        private BabynamesContext Context { get; set; }

        public NamesRepository(ILogger logger, BabynamesContext context)
        {
            Logger = logger;
            Context = context;
        }

        public NamesResult? GetBabyNames([FromBody] GridMetaData metaData)
        {
            try
            {
                var ordering = Ordering(metaData.SortProperties);
                var ordered = string.IsNullOrEmpty(ordering)
                    ? Context.Babynames.OrderBy(t => t.State)
                    : Context.Babynames.OrderBy(ordering);
                var result = ordered
                    .Filter(metaData.Filter)
                    .Select(t => t)
                    .Skip(metaData.StartIndex)
                    .Take(metaData.Count ?? 10)
                    .AsNoTracking()
                    .ToListAsync();
                var count = Context.Babynames.AsQueryable().Filter(metaData.Filter).CountAsync();

                Task.WaitAll(count, result);

                return new NamesResult
                {
                    Count = count.Result,
                    BabyNames = result.Result
                };
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Controller Error");
            }
            return default;
        }

        //https://dynamic-linq.net/basic-simple-query#ordering-results
        private static string Ordering(ICollection? properties)
        {
            List columns = new();
            if (properties == null)
            {
                return string.Empty;
            }
            foreach (var property in properties)
            {
                if (property.Direction == SortDirection.Ascending)
                {
                    columns.Add(property.PropertyName);
                }
                else
                {
                    columns.Add($"{property.PropertyName} desc");
                }
            }
            return string.Join(", ", columns);
        }
    }

The Frontend

As the Razor code sample below shows, I've specified a callback method that matches the GridItemsProvider delegate type called NamesProvider. I've also indicated that I will be using pagination to view data in small chunks one at a time, so I don't need to leverage the Virtualize attribute for QuickGrid. I've chosen to only display a few of the data fields provided by my Sqlite database in this demo application. I specify that all the PropertyColumns are sortable, and, in order to demonstrate how to implement a search function using Dynamic Linq, I've provided an input field that will act as a filter on the State data property.


@page "/"
@using Microsoft.AspNetCore.Components;
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.QuickGrid
@layout Shared.MainLayout

<PageTitle>Baby Names</PageTitle>
<div class="container py-3">
    <div class="row mb-4">
        <div class="col-lg-8 mx-auto text-center">
            <h1 class="display-6">Most Popular Baby Names by State</h1>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-10 mx-auto">
            <div class="grid" tabindex="-1">
                <QuickGrid @ref="Grid" ItemsProvider="@NamesProvider" Class="comic-name" Theme="default" Virtualize="false" Pagination="@Pagination">
                    <PropertyColumn Title="State" Property="@(c => c.State)" Sortable="true" IsDefaultSortColumn="true">
                        <ColumnOptions>
                            <div class="search-box">
                                <input type="search" autofocus @bind="Filter" @bind:event="oninput" placeholder="State Name..." />
                            </div>
                        </ColumnOptions>
                    </PropertyColumn>
                    <PropertyColumn Title="Name" Property="@(c => c.Name)" Sortable="true" />
                    <PropertyColumn Title="Sex" Property="@(c => c.Sex)" Sortable="true" />
                    <PropertyColumn Title="Rank" Property="@(c => c.RankWithinSex)" Sortable="true" />
                </QuickGrid>
            </div>
            <Paginator State="@Pagination" />
        </div>
    </div>
</div>

The code-behind for this Razor page contains the method matching the delegate, and illustrates how data is posted to the REST service that provides sorting, filtering, etc. specifications at the same time. Note that each time that the Filter properties are updated, I call the QuickGrid's RefreshDataAsync method to let the grid know that it needs to pull back data that reflects the changes to the Filter.


public partial class Index
    {
        [Inject]
        private HttpClient Client { get; set; } = default!;
        private GridItemsProvider<Babyname>? NamesProvider { get; set; }

        private PaginationState Pagination = new PaginationState { ItemsPerPage = 10 };
        private QuickGrid<Babyname>? Grid { get; set; }
        private string? FilterText { get; set; }
        private string? Filter
        {
            get { return FilterText; }
            set
            {
                FilterText = value;
                if (Grid != null)
                {
                    Task.Run(Grid.RefreshDataAsync);
                }
            }
        }

        protected override void OnInitialized()
        {
            NamesProvider = Provider;
        }

        private async ValueTask<GridItemsProviderResult<Babyname>> Provider(GridItemsProviderRequest<Babyname> request)
        {
            GridItemsProviderResult<Babyname> result = default;
            var metaData = new GridMetaData
            {
                StartIndex = request.StartIndex,
                Count = request.Count,
                SortProperties = request.GetSortByProperties().ToArray(),
                Filter = new Filter { Field = "state", Operator = Operator.Contains, Value = FilterText },
            };
            var namesResult = await GetNames(metaData);
            if (namesResult != null)
            {
                result = new GridItemsProviderResult<Babyname>()
                {
                    Items = namesResult.BabyNames != null ? namesResult.BabyNames : Array.Empty<Babyname>(),
                    TotalItemCount = namesResult.Count
                };
            }
            return result;
        }

        public async Task<NamesResult?> GetNames(GridMetaData metaData)
        {
            var response = await Client.PostAsJsonAsync("api/BabyNames/GetBabyNames", metaData);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadFromJsonAsync<NamesResult>();
            }
            return null;
        }
    }

A Blazor Modal Component Based on Bootstrap 5

According to all that I show thee, after the pattern of the tabernacle and the pattern of all the instruments thereof, even so shall ye make it.
כְּכֹל אֲשֶׁר אֲנִי מַרְאֶה אוֹתְךָ אֵת תַּבְנִית הַמִּשְׁכָּן וְאֵת תַּבְנִית כָּל-כֵּלָיו וְכֵן תַּעֲשׂוּ

Exodus 25:9 uses the Hebrew word תבנית (tavniyt) to describe a pattern or template. The word derives from the root בנה which relates to building (construction).

Source can be found at https://github.com/rlebowitz/Finaltouch.Modal

Demo can be found at https://rlebowitz.github.io/Finaltouch.Modal/

I often need to use a modal control for editing small forms in my applications. While it would be possible to write such a control from scratch, it's much simpler to adapt an existing modal for this purpose. I like using Bootstrap 5 these days so I'm presenting the code for a Blazor version of their modal here.

The Bootstrap 5 modal design includes three subsections; a header, body and footer. The header generally includes a title and as the documentation recommends, a dismiss action (means to close the modal). You can of course, incorporate different header content, but I provide an approach that displays a header if you pass a title value, along with a dismiss action. The Razor code below shows a template that incorporates these features.

  
   <div tabindex="-1" class="modal fade @ModalZoom @ModalClass" style="display: @ModalDisplay" @attributes="AriaAttributes">
    <div class="modal-dialog @ModalScroll @ModalCentered">
        <div class="modal-content">
            @if (Title != null)
            {
                <div class="modal-header">
                    <h5 class="modal-title">@Title</h5>
                    <button class="btn-close" data-dismiss="modal" aria-label="Close" @onclick="Close">
                    </button>
                </div>
            }
            <div class="modal-body">
                @Body
            </div>
            @if (Footer != null)
            {
                <div class="modal-footer">
                    @Footer
                </div>
            }
        </div>
    </div>
</div>

<div class="modal-backdrop fade @ModalClass" style="display: @ModalDisplay"></div>
  
  

Looking at the C# code-behind, you'll see a few useful parameters that can be used to alter the behavior of the modal. You can switch between the "standard" animation where the modal appears to drop vertically into view, or use a zoom-like animation. You can center the dialog within the view, and you can add a scrollbar to the modal itself, provided that the content is sufficiently long, instead of using the scrollbar for the entire viewport that will appear automatically. I thought it would be fun to provide some scrollable content using a Hebrew Ipsum Lorem text generator.

There's very little actual code or logic required in this component. I automatically add the various aria attributes that you would see using the regular Javascript version of the Bootstrap component. One important feature to pay attention to are the Task.Delay() statements I utilize in the Open() and Close() methods. These are used to ensure that you can actually see the animation effects; without the delays the cool animations would have no time to complete their execution.

  
    
using Microsoft.AspNetCore.Components;

namespace Finaltouch.Modal.App.Shared
{
    /// <summary>
    /// A Blazor Modal Template Component
    /// </summary>
    public partial class DialogTemplate
    {
        [Parameter]
        public RenderFragment? Body { get; set; }
        [Parameter]
        public RenderFragment? Footer { get; set; }
        [Parameter]
        public string? Title { get; set; }
        [Parameter]
        public bool UseZoom { get; set; }
        [Parameter]
        public bool Scrollable { get; set; }
        public bool Centered { get; set; } = true;
        private string ModalDisplay { get; set; } = "none";
        private string ModalClass { get; set; } = string.Empty;
        private string ModalZoom => UseZoom ? "modal-zoom" : string.Empty;
        private string ModalScroll => Scrollable ? "modal-dialog-scrollable" : string.Empty;
        private string ModalCentered => (Centered && !Scrollable) ? "modal-dialog-centered" : string.Empty;

        private Dictionary<string, object> AriaAttributes
        {
            get
            {
                var attributes = new Dictionary<string, object>();
                if ("block".Equals(ModalDisplay))
                {
                    attributes.Clear();
                    attributes.Add("aria-modal", "true");
                    attributes.Add("role", "dialog");
                }
                else
                {
                    attributes.Clear();
                    attributes.Add("aria-hidden", "true");
                }
                return attributes;
            }
        }

        public async Task Open()
        {
            ModalDisplay = "block";
            await Task.Delay(200);
            ModalClass = "show";
        }

        public async Task Close()
        {
            ModalClass = string.Empty;
            await Task.Delay(200);
            ModalDisplay = "none";
        }

    }
}

Some of the code and inspiration for this component came from this thread on Stack Overflow. It's worth reading to see how other folks have created modal components based on Bootstrap.

An Enumeration-based Dropdown for WASM Blazor

This is the enumeration of the Sons of Israel    וּבְנֵ֣י יִשְׂרָאֵ֣ל לְֽמִסְפָּרָ֡ם

I found the above reference to enumeration in Chronicals 27:1 that seemed appropriate. The Hebrew word (l'misparam) here comes from the root ספר which is a bit unusual in that it has a couple of different meanings. In this instance, it relates to counting, but in other contexts it relates to writing.

I've often used dropdown controls that derive their dropdown items from a collection of values taken from a database. For some dropdowns where only a few items are needed whose values don't frequently change it may be simpler to use a dropdown that uses an enumeration as a data source.

I've created a sample enumeration called Desserts shown below. I'll elaborate on the use of the Display attribute momentarily.

  
   public enum Dessert
    {
        [Display(Name ="Chocolate Cake")]
        ChocolateCake,
        Baklavah,
        [Display(Name = "Fruit Compote")]
        FruitCompote,
        Tiramisu,
        [Display(Name = "Toffee Squares")]
        ToffeeSquares
    }
  
  

The Razor code seen here is very similar to the code I used for my generic dropdown . I make use of the Enum.GetValues() method to iterate over the various values found in my Desserts enumeration.


@typeparam TEnum
<div class="dropdown" @onfocusout="OnFocusOut">
    <button class="btn btn-primary dropdown-toggle @(Show ? "show" : string.Empty)" data-toggle="dropdown" type="button" @onmousedown="OnLabelMouseDown" aria-haspopup="true" aria-expanded="false">
        @Label
    </button>
    <div class="dropdown-menu @(Show ? "show" : string.Empty)">
        @{
            foreach (var enumValue in Enum.GetValues(typeof(TEnum)).Cast<TEnum>())
            {
                <button class="dropdown-item" type="button" @onmousedown="(() => OnItemMouseDown(enumValue))">@enumValue.DisplayName()</button>
            }
        }
    </div>
</div>

  

The C# code-behind is seen below:

  
public partial class EnumDropDown<TEnum> where TEnum : struct, Enum?
    {
        [Parameter]
        public EventCallback<TEnum?> Callback { get; set; }
        [Parameter]
        public TEnum? Selected { get; set; } = null;
        [Parameter]
        public string DefaultLabel { get; set; } = "Select";
        public string? Label => Selected == null ? DefaultLabel : Selected.DisplayName();
        private bool Show { get; set; } = false;

        private void OnFocusOut()
        {
            Show = false;
            StateHasChanged();
        }

        public void OnLabelMouseDown()
        {
            Show = !Show;
        }

        public async Task OnItemMouseDown(TEnum? item)
        {
            Show = false;
            if (item != null)
            {
                if (Callback.HasDelegate)
                {
                    await Callback.InvokeAsync(item);
                }
            }
        }
    }

The point of using the Display attribute from the System.ComponentModel.DataAnnotations namespace is to provide a mechanism for displaying spaces and reordering items in the dropdown. C# doesn't allow you to put spaces in the enum member names, so using the Display attribute is a simple workaround for this limitation. As you can see, at least 3 of the member names require spaces. You'll see that in both the Razor and C# code-behind for this component I employ an extension method called DisplayName() (see below). This method checks the selected member of the enumeration for the presence of a Display attribute. If the attribute is present and it has a Name parameter, that parameter value is returned instead of the ToString() value of the enumeration member. This trick allows us to display member names with spaces (and possibly other characters) that can't normally be used in the Enum definition.

  
public static class EnumExtensions
    {
        public static string? DisplayName(this Enum value)
        {
            if (value == null)
            {
                return null;
            }
            // Read the Display attribute name
            var name = value.ToString();
            if (name != null)
            {
                var member = value.GetType().GetMember(name)[0];
                var displayAttribute = member.GetCustomAttribute<DisplayAttribute>();
                if (displayAttribute != null)
                {
                    return displayAttribute.GetName();
                }
            }
            return Enum.GetName(value.GetType(), value);
        }
    }  
  
  

You can watch a short video demonstrating the use of the dropdown below.

The source code shown in this posting and a simple demo Razor page utilizing the dropdown can be found in my Github repository.

A Generic Dropdown control for WASM Blazor

Drop down, ye heavens, from above      הַרְעִיפוּ שָׁמַיִם מִמַּעַל

I thought that the Hebrew quote above and it's accompanying translation from the King James Bible (Isaiah 45:8) would make a good introduction to a short post on designing a dropdown control in Blazor. Truth be told, the King James translation of the first word isn't really that accurate. The Hebrew word "Harifu" translates roughly as "imparts" though it can also refer to "shower". However, since I'm talking about dropdown controls I figure we'll stick with King James' translation.

I recently needed to build a form for an application where I wanted to incorporate a dropdown control that could bind to any kind of class, and not just a string. I saw a few examples on Stack Overflow but none of them incorporated all the features that I wanted, and in a few cases, the code didn't work correctly. I thought I'd share the simple solution I came up with in case someone out there is looking for something similar.

In the past, I'd always created Blazor dropdowns using <select> and <option> elements. They work fine when you're dealing with string values but in this instance, I wanted to be able to iterate over a List of objects of some specified type and leverage a property or method to display the label for each dropdown item. Looking at the Dropdown component found in Bootstrap 5, they use a combination of <div>, <button> and/or <a> elements to produce a working widget. Since our goal is to create a pure Blazor component, we have to make some changes to the basic Bootstrap 5 design to handle mouse events and bind the selected dropdown item appropriately.

The DropDown<TItem> Razor class and its code behind below show how this accomplished. You may notice that I'm using a handler for the @onfocusout event on this control. While looking at other examples which did not include anything other than an @onmousedown handler, I noticed that the dropdown wouldn't close when you released the mouse button. Some examples tried using a @onblur event to resolve this, but I found this didn't work satisfactorily, hence the @onfocusout event show here.


@typeparam TItem
<div class="dropdown" @onfocusout="OnFocusOut">
    <button class="btn btn-primary dropdown-toggle @(Show ? "show" : string.Empty)" data-toggle="dropdown" type="button" @onmousedown="OnMouseDown" aria-haspopup="true" aria-expanded="false">
        @Label
    </button>
    <CascadingValue Value="@this">
        <div class="dropdown-menu @(Show ? "show" : string.Empty)">
            @ChildContent
        </div>
    </CascadingValue>
</div>


 public partial class DropDown<TItem>
     {
        [Parameter]
        public RenderFragment? Label { get; set; }
        [Parameter]
        public RenderFragment? ChildContent { get; set; }
        [Parameter]
        public EventCallback<TItem?> OnSelected { get; set; }
        private bool Show { get; set; } = false;
        private void OnMouseDown()
        {
            Show = !Show;
        }

        private void OnFocusOut()
        {
            Show = false;
            StateHasChanged();
        }

        public async Task HandleSelect(TItem? item)
        {
            Show = false;
            await OnSelected.InvokeAsync(item);
        }
    }

In order to display the dropdown items, I use the following code. Note that I chose to use <button> elements instead of <a> anchors. I found that anchors sometimes exhibit some odd behavior when you specify a hash character for the href attribute value.


@typeparam TItem
<button class="dropdown-item" type="button" @onmousedown="OnMouseDown">@RenderLabel</button>


public partial class DropDownItem<TItem> : ComponentBase
    {
        [CascadingParameter]
        public DropDown<TItem> DropDown { get; set; }
        [Parameter]
        public TItem Item { get; set; }
        [Parameter]
        public RenderFragment<TItem> Label { get; set; }

        private async Task OnMouseDown()
        {
            if (DropDown != null)
            {
                await DropDown.HandleSelect(Item, Label);
            }
        }

        private RenderFragment RenderLabel => Label != null && Item != null ? Label(Item) : null;
    }

A simple example of how to use this control is seen below. The type of class I use here, City, has a string property called Name that I use to label each dropdown item. You can see the relevant CallbackEvent (OnSelected) and other code referenced here in this Github repository.


<DropDown TItem="City" OnSelected="@OnSelectedCity">
    <Label>@((SelectedCity == null) ? "Select a City" : SelectedCity.Name)</Label>
		<ChildContent>
			@if (Cities != null)
				foreach (var city in Cities)
                {
					<DropDownItem TItem="City" Item="@city">
                    <Label>@city.Name</Label>
                    </DropDownItem>
                }
		</ChildContent>
</DropDown>

You can watch a short video demonstrating the use of the dropdown below.

The source code shown in this posting and a simple demo Razor page utilizing the dropdown can be found in my Github repository.