Tuesday, 4 July 2023

Writing cookies with Blazor WASM

This article presents some source code of how to write and read cookies from Blazor WebAssembly - WASM. For Blazor WASM, we are going to use Javascript to write these cookies. Blazor WASM has not an easy way to write these cookies programatically, as the use of HttpContext accessor is discouraged and not available, i.e. you cannot just add cookies without round trips to backend services.

But via Js, the client can write cookies. I looked into a helper lib to write such cookies and do so using different attribute values for the cookies.
The following Mozilla Developer Network (MDN) page is helpful in detailing cookies, which attribute values can be set on them. Cookies are used to give user experience since they track user's on a web site and give tailored user experience - and advertising - and also can track the users accross servers / web sites as third-party cookies. They are small string values that are either stored on clients inside cookie storage in the browser's folder on the user's hard drive or in memory or other place such as partitioned cookies.

MND page - document.cookies

https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie First off, the source code is here:

Forked Repo with adaptions in cookie handling for Blazor WASM

https://github.com/toreaurstadboss/AltairCA.Blazor.WebAssembly.Cookie This is a forked repo from this repo:

Original repo with cookie handling for Blazor WASM

https://github.com/AltairCA/AltairCA.Blazor.WebAssembly.Cookie The most recent branch of mine is this one: https://github.com/toreaurstadboss/AltairCA.Blazor.WebAssembly.Cookie/blob/feature/more-cookie-keys/README.md
Let's first look at the interface for the util class that will write cookies :

Interface for cookie handling for Blazor.wasm, IAltairCABlazorCookieUtil.cs

 
 
using AltairCA.Blazor.WebAssembly.Cookie.Models;

namespace AltairCA.Blazor.WebAssembly.Cookie
{
    public interface IAltairCABlazorCookieUtil
    {
        /// <summary>
        /// Set a object in the cookie
        /// </summary>
        /// <param name="key">The key for the cookie (name)</param>
        /// <param name="value">Cookie value</param>
        /// <param name="span">TimeSpan that will be set to the 'expires' attribute value</param>
        /// <param name="path">Path in the request url which must exist for the cookie to be sent in requests </param>
        /// <param name="domain">The host to which the cookie will be sent</param>
        /// <param name="secure">Specifies that the cookie will be sent only over secure protocols</param>
        /// <param name="isSession">Flags the cookie as a session cookie (temporal) by setting the 'expires' attribute value to ''</param>
        /// <param name="partitioned">Requires that the browser has activated partitioned cookies</param>
        /// <param name="maxAgeInSeconds">Maximum age in seconds</param> 
        /// <returns></returns>
        Task SetValueAsync(string key, object value, TimeSpan? span = null, string? path = null,
            string? domain = null, bool? secure = null, SameSite? sameSite = null, bool? partitioned = null, 
            bool? isSession = null, int? maxAgeInSeconds = null);

        /// <summary>
        /// Set a string in the cookie
        /// </summary>
        /// <param name="key">The key for the cookie (name)</param>
        /// <param name="value">Cookie value</param>
        /// <param name="span">TimeSpan that will be set to the 'expires' attribute value</param>
        /// <param name="path">Path in the request url which must exist for the cookie to be sent in requests </param>
        /// <param name="domain">The host to which the cookie will be sent</param>
        /// <param name="secure">Specifies that the cookie will be sent only over secure protocols</param>
        /// <param name="isSession">Flags the cookie as a session cookie (temporal) by setting the 'expires' attribute value to ''</param>
        /// <param name="partitioned">Requires that the browser has activated partitioned cookies</param>
        /// <param name="maxAgeInSeconds">Maximum age in seconds</param> 
        /// <returns></returns>
        Task SetValueAsync(string key, string value, TimeSpan? span = null, string? path=null, string? domain=null, 
            bool? secure = null, SameSite? sameSite = null, bool? partitioned = null, bool? isSession = null,
            int? maxAgeInSeconds = null);
       
        Task<string> GetValueAsync(string key);
       
        Task<T> GetValueAsync<T>(string key) where T : class;
        
        Task RemoveAsync(string key, string? path = null);

    }
}
 
 
And here is the implementation.

Implementation for cookie handling for Blazor.wasm, AltairCABlazorCookieUtil.cs

 
 
using System.ComponentModel;
using AltairCA.Blazor.WebAssembly.Cookie.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.JSInterop;
using Newtonsoft.Json;

namespace AltairCA.Blazor.WebAssembly.Cookie
{

    internal class AltairCABlazorCookieUtil : IAltairCABlazorCookieUtil
    {
        readonly IJSRuntime JSRuntime;
        private readonly AltairCABlazorCookieConfigOptions _settings;
        public AltairCABlazorCookieUtil(IJSRuntime jsRuntime,IOptions<AltairCABlazorCookieConfigOptions> options)
        {
            JSRuntime = jsRuntime;
            _settings = options.Value;
        }

        public Task SetValueAsync(string key, object value, TimeSpan? span = null, string? path = null,
            string? domain = null, bool? secure = null, SameSite? sameSite = null, bool? partitioned = null, bool? isSession = null,
            int? maxAgeInSeconds = null)
        {
            return SetValueAsync(key, JsonConvert.SerializeObject(value), span, path, domain, secure, sameSite, partitioned,
                isSession);
        }
        public async Task SetValueAsync(string key, string value, TimeSpan? span = null, string? path=null, string? domain=null, 
            bool? secure = null, SameSite? sameSite = null, bool? partitioned = null, bool? isSession = null,
             int? maxAgeInSeconds = null)
        {
            if (string.IsNullOrWhiteSpace(path))
                path = _settings.Path;
            if (!span.HasValue)
                span = _settings.DefaultExpire;
            if (string.IsNullOrWhiteSpace(domain))
                domain = _settings.Domain;
            if (!secure.HasValue)
                secure = _settings.IsSecure;
            
            var curExp = span.HasValue && span.Value.Ticks > 0 && isSession != true && !maxAgeInSeconds.HasValue ?  DateToUTC(span.Value) : "";            
            
            List<string> keyvals = new List<string>();
            keyvals.Add($"{key}={value}");
            keyvals.Add($"expires={curExp}");
            keyvals.Add($"path={path}");
            if(!string.IsNullOrWhiteSpace(domain))
                keyvals.Add($"domain={domain}");
            if(secure.HasValue && secure.Value)
                keyvals.Add("secure");
            if (maxAgeInSeconds.HasValue && isSession != true)
            {
                keyvals.Add($"max-age={maxAgeInSeconds.Value}");
            }
            if (sameSite.HasValue){
                DescriptionAttribute desc = (DescriptionAttribute) typeof(SameSite).GetMember(sameSite.Value.ToString()).First().GetCustomAttributes(typeof(DescriptionAttribute), false).First();
                keyvals.Add($"samesite={desc.Description}");
            } 
            string cookieToSet = string.Join(";", keyvals);
            if (partitioned == true){
                cookieToSet += ";partitioned";
            }
            
            await SetCookie(cookieToSet);
        }

        public async Task RemoveAsync(string key,string path = null)
        {
            if (string.IsNullOrWhiteSpace(path))
                path = _settings.Path;
            List<string> keyvals = new List<string>();
            keyvals.Add($"{key}=");
            keyvals.Add($"Path={path}");
            keyvals.Add($"expires=Thu, 01 Jan 1970 00:00:01 GMT;");
            await SetCookie(string.Join(";", keyvals));
        }

        public async Task<T> GetValueAsync<T>(string key) where T : class
        {
            var res = await GetValueAsync(key);
            if (res == null)
                return default(T);
            return JsonConvert.DeserializeObject<T>(res);
        }
        public async Task<string> GetValueAsync(string key)
        {
            var cValue = await GetCookie();
            if (string.IsNullOrEmpty(cValue)) return null;                

            var vals = cValue.Split(';');
            foreach (var val in vals)
                if(!string.IsNullOrEmpty(val) && val.IndexOf('=') > 0)
                    if(val.Substring(0, val.IndexOf('=')).Trim().Equals(key, StringComparison.OrdinalIgnoreCase))
                        return val.Substring(val.IndexOf('=') + 1);
            return null;
        }

        private async Task SetCookie(string value)
        {
            await JSRuntime.InvokeVoidAsync("eval", $"document.cookie = \'{value}\'");
        }

        private async Task<string> GetCookie()
        {
            return await JSRuntime.InvokeAsync<string>("eval", $"document.cookie");
        }
        private static string DateToUTC(TimeSpan span) => DateTime.Now.Add(span).ToUniversalTime().ToString("R");
    }
}


//we also have this enum used in cookie handler class above

using System.ComponentModel;

namespace AltairCA.Blazor.WebAssembly.Cookie.Models;

public enum SameSite {
    
    [Description("lax")]
    Lax = 0,

    [Description("strict")]
    Strict = 1,

    [Description("none")]
    None = 2
    
}
 
 


The MDN article details a lot around cookies and there are a lot of way of controlling these cookies via attributes. Most browsers limit Cookie sizes to be 4 kilobytes maximum length (4096 bytes) of all cookies on a server. And a maxiumum of 50 cookies, still must be below the 4 kB limit. https://stackoverflow.com/a/4604212 We set up the cookie handling via Program.cs of a Blazor WASM like this :

Implementation for cookie handling for Blazor.wasm, AltairCABlazorCookieUtil.cs

 

builder.Services.AddAltairCACookieService(options =>
{
    options.DefaultExpire = TimeSpan.FromMinutes(15);
});




This extension method on IServiceCollection adds the cookie handling as a singleton service, AltairCABlazorCookieUtil.cs

 

using AltairCA.Blazor.WebAssembly.Cookie.Models;
using Microsoft.Extensions.DependencyInjection;

namespace AltairCA.Blazor.WebAssembly.Cookie.Framework;

public static class PipelineExtension
{
    public static IServiceCollection AddAltairCACookieService(this IServiceCollection services,Action<AltairCABlazorCookieConfigOptions> configure)
    {
        services.Configure(configure);
        services.AddSingleton<IAltairCABlazorCookieUtil, AltairCABlazorCookieUtil>();
        return services;
    } 
}

//note - the extension method above also uses this model class to set up default options for cookies 

namespace AltairCA.Blazor.WebAssembly.Cookie.Models;

public class AltairCABlazorCookieConfigOptions
{
    public TimeSpan DefaultExpire { get; set; } = TimeSpan.Zero;
    public string Path { get; set; } = "/";
    public string Domain { get; set; } = string.Empty;
    public bool IsSecure { get; set; } = false;
}



As can be seen in the implementation, these default config options are injected in the constructor via :

AltairCABlazorCookieUtil.cs - constructor parameter injecting the options which was set via services.Configure in the extension method of the pipeline

 
public AltairCABlazorCookieUtil(IJSRuntime jsRuntime,IOptions<AltairCABlazorCookieConfigOptions> options)
{
	JSRuntime = jsRuntime;
    _settings = options.Value;
}

As we can see, we remove the cookie by setting it to expire at Unix Epoch zero (1970, 1st of January) in the cookie handling. A good util to inspect Cookies and even edit them are available in this Google plugin: Edit this Cookie




Counter.razor - using the Cookie util in Blazor WASM sample app

 
 
 @inject IAltairCABlazorCookieUtil _cookieUtil;
 
  
 
 
private async Task IncrementCount()
    {
        currentCount++;
        Content = await _cookieUtil.GetValueAsync("c");
        ContentObj = await _cookieUtil.GetValueAsync<object>("d");

        await _cookieUtil.SetValueAsync("c", "this is cookie with key c");
        await _cookieUtil.SetValueAsync("d", new
        {
            hello = "hello world. i am a cookie with key d"
        });
        await _cookieUtil.SetValueAsync("cookieWithSameSiteSet", "Cookie which specified cross site request inclusion of the cookie : SameSite value (lax | strict | none)", sameSite: SameSite.Lax);

        await _cookieUtil.SetValueAsync("cookiePartitioned", "Partitioned cookie", partitioned: true);
     
        await _cookieUtil.SetValueAsync("cookieWithMaxAge", "Max age cookie", maxAgeInSeconds: 600);

        await _cookieUtil.SetValueAsync("cookieWhichIsToBeSetToSessionCookie", "Session cookie = temporal cookie", isSession: true);

    }
  
One important note about the cookie util here, observe the usage of the 'eval' method to set the cookie via Js in the util class and also retrieve cookies :

Implementation for cookie handling for Blazor.wasm, AltairCABlazorCookieUtil.cs

 
 
   private async Task SetCookie(string value)
        {
            await JSRuntime.InvokeVoidAsync("eval", $"document.cookie = \'{value}\'");
        }

        private async Task<string> GetCookie()
        {
            return await JSRuntime.InvokeAsync<string>("eval", $"document.cookie");
        }
 
 


Using 'eval' we let Js run the Js code we pass in here in Blazor WASM app. This also means that we cannot write HttpOnly cookies, since we rely fully on Js here.

As some of you know, third party cookie support are planned by Chrome to be discontinued in support. The following article is interesting reading about this. https://itrust-digital.com/cookieless-future/

Saturday, 17 June 2023

Generic factory in C#

I tested out methods for building a simple generic factory in C#. This is using reflection to instantiate objects. It shows how we can combine some central methods in reflection to instantiate objects from types, they either being non-generic types, generic types which are either closed generic types or open generic types :
  • Activator.CreateInstance to instantiate the objects
  • MakeGenericType to close the generic type, which must be an open generic type
  • IsGenericTypeDefinition to check if the type is an open generic type
Consider this code where we attempt to make a generic type from an already closed type, it gives an InvalidOperationException telling us that we must check that IsGenericTypeDefinition is true on the type.

var someconcrete = typeof(Dictionary<string, int>);
var foo = someconcrete.MakeGenericType();

The Generic factory could of course be complex, support a multitude of scenarios, including resolving constructor arguments and their dependencies. This is more just demonstration code how you could instantiate objects via either closed or open generics in .NET. Observe that Activator.CreateInstance got a lot of different possible overloads.

Generic factory pattern in C# using reflection - simple approach






public static class GenericFactory {

	public static object CreateInstance<T>(Type type){		
		if (type.IsGenericTypeDefinition){
			var closedGenericType = type.MakeGenericType(typeof(T));	
			return Activator.CreateInstance(closedGenericType);			
		}		
		return Activator.CreateInstance<T>();	
	}

	public static TReturn CreateInstance<T, TReturn>(Type type)
	{
		if (type.IsGenericTypeDefinition)
		{
			var closedGenericType = type.MakeGenericType(typeof(T));
			return (TReturn) Activator.CreateInstance(closedGenericType);
		}
		return (TReturn) Activator.CreateInstance<TReturn>();
	}

	public static TReturn CreateInstance<T1, T2, TReturn>(Type type, params object[] args)
	{
		if (type.IsGenericTypeDefinition)
		{
			var closedGenericType = type.MakeGenericType(typeof(T1), typeof(T2));
			return (TReturn)Activator.CreateInstance(closedGenericType, args);
		}
		return (TReturn)Activator.CreateInstance(type, args);
	}

	public static object CreateInstance(Type type, Type[]genericTypeArguments, params object[] args)
	{
		if (type.IsGenericTypeDefinition)
		{
			var closedGenericType = type.MakeGenericType(genericTypeArguments);
			return Activator.CreateInstance(closedGenericType, args);
		}
		return Activator.CreateInstance(type, args);
	}

	public static TReturn CreateInstance<TReturn>(Type type, Type[] genericTypeArguments, params object[] args)
	{
		if (type.IsGenericTypeDefinition)
		{
			var closedGenericType = type.MakeGenericType(genericTypeArguments);
			return (TReturn) Activator.CreateInstance(closedGenericType, args);
		}
		return (TReturn) Activator.CreateInstance(type, args);
	}

	public static TReturn CreateInstance<T, TReturn>(Type type, params object[] args)
	{
		if (type.IsGenericTypeDefinition)
		{
			var closedGenericType = type.MakeGenericType(typeof(T));
			return (TReturn)Activator.CreateInstance(closedGenericType, args);
		}
		return (TReturn)Activator.CreateInstance(type, args);
	}

	public static T CreateInstance<T>(){
		return (T) Activator.CreateInstance(typeof(T));
	}
	
	public static T CreateInstance<T>(params object[] args){
		return (T) Activator.CreateInstance(typeof(T), args);
	}
	
	
}


Next up, some sample code to test out these helper methods. The code shows that there really is few methods involved to create instances from open generic types or closed generic types. The three mentioned methods and properties at the top of this article.

Sample code using Generic factory



  
  
void Main()
{
	
	//var someconcrete = typeof(Dictionary<string, int>);
	//var foo = someconcrete.MakeGenericType();
	
	var redCar = GenericFactory.CreateInstance<Car>();
	redCar.Color = Colors.Red;
	redCar.Model = "A5";
	redCar.Make = "Audi";
	redCar.Dump("The red car was created using default constructor and reflection with Activator.CreateInstance");
	
	var blueCar = GenericFactory.CreateInstance<Car>("Tesla", "Model X", Colors.Blue);
	blueCar.Dump("The blue car was created using constructor arguments matching the closest constructor with reflection and Activator.CreateInstance");
	
	var carPool = GenericFactory.CreateInstance<Car>(typeof(VehiclePool<>));
	carPool.Dump("Empty carpool which is of type object was created with reflection passing in an open generic type and specifying the type to close the generic with using MakeGenericType");

	var carPool3 = GenericFactory.CreateInstance<Car, VehiclePool<Car>>(typeof(VehiclePool<>));
    carPool3.AddVechicle(1, redCar);
	carPool3.AddVechicle(2, blueCar);
	carPool3.Dump("CarPool casted to specific type VehiclePool<Car> contains these cars - it was created using open generic type specifying a type to close the generic with with MakeGenericType:");
	
	var dictionaryOfIntAndString = GenericFactory.CreateInstance<int, string, Dictionary<int, string>>(typeof(Dictionary<,>));

	dictionaryOfIntAndString[0] = "Audi A5";
	dictionaryOfIntAndString[1] = "Audi A8";
	dictionaryOfIntAndString[2] = "Audi RS8";
	
	dictionaryOfIntAndString.Dump("Dictionary<int,string> contains these cars. It was constructed using an open generic type Dictionary<,> and passing in the generic type arguments of int and string using Activator.CreateInstance with MakeGenericType");
		
}
  
    
The sample code uses these types :

Sample types using Generic factory



  
  
  

public class VehiclePool<T> : IPool<T>{
	private Dictionary<int, T> _pool = new Dictionary<int, T>();
	
	public Dictionary<int, T> Pool {
		get {
			return _pool;
		}
	}
	public VehiclePool()
	{
	}

	public void AddVechicle(int vehicleId, T vehicle)
	{
		if (!_pool.ContainsKey(vehicleId)){
			_pool.Add(vehicleId, vehicle);
		}
	}

	public T GetVehicle(int vehicleId)
	{
		if (_pool.ContainsKey(vehicleId)){
			return _pool[vehicleId];
		}
		return default(T);
	}

	public void RemoveVehicle(int vehicleId)
	{
		if (_pool.ContainsKey(vehicleId))
		{
			_pool.Remove(vehicleId);
		}
		else
		{
			throw new ArgumentException($"Vehicle with {vehicleId} does not exist");
		}
	}
}

public interface IPool<T> {
	void AddVechicle(int vehicleId, T vehicle);
	void RemoveVehicle(int vehicleId);
	T GetVehicle(int vehicleId);
}

public class Car {
	
	public string Model { get; set; }
	public string Make { get; set; }
	public int WheelCount { get; set; } = 4;
	public Color Color { get; set; }
	
	public Car()
	{		
	}
	
	public Car(string make, string model, Color color)
	{
		Make = make;
		Model = model;
		Color = color;
	}
}

  
  
Here is the output.

Sample code using Generic factory



Note that Activator.CreateInstance returns object, so if you want a strongly typed object, you should specify the return type, TReturn in the code sample above. You could consider using dynamic here, but then you loose the Intellisense if you want to avoid unboxing the object returned to a specific type. Then we would use a very basic method first like this:
 
 

public static T CreateInstance<T>(params object[] args){
		return (T) Activator.CreateInstance(typeof(T), args);
}
 
 
Using dynamic we can ignore casting the object to a specific type and continue using late binding, which we use already with reflection.

    dynamic redCar = GenericFactory.CreateInstance(typeof(Car));
	redCar.Color = Colors.Red;
	redCar.Model = "A5";
	redCar.Make = "Audi";
	redCar.Dump("The red car was created using default constructor and reflection with Activator.CreateInstance");


Thursday, 18 May 2023

Animations in Blazor



I tested out animations in Blazor today, using the AOS - Animate on Scroll - library. I will use Blazor WASM for this. The sample code in this article can be cloned from my GitHub repo here: https://github.com/toreaurstadboss/BlazorAnimateSample This library is very easy to set up for Blazor. First off, go to the AOS website for installation instructions. AOS Github Pages On this site, copy the links to the CSS and Js file from the CDN. But note that I instead used VS 2022 and choose:
Add=>Client-side Library


The benefit of using this way of adding Aos is that the CSS and Js is installed into lib folders and you can drag the two files into the <head> section and <script> section inside body tag at the bottom of the index.html file. You set up AOS using the init method. You can either define a startEvent or not, it should default to event DOMContentLoaded i.e. when the element is displayed, the animation is started. The use of AOS and init method is explained in the GitHub repo for AOS: https://github.com/michalsnik/aos I set up AOS like this in index.html:
 

    <script src="_framework/blazor.webassembly.js"></script>
    <script src="js/animate.js"></script>
    <script src="lib/aos/aos.js"></script>
    <script>
        AOS.init({
            easing: 'ease-in-out',
            //startEvent: 'custom'
        });
    </script>
    
 
You can set the startEvent to 'custom' for example if you want to disable automatically loading the start of animations as soon as the element is scrolled into view or displayed in some other control manner. (actually you could set it to 'myEvent' here or some other gibberish value, to turn off automatically loading animations. Over to the file animate.js which will be used by the Animation component in Blazor (will be described later in this article).
 
 



function RegisterAnimationStartupTrigger(wrapperAnimationElementId, triggerElementId, triggerEventId) {
    //debugger
    if (event != null && event.target != null && event.target != undefined && event.target.closest) {
        var closestParentDiv = event.target.closest('div');
        if (closestParentDiv != null && closestParentDiv.id == wrapperAnimationElementId) {

            //sub elements of the wrapper div should not trigger animation, to avoid AOS running animation again
            return;
        }
    }
    
    var elem = document.getElementById(wrapperAnimationElementId);
    if (elem == null || elem == undefined) {
        return;
    }
    var triggerElement = document.getElementById(triggerElementId);
    if (triggerElement == null || triggerElement == undefined) {
        return;
    }

    elem.classList.remove('aos-init'); //remove aos-animate class to avoid auto loading animation on scroll
    elem.classList.remove('aos-animate'); //remove aos-animate class to avoid auto loading animation on scroll

    triggerElement.addEventListener(triggerEventId, function () { AddAosAnimateCssClass(elem, triggerEventId, wrapperAnimationElementId); }); //remove aos-animate class to avoid auto loading animation on scroll
}

function AddAosAnimateCssClass(elem, triggerEventId, wrapperAnimationElementId) {
    //debugger
    if (event != null && event.target != null && event.target != undefined && event.target.closest) {
        var closestParentDiv = event.target.closest('div');
        if (closestParentDiv != null && closestParentDiv.id == wrapperAnimationElementId) {

            //sub elements of the wrapper div should not trigger animation, to avoid AOS running animation again
            return;
        }
    }
    if (elem == null || elem == undefined) {
        return;
    }

    elem.classList.remove('aos-init');
    elem.classList.remove('aos-animate');

    if (triggerEventId.toLowerCase() == 'change') {
        if (!event.target.checked) {
            return; //in case this is a checkbox, only trigger on checked state
        }
    }

    setTimeout(function () {
        elem.classList.add('aos-init');
        elem.classList.add('aos-animate');
    }, 500);
}

function RestartAosEventToImplicitEventDomContentLoaded() {
    AOS.init({
        easing: 'ease-in-out',
        startEvent: 'DOMContentLoaded'
    });
}

function DisableAosEventToImplicitEventDomContentLoaded() {
    AOS.init({
        easing: 'ease-in-out',
        startEvent: 'MyCustomEvent'
    });
}
 
 
We set up some helper methods here to be able control playing animations on demand. This is not required however, it was just an experiment from my side to see how you could select an element in the DOM and a event for that element (DOM event) to control how to start the animation. The Animation.razor component looks like this, with its code behind.
 
 

@inject IJSRuntime JsRuntime
<div id="@_wrapperDivUniqueId" data-aos="@SelectedAnimation.GetDisplayName()" data-aos-delay="@Delay" data-aos-duration="@Duration">
  @ChildContent
</div>

@code {
    private string _wrapperDivUniqueId = $"wrapperDiv_{Guid.NewGuid().ToString("N")}";

    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    /// <summary>
    /// Duration must be set between 50 to 3000 ms, see defined limit here : https://github.com/michalsnik/aos
    /// </summary>
    [Parameter]
    public int Duration { get; set; } = 1000;

    /// <summary>
    /// Delay must be set between 0 to 3000 ms, see defined limit here: https://github.com/michalsnik/aos
    /// </summary>
    [Parameter]
    public int Delay { get; set; } = 50;

    /// <summary>
    /// Animation to use. Use name list defined in Animations. See here: <see cref="AnimationNames" /> for a list of supported Animations.
    /// </summary>
    [Parameter]
    public AnimationNames SelectedAnimation { get; set; } = AnimationNames.Fade;

    /// <summary>
    /// DOM id of the element that will trigger the animation. If not set, the animation will happed as default, when element scrolls into view according to AOS standard
    /// </summary>
    [Parameter]
    public string? TriggerElementId { get; set; }

    /// <summary>
    /// DOM event for the element that will trigger the animation. See https://www.w3schools.com/jsref/dom_obj_event.asp for a list of DOM events. If not set, the animation will happen as default, when the element scrolls into view according to AOS standard.
    /// </summary>
    [Parameter]
    public string? TriggerEventId { get; set; }

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (!string.IsNullOrWhiteSpace(TriggerElementId) && !string.IsNullOrWhiteSpace(TriggerEventId))
        {
            //turn off automatic animation on scroll for the element

            await JsRuntime.InvokeAsync<string>("RegisterAnimationStartupTrigger", new[] {
                _wrapperDivUniqueId, TriggerElementId, TriggerEventId });
        }
    }


    protected override void OnParametersSet()
    {
        if (Duration < 50)
        {
            Duration = 50;
        } 
        else if (Duration > 3000)
        {
            Duration = 3000;
        }
        if (Delay < 0)
        {
            Delay = 0;
        }
        else if (Delay > 3000)
        {
            Delay = 3000;
        }
        if (string.IsNullOrWhiteSpace(SelectedAnimation.GetDisplayName()))
        {
            SelectedAnimation = AnimationNames.Fade;
        }       
    }

}

 
 

In the component above, we use the parameter ChildContent which is a RenderFragment? which is used in the razor markup. We wrap a div and generate a unique id which is used in Javascript to control the on demand coupling of starting the animation. In many cases, you could just use the default DOMContentLoaded if you want to just play the animation when the element is displayed. Here is how you use the Animation component in an example component:
 
 
@page "/counter"
@inject IJSRuntime JS

<PageTitle>Counter</PageTitle>

<h1>Counter with Blazor animations</h1>

<p role="status">Current count: @currentCount</p>

<input type="checkbox" id="CheckboxToggleViaSpecificJsEvent" />
    Check here to start the animation [TriggerElementId: CheckboxToggleViaSpecificJsEvent, TriggerEventId: change]
<br />
<br />
<Animation Duration="1000" SelectedAnimation="@AnimationNames.Fade" TriggerElementId="CheckboxToggleViaSpecificJsEvent" TriggerEventId="change">
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
</Animation>
<br />
<br />


<button @onclick="AOSRestartStartEvent" class="btn btn-outline-success">
    Click here to enable AOS start event to DOMContentLoaded
</button>
<br /><br />

<button @onclick="AOSCustomStartEvent" class="btn btn-outline-success">
    Click here to disable AOS start event to DOMContentLoaded (custom start event)
</button>
<br />
<br />

<hr />

<label>
    <h5 class="text-muted">
        Select the animation to show when button is visible
        <InputSelect @bind-Value="SelectedAnimation">
            @foreach (var item in Enum.GetValues(typeof(AnimationNames)).Cast<AnimationNames>())
            {
                <option value="@item">@item.GetDisplayName()</option>                
            }
        </InputSelect>
    </h5>
</label>

<br />

<label>  
 <InputCheckbox @bind-Value="@showAnotherCurrentCountBtn" />
   Check here to start the animation [No trigger element, visbility of button below controlled by data bound flag for the checkbox]
</label>

@if (showAnotherCurrentCountBtn){
    <Animation Duration="1500" SelectedAnimation="@SelectedAnimation" Delay="50">
        <button class="btn btn-outline-primary" @onclick="IncrementCount">Click me</button>
    </Animation>
}
<br />
<br />

@code {
    private int currentCount = 0;
    private bool showAnotherCurrentCountBtn = false;

    private AnimationNames SelectedAnimation = AnimationNames.Fade;


    private void IncrementCount()
    {
        currentCount++;
    }

    private async Task AOSRestartStartEvent()
    {
        await JS.InvokeAsync<string>("RestartAosEventToImplicitEventDomContentLoaded");
    }

    private async Task AOSCustomStartEvent()
    {
        await JS.InvokeAsync<string>("DisableAosEventToImplicitEventDomContentLoaded");
    }

} 
 
 
The AnimationNames is an enum which allows you to set one of the pre-defined animations in AOS. It is possible to define a custom (CSS-based) animation to use with AOS too, I might look into that in another article later on.
 
 using System.ComponentModel.DataAnnotations;

namespace BlazorAnimationSample.Components
{

    public enum AnimationNames
    {
        [Display(Name = "fade")]
        Fade = 0,

        [Display(Name = "fade-up")]
        FadeUp,

        [Display(Name = "fade-down")]
        FadeDown,

        [Display(Name = "fade-left")]
        FadeLeft,

        [Display(Name = "fade-right")]
        FadeRight,

        [Display(Name = "fade-up-right")]
        FadeUpRight,

        [Display(Name = "fade-up-left")]
        FadeUpLeft,

        [Display(Name = "fade-down-right")]
        FadeDownRight,

        [Display(Name = "fade-down-left")]
        FadeDownLeft,

        [Display(Name = "flip-up")]
        FlipUp,

        [Display(Name = "flip-down")]
        FlipDown,

        [Display(Name = "flip-left")]
        FlipLeft,

        [Display(Name = "flip-right")]
        FlipRight,

        [Display(Name = "slide-up")]
        SlideUp,

        [Display(Name = "slide-down")]
        SlideDown,

        [Display(Name = "slide-left")]
        SlideLeft,

        [Display(Name = "slide-right")]
        SlideRight,

        [Display(Name = "zoom-in")]
        ZoomIn,

        [Display(Name = "zoom-in-up")]
        ZoomInUp,

        [Display(Name = "zoom-in-down")]
        ZoomInDown,

        [Display(Name = "zoom-in-left")]
        ZoomInLeft,

        [Display(Name = "zoom-in-right")]
        ZoomInRight,

        [Display(Name = "zoom-out")]
        ZoomOut

    }

}
 


You can clone the Blazor Animation sample easily from Github by following Git command:

git clone https://github.com/toreaurstadboss/BlazorAnimateSample.git