IMemoryCache Entry Invalidation (Manual Cache Busting)
IMemoryCache is great for speeding up expensive operations (database reads, HTTP calls, heavy computations). But many real systems need more than a TTL:
IMemoryCache is great for speeding up expensive operations (database reads, HTTP calls, heavy computations). But many real systems need more than a TTL:
.NET 10 is the next Long-Term Support (LTS) release in the .NET family. LTS matters because it’s the version many teams standardize on for the next 2-3 years: you get a stable baseline, predictable support windows and a natural time to pay down technical debt (tooling, CI images, container base images, dependency bumps).
Read Blog PostAzure now provides a unified Realtime API for low‑latency, multimodal conversations over WebRTC or WebSockets. If you’ve used the earlier preview versions (for example the GPT‑4o realtime preview), the new generation model is simply called gpt-realtime
and the API follows the same event-driven pattern: you open a session, configure defaults via session.update, stream input and receive streaming output (text, function calls, audio, etc.).
Logging is part of the contract of many components: when things fail, when branches are taken, when work completes. If a class owns logic, it should own its log output too. That makes logs worth testing–especially for diagnostics, reliability and supportability.
Read Blog PostWhen working with asynchronous or parallel code in C#, you’ll inevitably encounter two common ways to start tasks: Task.Run and TaskFactory.StartNew. At first glance, they seem similar - but they behave differently and should be used appropriately depending on the context.
The Model Context Protocol (MCP) server acts as a centralized context management backend for advanced AI applications.
Unlike traditional session or prompt-based approaches, the MCP server manages a persistent, structured context that can be queried, updated and synchronized across distributed AI components and user sessions. By providing a standard API for serializing, retrieving and sharing context, the MCP server enables seamless interoperability between different models, services and clients. This is particularly important in multi-agent systems, long-running workflows or environments where state continuity and context portability are required.
Read Blog Post.NET does not have a built-in mechanism for querying DNS records; nevertheless, this is a use case that is required relatively often.
Read Blog PostNowadays, you can’t actually run a website on the Internet without having a protection mechanism against content bots. One possibility is the use of CAPTCHAs. CAPTCHAs are small tasks that a human can easily solve, but a bot (almost) cannot.
Read Blog PostWith .NET 9, Microsoft has added new options to the System.Text.Json library to format the output of JSON objects - features that, in my opinion, should have been available with day 1.
The recommended variant for specifying the SDK in .NET is the global.json file. This centrally guarantees that all computers on which the code is compiled ideally have the same SDK installed and use it.
Read Blog PostFor several years now, C# has supported Records as a new “type”. Initially only for classes (which is why the class is optional for a record class), later also for structs. Records are specially designed for use as data containers aka DTOs (please dont use DTO in your class name!). They are immutable and have special semantics for equality.
Read Blog PostAnti-idle apps for Microsoft Teams and the like are a dime a dozen, but how about creating your own? In this article, I’ll show you how to create an anti-idle app for Microsoft Teams using .NET and C#.
Read Blog PostQR Codes are a very popular way to pass on information - for example an URL. The QR code can be placed on all kinds of places, for example in parking lots for buying parking tickets.
Read Blog PostThe Microsoft Graph and Entra documentation are both very comprehensive and provide a lot of information - but they often contain no examples or no working examples. In addition, the SDKs are either not, insufficiently or incorrectly documented.
Read Blog PostIf you browse through certain libraries or the .NET Runtime from time to time, you will notice that the attribute MethodImplOptions.AggressiveInlining can be found in some places - but what is this actually?
Read Blog PostNew year - new .NET drama. You would have thought that positive lessons had been learned from the last Moq drama; but we were proven wrong.
Read Blog PostIn the world of Microsoft SQL Server , views are a powerful tool for simplifying complex data queries. Simple views offer no real performance gain but are often used to implement simple database queries (I still would prefer App implementations over Database implementations for simple views). But indexed views offer a real performance gain.
Read Blog PostEF Core Migration Bundles
are standalone executable files that contain one or more Entity Framework Core
migrations and can be applied directly to a database. They are particularly useful for deploying migrations independently of the source code or development environment, e.g. in production environments.
Using migration bundles simplifies the deployment process as no additional software or configuration is required to perform the migrations. In CI/CD systems like Azure DevOps
in particular, they can be executed across all platforms on all operating systems and therefore offer a flexible alternative to DACPAC deployments
, which are often dependent on Windows tooling.
There are various reasons why it is useful to channel certain requests through your own application to an external endpoint; the most obvious is, for example, as a workaround for client statistics from browser adblockers like Microsoft Clarity or Cloudflare Web Analytics.
Read Blog PostRate Limit is a great tool to protect your own website and content from misuse; in some cases, however, rate limiting is also bad: for example, if you want your own content to be indexed by Google Search in order to increase your own visibility.
Read Blog PostThere are many ways to remove spaces or other characters in a string - there are just very big differences in terms of performance and efficiency.
Read Blog PostCode formatting is a very important element when developers work together on a project - and you are always well advised not to invent your own formatting rules, but to use those that are a standard or de facto standard in the respective programming language.
In C#, many rules are now controlled via the editorconfig
, but there is still a lack of standardized formatting tools in .NET - dotnet format simply does not support many things - so that different functionalities exist in different IDEs (Visual Studio
, Visual Studio Code, Rider).
Sustainable Code is a constantly growing GitHub repository created by me
, in which I collect various everyday code snippets and measure the performance of the different implementation ways.
The goal is to create a collection of code that virtually everyone has in front of them every day and can thus easily implement the best way for themselves and their use case.
A popular unit test - and also a necessary test - is the correct registration of interfaces and their implementation with dependency injection. And a common mistake is that the associated IServiceCollection interface is used for mocks that lead to faulty tests.
Read Blog PostWhen working with ZIP files in .NET, there may be cases where the file is not stored on disk but comes directly as a Stream. This could happen if you’re downloading the ZIP file from a network, receiving it via an API, or working with in-memory file data. In this blog post, I’ll show you a simple example of handling ZIP files using streams in .NET and how to process their content without saving the ZIP to disk.
Read Blog PostWorking with compressed files is common in many applications, whether you’re extracting data from an archive, installing software packages, or retrieving bundled files. Thankfully, .NET finally provides an efficient, straightforward way to decompress ZIP files using the System.IO.Compression namespace. In this post, I’ll walk through a simple code snippet that you can use to decompress ZIP files in your .NET apps.
Read Blog PostWhen working with .NET apps you may sometimes need to bundle multiple files into a single compressed archive for easier storage, transfer, or processing. In this post, I’ll show you a simple and effective way to compress a folder into a .zip file using just a few lines of code with the built-in .NET namespace System.IO.Compression .
Read Blog PostIn C# (.NET 6 and above), there is now a very simple way to read out the CPU load with minimal overhead - i.e. without threads. The PerformanceCounter from the System.Diagnostics namespace helps us with this.
Dealing with empty lists is an everyday situation in .NET. An empty list is often preferred to a null in order to control the logic. But how expensive is it to return an empty list?
We are currently in the preview phase of .NET 9 , which releases in Nov 2024 - and if you want to test it extensively like I do, store the preview version in the global configuration global.json . But how do you have to define the version here for it to work?
Read Blog PostStrings are one of the most commonly used types in .NET applications - and very often the source of inefficient code. For example, cleaning up a string - such as removing invalid or non-visible characters - is one of the most common use cases for user input. Unfortunately, the most convenient, but not the most efficient, implementation imaginable is used in this case: Linq.
Read Blog PostRefit is an open-source library for .NET developers that simplifies the process of making HTTP API calls. It allows developers to define a set of interfaces that describe the API endpoints they want to interact with and then Refit automatically generates the necessary code to make the HTTP requests. This can significantly reduce boilerplate code and make the interaction with web APIs more type-safe and maintainable.
Read Blog PostStrong Name Signing is a mechanism in .NET development that ensures the integrity and authenticity of assemblies. It is based on a public-private key procedure.
Contrary to what many assume, this is not a security mechanism, but a mechanism to ensure the uniqueness of the identity. It is therefore also recommended to store both private and public keys directly in the repository - and not to hide them; especially not in open source projects.
YAML files are unfortunately part of everyday life for all developers these days; and although they are very error-prone and almost impossible to edit without an IDE and schema information without constantly running into errors - many greetings to all CI systems that think this was a good idea: it wasn’t - we have to accept that we have to process them.
Read Blog PostTLDR;
You can see the full sample in my GitHub repository BEN ABT Samples - ASP.NET Core Form protection with Cloudflare’s Turnstile
Read Blog Post
It’s now been a few months since the GDPR-drama and data-harvesting around Moq (Stop using Moq as a guinea pig to get feedback on and develop SponsorLink ) happened - and the only conclusion that remains is: please migrate away from Moq, as quickly and efficiently as possible.
Read Blog Post.NET event counters are a relatively new API for collecting metrics from .NET applications. They are part of the EventSource and EventCounter namespace since .NET (Core) 3.0.
Read Blog PostBy default, Azure Application Insights comes with necessary and important telemetry capabilities to monitor the basic functions of an application and collect telemetry.
Read Blog PostThe Azure Communication Service is a fairly new but already popular service for sending emails at scale. In this article, I would like to show you how you can use the service via a connection string in your .NET project.
Read Blog PostThe Azure Communication Service is a fairly new but already popular service for sending emails at scale. In this article, I would like to show you how you can use the service via a Azure Managed Identity in your .NET project.
Read Blog PostOne of the last blog posts (Text and EMail Templates with Handlebars.NET ) was generally about HandleBars.NET - a very popular template engine. This post is about how you can easily implement layouts with Handlebars.
Read Blog PostAPI models are one of the elements where I personally see the most naming errors - which have a massive impact on the architect and cause subsequent errors. The solution is very simple: follow the naming rules!
Read Blog PostIn many code bases there are Services and Providers - and often they do the same thing structurally; but what is the idea of a Service- and Provider-Classes?
Database entities are the objects that represent the tables in your database. They are the objects that you use to read and write the database.
Read Blog PostOften seen, often used incorrectly: DTOs. Data Transfer Objects.
In principle, DTO is an umbrella term, a design pattern that is used to transfer data between. In reality, however, the umbrella term is used directly as an implementation, which has disadvantages in all cases.
Read Blog PostA frequent requirement in apps is the conversion of templates, e.g. for sending e-mails, for PDF templates or other text modules. There are many different ways to do this, ranging from simple string replacements to the Razor engine of ASP.NET Core.
Read Blog PostQR codes are a simple and very popular way of exchanging data and information - even in .NET. They have become part of everyday life.
Read Blog PostThere are various ways to deploy an application, but Zip deployment is the variant that is recommended the most - regardless of whether you are using Azure, AWS or other cloud and hosting providers.
Read Blog PostWith .NET 8, the System.ComponentModel.DataAnnotations Namespace has been revised and some new attributes have been added that have been requested by the community for some time and have only been implemented through custom implementations.
Read Blog PostA database entity represents an identifiable entry, often also things from the real world, which are to be stored and managed in the database. The purpose of database entities is to provide a structured and efficient implementation for organizing and managing information. By identifying entities, defining attributes and establishing relationships, a coherent and meaningful structure is created that allows data to be stored, retrieved and updated effectively. This facilitates data management and analysis in applications and systems.
Read Blog PostIn C#, optional arguments are parameters in a method that have default values specified in the method’s declaration. This means that when you call the method, you can omit values for these optional parameters and the method will use the default values defined in its signature. Optional arguments were introduced in C# 4.0 to make it more convenient to work with methods that have a large number of parameters with sensible default values.
Read Blog PostAs has been the case for many releases, the .NET 8 team is spending a lot of development effort to improve the .NET Runtime in terms of performance. Because fast performance means one thing above all: low energy consumption and high scalability.
Read Blog PostSome APIs do not follow standards, ignore ISO8601 and return UnixTime. This is not nice, but can be easily fixed with a custom converter for System.Text.Json.
Read Blog PostA little more than three months ago, Microsoft integrated a new functionality into Visual Studio 2022: Build Acceleration .
This mechanism, which can be optionally activated, apparently ensures that build times for .NET projects can be reduced by up to 80%. This is, of course, an announcement that I wanted to take a closer look at.
Read Blog PostI often see snippets in EF Core code reviews such as the following:
1dbContext.Users.Where( user => user.Id == id );
The query filter user => user.Id == id is contained directly in the Where - often not just in one place but sometimes in dozens of places. Here I ask myself: why is this not simply outsourced to a central place? It’s so simple!
Unit testing is a type of software testing that is performed on the smallest unit of a software application, called a “unit”. A unit can be a function, method or module that is tested in isolation from other parts of the code.
Read Blog PostIn many software architectures the problem exists that there are methods, which are specified a multiplicity of type-same parameters, whose meaning is however fundamentally different. In principle, this includes all handling of Ids or other essential values that have a logical meaning.
Read Blog PostSeptember last year, Microsoft announced that a large number of backend services would be migrated to .NET 6. This, they said, was an enterprise-wide initiative .
Read Blog PostStructs have their advantages in .NET: they are especially efficient in the runtime if used correctly.
But if you use structs with an interface, the massive advantages unfortunately turn into disadvantages:
As soon as an interface is attached to a struct, Boxing
comes into effect; the values are thus copied over and over again, which is usually not what you want - but it also shows up in the benchmarks.
Both C# is null and == null are used to check if a variable or object is null, but they work slightly differently.
Symbolic Links (often abbreviated as symlinks) are a type of file or folder shortcut in Windows that reference another file or folder in the file system, rather than copying its contents. Unlike a normal shortcut, a symlink acts as if it were the original file or folder, so any changes to the symlink will affect the original file and vice versa.
Read Blog PostThe isolated mode of Azure Functions with .NET allows for greater control over the runtime environment and dependencies of the function. In this mode, the function runs in its own process, separate from the Azure Functions host. This allows for custom runtime versions and specific versions of dependencies to be used.
Read Blog PostStatische Methoden in C# sind Methoden, die auf eine Klasse und nicht auf eine bestimmte Instanz einer Klasse angewendet werden. Sie können aufgerufen werden, ohne dass zuvor eine Instanz der Klasse erstellt wurde. Ein Beispiel für eine statische Methode ist die Math.Sqrt() Methode, die die Quadratwurzel einer Zahl berechnet.
Read Blog PostExpressions are now an absolute part of a developer’s everyday life in .NET thanks to Linq.
However, due to their nature, expressions are not one of the very best performing tools, which is why the .NET team is also doing a lot to improve general performance while maintaining usability.
Read Blog Post.NET has two principal ways for handling times: DateTime and DateTimeOffset .
The big deficit of DateTime, which was also recognized early in .NET 1.0, is that it is not clear from the DateTime information which time zone the time information represents. Therefore DateTime is also called implicit representation of time information, whose “hope” is that the time information is always in relation to UTC-0. DateTime cannot guarantee this, which is why errors often occur in combination with time zones and DateTime. DateTime supports only two possibilities at this point: the local time of the application or UTC.
Read Blog PostMicrosoft has announced in an impressive blog post on the .NET DevBlogs that they have started an enterprise-wide migration to migrate backend services.
Read Blog PostBeginning with C# 3, variables that are declared at method scope can have an implicit “type” var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.
Read Blog Post
IoT Hub -> Devices -> Select Device -> Configurations)To use the DeviceClient , which opens the connection to your Azure IoT Hub , you need the NuGet package Microsoft.Azure.Devices.Client
Read Blog PostIn .NET, there is a very fast and easy way to pump a variety of entities into an SQL database: SqlBulkCopy
Read Blog PostThis pretty simply snippet exports your Image into a byte-array.
1public static byte[] ToByteArray(this System.Drawing.Image image)
2{
3 using(MemoryStream memoryStream = new MemoryStream())
4 {
5 image.Save(memoryStream);
6 return memoryStream.ToArray();
7 }
8}
Usage:
1System.Drawing.Image myImage = .....
2
3byte[] imageAsByteArray = myImage.ToByteArray();
ImageSharp uses the same signature to export bytes into a MemoryStream
Read Blog PostThe most current and currently recommended way to download .NET Framework, .NET Standard or .NET Core files from the Internet is the HttpClient class.
Read Blog PostUnter anderem durch die Aktivität im myCSharp.de-Forum ist mir aufgefallen, dass viele Entwickler doch Probleme mit der Konfiguration von WCF-Diensten haben. Zugegeben; ich bin auch kein großer Fan des .NET-Konfigurationsframeworks. Es vereinfacht manches, aber es verkompliziert auch vieles, da unnötige Werte Verwirrung stiften.
Read Blog PostDie Zeit am Flughafen möchte ich dazu nutzen einer meiner Anfragen per E-Mail zu beantworten.
Hallo Benjamin, wie testest du Quellcode, der mit internal deklariert ist?
Read Blog Post
Dieser Codeschnippsel soll exemplarisch zeigen, wie man in C# eigene Events definiert.
Als Beispiel dient hier die Überwachung von E-Mails in der Konsole.
Read Blog PostOft werden Warteschlangen benötigt, um Aufgaben zu Verwalten oder durch etwaige Parallelität die Performance zu Steigern. Mit .NET 4.0 hat Microsoft einen großen Schritt in diese Richtung getan und den Entwicklern durch die sogenannten ConcurrentCollections viel Arbeit abgenommen.
Read Blog Post