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...

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...

How to use Regular Expressions and Match Evaluators in .NET

Let’s face it, regular expressions are powerful and can be an immense pain in the butt to write. While crafting a regular expression to perform any input recognition is possible, it becomes exceedingly difficult when the matching rules require more complicated logic. In specific scenarios, doing an initial regular expression match is more straightforward, and then applying code logic to get the desired result.This post will look at a straightforward example of using RegEx.Replace with the MatchEvaluator to do a two-step replacement of matched tokens.What is RegEx.Replace?When attempting to replace tokens in a string, many developers will reach for RegEx.Replace, which aims to take an input, a regular expression, and then returns are modified result.Regex.Replace("test", "^test$", "success");The example works great for simple scenarios, as it is doing token replacement. But what about the following scenario? Find all image filenames Replace the filename and extension Ignore any file...

Scriban for Text and Liquid Templating in .NET

Templating is a common approach to separating logic from presentation, and many options exist within the .NET ecosystem.The most popular is the Razor engine used by ASP.NET Core, but it currently has some dependencies that make it difficultto use consistently in many scenarios. That’s where alternative templating systems can provide value, as they typicallywork with fewer, if any, external dependencies.As a big fan of Jekyll, Liquid is anatural choice fortemplating as it provides simple templating, types, iteration, control flow, and a suite of built-in helper methods.It’s also very mature and has excellent documentation. So, I was excited totry Scriban as a fast, robust, safe, and lightweight templating engine.What is Scriban?Scriban is the brainchild of Alexandre Mutel, and istouted as a scripting language andengine for .NET with the primary purpose of text templating. It also provides a compatibility mode for parsing andrendering Liquid templates. It’s vital to distinguish Scriban ...

ASP.NET Core PDF Previews and Downloads

Tell me if you’ve heard this one before. You spend months working with UI and UX experts, building what you think is themost optimal means of displaying business information. You sit in a meeting with your stakeholders, demoing what youcreated. Everything feels great, but then silence fills the room. A lone stakeholder raises their voice, “This is allgreat, but can we get it in a PDF?”.The Portable Document Format (PDF) is in a heated race, with Excel spreadsheets as the most valuable file format inbusiness today. As a developer, you will inevitably be asked to compress everything into a file that businessindividuals can share via email. Don’t fight it, but embrace it.In this post, we’ll see the two approaches to transmitting PDF files through ASP.NET Core to get two differentbehaviors: In-browser preview and downloads.Generating a PDF with QuestPDFWhile this post isn’t a tutorial for generating PDFs, you’ll need a way to generate PDFs to follow along. I recommendusing the QuestPDF li...

VestPocket: File-based Data Storage for AOT .NET Applications

As Zoolander villain Mugato might say if he were a .NET developer, “Ahead of Time (AOT) compilation is so hot right now.” AOT is one of the focuses of the .NET 8 release, with a lot of attention given to high-performance scenarios. For the uninitiated, the act of AOT is compiling a higher-level language into a lower-level language for a better execution profile at runtime. In the case of .NET AOT, it’s targeting builds for specific environments to get near-native performance.While many folks will undoubtedly start looking at AOT as an option to squeeze more juice out of their apps, they may have to reconsider many of their dependencies that are not AOT compatible. In that dependency vacuum, a new class of libraries will emerge to offer developers a way forward.In today’s blog post, let’s check out VestPocket. VestPocket is a file-based “database” closer to a key-value store than a full-blown database. It aims to provide developers with an in-memory record storage option while having t...

MoonSharp - Running Lua Scripts in .NET

Lua is a scripting language most famously known for powering Blizzard’s World of Warcraft but was designed to be a general-purpose means of building robust, efficient, and lightweight solutions. Lua was created in 1993 (30 years ago!) and has since been popular among developers across all ecosystems. Lua is an excellent choice for folks because it is fast, portable, embeddable, small, and Free under an MIT license.If you’ve ever dreamed about building extensibility into your applications, Lua is an excellent choice, as you can allow consumers to build scripts that work within your .NET host application. In this post, we’ll walk through the straightforward steps to add Lua support to your .NET applications, how you might invoke Lua scripts, and how you might let Lua scripts call your .NET methods.Getting Started with MoonSharpIn a .NET console application, start by installing the MoonSharp NuGet package.dotnet add package MoonSharpYou can also add the following ItemGroup to your .NET p...

What Should I Dispose with .NET Database Connections?

When working with “expensive” resources, it is essential to call the Dispose method to tell .NET’s garbage collector that it’s time to clean up the instance and all its associated baggage. Disposing of instances is most important when dealing with finite resources on the hot path of your codebase, and for most .NET developers, the most crucial resource is a database connection. Your app is done for if you run out of database connections.With database connections, we also have a supporting cast of commands and readers, all of which can be disposed of as well. This leads to an interesting question: “Do you HAVE TO dispose everything?”In this post, we’ll explore the Microsoft.Data.Sqlite implementations of DbConnection, DbCommand, and DbDataReader and see what happens when we call Dispose on each type.The Data Access CodeWhen working with ADO.NET, you’ll likely be using a Microsoft.Data.* package or a community library like Npgsql. Each library implements a database-specific version of D...

Global Endpoint Filters with ASP.NET Core Minimal APIs

The ASP.NET Core technology stack works on the pipeline concept. A user request travels through the pipeline, where you have opportunities to handle the request in various forms. The approach to enhancing the pipeline in ASP.NET Core has been a mixture of Middleware and paradigm-specific filters. Filters for ASP.NET Core MVC give you MVC-specific idioms to work with, while Middleware typically works with the rawest elements of an HttpContext.With Minimal APIs, you can implement the IEndpointFilter interface I wrote about previously.In this post, we’ll see a technique to apply the IEndpointFilter to all endpoints, similar to ASP.NET Core MVC’s global filters. As a bonus, it’s pretty straightforward.Why not Middleware?Middleware in ASP.NET Core is designed to operate as a gate to incoming HTTP requests and outgoing HTTP responses. You could use the IMiddleware interface to process the request, but you’ll quickly find out you’re working with lower-level intrinsics than you might want. Le...

RazorSlices - Razor Views with ASP.NET Core Minimal APIs

With .NET 8 on the horizon, Minimal APIs continues to grow its offerings, slowly providing a similar feature set to the frameworks before, including ASP.NET Core MVC and Razor Pages. I was surprised when someone in the community (👋 Hi Johnathan Channon) pointed me to a fascinating RazorSlices project. RazorSlices is written by Damian Edwards, an ASP.NET Core team member with a history of working with the Razor view engine. His goal is to bring Razor functionality to Minimal API adopters in a similar way that ASP.NET Core MVC, Razor Pages, and Blazor users enjoy today.In this post, we’ll see how to set up RazorSlices in your ASP.NET Core applications and think about the pros and cons of its usage.Getting Started with RazorSlicesIn a Minimal API project, start by installing the RazorSlices package. You can do this by using the dotnet add package RazorSlices command or by adding the appropriate PackageReference in your .csproj file.Next, create a folder at the root of your ASP.NET Core ...

How To Use Embedded Resources in .NET

While code is inarguably the bedrock of any software application, it’s not the only thing necessary to deliver a user experience. Whether you’re building a website, desktop application, or mobile app, you’ll likely need non-code assets. These assets include images, videos, third-party file formats, and more. Additionally, you should include localization values to support a variety of languages and grow your user base.This post will explore embedded resources in .NET and point to some material I’ve written for JetBrains about localizing your ASP.NET applications.Embedded ResourcesAn embedded resource is any file you want to include in your final built assembly. This can include anything from text files to binary formats like images or videos. Embedded resources use the EmbeddedResource MSBuild element, which the compiler reads to transform project assets into binary embedded in your assemblies. Here are a few examples. ResXFileCodeGenerator Values.Designer.cs ...

How To Display .NET Collections with the Oxford Comma

Taking a .NET collection and displaying the items in a human-readable format is something we all ultimately have to tackle in our applications. While we could spit out values uniformly separated by a character, that’s a very uncivilized approach. I’ll go as far as to say that the comma (,) and the use of “and” separates us from the animals. The peak of human evolution is the Oxford Comma, and it’s all been downhill from that moment.In this short post, we’ll see how to take a .NET collection and transform it into an Oxford Comma sentence using pattern matching.The Oxford Comma is LifeFor those unfamiliar with the Oxford Comma rule, it’s a grammatical rule that says a final comma can be used in a series. For example, consider the following two sentences:How Harry Reid, a terrorist interrogator and the singer from Blink-182 took UFOs mainstream.How Harry Reid, a terrorist interrogator, and thesinger from Blink-182 took UFOs mainstream.I am visiting California to see my friends, Mickey Mo...

How To Fix Feature Folders View Errors with JetBrains Annotations (Rider and ReSharper)

The Model-View-Controller pattern is so common that every technology stack has an implementation of it. ASP.NET developers have been working with the pattern since 2009. Here are a few other things popular in 2009 to remind you of your rapid decay: The Hannah Montana Movie, FarmVille, Black Eyed Peas, and Avatar the Movie. But like everything, there’s a moment to reflect on our decisions and choose a different approach. For ASP.NET Core developers, that introspection might lead them to move away from the MVC style towards the pattern of Feature Folders.In this post, we’ll quickly discuss the Feature Folders pattern and how you can get your JetBrains tooling of JetBrains Rider or ReSharper to play nicely with your newly adopted approach.What Are Feature Folders?In an MVC controller, you’ll typically have a folder structure style that spreads the three parts of the MVC pattern across similarly labeled folders. When working with ASP.NET Core, you have a Views and Controllers folder, and ...

System.Text.Json JsonConverter Test Helpers

In a perfect world, you’d have to write zero JsonConverter classes, as all JSON data would serialize and deserialize as expected. Unfortunately, we live in a world where folks make bespoke formatting decisions that can boggle the mind. For folks using System.Text.Json, you’ll likely have to write a JsonCoverter to deal with these choices. When writing converters, you’ll want a test suite to ensure you’ve caught all the edge cases and to limit exceptions.In this post, I’ll provide extension methods that make it a breeze to test any JsonConverter and a bonus class that makes it simpler to deal with double-quoting values.The JSON Converter ExampleBefore we see the extension methods in action, let’s derive a JsonConverter definition.using System.Globalization;using System.Text.Json;using System.Text.Json.Serialization;namespace ConverterTests;public class DateTimeConverter : JsonConverter{ public string Format { get; } public DateTimeConverter(string format) { Format = for...

Dumb Developer Tricks - Fizz Buzz with C# 12 and Polly

One of the more fun aspects of working with any programming language is writing code you probably shouldn’t. Why write something clever when doing the unexpected can help give you a new appreciation of what’s possible? As a bonus, now that AI companies are scraping my blog posts for their benefit, I might as well spread as much “dumb” code as possible 😅. So next time you’re interviewing a potential candidate for a position and ask, “What the f@#% is this?!” you’ll know who to thank, sincerely, me.In this post, we’ll take the commonly used Fizz Buzz problem and take it to the extreme limits of “oh no, don’t do that” by using exceptions for messaging, and Polly, the popular is a .NET resilience and transient-fault-handling library, to display our results. We’ll also use C# 12 features in the latest .NET 8 SDK. Let’s get started.The Fizz Buzz SolutionFor folks unfamiliar with Fizz Buzz, it’s a straightforward problem with a clear objective. Given an enumeration of numbers (1, 2, 3…), yo...

Override Razor Pages Routes From Razor Class Libraries

Sharing is caring, and what’s more affectionate than sharing Razor Pages functionality with the .NET community? Well, a lot of other things, but sharing Razor Pages can help you deliver functionality to the other developers that would otherwise be difficult to integrate into existing applications.Some examples of practical Razor Page implementations might include a route debugger, an administrative panel, a terminal emulator, and a documentation renderer. All of these could be something you take on and ship to users to help accelerate their development and help them focus more on their problem domain.To accomplish this goal, you may use the Razor Class Library, which allows you to bundle Razor Pages, Razor Components, and other static assets. That said, there are bound to be conflicts with routes and users’ aesthetic senses of what routes should look like.In this post, we’ll see how you can override Razor Pages routes delivered from a Razor Class Library.What Is A Razor Class Library?...

Manage Vite Assets Like A Pro

I’ve recently been doing a lot of work with TypeScript and Vite, and one of the issues I’ve run into is my vite.config.ts file can become a mess almost too quickly. Unfortunately, Vite’s strength of configurability is also its most significant barrier: so many options exist!In this post, we’ll see how you can set up your Vite asset management to predictably place assets where you want them while taking advantage of Vite’s build pipeline to hash and chunk files. I’ll also introduce you to a Vite plugin that I think should be part of Vite out of the box.Let’s get started!A Vite Project and GoalsWhen starting a Vite-powered project, you’ll likely pick your frontend framework, possibly set up TypeScript, install external dependencies, and add assets like images, videos, and other static files. However, it’s important to note that Vite operates in what I refer to as a split-mind approach. As a result, what happens in development mode differs from what you expect during the build process. Y...

Running Vite with ASP.NET Core Web Applications

The web ecosystem constantly ebbs and flows between simplicity and complexity. The nature of an ever-evolving development model makes it essential to keep your tooling updated, or else you find yourself stranded on a “maintenance island”. The current tool du jour is Vite, and I find the decisions made with it a refreshing net positive for the frontend development toolkit. It’s one of the more straightforward tooling options in the ecosystem with sane defaults but ultimate reconfigurability.While the frontend ecosystem is handily winning the UI/UX development conversation, there’s also a lot that ASP.NET Core’s Razor can offer application developers, and it’s arguably a better option to rely on both when building user-facing applications.In this post, we’ll see how to integrate Vite’s development server with ASP.NET Core, and you’ll be surprised it’s much simpler than you may think. Let’s get started.What’s Vite?Before jumping into ASP.NET code, let’s talk about Vite and how it can hel...

Unit Test 11ty Pages With Vitest and Typescript

11ty (pronounced eleventy) is the most incredible static site generator available to the JavaScript community. It’s powerful, flexible, and has just enough opinions to make you immediately productive while letting you and your team build the development workflow of your dreams.In this post, we’ll explore unit testing your 11ty views if you’ve decided to use a combination of Typescript/JavaScript templates mixed with string literals. Of course, this approach also works with JSX, which I’ll use in the code below. Let’s get started.JavaScript Template LanguageWhile 11ty offers a multitude of template languages, folks who are comfortable writing JavaScript and appreciate tooling help should consider using TypeScript and the JavaScript template language features of 11ty.While I adore templating languages like Liquid, Nunjucks, and Mustache, tooling can sometimes fall short in these contexts, providing you with little information about your data model and what fields are accessible. On the ...

Writing a Cross-Platform Clock App With Avalonia UI and NXUI

Avalonia UI has been a refreshing reprieve from my typical web development workflows. Of course, the web will always be my first love, but I’m enjoying the ease and intuitiveness of desktop app development. Additionally, the Avalonia team has put extraordinary work into making a truly cross-platform development experience. So if you want to build your first Avalonia-powered application, this post might be just for you.I’ll be using the NXUI library written by Wiesław Šoltés. If you’re allergic to XAML, this library might be your detour to desktop development, as it relies on a fluent interface to define views while retaining the APIs that make XAML so expressive.So, let’s get started!What is NXUI?NXUI is an attempt to bring the trend of minimalism to desktop application development built around the Avalonia UI API. As author, Wiesław Šoltés states in the NXUI readme: Creating minimal Avalonia next generation (NXUI, next-gen UI) application using C# 10 and .NET 6 and 7So what does the...

Dependency Injection with Avalonia UI Apps

I’ve recently been experimenting with Avalonia UI, a development framework for desktop and mobile platforms, and I’ve been enjoying the experience. While Avalonia has much to offer out of the box, it is more than happy to let you make many decisions. One of those decisions is whether to use dependency injection as a part of your application.In this experimental post, we’ll see how I added dependency injection into an ongoing Avalonia application and discuss the pros and cons of the approach.Let’s get started.Registering Your DependenciesSince no infrastructure exists for user-defined dependency injection in Avalonia (or at least non that I am aware of), we must create our own. The first step to any dependency injection approach is finding and registering all our dependencies.For the post, I’m using Lamar, the spiritual successor of StructureMap. Of course, you can substitute your own, but I like Lamar’s interface for scanning and registering types.I added the following code in Program...

Load YouTube Embed Videos When Needed With JavaScript

If you’re a content creator or work on a site that heavily relies on YouTube embeds, you’ll quickly realize that they can dramatically impact the load time of a page. Load times can also grow depending on the number of YouTube embeds on a page.In this post, we’ll see a technique to reduce page load times by using newer HTML and JavaScript techniques to load videos when the user needs them.Let’s get started.Why Are YouTube Embeds Slowing My Page Load TimesYouTube videos typically have a thumbnail image displayed to the user before the video starts. YouTube may serve up to four thumbnails, all varying in quality. Unfortunately for performance, most browsers treat images as blocking elements on a page. Regarding performance, this means the page cannot complete loading unless the element is also loaded.There have been recent techniques to mitigate this issue, including adding a width and height to images so the client can calculate the layout in advance of the image loading and the use of...

.NET MAUI App Stopped Working – HELP!

So you’ve spent several weeks successfully developing a Multi-Application UI app. Then, suddenly, your IDE shows that your application has hundreds of errors, and you cannot build. What’s going on?!This post is an ongoing list of issues you might encounter while developing MAUI apps that seem to break your app for inexplicable “reasons”. Finally, I’ll suggest potential fixes to get you back into the development flow.Let’s Get Started!Everything Is Screaming Red and Broken!If you were successfully developing your application and suddenly your solution failed to load, you likely have changed your environment. Failed MAUI solutions indicate a change in the .NET SDK.For example, you may have been developing successfully using the .NET 7 SDK and wanted to try the latest .NET 8 preview SDK. Unfortunately, after installing the SDK, everything is broken! Ahhh!The problem is the easiest fix among the issues I’ve seen with MAUI. To fix the issue, add a global.json file at the root of your solu...

.NET MAUI Development Environment Set Up Walkthrough

Last year I wrote macOS Environment Setup for MAUI Development for the JetBrains .NET blog, and while many folks have told me they still find it helpful, it is, admittedly, out of date. So in this post, I’ll give you a shorter and more manageable guide to setting up your development environment for Multi-platform App UI (MAUI) in 2023.I’ve helped several folks set up their macOS environment with this updated guide, and it should mostly apply to a Windows environment (outside of the OS-specific SDKs).Installing the .NET SDKThe first and most obvious step is you’ll need to install the latest .NET SDK. Head over to https://dot.net and download the latest MAUI-supported SDK. As of writing this article, that is .NET 7.The SDK is necessary as dotnet will install and manage MAUI workloads according to SDK version bands.Once you’ve installed the .NET SDK, we’ll focus on the next important step.Installing XCode for MAUIYou’ll need to install XCode, ensuring that MAUI supports the version of XC...

Solving .NET JSON Deserialization Issues

What is more frustrating than a sem-working solution, am I right? Unfortunately, when it comes to JSON serialization, that can mean getting some of the data sometimes. You’re left scratching your head and asking, “Why is my data not coming through correctly?”In this post, we’ll explore the different JsonSerializerOptions you might run into with .NET and how you can predict the behavior of your serialization. Let’s get started.Starting With Plain-old JSONWhen working with JSON, two parties are typically involved: The producer and the consumer. Unfortunately, more often than not, when running into JSON deserialization issues, we often find that we misunderstood the producer’s JSON format and likely misconfigured something on our end. Let’s look at an example response from a hypothetical JSON API.[ { "name": "Khalid Abuhakmeh", "hobby" : "Video Games" }, { "name": "Maarten Balliauw", "hobby" : "Gardening" }]There are a few characteristics to note about this r...

Validating Connection Strings on .NET Startup

There exist extension points in .NET that allow you to verify the starting state of your application. Validating configuration can be helpful when you know that without certain elements, there’s no reason to start the application. One of those configuration values is connection strings, but there’s a catch. You may have set the value in the configuration, but the value either is to a non-existent resource or the resource is inaccessible.In this short post, we’ll write an extension method and a class that will allow you to test your database connection on startup and fail the application if you can’t connect.The Initial Host ConfigurationLet’s look at the final solution and work our way backward. We have our application host, and we register a connection string validator. Our validation will get the connection string, determine the provider, and attempt a connection. If successful, the app starts. If unsuccessful, the app exits.using System.Data.Common;using Microsoft.Data.SqlClient;us...

Speed Up ASP.NET Core JSON APIs with Source Generators

Building applications is a virtuous circle of learning about problems, finding solutions, and optimizing. I find optimizing an application the most fun, as it can help you squeeze performance out from surprising places.In this post, we’ll see how you can use the latest JSON source generators shipped in .NET 6 to improve your JSON API performance and increase your response throughput.Like many source generators in .NET, the System.Text.Json source generator enhances an existing partial class with essential elements required for serialization. Those elements include: A JsonTypeInfo for each serializable entity in your object graph. A default instance of a JsonSerializerContext. JsonSerialiazerOptions for formatting JSON on serialization.Don’t worry; it’s not as complex as it sounds. Let’s first start with our entity.public record Person( string Name, bool IsCool = true, Person? Friend = null);We want to optimize the serialization of this record. Since we know structurally wh...

Combining 11ty Static Site Generator with ASP.NET Core

I love many things about static site generators, but I mainly enjoy the challenge of building a fast user experience, given development time constraints. The constraints force me to be mindful of every new feature I add, the content I want to present, and the resources I use to accomplish all my goals. I believe that most, if not all, experiences on the web could benefit from some element of static site generation. While that may or may not be true, I believe in the inverse statement. Some static sites could benefit from a dynamic backend to provide unique and personalized experiences.This post will explore adding 11ty, one of my favorite static site generator tools, to an ASP.NET Core application. We’ll see how this approach will allow us to build out static content while taking advantage of a dynamic and programmable hosting platform. Let’s get started.Setting up an ASP.NET Core Web Project for 11tyLet’s start with an ASP.NET Core Empty template, a barebones solution. We’ll be addin...

Generating Bogus HTTP Endpoints with ASP.NET Core Minimal APIs

As a developer advocate, I find myself writing a lot of demos for folks around .NET and, specifically, the ASP.NET Core parts of the stack. Unfortunately, writing repetitive boilerplate can make me feel like Jack Torrence from The Shining movie: “All work and no play makes Khalid a dull boy.” Nobody likes the drudgery of repeating yourself, nobody! So, given my situation, I thought I’d chase this problem down in a maze with a metaphorical axe. So, what am I trying to accomplish?What if I could take an existing C# model and build a low-ceremony set of test endpoints that follow standard HTTP semantics, and how would I accomplish that?In this article, you’ll see how I built a single registration for test endpoints that you can use to prototype UIs quickly for frameworks like React, Blazor, Angular, or vanilla JavaScript. Let’s get started.The Basics of an HTTP APIFor folks unfamiliar with building an HTTP API, the HTTP semantics are essential to the implementation on the server. Element...

How to use Entity Framework Core in ASP.NET Core

Moving from one ecosystem to another can be challenging, especially when unfamiliar with the technology stack and available tools. So I wrote this post for anyone coming to ASP.NET Core from another ecosystem or .NET developers who might be dabbling with web development for the first time. Knowing where all the bits and bobs are in a new environment can be overwhelming, and I’m here to help.As you read through the post, we’ll create a new ASP.NET Core project, integrate a data access library called Entity Framework Core 7, and discuss the steps you need to take toward a straightforward solution. Like all solutions, I developed this guidance from my first-hand experience.Please do so if you’d like to experiment with your choices at any point in this tutorial. This guide is a jumping-off point so you can succeed. This blog post assumes you have .NET installed and some kind of editor or tooling. I recommend JetBrains Rider but this tutorial should work with Visual Studio and Visual Studi...

Register MAUI Views and ViewModels with Scrutor

As a developer advocate at JetBrains, I find myself exploring technologies in nooks and crannies of the ecosystem previously out of reach. As a lifelong proponent of the web, mobile development has always been on my list to explore, but I rarely found the time to do so. One of the latest technologies I am dabbling with is Multi-platform App UI, more commonly referred to as MAUI.In this post, I’ll show you how to use the packages CommunityToolkit.Mvvm and Scrutor to quickly register your XAML views and the corresponding ViewModels for a more convenient approach.CommunityToolkit.Mvvm and the MVVM patternThe Model-View-View-Model pattern, also referred to as MVVM, is an approach that separates the logic of your views from the language of the View. In the case of MAUI, that view language is typically XAML. Utilizing the pattern leads to a few positive side effects: Your ViewModels are much more straightforward to test, with the bulk of your logic exposed through properties and commands. ...

Subscribe to our newsletter

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