Blog Posts with tag "Csharp"

Automatically discover tools for Azure OpenAI Realtime API

Automatically discover tools for Azure OpenAI Realtime API

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

Read Blog Post
Task.Run vs. TaskFactory.StartNew

Task.Run vs. TaskFactory.StartNew

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

Read Blog Post
Standardizing AI Context: the Model Context Protocol

Standardizing AI Context: the Model Context Protocol

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
When to use records in C#

When to use records in C#

For 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 Post
Increase Command Timeout for EF Core Migration Bundles

Increase Command Timeout for EF Core Migration Bundles

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

Read Blog Post
Auto Format your Code on save with Visual Studio

Auto Format your Code on save with Visual Studio

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

Read Blog Post
Sustainable Code with .NET 9

Sustainable Code with .NET 9

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.

Read Blog Post
How to process ZIP Files from a Stream in .NET

How to process ZIP Files from a Stream in .NET

When 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 Post
Decompress a ZIP archive with .NET

Decompress a ZIP archive with .NET

Working 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 Post
Efficiently clean a string with .NET

Efficiently clean a string with .NET

Strings 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 Post
Refit .NET - my personal caller best practise

Refit .NET - my personal caller best practise

Refit 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 Post
Strong Name Sign .NET Assemblies via SNK

Strong Name Sign .NET Assemblies via SNK

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

Read Blog Post
Handle Yaml Files with .NET

Handle Yaml Files with .NET

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 Post
.NET Naming Best Practises: DTOs

.NET Naming Best Practises: DTOs

Often 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 Post
The well-structured Entity in EF Core

The well-structured Entity in EF Core

A 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 Post
When to use optional arguments and parameter defaults in c#

When to use optional arguments and parameter defaults in c#

In 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 Post
Re-use EF Core Expressions to avoid redundant queries

Re-use EF Core Expressions to avoid redundant queries

I 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!

Read Blog Post
Better Code with custom Strong-Id Types

Better Code with custom Strong-Id Types

In 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 Post
A struct with an interface is inefficient in .NET

A struct with an interface is inefficient in .NET

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

Read Blog Post
Create Symbolic Links on Windows with .NET

Create Symbolic Links on Windows with .NET

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 Post
Statische Methoden in C# / .NET

Statische Methoden in C# / .NET

Statische 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 Post
Compile Linq Expressions to increase performance

Compile Linq Expressions to increase performance

Expressions 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
DateTime vs. DateTimeOffset - UtcNow vs. Now

DateTime vs. DateTimeOffset - UtcNow vs. Now

.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 Post
Load an image into a byte-array with C#

Load an image into a byte-array with C#

This 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();

Hint: ImageSharp

ImageSharp uses the same signature to export bytes into a MemoryStream

Read Blog Post
Einfaches WCF-Beispiel ohne komplizierte Config

Einfaches WCF-Beispiel ohne komplizierte Config

Unter 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 Post