C# – Serialize anonymous types with System.Text.Json

It’s common to need to customize serialization. When you need to do this, you’d typically need to create a custom JSON converter and pass it in during serialization. Depending on your scenario, an alternative approach is to use anonymous types, like this: Basically you select properties from another object and format them as desired, and … Read more

C# – How to use JsonConverterFactory

Let’s say you want to serialize the four datetime types – DateTime, DateTime?, DateTimeOffset, and DateTimeOffset? – in the same way. You want to serialize them to use the US date style (ex: 7/14/2021). There are two main ways to accomplish this: 1) Create a custom JsonConverter for each type or 2) Create a JsonConverterFactory … Read more

System.Text.Json – How to serialize non-public properties

By default, System.Text.Json.JsonSerializer only serializes public properties. If you want to serialize non-public properties, you have two options: In this article, I’ll show examples of both approaches for handling non-public properties. Updated 2022-02-22 to explain the new JsonInclude attribute added in .NET 5. Write a custom JSON converter to serialize non-public properties When the built-in … Read more

The JSON value could not be converted to System.DateTime

When you’re using System.Text.Json to deserialize a DateTime value, if the value isn’t in the format it expects, then it’ll throw a JsonException. It expects datetimes to be in the ISO-8601-1:2019 format (for example: 2021-07-12T12:35:34+00:00). For example, the following code is trying to deserialize a DateTime value in an unexpected format: This’ll throw the following … Read more

C# – Async/await with a Func delegate

To make a Func delegate awaitable, you have to make its out parameter a Task, like this: This Func accepts an int parameter and returns a Task. Since it returns a Task, it can be awaited. Notice that this isn’t returning a value. Normally you’d use an Action delegate if you didn’t want to return … Read more

WinForms – How to prompt the user for a file

In a WinForms project, you can prompt the user to select a file by using the OpenFileDialog control: When you call ShowDialog(), it’ll prompt the user to select a file: When the user clicks Open, you’ll be able to get the file path they selected from the OpenFileDialog.FileName property. To use the OpenFileDialog control, drag … Read more

C# – Use FluentAssertions to improve unit tests

FluentAssertions is a library that improves unit tests by providing better failure messages, simplifies assertions in many scenarios, and provides a fluent interface (which improves code readability). In this article, I’ll show a few examples of how FluentAssertions can improve unit tests by comparing it with the built-in assertions (from Microsoft.VisualStudio.TestTools.UnitTesting). Install FluentAssertions Add the … Read more

C# – Parameterized tests in xUnit

Here’s an example of adding a parameterized unit test in xUnit: To parameterize a unit test, you have to do three things: If you’re used to doing parameterized tests with MSUnit, [Theory] is equivalent [DataMethod], and [InlineData] is equivalent to [DataRow]. In the rest of the article, I will show how to add parameterized tests … Read more

C# – Access modifiers

Access modifiers are used to hide class members (methods/properties/fields) from other code. When you define a class/method/property/field, you put an access modifier on it. In C#, there are four main access modifiers: Access modifiers are enforced at compile time. When you try to use a class member that you can’t access, you get the CS0122 … Read more

C# – IDE0060: Remove unused parameter

If you have a method with a parameter, and that parameter is not used in the method, then you’ll get the IDE0060 message telling you to remove the unused parameter. Here’s an example of code that would trigger this message: The encrypt parameter isn’t being used in the Send() method, triggering the IDE0060 message: IDE0060 … Read more

SQL – Select from information_schema.columns

You can query the information_schema.columns system view to get information about all columns in the database. Here’s an example: Here’s the first few rows this returns: TABLE_NAME COLUMN_NAME Movies Id Movies Title Movies Year In this article, I’ll show more examples of querying information_schema.columns. Get columns filtered by name Let’s say you want to find … Read more

Collection was modified; enumeration operation may not execute

If you try to add/remove items from a collection while it’s being looped over in a foreach loop (enumerated), then you’ll get the following exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.at System.Collections.Generic.List`1.Enumerator.MoveNext() This error can happen in two scenarios: The solution to this problem depends on which scenario you’re in. In this … Read more

Case sensitivity in SQL Server

In SQL Server, the collation property controls case sensitivity. Case sensitivity affects sorting and queries (even the column names must match exactly if you’re using a case-sensitive collation at the database-level). The default collation when you create a database in SQL Server is SQL_Latin1_General_CP1_CI_AS. The CI stands for case-insensitive, which means SQL Server databases are … Read more

System.Data.SqlClient is missing in a .NET Core project

When you create a new project in .NET, and you try to use a class from ADO.NET, such as SqlConnection or SqlDataReader, you’ll get missing reference errors. For example, your code might look something like this, and it’ll have red-squiggly lines under SqlConnection: In the past, you’d simply add a reference to System.Data.SqlClient, like this: … Read more

ASP.NET Core – How to unit test an ApiController

The key to unit testing an ApiController class is to mock out all of its dependencies, including the controller’s HttpContext property, like this: If the controller method you’re testing uses anything from the HttpContext, then you’ll want to swap in your own value. Otherwise HttpContext will be null and you’ll get a NullReferenceException. Fortunately Microsoft … Read more

C# – Try/finally with no catch block

Try/finally blocks are useful for when you are required to do something at the end of a method no matter what. The finally block always executes, even if there’s an exception (there is one case where this isn’t true, which I’ll explain in the Unhandled exception section below). There are a few common scenarios where … Read more

C# – Parsing a DateTime from a string

You can convert a string to a DateTime (parse) with one of these methods: I’ll show examples of using both methods for parsing various DateTime formats. Using DateTime.Parse() DateTime.Parse() can handle parsing a wide variety of culture-specific standard DateTime formats and the ISO-8601 format (which is the default date format for JSON serialization). By default, … Read more

CA1806: Do not ignore method results

The CA1806 warning is triggered whenever you call a method and ignore the return value. I’ll show examples of a few of the scenarios where you might run into this. CA1806 – When you call a string method and don’t use the new string Strings are immutable. Once you create a string, you can’t change … Read more

Postman – Save a response value into a variable

When sending a request with Postman, we can parse a value from the response and save it into a global variable or environment variable. This is useful when we need to use a value obtained from one request in other requests; for example, when we obtain an access token that needs to be included as … Read more

NLog – Log to console

There are two configuration options for logging to the console when you’re using NLog: In this article, I’ll show how to configure these two targets using nlog.config. At the end, I’ll show an example of configuring NLog programmatically. Console target Add a Console target and a rule that writes to that target in nlog.config, like … Read more