Server-Sent Events in ASP.NET Core and .NET 10

Like many .NET developers, I’m starting to look at the features coming in .NET 10, C# 14, and specifically ASP.NET Core. To my surprise, ASP.NET Core Minimal APIs now support Server-Sent Events (SSE). For folks who don’t know what Server-Sent Events are, they are a unidirectional channel from the server to a client where a client can subscribe to events. SSE is handy for building live news feeds, stock ticker applications, or any system that has real-time information.Inevitably, folks will ask, what’s the difference between SSE and SignalR? The difference is that SSE is lighter than WebSockets, and you can implement an SSE solution using the HTTP protocol. Whereas WebSockets, SignalR’s default operating mode, is a different protocol entirely. WebSockets are great, but the bidirectional communication between server and client adds additional costs that are typically unnecessary for the systems I mentioned previously.In this post, I’ll show you how to implement a straightforward SSE exa...

Generic C# Methods with Enum Constraints for .NET

Every couple of years, I tend to write the same variation of an enum helper that reads metadata from an enumeration using reflection. Almost any .NET developer with a few years of experience has done the same. The implementation uses Generics to work for any enum defined in my solution, as there is typically more than one described in a typical .NET solution. Historically, generics and enums didn’t work well because of the limitations of generics when dealing with this particular type, but to my surprise, they do now!In this post, we’ll explore how to write the helper method I’m describing while ensuring the generic constraints stop us from passing in arguments other than enums.Straight To The ImplementationSince this post will be short, I’ll start with a sample you can play with.using System.ComponentModel;using System.Reflection;// get all descriptions{ Console.WriteLine("Groceries:\n"); var descriptions = Enums.GetDescriptions(); foreach (var (value, description) in descri...

Strongly-Typed Markdown for ASP.NET Core Content Apps

Every development career has milestone moments. One we all likely share is building a custom content management system, or CMS, as developers like to refer to it. A common approach to melding metadata and content is utilizing the old reliable Markdown format, which fuses YAML frontmatter with a simple content format. While YAML is flexible, it can be less than ideal when wanting to use that embedded data in your ASP.NET Core applications.In this post, I’ll show you a quick experiment around processing Markdown files and their YAML into a strongly-type C# object. The example allows you to easily modify content while still having access to instances of data that you can strongly type.The Magnificent MarkdownMarkdown is a very flexible format whose strength comes from its simplicity. Let’s examine a document that defines a person’s profile.---name: "Khalid Abuhakmeh"profession: "Software Developer"hobbies: ["video games", "movies", "boxing"]---## SummaryI am writing a little about myself...

The Curious Case of .NET ConcurrentDictionary and Closures

I was recently looking at the Duende Software codebase, and I kept seeing the same suggestion offered by the IDE tooling whenever I encountered a ConcurrentDictionary: “Closure can be eliminated: method has overload to avoid closure creation.”While the suggestion appears in the tooling, there isn’t a quick fix action to apply the change. It left me scratching my head because there wasn’t an immediately obvious solution.This post will define closures and explain their problems. We’ll also explain how to change your usage of ConcurrentDictionary to avoid closures altogether.What Are Closures?If you’ve ever worked with an Action, Func, delegate, or LINQ, then you’ve likely encountered a closure. A closure is a language mechanism that allows you to treat a function with free variables as if it were an object instance you may pass, invoke, or use in another context from when you first created it. Justin Etheredge has a great article explaining closures in-depth, but it’s when you use a lam...

ASP.NET Core and Chunking HTTP Cookies

If you’ve spent time around web development or your grocery store’s baked goods aisle, you’ve probably dealt with cookies. Let’s discuss the web kind today. A cookie is a header key-value pair that is set on the server using the Set-Cookie key, and a value of =. Cookies persist on the client, where the client will send each cookie to the server on each subsequent request. It’s a simple way to persist state in the stateless web environment and avoid complex session management infrastructure. That said, cookies have limitations, mainly the 4kb size limit for each unique cookie. Size limits can be a serious problem for ASP.NET Core applications, which rely heavily on maintaining user session data in an encrypted and encoded cookie.In this post, we’ll look at a sample I wrote that uses the same ICookieManager abstraction that ASP.NET Core uses to chunk large cookies successfully.Why You Would and Wouldn’t Use CookiesAs the introduction mentions, cookies are a straightforward mechanism for...

Vogen and Value Objects with C# and .NET

When it comes to programming, correctness is the name of the game. Every developer aims to understand, model, and limit potential outliers when executing code because those unknown variables can lead to exceptions and critical failures. There are many techniques developers use, but I recently discovered a new library (at least to me) in the .NET community that aims to help developers constrain potential inputs using value objects.In this post, we’ll write a quick sample using Vogen to demonstrate how value objects can make our code clearer and less error-prone.What is a Value Object?A value object represents a logical concept but is a .NET primitive value such as int, bool, string, and more. A straightforward example might be a birth date. Most developers would define a birth date using the DateTime type, hoping that the variable name clarifies the value’s intention.DateTime birthDate = new DateTime(1990, 1, 1);The drawback to this code is nothing stops a developer from unintentionall...

Initialize ASP.NET Core TagHelpers with Shared Data

ASP.NET Core has a superpower that few other frameworks have, largely thanks to the Razor engine. Razor syntax is a mix of HTML and C#, and most Razor syntax implementations will skew heavily towards HTML over C#. However, C# syntax offers the most value in control flow mechanics using if, for, and switch statements. Razor’s power is thatevenHTML syntax is processed by C# and converted into compiled artifacts. This gives Razor a unique opportunity to do some amazing tricks.In this post, we’ll see how to use the TagHelpers infrastructure to initialize all tag helper usage across your application and inject necessary shared data.The TagHelper In QuestionLet’s start by writing a simple tag helper that will replace the contents of a span tag when atext attribute is set.using Microsoft.AspNetCore.Mvc.Razor;using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Razor.TagHelpers;namespace WebApplication2.Models;[HtmlTargetElement("span")]public class MyTagHelper: TagHelper{ [...

Writing a String Numeric Comparer with .NET 9

I recently saw that .NET 10 adds a numeric comparer, allowing you to sort string elements that may contain numeric values at the end of a string. Think movie sequels or number versions of an operating system. To my surprise, I could not believe it wasn’t already included in .NET, but then I sat down to try to write my own, and I now “get it”. The edge cases alone can drive you mad. Numeric ordering is subjective. Should the numbers come before Roman numerals? Should Roman numerals be parsed as numbers? What about decimals?Anyway, I’ve added my numeric comparer implementation in this post, which uses some of the latest .NET features. Enjoy!A List of Numbered ThingsA number at the end of a text is typical for movies, books, video games, and products. These numbers denote a newer and better iteration of an item. For example, I have a combination of movies, Windows versions, and some decimal values.var numberedThings = new List{ "Godfather", "Godfather 3", "Scream", "Scream 2", "Scr...

Great .NET Documentation with Astro, Starlight, and MarkdownSnippets

The hallmark of every great project is equally great documentation, but it can be increasingly difficult for developers to keep both in sync. Luckily, I’ve been experimenting again with a combination of Starlight and MarkdownSnippets to make maintaining code samples and documentation much more convenient.In this post, we’ll see how to set up your repository so that MarkdownSnippets pulls samples from your codebase and updates your Starlight documentation.Directory Structure and ToolsTo get started, let’s set up our repository for success. Let’s begin with folders. We’ll want to create the following folders at the root of a newly created directory.- docs- srcThe docs directory will hold our documentation powered by Starlight, and thesrc directory will have all our .NET code.We’ll want to run the following dotnet commands within the same directory.dotnet new tool-manifestNext, let’s install the MarkdownSnippets tool.dotnet tool install MarkdownSnippets.ToolFinally, let’s create the Mark...

Alpine.Js Polling ASP.NET Core APIs For Updates

Building dynamic JavaScript experiences has come a long in the 20 years since I first started software development, but updating the document object model (DOM) can still be a real pain in the butt. That’s why we’ve seen single-page application frameworks explode in use. While JavaScript provides a very capable API when interacting with the DOM, it can be verbose.In this post, we’ll see how to use the Alpine.Js library’s declarative attribute approach to create a real-time updating UI with minimal JavaScript and no direct use of the DOM APIs.The Strength of Alpine.jsAlpine.js is a lightweight JavaScript framework that allows you to compose behavior directly in your HTML markup. The library consists of 15 attributes, six properties, and two methods. While its surface API is small, what it offers is, as the site says,“powerful as hell.”The strength of Alpine.js comes from its data model, which uses reactivity to detect changes to data and update the UI elements accordingly. Reactivity m...

Building a Persistent Counter with Alpine.Js

If you read this blog, you likely know I predominantly work with .NET technologies and use web technologies such as HTML, CSS, and JavaScript. The web is an excellent space for new and exciting ways to solve age-old problems. I recently thought about the Blazor “Counter” example that ships with the Blazor Wasm template and how I’ve solved the same problem using Htmx. The issue with Htmx is that it still requires a backend to manage the state; in the case of a counter, this state is the current count. What if you wanted to build a self-contained client-side experience?Alpine.js is a declarative library aimed at helping developers build client-side interactivity using HTML attributes on DOM elements. This post will show you how to create the same Blazor Counter example with very little JavaScript and network payloads.Installing Alpine.jsSince Alpine.js is a JavaScript library, you only need to reference the necessary files in your HTML pages. In an ASP.NET Core application, that’s typic...

Dynamic Htmx Islands with ASP.NET Core

I’m a big fan of static site renderers, and they are still one of the missing elements that would make ASP.NET Core more compelling for users across the vast ecosystem divide. In the meantime, developers must rely on tools like Astro, Jekyll, and 11ty to build static site experiences. Recently, I read about Astro 5.0 and its server island implementation. Server islands allow for mostly static pages to carve out portions of the page that will be rendered on-demand by, you guessed it, the server. This allows site authors to deliver fast, statically rendered pages that benefit the user while allowing for dynamic user-specific content.In this post, we’ll see how to implement a similar island approach in ASP.NET Core applications that utilize response and output caching for performance increases while still carving out small page sections for dynamic content. We’ll use Htmx to trigger requests for dynamic content based on three exclusive page events.What is an Island?As described in the in...

Update HTML Elements with Htmx Triggers and ASP.NET Core

Let me start by saying that I love the combination of Htmx and ASP.NET Core, and it is a pairing that any .NET developer should consider, whether maintaining an existing application or building a new one. It’s very cool. I was recently talking about revisiting thehx-trigger andHX-Trigger header technique with ASP.NET Core on Mastodon with Illya Busigin, and they mentioned they use the same method to update the avatar image when a user updates their profile. So, I thought I’d try and see how to implement it myself.In this post, we’ll see how to use theHX-Trigger facility in Htmx to update existing UI elements on a rendered HTML page.The Moving PartsWhen building any new feature in an application, you need to arrange multiple components to work together. Let’s address all the parts you’ll need to make this experience. A User Profile store Profile Settings endpoints for display and updating An endpoint to refresh the avatar element on the pageWe’ll be using the capabilities of ASP.NET...

Add EF Core Migrations to .NET Aspire Solutions

Folks working with EF Core are likely very fond of the library’s migration features, one of the most vital selling points for adopting an ORM. If you’re building a .NET solution, your database schema will evolve, and adding, removing, and updating are everyday actions you must perform..NET Aspire can ease the development of distributed solutions, but you still need to bridge the gap between development time actions and runtime execution. With EF Core, a development time action is managing migrations, while at runtime, you’ll need to execute those migrations against a database. The original tutorial by the Microsoft documentation explains how to run a .NET Aspire application with migrations but leaves out how to do development time tasks.In this post, we’ll explore how to manage migrations during the development process so you can get the most out of your .NET Aspire and Entity Framework Core adoption.The Solution StructureWe’ll first need to understand the solution structure of our As...

Htmx and Playwright Tests in C#

Community member Jonathan Channon recently approached me about an appropriate way to test your Htmx-powered applications using the Playwright testing framework. It can be annoying to get the timing right between sending an HTMX request, processing it on the server, and applying it to the page.In this post, we’ll see a surefire way to wait for Htmx to finish before testing the state of your pages, thus leading to more reliable tests and faster test execution. Let’s go.The Htmx Counter ApplicationLet’s first see what application we’ll be testing. It’s a simple **Counter** component that increases in value when the user presses a button.@model HtmxPlaywrightIntegration.ViewModels.CounterViewModel @Model.Count Increment The ASP.NET Core endpoint is straightforward.using HtmxPlaywrightIntegration.ViewModels;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.RazorPages;namespace HtmxPlaywrightIntegration.Pages;public class IndexMod...

Intersperse Values for Enumerable Collections

JavaScript, for better or worse, has a much smaller standard library than what .NET developers are used to with the base class library (BCL). The JavaScript community has made many attempts to build a standard library, and I’m sure some of them are great. As I was scanning the options, I came across a fascinating method named intersperse, which “inserts a separator between the elements of its list argument”.In this post, I’ll implement the same method in C# as an extension method on the IEnumerable interface.Intersperse implementation in C#Let’s first look at a few examples and the expected output before we look at the implementation of the method.var hello = new string("Hello".Intersperse('-').ToArray());var one = new string("1".Intersperse('x').ToArray());var @null = ((IEnumerable)null!).Intersperse(',').ToArray();var array = new[] { 1, 2, 3 }.Intersperse(42).ToArray();var menu = new [] {"Home", "About", "Privacy" } .Intersperse(" > ") .Aggregate((a, b) => $"{a}{b}");Console.W...

Checked and Unchecked Arithmetic Operations in .NET

The other day, I played around with the Fibonacci sequence and overflowed myint variables in surprisingly low iterations. Did you know you’ll overflow an integer in **48** iterations? Don’t believe me? Let’s take a look at the result of the code you’ll see later in this post.Enter an integer: 48Fibonacci sequence for 48:0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170,1836311903,-1323752223You’ll notice that the last value has looped back to a negative value. Oh no! This is a tell-tale sign that an overflow has occurred.This post will explore how to keep your applications safe from these overflow issues.The code causing the overflowFirst, let’s look at my implementation of the Fibonacci sequence generator. I’m usingSpectre.Console to make the output more appealing, b...

Confirmation Dialogs with Htmx and SweetAlert

When building web experiences, there are safe operations and destructive ones. In the case of dangerous actions, it’s widespread to ask the user if they’d like to continue with the action before ultimately executing it.In this post, we’ll explore a valuable feature in the Htmx documentation that allows you to intercept outgoing requests and present a Sweet Alert confirmation dialog. This feature can greatly enhance user experience and control in your web applications. Let’s dive in.The htmx:confirm eventHtmx users are likely familiar with the hx-confirm attribute, which is a declarative way to use theconfirm JavaScript function. This uses your browser’s native functionality to display a confirmation dialog that allows the user one last chance to cancel their action. Delete Important StuffBut folks likely don’t know that the htmx:confirm event is triggered before **every** request. This allows you to intercept, stop, or continue any Htmx request on the client. This opens up a lot of...

How To Pick The Right Constructor When Using ActivatorUtilities In .NET

If you’ve ever worked with reflection in .NET, you’re likely familiar with Activator. In .NET 6, ActivatorUtilities was introduced to make it easier to create classes with dependencies. Constructor dependency injection is common in the .NET space, and you’re likely to run into several types that require constructor parameters before being created. TheActivator class is a relic of a simpler time, whereas ActivatorUtilities meets developers where .NET is today.In this post, we’ll look at a code example of how to guideActivatorUtilities toward the constructor you want to use when building instances of types that may have multiple constructors.Registering a Type and the DependenciesLet’s start by looking at a Person class that has a total of three constructors. Wowza!public class Person(string name, int age = 0){ public Person(string name) : this(name, 0) { Console.WriteLine("Person(string)"); } public Person(object name) : this(name.ToString()!, 41) ...

Add a Property to the Top-level Statements Program class

The evolution of the C# language has introduced us to many new features and probably made a lot of folks re-evaluate how they write their apps. In the latest versions of .NET, nothing has been marked such a stylistic shift as the introduction of top-level statements.In this short post, we’ll examine how to add properties to your Program instance to improve the readability of utility console applications.Top-level statement filesWhen starting a new console application, you can create a Program.cs file and opt into the top-level statements style. The single line below is a valid .NET application.Console.WriteLine("Hello, World");At compile-time, the compiler generates the typical ceremony associated with traditional applications. Looking at our app’s low-level C# version, we’ll see the symbols we typically expect to see in a .NET app.using System;using System.Runtime.CompilerServices;[CompilerGenerated]internal class Program{ private static void $(string[] args) { Console.WriteLine...

Fix .NET MAUI MissingEntitlement and Provisioning Profiles Issues

There are times on this blog when I write posts for the reader’s benefit and times when I need to memorialize my ownpain and suffering to find a solution to a seemingly simple issue. This post is the latter.In this post, we’ll see what it takes to fix the MissingEntitlement and “Could not find any available provisioningprofiles” errors.Also, be warned: You might not like what you see.Ok, let’s go!iOS, Security, and EntitlementsI recently purchased the “.NET MAUI in Action” book and was workingthrough the sample application in Chapter 3. The author’sperspective differs from mine in that their app targets Windows, and I am targeting iOS. As one might expect, thedetails between the two target platforms differ.This difference led to my first issue running the sample application targeting iOS; I got this exception and crashed theapplication.System.Exception: Error adding record: MissingEntitlement at Microsoft.Maui.Storage.KeyChain.SetValueForKey(String value, String key, String service)...

Health Checks for ASP.NET Core and Entity Framework Core

I’ve recently been reading up on .NET Aspire and have found a lot of cool .NET tech underpinning the offering. One ofthe tools that has gotten a glow-up since I last looked at it has been Microsoft.Extensions.Diagnostics.HealthCheckspackage provides you with the infrastructure to perform various types of system health monitoring.In this post, we’ll look at installing the health checks package into existing ASP.NET Core applications and using anadditional package to perform health checks on your databases using Entity Framework Core.Install and Set Up Health ChecksIn an existing ASP.NET Core application, you’ll need to install the following package.dotnet add package Microsoft.Extensions.Diagnostics.HealthChecksOnce the package has been installed, you must do several setup tasks in your Program file.The first step is to register the HealthChecks middleware and services in the services collection.builder.Services.AddHealthChecks();Next, in your ASP.NET Core request pipeline, you’ll need...

How To Fix .NET Nullability Warnings For Guarded Members

Nullability provides developers with development-time warnings that can help reduce dereferencing issues. These errorscan be costly, but with the power of a few additional checks in code, developers can easily avoid them, putting them incontrol of their code’s quality.In this post, we’ll see a code sample that should be “safe” yet continues to give IDE and build-time warnings aboutdereferencing of a possibly null reference. We’ll also see how to adjust your code to remove unnecessary warnings incurrent and future projects.Dereference of a possibly null referenceLet’s look at some basic C# code, which you likely have something similar to in your projects.var database = new Database();// Name cannot be null when Initialize is trueif (database.Initialized){ // This has a warning about Name being null var length = database.Name.Length; Console.WriteLine($"{database.Name} and length is {length}");}Console.WriteLine("Hello, World!");public class Database{ public string? Name...

HTML Datalist for ASP.NET Core Inputs

In my last blog post, I discussed range inputs. This time, we’ll examine a tag helper that adds support for the HTML element of datalist.In this short post, I’ll explain what a datalist is and why you may want to consider using it in your ASP.NET Core applications. Finally, we’ll implement a set of tag helpers to make using the datalist element more straightforward with your ASP.NET Core MVC and Razor Page applications.What is datalist?True to its name, the datalist element allows web developers to create a list of options that are permissible or recommended for form input elements. This allows users to choose from a predefined list the application developer has curated.Let’s look at a quick HTML example pulled from the MDN web docs.Choose a flavor: The ice-cream-choice field will use the datalist options and provide users with a dropdown of potential options but still allow users to type their choices using freeform text.The list attribute supports multiple input t...

HTML Range Inputs with ASP.NET Core TagHelpers

I’ve recently been rediscovering all the input fields that HTML offers and how they can help developers build more straightforward user experiences. The library of native HTML controls is impressive, with 22 HTML input types as of this post.Looking through ASP.NET Core’s InputTagHelper, I counted 14 supported input types based on the .NET common language runtime types you may use in your models. That’s over 8 controls missing from ASP.NET Core. The missing range input is one of the most valuable controls.In this post, we’ll write an ASP.NET Core tag helper that piggybacks on the InputTagHelper and turns a number property into a range input.What is the range Input?The range input is as it sounds. Developers commonly refer to these elements as a “slider” since users typically slide an indicator to set a value. The input allows users to choose a value constrained by a minimum and maximum value. The limitation ensures that users can only choose valid values. When defining a range input, y...

HTML5 Validation for ASP.NET Core Models and Razor Views

I was recently working on an HTMX and ASP.NET Core demo and wanted to limit client-to-server requests to valid requests. This is a built-in feature for HTMX, as long as you utilize HTML5 validators on your forms and inputs. As many ASP.NET Core practitioners know, the default client-side validation in ASP.NET Core is not HTML5 but a mix of custom data-val attributes and JQuery. The current approach is acceptable, but it makes adopting new frameworks, supporting native HTML capabilities, and dropping extraneous dependencies more difficult.Could we drop the JQuery validation dependency in favor of HTML5 validation? Luckily, we can thank OSS author Andrew White for his latest NuGet package, FinBuckle.Html5Validation. This package allows us to disable the default behavior of ASP.NET Core MVC and Razor Pages for a more modern approach.What is HTML5 Validation?Before HTML5, developers wrote all client-side validation using JavaScript code. While JavaScript code allowed for complex scenarios...

What is HSTS and why is it in my ASP.NET Core app?

When creating a new ASP.NET Core application, you get a set of middleware that performs typical web application duties. Some include serving static assets, routing, HTTPS redirection, and exception handling. Folks looking will also notice a middleware registration of the app.UseHsts() found in every ASP.NET Core app.What is HSTS, why would you want it, and how do you configure the HSTS options in ASP.NET Core? Let’s find out.What is HSTS?HSTS (HTTP Strict Transport Security) is a method by which your application server can tell clients to use a secure connection when sending requests. As you may know, HTTP is unsecured communication, while HTTPS uses encryption to improve users’ privacy and security. Applications can transition user sessions from HTTP and HTTPS, and historically, it was very common to move from an unsecured part of a website to a secured section. For example, shopping sites used to display store items over HTTP and then only use HTTPS for the checkout process.This sti...

How To Encrypt ASP.NET Core Route Parameters

I recently read a classic blog post from the RavenDB community recommending developers think twice about exposing primary identifiers in their URLs. There are several reasons for this, which I’ll summarize in this post, but I wanted to revisit the problem and see what the current ASP.NET Core development stack has to offer when it comes to solving this problem.In this post, we’ll see some code that can both encrypt and decrypt sensitive identifiers in the URL path.Why Obscure Identifiers?Many people first think, “Why obscure identifiers in the first place?” I mean, it’s just an ID, right?There are several arguments as to why it may be a “bad” practice.1. URL TamperingWhile we all do our best to secure our applications, there are times when we may forget to properly verify that a user has permission to access a particular resource.https://example.com/?id=1Over the years, we’ve become acutely aware that changing the value of the id in a URL might return a different resource. This may be...

State Machines, Light Switches, and Space Travel with Stateless and .NET 8

State machines are so integral to software development that they often seem invisible to developers. They are used sofrequently yet abstracted away through APIs and syntax that many developers don’t directly deal with them. However, we’dlike to.At their core, state machines are systems with finite inputs and deterministic pathways. While they can be complex, thebasic structure of nodes and vertices makes them more approachable than they may initially seem.In this post, I’ll guide you through the process of building two state machines using the .NETlibrary Stateless. We’llalso discuss effective strategies for incorporating state machines into your code.Getting Started with StatelessTo start using Stateless, you’ll need to install the latest versionof the package using NuGet.dotnet add package StatelessFrom here, you will use the StateMachine class to define the state object and the triggers that mutate the machine’sstate.The example used in the Stateless documentation is that of a phon...

Blazor HTML Forms, Submitting, and Antiforgery Tokens

I love the web and HTML. It’s certainly come a long way since its inception and what it provides as a core experiencefor web developers. While folks can certainly build HTML-exclusive experiences, adding forms on a page inevitably leadsto introducing a backend tech stack. Recently, I’ve been experimenting with Blazor Server-side Rendering (SSR) and howdevelopers can use its component-driven approach while still building the web experience they know and love.In this post, we’ll see how to use the plain-old form tag with a Blazor SSR page, handle form posts, and attachantiforgery tokens.Why not use EditForm?Anyone familiar with Blazor would likely immediately think, “Why not usethe EditFormcomponent?” Well, for my taste, the EditForm component has so many hooks, fields, and requirements that it begins tofeel like a burden compared to the humble HTML form. In my opinion, much of the EditForm functionality is overkill foran SSR scenario.You’re welcome to use EditForm if you find its featu...

Fix Missing OpenAPI Elements From ASP.NET Core Minimal API Apps

When working in .NET, there’s a lot of room for reorganizing a codebase, but sometimes we can organize ourselves into amess of a problem. Recently, when working on an ASP.NET Core Minimal API demo, I seemingly broke an endpoint’s OpenAPIdefinition, and it was no longer in the list of endpoints.In this short post, we’ll compare two endpoints and discuss why one is different than the other, why it might breakOpenAPI integrations, and how to fix it.Let’s start with a typical Minimal API endpoint.app.MapGet("/hello", () => { return new Hello("World"); }) .WithName("Hello") .WithOpenApi(); record Hello(string Target);Our endpoint registration contains enough metadata to determine the parameters, the return type and its structure, andthe name of our endpoint. Great! That’s more than enough for ASP.NET Core to generate an OpenAPI definition entry.Let’s do some refactoring of our handler to a local function.Task Handler(){ return Task.FromResult(new Hello("World"));}a...

ASP.NET Core, SSR Web Components, and Enhance Wasm

Web components are some of the most exciting technology I’ve seen in a long time. They promise to revolutionize how wewrite, maintain, and ship HTML-based applications. With web components, you can extend the set of HTML tags specific toyour site while still providing the functionality you intended with less markup.And then there’s Web Assembly, or Wasm for short, a technology that opens up a world of possibilities. It enables allecosystems to package functionality in a reusable format that can be deployed across a wide range of platforms.Could we combine them to provide ASP.NET Core with brand-new server-side rendering functionality while avoiding theclient-side costs of web components as they attach to the DOM? Sure we can!With Enhance Wasm.What is Enhance WASM?Enhance WASM is an open-source initiative to bring the features of Enhance, a dynamicweb apps framework, to the server for all technology stacks through Wasm. As mentioned in the opening, web componentsare significant but tak...

How to add HTTP headers to Blazor Components with RazorComponentResult

In a previous post, ]I wrote about using RazorComponentResult to render Blazor components](/how-to-use-blazor-server-rendered-components-with-htmx) from ASP.NET Core Minimal APIs. The ability allowsdevelopers to reuse Blazor components in new and exciting scenarios, specifically with JavaScript UI frameworks andlibraries such as React, Vue, Angular, and my favorite library, HTMX.In this concise post, we’ll explore setting HTTP Headers for RazorComponentResult and creating an extension methodthat simplifies this task, making your development process more efficient.RazorComponentResult RecapBlazor is a component-driven development framework inspired by the JavaScript React library.Components aim to encapsulate UI elements into reusable elements to help accelerate development. They can vary in size,from buttons, links, and textboxes to logical components such as detail cards, tables, video elements, and so on.Component trees also help manage a page’s state, and Blazor provides some DOM d...

Working with Rust Libraries from C# .NET Applications

I’ve been on a Rust learning journey lately, and it’s had me thinking about how I can consume Rust libraries fromexisting .NET applications. The .NET team has done much work regarding interoperability during the .NET 6 to .NET 8 era,and .NET 9 seems poised to continue that trend.In this post, we’ll create a Rust library and consume it from a .NET application. This post assumes you have installedthe .NET SDK and Rust SDK (cargo).A Simple Rust LibraryAfter creating a .NET Solution, I first created a new Rust library using cargo. The command is relativelystraightforward.cargo init --lib calculatorThis creates a new calculator library folder with the most critical files: Cargo.toml and lib.rs. Let’s updatethe Cargo.toml file to produce an artifact that our .NET application can consume, a dynamic library.[package]name = "calculator"version = "0.1.0"edition = "2021"[lib]name="calculator"crate-type=["dylib"][dependencies]rand = "0.8.5"I’ve also included the rand dependency for my Rust code l...

Fix Unable To Resolve DbContextOptions For EF Core

I recently hosteda live stream with badass-as-a-service Chris Klug, titled “Stop using Entity Framework Core as a DTO Provider!”.It’s worth a watch, and it gave me, a long-time Entity Framework user, a lot to think about and reevaluate in myworkflows. That said, regardless of whether you agree with Chris’ style, he showed a masterclass of tool usage and anunderstanding that’s easy to admire. In our live stream, one new trick (to me, at least) stood out as something everyEntity Framework Core user should know about.In this post, we’ll explore one strategy to appease the dotnet ef CLI tools regarding design-time configuration andhow it opens up a world of possibilities when dealing with database migrations.Dependencies and ceremonyEntity Framework Core is heavily built around conventions and flexibility. It’s a multi-provider object-relationalmapper (ORM), so it needs to operate under many unknown factors, with you, the developer, filling in the gaps. Whatdatabase are you using? How man...

Event Queues and Buffering Functions with JavaScript

I was testing JetBrains’latest Full Line Code Completion pluginin WebStorm by writing a quick JavaScript demo, and by the end, I was pretty happywith what I had built. The JavaScript uses a queue that pushes events to change classes on buttons in 250ms intervalsto create a smooth color transition from one style to another.Is it practical? I don’t know, but it sure is fun. I’ve included all the demo’s contents in a single file so you cantest it locally. By the end of this post, you’ll have seen an event queue and how to use it in your JavaScript.Write a JavaScript Event QueueThe premise of my event queue is straightforward. Push events into a queue and have them execute on a set universalinterval. I also wanted the ability to clear the queue of any remaining events.class EventQueue { constructor(interval) { this.queue = []; this.interval = interval; this.startProcessing(); } enqueue(eventFunction) { this.queue.push(eventFunction); } clear() { ...

Output CSV Results to Console Table in Rust

‘ve recently been working with Rust and learning about the language and ecosystem by implementing small, typical taskapplications. There’s no better way to learn than to jump into it.In this post, I’ll cover how I could read data from a CSV file, deserialize the contents into an array of struct, andthen output that collection into a pretty console table.To follow along, I assume you have a working Rust environment. Ifnot, I suggest RustRover, which works excellently and provides excellent tooling around the Rust ecosystem.Let’s get into it.Crate DependenciesI had to research to find the appropriate dependencies required to read a CSV from disk and then deserialize the rowsinto a Rust struct. These are the dependencies I found: csv, serde, and lazy_static.The csv crate provides helper methods to read CSV files using a readers pattern. We’ll see how this works when we getto the code sample.The serde crate allows me to serialize and deserialize directly into Rust data structures, whichI’...

Responsive Images Crash Course for ASP.NET Core Developers

Yes, I’m guilty! I’m guilty of ignoring the web platform and all the extraordinary riches waiting for discovery. For allthe lip service the .NET community loves to give towards being performance-minded, it’s a shame we stop at the responseleaving the server. No more fellow reader; it’s time we think beyond the server and think about HTML and, in the case ofthis post, images.In this post, I’ll show you how to optimize your image delivery using newer HTML features and the differences betweenthe two approaches. We’ll see how and why you may want to use each approach by weighing the pros and cons. Finally,we’ll look at cute puppies because who doesn’t love puppies?! Nobody.The Humble Image TagIf you’ve ever written HTML, you’ll almost certainly have used the img tag. Images are an essential element of mostweb pages, yet they can also be the downfall of many. Suboptimal images can drag down your Core Web Vitals, themetrics used to determine how a user may perceive your site’s performance. ...

How To SSR Web Components In ASP.NET Core using TagHelpers

Web Components are gaining momentum in the web platform space, and frankly, it’s bittersweet for us ASP.NET Coredevelopers. On the one hand, you can use Web Components in your current ASP.NET Core applications, as I demonstrated ina previous post, but it isn’t the best experience it could be. You’ll have flashes of unstyled content, layout shifts,JavaScript code that blocks the critical rendering path, and you’ll not get the server-side rendering (SSR) goodnessdeveloped exclusively for the JavaScript ecosystem.In hispost “THE GOOD, THE BAD, THE WEB COMPONENTS”, Zach Leathermanwrote about the ideal way to deliver web components to avoid some of the issues I described. In this blog post, we’llsee how we can use ASP.NET Core’s Tag Helpers to deliver the best experience to users when using Web Components.The ideal Web Component delivery methodWeb Components are a mix of JavaScript and HTML. Nesting your HTML within a custom element tag is best for delivering aprogressively enhanced and se...

Blazor’s CSS isolation ::deep issue and solution

Lately, I’ve been helping a few developers solve some of their issues around Blazor adoption. While I have mixedfeelings about the technology, my urge to help developers overcome their challenges outweighs my trepidation with thetechnology itself.Recently, I had a Blazor developer have issues with the ::deep cascading style sheet (CSS) pseudo-selector and thestyle’s inability to cascade styles to child components. If you’re having a similar issue, I have a detailed issuebreakdown and potential solution. Let’s get started.What is CSS isolation?Blazor is a component-based framework that takes much inspiration from the JavaScript ecosystem’s React component model.The model focuses on reusability through encapsulation and manifests in a single-file style that combines Razor markupand C# logic.In a Blazor application, CSS can be scoped to a single component by adding a convention-based filename similar to acomponent. For example, if your application contains a Counter.razor component, any...

How to use No-Class Frameworks to Move Fast in Style

Software development can be a struggle between form and function. With many developers, function takes the driver’sseat, while the aesthetics of an application are lucky to have a seat in the vehicle. Rational minds might say, “Well,what does it matter how it looks? As long as it works right?” but great design isn’t always rational; it’s emotional.Many developers look to supplement their design deficits with style libraries like Bootstrap, Tailwind CSS, and Bulma toevoke strong user emotions. These are great initial options, but they typically are temporary substitutes for greaterambitions of bespoke design systems. Style libraries can also stand in the way of evolving a UI to meet user needs sincethey heavily rely on library-specific HTML, JavaScript, and CSS classes. Removing these dependencies is unlikely oncethey find their way into your codebase.To my surprise, there have been a few attempts to give developers a strong design starting point while leveraging HTML’sexisting semanti...

How to Integrate HTMX and Shoelace Web Components

In my last post, Shoelace Web Components with ASP.NET Core, I showed ASP.NET Core developers how tointegrate the web components of Shoelace into an existing web application. It’s incredible, and you should check it out.If you’ve read this blog any time, you might have read a post or two about HTMX, a library forbuilding dynamic and maintainable web experiences; I love it.While the two libraries can work together, there’s an issue you need to work around to get the advantages of both. Inthis post, we’ll discuss the issues with using Shoelace with HTMX and how to get it working again with your ASP.NET Coreapplications. If you’re using any other technology stack (Django, Spring, or Next.js), don’t worry; the solution herewill work for you, too.Update in HTMX 2.0 and Shadow DOM supportFor folks using HTMX 2.0, the HTMX library has since resolved this issue and you’re no longer required to perform the steps in this blog post. Users of HTMX pre-2.0 will still need the following blog post, b...

Shoelace Web Components with ASP.NET Core

Web Components are a powerful way to add UX to your web applications while using the web platform. That makes them idealas they can be used in various ecosystems with little or no changes. They also require no build pipelines as they aresupported natively in most clients. This is in stark contrast to approaches like React or Blazor.A mature web component library like Shoelace allows you to share common UI components withteams working on different technology stacks. This can create a consistent user experience regardless of the servertechnology used to render the pages. Take advantage of server-side rendering strengths without heavy SPA libraries orconfusing build pipelines.In this repository, you will find a sample using Shoelace components that work with ASP.NET Core Razor Pages andTagHelpers.What is a Web Component?A web component is a reusable component written to take advantage of thestandard component model built into some of the most popular web clients, such as Chrome, Firefox,...

How to Map SQL Results To Any Object Using Entity Framework Core 8

Entity Framework Core 8 packs a punch, aiming for the undisputed title of “most powerful Object-Relational Mapper (ORM)”in the .NET space. Many folks in our community are typically divided about using ORMs, with many preferring Micro-ORMs.A Micro-ORM has basic mapping functionality from SQL results but lacks object-tracking features that make ORMs what theyare.What Micro-ORMs lack in object-tracking, they make up for in simplicity and functionality. The most popular library isDapper, which allows folks to write SQL, execute the query, and map the results to any .NET Object. Well, with EntityFramework Core 8, you can have Dapper-like functionality with the strengths of EF Core.This post will be short, but for most folks, this is a public service announcement to improve performance and tuneexisting code paths. Let’s get started.What’s this about Mapping Any Object?Before the EF Core 8 release, all entities that were to be queried from a DbContext had to be registered within theimplement...

Increase Performance with Complex Types in Entity Framework Core 8

With the release of .NET 8, we also see the release of Entity Framework Core 8 and a bounty of new features. One of myfavorite new features is Complex Types. When data modeling with Entity Framework Core, we may unnecessarily add tablesto our database schema because “that’s just how database modeling works”. This can lead to table sprawl, decreasedinsert performance, and increased query times.In this post, we’ll explore how to use Complex Types in Entity Framework Core 8 to reduce the number of tables inour schema, simplify inserts, and increase query performance.What are Complex Types?Entity Framework Core has long had the concept of “owned types”, which are properties dependent on their parent object.Depending on your data model, these pieces of information only make sense within the context of additional data. Forexample, in a hypothetical domain, a physical address may only make sense when related to a customer. Otherwise, it isan arbitrary piece of information. Let’s look at how ...

HTML Web Components with Vanilla JavaScript and ASP.NET Core

A general fog of “I hate JavaScript” hovers over the .NET development shops worldwide. While it’s understandable thatJavaScript can sometimes be annoying, it has grown significantly recently. One of the areas more ASP.NET Core developersshould take note of is Web Components. Web Components allow you to create custom HTML elements for your views that canbe one-off or reusable.With Blazor, ASP.NET Core developers are being exposed to component-based development, but the approach I am going toshow you today uses a technique called HTML web components. Unlike Blazor components, these components wrap existingHTML and enhance the contents into something with interactivity. Let’s take a look.What are HTML Web Components?Web developer Jim Nielsen wrote a blog post titled “Html Web Components”where he compares the React component model with what he feels is a better way to write Web Components. His UserAvatarexample might look familiar to Blazor developers.If you’re getting into web components...

.NET Tasks, List’s ForEach, and Problems

I was scrolling the Mastodon timeline when I noticed a fellow .NETdeveloper, Bill Seipel, having an unexpected experience with List.ForEachand async/await. At first glance, I thought he was modifyingthe collection he was iterating over, but then I realized the issue was much more subtle.In this post, we’ll discuss what’s happening in a recreation of his code and how you might fix it.Let’s get started.List.ForEach and Tasks lead to problemsFor those unaware, the List type has a ForEach method, which allows the user to pass an Action. The methodpasses the iteration’s item, allowing you to execute something similar to a foreach method. In a sense, it’s syntacticsugar. In another, it’s a relic before async/await. Let’s see an example code that can get you in trouble.List projects = new(); List measures = ["cm", "m", "km"]; measures.ForEach(async x => { var result = await GetResultOfMeasure(x); projects.Add(result); }); Console.WriteLine(projects.Count); async Task ...

How To Use Blazor Server-Rendered Components with HTMX

A few new tricks have shipped with the .NET 8 release, and I’d like to take this time to experiment with them.Specifically, I wanted to see if folks investing in a Blazor component library could still use the excellent HTMXlibrary. If you want to write even less JavaScript, this blog post will be right up your alley.This post will explore how to take a server-rendered component and give it some client-side flair without needing websockets or web assembly. We’ll even explore rewriting the Counter component found in the Blazor template and buildingit with HTMX in mind. Let’s go!What is HTMX?For folks familiar with Blazor’s interactive server mode, SignalR, aka Web sockets, the HTMX model isn’t much different.The client communicates with the server, and the server retains stateful information. The big difference is that HTMXtakes a hypermedia approach, meaning it leans on the web’s traditional request/response nature. There are no persistentconnections between the client and the server. ...

How to use IAsyncEnumerable with Blazor Stream Rendering

With the release of .NET 8, one killer feature will immediately increase the responsiveness of your APIs and Blazorapplications: the ability to stream responses. Yes, you could stream responses before, but it’s never been easier withsupport for IAsyncEnumerable on API endpoints and the use of StreamRenderingAttribute on your Blazor Unitedapplications.This post will explore why you want to use IAsyncEnumerable and StreamRendering to get the fastest Time to firstbyte (TTFB) out of your ASP.NET Core web applications. Let’s get started.What is IAsyncEnumerable?The interface IAsyncEnumerable is a newish interface designed with the idea that retrieving each element within theiteration is an asynchronous task. This is different than a typical Task as the operation to retrieve theenumerable is considered one step. If you’ve used any data-access layer, you’ve likely invoked methodslike ToListAsync or ToArrayAsync, invoking a request to your database and materializing the result in a singleoper...

View Transitions API with ASP.NET Core and HTMX

I recentlyhosted JetBrains JavaScript Day with guest speaker Fred K. Schott of Astro fame,who spoke about the View Transitions API being introduced in modern browsers. You should watch the video, which willgive you a primer for this blog post; frankly, it’s such an incredible presentation.In this post, we’ll explore how to mix three remarkable web technologies to get a fantastic user experience with littleto no effort on your part. Of course, I’m speaking about using ASP.NET Core Razor Pages, HTMX, and View Transitions tosmooth the transition between pages and reduce the perceived performance of those hops between pages.Let’s get started.What are View Transitions?View Transitions is a new approach that gives web designers more native-like animated transitions between navigationevents. These navigation events can be complete page transitions or elements moving from one part of the page toanother. As web developers, we can focus on performance practices while allowing the web platform t...

How to Write a .NET Markdig Extension for Markdown Processing

Markdown is a powerful writing format with simplicity at its core. It’s no surprise that it is as popular as it is sinceit can help authors focus more on the art of writing rather than the aesthetics of their work. While there is a standardspecification for the language, there are extensions to the Markdown syntax that can enhance the authoring experience inniche contexts. For example, LaTex support for mathematics, improved media support for online services like YouTube, anddiagram support via Mermaid for all aspiring software architects.With Markdown, if you can write it, you can parse and translate it to a desired output. In this post, we’ll explorethe Markdig library by author Alexandre Mutel, which is.NET’s fastest and most powerful CommonMark-compliant Markdown parser. Most importantly, it’s also extensible!What is Markdown and Markdig?For folks new to Markdown, it is a text-based format used to help writers focus on the structure and content of theirwork rather than the aesthet...

Faster .NET Database Integration Tests with Respawn and xUnit

The nuances of data access are myriad, so when writing tests around complex data scenarios, I recommend just workingwith the actual database. Over time, you’ll find yourself with more valuable tests but, often, relatively slower testscompared to their in-memory alternatives. Like all things, there are trade-offs, but you can still strategize in makingyour tests faster.In this post, I’ll show you how to take advantage of xUnit class fixtures and the OSS library Respawn to manage thestate of your database across tests. This will help speed up your tests when faster steps replace a few expensive ones.What is Respawn?Respawn is a utility library designed to help developers resetdatabases to an “initial state”. With some configuration, Respawn can intelligently reset a database for testing usecases.Other strategies might employ complete database tear-downs, complex transaction management, or expensive Dockercontainerization strategies. When mixed with your database management strategy arou...

MemoizR - Declarative Structured Concurrency for C#

Recently, I’ve been focusing on the front-end side of building web applications with topics like React Hooks and AngularSignals. It’s a fascinating data model that can make working with data dependency graphs much more straightforward.To my surprise, other folks in the .NET community have also been inspired by the work happening in the frontend space.While scanning NuGet, I found MemoizR, a library that takes inspiration fromthe frontend world to bring the concept of dynamic lazy memoization to .NET developers.In this post, we’ll see a short example using the library and explain the sample output. Let’s go!What is MemoizR?According to the author, Timon Krebs, MemoizR is a declarative structured concurrency implementation for .NET thatsimplifies (and enhances) standard data flow methods across multiple threads. These methods include error handling,branching logic, and data mutation. Doing so helps developers manage concurrency more efficiently for simple to complexmulti-thread scenario...

Testing Typesense search with Testcontainers and .NET

Search is an essential part of any modern application. Without a first-class emphasis on great search, many applicationsaren’t much better than a spreadsheet. Luckily for application developers, we’re spoiled for options for delivering anexcellent search experience to our users. One of the options I’ve been playing with recently is Typesense, which aims tobe an open-source alternative to commercial-service Algolia.In this post, we’ll look at how you can play around with Typesense within the context of .NET using Testcontainers.Testcontainers is a library that makes spinning up containers so simple you’ll wonder how you ever lived without it.Let’s get started.What is TypesenseSearch is challenging to get right, with many commercial options. The most notable commercial offerings includeElasticsearch and Algolia, which come with licensing costs or are search-as-a-service solutions. While great choices intheir own right, the options might not fit your particular goals for finding a search...

Subscribe to our newsletter

Subscribe to our newsletter and never miss new stories and promotions.