C# – Get subclass properties with reflection

When you use reflection to get properties, you can get just the subclass properties by using BindingFlags.DeclaredOnly (this causes it to exclude inherited properties). Here’s an example: Note: Use GetType() if you have an object. Use typeof() if you have a class. The code outputs just the subclass properties (from the Driver subclass): Get base … Read more

C# – How to read problem details JSON with HttpClient

Problem details (RFC7807) is a standardized error response format that has a Content-Type of application/problem+json, an error response code (i.e. 400 – Bad Request), and has a response body that looks like this: This can be extended to include any number of properties. The example shown above comes from the default way ASP.NET Core returns … Read more

XML doc warnings: CS1573 and CS1572

I’ll show examples of the XML documentation warnings and how to fix them. CS1573 Parameter ‘X’ has no matching param tag in the XML comment (but other parameters do) Warning CS1573 means there’s a missing <param> tag for one of the method parameters. This usually happens when you add a new parameter (or rename one … Read more

C# – How to unit test a model validation attribute

You can unit test a validation attribute by creating an instance of it and then testing the two methods: In this article, I’ll show examples of unit testing these methods in a custom validation attribute and in a built-in validation attribute (i.e. [Range]). Unit testing a custom validation attribute Consider the following custom validation attribute … Read more

ASP.NET Core – Create a custom model validation attribute

There are many built-in model validation attributes available – such as [Required] and [Range] – which you can use to handle most validation scenarios. When these aren’t sufficient, you can create a custom validation attribute with your own validation logic. I’ll show an example of how to do that. 1 – Subclass ValidationAttribute and implement … Read more

How to send a request with Postman

Postman is a great tool for web development. You can send a request to any web API, look at the response details, and reuse the the request later (which saves lots of effort!). This is useful for testing your own web API, or for when you’re integrating with a third-party API and want to try … Read more

SQL – How to use GROUP BY

You can use GROUP BY to group rows based on one or more columns. This produces one row per group in the query results. Each group contains the grouping columns and the result(s) of any aggregate function(s) (COUNT/MIN/MAX/AVG/SUM) you want to use on the group. Let’s say you have the following table and you want … Read more

C# – Deserialize JSON using different property names

When JSON property names and class property names are different, and you can’t just change the names to match, you have three options: These options affect both deserialization and serialization. Let’s say you have the following JSON with camel-cased property names: Here’s an example of using the JsonPropertyName attribute: Note: The Newtonsoft equivalent is [JsonProperty(“title”)] … Read more

C# – Deserialize JSON with a specific constructor

When your class has multiple constructors, you can use the JsonConstructor attribute to specify which constructor to use during deserialization. Here’s an example. The Person class has two constructors. I put the JsonConstructor attribute on one of the constructors: Note: JsonConstructor for System.Text.Json was added in .NET 5. Now deserialize a JSON string to the … Read more

Redirect a request in ASP.NET Core

Redirecting a request means returning a response with redirect status code (3xx) and a redirect URL in the Location header. The client uses this info to follow the redirect (which means making a request to the redirect URL). You can redirect by using a helper method (from ControllerBase) or returning a RedirectResult. I’ll show several … Read more

C# – Call a constructor from another constructor

To call one constructor from another one, you have to use the constructor chaining syntax, like this: This means when you use the Person(string name) constructor, it’ll first call the Person(string name, string birthDate) constructor. If the constructor is in a base class, use base() instead of this(): Employee subclasses Person. So calling base(name) here … Read more

C# – Handling redirects with HttpClient

HttpClient handles redirects automatically. When you send a request, if the response contains a redirect status code (3xx) and redirect location, then it’ll send a new request to the redirect location. You can turn off this auto-redirect behavior by passing in an HttpClientHandler with AllowAutoRedirect=false. This prevents it from following redirects automatically, and allows you … Read more

The required library hostfxr.dll could not be found

Problem You are trying to run a .NET executable and you get the following error: A fatal error occurred. The required library hostfxr.dll could not be found.If this is a self-contained application, that library should exist in [C:\MyApp].If this is a framework-dependent application, install the runtime in the global location [C:\Program Files\dotnet] or use the … Read more

C# – Connect to a MySQL database

The simplest way to connect to a MySQL database in a .NET project is to use the MySql.Data package (from Oracle). It provides classes that implement the standard ADO.NET interfaces (such as IDbConnection). First, add the MySql.Data package to your project (this is using View > Other Windows > Package Manager Console): Now use the … Read more

C# – How to use SortedSet

When you have a collection of elements that you’re continuing to add to, and need to keep the objects in sorted order at all times, you can use SortedSet. Internally, it uses a tree data structure to keep elements in sorted order (O(log n) insertion). This is far more efficient than repeatedly sorting a list … Read more

C# – Deserialize JSON to a derived type

The simplest way to deserialize JSON to a derived type is to put the type name in the JSON string. Then during deserialization, match the type name property against a set of known derived types and deserialize to the target type. System.Text.Json doesn’t have this functionality out of the box. That’s because there’s a known … Read more