Saturday, 4 January 2025

Slider component for Blazor

I have added a Blazor component for Blazor, which uses INPUT of type range and additional CSS styling for more flexible setup of look and feel. The Blazor component is available on Github in my repo here:

https://github.com/toreaurstadboss/BlazorSlider

Blazor lib component

This repository contains Blazor lib Slider component that shows an input of type 'range'.

The slider got default horizontal layout, where the minimum value for the slider is shown to the most left of the scale, which goes along the x-axis for the slider got towards higher values and the maximum value is the value to the most right. The slider x-axis goes along the 'slider track'.

The value of the slider is indicated by the 'slider thumb'. Below the slider are shown 'tick marks', which are controlled by the Minimum and Maximum values and StepSize. Note that the supported data types are the data types that are IConvertible and struct, and the code expects types that can be converted to double. You can use integers for example, but also decimals or floats and so on. In addition, enums can be used, but it works only if your enum got consecutive values, for example 0,1,2,3,4 . The best results are if these consecutive values got the same StepSize. To start using the Blazor slider, add this using in your .razor file where you want to use the component.
 
@using BlazorSliderLib

Please note that the slider has been tested using Bootstrap, more specifically this version:

"bootstrap@5.3.3"
Here is sample markup you can add to test out the Blazor slider (3 sliders are rendered using a custom model and the updated values are shown in labels below :

    <div class="container"> 

        <div class="row">
            <div class="form-control col-md-4">
                <p><b>EQ5D-5L question 1.</b> <br />Mobility. Ability to walk.</p>
                <BlazorSliderLib.Slider T="Eq5dWalk" UseAlternateStyle="AlternateStyle.AlternateStyleInverseColorScale" Title="Ability to walk" ValueChanged="@((e) => UpdateEq5dQ1(e))"
                MinimumDescription="No Problems = The best ability to walk you can imagine" MaximumDescription="Incapable = The worst ability to walk you can imagine" />
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <p><b>EQ5D-5L question 6.</b> <br />We would like to how good or bad your health is TODAY.</p>
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <BlazorSliderLib.Slider T="int" UseAlternateStyle="AlternateStyle.AlternateStyle" Minimum="0" Maximum="100" @bind-Value="@(Model.Data.Eq5dq6)" Stepsize="5" Title="Your health today"
                MinimumDescription="0 = The worst health you can imagine" MaximumDescription="100 = The best health you can imagine" />
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <p><b>EQ5D-5L question 6.</b> <br />We would like to how good or bad your health is TODAY. V2 field.</p>
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <BlazorSliderLib.Slider T="int" Minimum="0" Maximum="100" ValueChanged="@((e) => UpdateEq5dq6V2(e))" Stepsize="5" Title="Your health today (v2 field)"
                MinimumDescription="0 = The worst health you can imagine" MaximumDescription="100 = The best health you can imagine" />
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <p>Value of Model.Data.Eq5dq1</p>
                @Model.Data.Eq5dq1
            </div>
        </div>

        <div class="row">
            <div class="form-control col-md-4"> <p>Value of Model.Data.Eq5d6</p>
                @Model.Data.Eq5dq6 
            </div> 
        </div>

        <div class="row">
            <div class="form-control col-md-4">
                <p>Value of Model.Data.Eq5d6V2</p>
                @Model.Data.Eq5dq6V2
            </div>
        </div>

    </div>

The different setup of sliders

The slider is set up either with an alternate style or using the default styling for sliders, that is, the slider uses an input type of 'range' and the default documented styling on Mozilla Developer Network (MDN) to render a Blazor slider. In addition, it is possible to set up the alternate style to use a inverted color range where higher values will get a reddish color and lower values will get a greenish color. The standard alternate style will show greenish colors for higher values. The following screenshot shows the possible styling that is possible. Note that the default styling is shown in the slider at the bottom, which will render a bit different in different browsers. In Chrome for example, the slider will render with a bluish color. In Edge Chromium, a grayish color is used for the 'slider tick' and 'slider thumb'. Screenshots showing the sliders: The following parameters can be used:
Title
Required. The title is shown below the slider component and centered horizontally along the center of the x-axis which the slider is oriented.
Value
The value of the slider. It can be data bound using either the @bind-Value directive attribute that supports two-way data binding. You can instead use the @ValueChanged event callback, if desired.
Minimum
The minimum value along the slider. It is default set to 0 for numbers. For enums, the lowest value is chosen of the enum (minimum enum alternative, converted to double internally).
Maximum
The maximum value along the slider. It is default set to 100 for numbers. For enums, the higheset value is chosen of the enum (maximum enum alternative, converted to double internally).
Stepsize
The step size for the slider. It is default set to 5 for numbers. For enums, it is set to 1. (note that internally the slider must use double values to work with the _tickmarks_, which expects double values).
ShowTickmarks
Shows tick marks for slider. It is default set to 'true'. Tick marks are generated from the values of Minimum, Maximum and StepSize.
MinimumDescription
Shows additionally description for the minimum value, shown as a small label below the slider. It will only be shown in the value is not empty.
UseAlternateStyle
If the UseAlternateStyle is set to either AlternateStyle and AlternateStyleInverseColorScale, alternate styling is used.

CSS rules to enable the slider

Actually, it is necessary to define a set of CSS rules to make the slider work. The slider's css rules are defined in two different files.

Default CSS rules

`Slider.css` The CSS rules below are taken from MDN Mozilla Developer Network page for the input type 'range' control. Input type 'range' control MDN article:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range

Additional settings are set up. The width is set to 100% so the slider can get as much horizontal space as possible and 'stretch'. There are also basic styles set up for both the tick label and datalist.The datalist is the tickmarks for the slider. The tick marks are automatically generated for the slider.


.sliderv2
{
    width:100%;
}

.sliderv2Label {
    font-weight: 400;
    text-align: center;
    left: 50%;
    font-size:0.7em;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, margin-bottom: 2px;
}

datalist {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    writing-mode: vertical-lr;
    width: 100%;
}

.tick-label {

    justify-content: space-between;
    font-size:0.6em;

    top: 20px; /* Adjust this value as needed */
}

input[type="range"] {
    width: 100%;
    margin: 0;
}


Alternate CSS rules

`SliderAlternate.css` The alternate CSS rules are setting up additional styling, where color encoding is used for the 'slider track' where higher values along the 'slider track' get a more 'greenish color', while lower values gets 'reddish values'. It is possible to set up the inverse color encoding here, with higher values getting 'reddish color'. Lower values gets more 'greenish colors' in this setup.


.alternate-style input[type="range"] {
    -webkit-appearance: none; /* Remove default styling */
    width: 100%;
    height: 8px;
    background: #ddd;
    outline: none;
    opacity: 0.7;
    transition: opacity .2s;
}

    .alternate-style input[type="range"]:hover {
        opacity: 1;
    }

    .alternate-style input[type="range"]::-webkit-slider-runnable-track {
        width: 100%;
        height: 8px;
        background: linear-gradient(to left, #A5D6A7, #FFF9C4, #FFCDD2); /* More desaturated gradient color */
        border: none;
        border-radius: 3px;
    }

        .alternate-style-inverse-colorscale input[type="range"]::-webkit-slider-runnable-track {
            background: linear-gradient(to right, #A5D6A7, #FFF9C4, #FFCDD2) !important; /* More desaturated gradient color, inverted color range */
        }


.alternate-style input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none; /* Remove default styling */
    appearance: none;
    width: 25px;
    height: 25px;
    background: #2E7D32; /* Even darker green thumb color */
    cursor: pointer;
    border-radius: 50%;
    margin-top: -15px !important; /* Move the thumb up */
}

    .alternate-style input[type="range"]::-moz-range-track {
        width: 100%;
        height: 8px;
        background: linear-gradient(to left, #A5D6A7, #FFF9C4, #FFCDD2); /* More desaturated gradient color */
        border: none;
        border-radius: 3px;
    }

        .alternate-style-inverse-colorscale input[type="range"]::-moz-range-track {
            background: linear-gradient(to right, #A5D6A7, #FFF9C4, #FFCDD2 !important; /* More desaturated gradient color, inverted color range */
        }

    .alternate-style input[type="range"]::-moz-range-thumb {
        width: 25px;
        height: 25px;
        background: #2E7D32; /* Even darker green thumb color */
        cursor: pointer;
        border-radius: 50%;
        transform: translateY(-15px); /* Move the thumb up */
    }


The implementation for the Blazor slider looks like this, in the codebehind file for the Slider:


using Microsoft.AspNetCore.Components;

namespace BlazorSliderLib
{

    /// <summary>
    /// Slider to be used in Blazor. Uses input type='range' with HTML5 element datalist and custom css to show a slider.
    /// To add tick marks, set the <see cref="ShowTickmarks"/> to true (this is default)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public partial class Slider<T> : ComponentBase
        where T : struct, IComparable
    {

        /// <summary>
        /// Initial value to set to the slider, data bound so it can also be read out
        /// </summary>
        [Parameter]
        public T Value { get; set; }

        public double ValueAsDouble { get; set; }

        public double GetValueAsDouble()
        {
            if (typeof(T).IsEnum)
            {
                if (_isInitialized)
                {
                    var e = _enumValues.FirstOrDefault(v => Convert.ToDouble(v).Equals(Convert.ToDouble(Value)));
                    return Convert.ToDouble(Convert.ChangeType(Value, typeof(int)));
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                return Convert.ToDouble(Value);
            }
        }        

        [Parameter, EditorRequired]
        public required string Title { get; set; }

        [Parameter]
        public string? MinimumDescription { get; set; }

        [Parameter]
        public string? MaximumDescription { get; set; }

        [Parameter]
        public double Minimum { get; set; } = typeof(T).IsEnum ? Enum.GetValues(typeof(T)).Cast<int>().Select(e => Convert.ToDouble(e)).Min() : 0.0;

        [Parameter]
        public double Maximum { get; set; } = typeof(T).IsEnum ? Enum.GetValues(typeof(T)).Cast<int>().Select(e => Convert.ToDouble(e)).Max() : 100.0;

        [Parameter]
        public double? Stepsize { get; set; } = typeof(T).IsEnum ? 1 : 5.0;

        [Parameter]
        public bool ShowTickmarks { get; set; } = true;

        [Parameter]
        public AlternateStyle UseAlternateStyle { get; set; } = AlternateStyle.None;

        [Parameter]
        public EventCallback<T> ValueChanged { get; set; }

        public List<double> Tickmarks { get; set; } = new List<double>();

        private List<T> _enumValues { get; set; } = new List<T>();

        private bool _isInitialized = false;

        private async Task OnValueChanged(ChangeEventArgs e)
        {
            if (e.Value == null)
            {
                return;
            }
            if (typeof(T).IsEnum && e.Value != null)
            {
                var enumValue = _enumValues.FirstOrDefault(v => Convert.ToDouble(v).Equals(Convert.ToDouble(e.Value))); 
                if (Enum.TryParse(typeof(T), enumValue.ToString(), out _)) {
                    Value = enumValue; //check that it was a non-null value set from the slider
                }
                else
                {
                    return; //if we cannot handle the enum value set, do not process further
                }
            }
            else
            {
                Value = (T)Convert.ChangeType(e.Value!, typeof(T));
            }

            ValueAsDouble = GetValueAsDouble();

            await ValueChanged.InvokeAsync(Value);
        }


        private string TickmarksId = "ticksmarks_" + Guid.NewGuid().ToString("N");

        protected override async Task OnParametersSetAsync()
        {
            if (_isInitialized)
            {
                return ; //initialize ONCE 
            }

            if (!typeof(T).IsEnum && Value.CompareTo(0) == 0)
            {
                Value = (T)Convert.ChangeType((Convert.ToDouble(Maximum) - Convert.ToDouble(Minimum)) / 2, typeof(T));
                ValueAsDouble = GetValueAsDouble();
            }

            if (Maximum.CompareTo(Minimum) < 1)
            {
                throw new ArgumentException("The value for parameter 'Maximum' is set to a smaller value than {Minimum}");
            }
            GenerateTickMarks();

            BuildEnumValuesListIfRequired();

            _isInitialized = true;

            await Task.CompletedTask;
        }

        private void BuildEnumValuesListIfRequired()
        {
            if (typeof(T).IsEnum)
            {
                foreach (var item in Enum.GetValues(typeof(T)))
                {
                    _enumValues.Add((T)item);
                }
            }
        }

        private void GenerateTickMarks()
        {
            Tickmarks.Clear();
            if (!ShowTickmarks)
            {
                return;
            }
            if (typeof(T).IsEnum)
            {
                int enumValuesCount = Enum.GetValues(typeof(T)).Length;
                double offsetEnum = 0;
                double minDoubleValue = Enum.GetValues(typeof(T)).Cast<int>().Select(e => Convert.ToDouble(e)).Min();
                double maxDoubleValue = Enum.GetValues(typeof(T)).Cast<int>().Select(e => Convert.ToDouble(e)).Max();
                double enumStepSizeCalculated = (maxDoubleValue - minDoubleValue) / enumValuesCount;

                foreach (var enumValue in Enum.GetValues(typeof(T)))
                {
                    Tickmarks.Add(offsetEnum);
                    offsetEnum += Math.Round(enumStepSizeCalculated, 0);
                }
                return;
            }

            for (double i = Convert.ToDouble(Minimum); i <= Convert.ToDouble(Maximum); i += Convert.ToDouble(Stepsize))
            {
                Tickmarks.Add(i);
            }

        }      

    }

    public enum AlternateStyle
    {
        /// <summary>
        /// No alternate style. Uses the ordinary styling for the slider (browser default of input type 'range')
        /// </summary>
        None,

        /// <summary>
        /// Applies alternate style, using in addition to the 'slider track' an additional visual hint with an additional 'slider track' right below that shows a reddish color for lowest parts of the scale to the slider and towards yellow and greenish hues for higher values
        /// The alternate style uses a larger 'slider thumb' and alternate style to the 'slider-track'. The alternate style gives a more interesting look, especially in Microsoft Edge Chromium.
        /// </summary>
        AlternateStyle,

        /// <summary>
        /// Similar in style to the alternate style, but uses the inverse scale for the colors along the slider
        /// </summary>
        AlternateStyleInverseColorScale
    }

}


The markup of the Slider looks like this:


@using Microsoft.AspNetCore.Components.Forms
@using BlazorSliderLib
@typeparam T where T : struct, IComparable

<div class="slider-container sliderv2 @((UseAlternateStyle == AlternateStyle.AlternateStyle || (UseAlternateStyle == AlternateStyle.AlternateStyleInverseColorScale))? "alternate-style" : "") @(UseAlternateStyle == AlternateStyle.AlternateStyleInverseColorScale ? "alternate-style-inverse-colorscale" : "")">
<input type="range" @bind="@ValueAsDouble" min="@Minimum" max="@Maximum" step="@Stepsize" list="@TickmarksId" @oninput="OnValueChanged" />
<datalist id="@TickmarksId">
    @{
        var itemIndex = 0;
    }
    @foreach (var value in Tickmarks){
        if (typeof(T).IsEnum){
            var itemLabel = _enumValues.ElementAt(itemIndex);
            <option class="tick-label" value="@value" label="@itemLabel"></option>
        }
        else {
            <option class="tick-label" value="@value" label="@value"></option>
        }
        itemIndex++;    
    }
</datalist>

<div class="row">
@if (!string.IsNullOrWhiteSpace(MinimumDescription)){
    <div class="col-md-4">
        <label class="sliderv2Label text-muted">@MinimumDescription</label>
    </div>
}
@if (!string.IsNullOrWhiteSpace(Title)){
    <div class="col-md-4">
        <label class="sliderv2Label text-muted" style="text-align:center">@Title: @Value</label>
    </div>
}

@if (!string.IsNullOrWhiteSpace(MaximumDescription)){
    <div class="col-md-4" style="text-align:right">
        <label class="sliderv2Label tet-muted text-end">@MaximumDescription</label>
    </div>
}

</div>

<link rel="stylesheet" href="_content/BlazorSliderLib/Slider.css" />
<link rel="stylesheet" href="_content/BlazorSliderLib/SliderAlternate.css" />

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico"/>


</div>


The slider control is provided "as is" and is free to change and use of no charge.

https://github.com/toreaurstadboss/BlazorSlider?tab=MIT-1-ov-file#readme

Friday, 27 December 2024

Terminating a process running on local port using Powershell

Developers who work with frontend and backend often switching between tools get a message that a certain process is holding a port. For example, using the dotnet command, you can get a message that the address is already in use. Note - you usually must decide if you really want to terminate the process running on a certain port, but if you are sure that you just want to close the process and free up the local port for its use, it would be nice to have a way of
just closing the process running on that local port. A typical output would be:

 System.IO.IOException: Failed to bind to address http://127.0.0.1:5000: address already in use.

We can locate which process is using te port, that is, the local port, and then terminate the process. This will free up the local port so we can use it. Here is a Powershell function that will find the process running at a local port, if any, given by a specied port number.


<#
.SYNOPSIS
Stops the process using the specified local port 

.DESCRIPTION
This function finds the process, if any, using the specified port and stops it.
In case there are no process, the function exits.

.PARAMETER portId
The port number to check for the process

.RETURNS int
If successful, returns 0. If not, returns -1.

.EXAMPLE
Terminate-Port -portId 5000
#>
function Terminate-Port {
    param (
        [Parameter(Mandatory = $true)]
        [int]$portId
    )

    # Get the process ID (PID) using the specified port 
    try {
        Write-Host "Looking for processing running using local port: $portId"
        $connection = Get-NetTCPConnection -LocalPort $portId -ErrorAction Stop
        if ($connection) {
            Write-Output "Port $portId is in use by process ID $($connection.OwningProcess | Select-Object -Unique)."
        } else {
            Write-Output "Port $portId is not in use."
            return 0 | Out-Null
        }
    } catch {
        Write-Output "An error occurred: $_"
        return -1 | Out-Null
    }

    $processId = $connection.OwningProcess

    if ($processId -and $processId -gt 0) {
        $process = Get-Process -Id $processId
        if ($process) {
            # Stop the process
            try {
                Stop-Process -Id $processId -Force
                Write-Host "Process running at port $portId was terminated."
                return 0 | Out-Null
            } catch {
                Write-Host "Could not stop process. Reason: $error"
            }
        }
    }

    Write-Host "No process found using port $portId."
    return -1 | Out-Null
}



To terminate , we just run the command

 Terminate-Port -portId 5000


Screenshots of the function being run: BEFORE the command Terminate-Port is run and AFTER. Note that the process running at the given portId was terminated and then the local port is freed up again.
AFTER

Monday, 23 December 2024

Custom spans in C#

This article will look more into Spans in C# and demonstrate how you can create a custom Span yourself.

Span<T> and ReadOnlySpan<T> were introduced in 2018 with C# 7.2 and .NET Core 2.1.

These types provide a way to work with contiguous regions of memory safely and efficiently, without copying data.

They are particularly useful for performance-critical applications, as they allow for slicing and accessing memory without the overhead of array bounds checking.

The introduction of spans marked a significant improvement in how .NET handles memory, offering developers more control and flexibility.

I have added a Github repo for the code shown in this article here:
https://github.com/toreaurstadboss/CustomSpan

ref struct and provide methods for supplying either a reference to an object or in more usual case, an arry. Inside the ref struct, with two fields :

    private readonly ref T _reference;
    private readonly int _length;

To provide support for passing in an array and a start index and length in the constructor of the ref struct


public CustomSpan(T[] array, int start, int length)
{
    ArgumentNullException.ThrowIfNull(array);
    if (!typeof(T).IsValueType && array.GetType() != typeof(T[]))
    {
        // Covariance guard
        throw new ArgumentException($"Covariance between types {typeof(T).FullName} and {array.GetType().FullName} is not supported in CustomSpan");
    }

#if TARGET_64BIT
    if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length)
    {
        throw new IndexOutOfRangeException("The index was out of bounds for the array");
    }
#else
    if ((uint)start + (uint)length > (uint)array.Length)
    {
        throw new IndexOutOfRangeException("The index was out of bounds for the array");
    }
#endif

    _reference = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), (nint)(uint)start); //nint - native integer
    _length = length;
}


MemoryMarshal class inside System.Runtime.InteropServices contains helper methods such as GetArrayDataReference, which returns a reference to the 0-th element of an array. As we can see, array variance checks are done in the method. The Unsafe class inside System.Runtime.CompilerServices provides a method Add which is used to add an element offset to a reference, handy for getting the offset. As we see, there are no copying of memory blocks, only a reference to the first element of the array and start, the offset. The length variable specified here just defines the length to use for bounds checking. Note that we must handle also if the code executes inside 32-bits and 64-bits environments. We finally return a reference to the array given by an offset provided the value start. The (nint) used here is native integer. We also want to provide an indexer, so we can retrieve a value directly. We also provide a writable indexer too, in the method GetWritable. This is not considered good practice regarding encapsulation, just to demonstrate how you could do it.


// Read-only indexer
public ref readonly T this[int index]
{
    get
    {
        if ((uint)index >= (uint)_length)
        {
            throw new IndexOutOfRangeException();
        }
        return ref Unsafe.Add(ref _reference, index);
    }
}

// Read-write indexer
public ref T GetWritable(int index)
{
    if ((uint)index >= (uint)_length)
    {
        throw new IndexOutOfRangeException();
    }
    return ref Unsafe.Add(ref _reference, index);
}


We also provide a method that returns a readonly span from the custom span.


    public ReadOnlySpan<T> AsReadOnlySpan()
    {
        return MemoryMarshal.CreateReadOnlySpan(ref _reference, _length);
    }

To use this CustomSpan, demo code is shown below:


void Main(){

    var nums = Enumerable.Range(0, 1000).ToArray(); 
    var spanOfNums = new CustomSpan<int>(nums, 500, 500); 
    var twentyToFifty = spanOfNums.Slice(20, 5);
    
    Console.WriteLine("Output of the twentytoFifty span:");
    twentyToFifty.PrintArrayContents(); //prints 520..525


    for (int i = 0; i < twentyToFifty.Length; i++)
    {
        twentyToFifty.GetWritable(i) = (int) Math.Pow((double)twentyToFifty[i], 2); //mutates the Span contents - squares the elements , using GetWritable
    }
    
    Console.WriteLine("\nOutput of the mutated twentytoFifty span:");
    twentyToFifty.PrintArrayContents();
}


The output looks like this:


Output of the twentytoFifty span:
520
521
522
523
524

Output of the mutated twentytoFifty span:
270400
271441
272484
273529
274576



Usually, you would use the built-in spans in C#, as they contain the necessary functionality you need. This article was just a dive into how Spans are implemented, the code for Spans are available on the .NET source code web site :

https://source.dot.net https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Span.cs,d2517139cac388e8