NLog – Archive by file size

To archive by file size when you’re using NLog, you can configure nlog.config like this: You specify archiveAboveSize in bytes. The above configuration is specifying ~1 MB. When your log file hits the specified size, NLog will “archive” the file, which really just means it will rename the log file and start a new log … Read more

CA1062: Validate parameter is non-null before using it

When you have a public method that isn’t null checking its parameters, then you’ll get the CA1062 code analysis warning. This is part of the Nullable Reference Types feature. For example, the following code isn’t null checking the movieRepository parameter: This results in the CA1062 code analysis warning: CA1062 In externally visible method ‘void StreamingService.LogMovies(MovieRepository … Read more

How to enable the built-in .NET Analyzers

Previously you had to install and enable .NET Analyzers if you wanted to use it. Now, when you create a new project, it’s already installed and enabled by default (but you may want to change its settings). There are two main scenarios: If .NET Analyzers is already installed When you create a new project targeting … Read more

C# – Using ClassInitialize in a test class

You can use the ClassInitialize attribute on a method when you want to initialize something for all unit tests in a test class. This initialization method only runs once and is ran before any of the unit tests. Here’s an example of how to add ClassInitialize: Note: ClassCleanup is the opposite of ClassInitialize. It runs … Read more

Install and configure a Windows Service from the command line

In this article I’ll show how to install and configure a Windows Service, query its status and properties, and then how to uninstall it. I’ll be using the command line utilities installutil.exe and sc.exe to install and configure the service. Add a service installer class to your Windows Service project In order to use installutil.exe … Read more

C# – DataGridView index out of range exception

Problem When you’re using WinForms and click a DataGridView column header, you get an exception like this: Index was out of range. Must be non-negative and less than the size of the collection. This problem is caused by the column header “row” triggering a click event (such as CellContentClick) with event args containing RowIndex of … Read more

HackerRank – Two Strings solution

In this article, I’ll explain how to solve the Two Strings algorithm problem on HackerRank. Problem statement: Given two strings, determine if they have a substring in common. The strings can have up to 100k characters. Example: Given “hello world” and “world”, do they have a substring in common? Yes, they many substrings in common. … Read more

C# – SQL Bulk Insert with SqlBulkCopy

When you need to insert multiple rows into the database, consider doing a Bulk Insert instead of inserting one row at a time. Bulk Insertions are up to 20x faster than executing SQL Insert repeatedly. The simplest way to do a SQL Bulk Insert is by using the built-in SqlBulkCopy (from System.Data.SqlClient) with a DataTable. … Read more

Refactoring the Nested Conditionals code smell

Nested conditionals are a code smell because they make the code harder to understand. They tend to grow more and more complicated over time because developers will keep adding conditions and more levels of nesting. The deeper the nesting, the more time it’ll eventually take to refactor it. Code Smell: Nested conditionals.Definition: A conditional block … Read more

C# – Waiting for user input in a Console App

The following code shows how to wait for user input in a Console App: When the user types something in and presses the Enter key, Console.ReadLine() will return what they typed. Console.ReadLine() vs Console.ReadKey() Console.ReadLine() waits for the user to press Enter, and then returns everything they typed in. Console.ReadKey() returns individual key presses. It … Read more

C# – Create a custom JsonConverter for System.Text.Json

Most of the time System.Text.Json will get you want you want. You can pass in options to control JSON serialization and deserialization to a certain extent. But sometimes you’ll run into scenarios where you need to customize how it handles a specific type. This is where JsonConverter comes in. You can customize serialization / deserialization … Read more

JsonException: A possible object cycle was detected

When you use System.Text.Json.JsonSerializer to serialize an object that has a cycle, you get the following exception: System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 0. In .NET 6+, you can … Read more

C# – How to handle nulls with SqlDataReader

SqlDataReader returns a DBNull object when a column is null. This isn’t the same as a C# null. You can check if the column is null by comparing it with DBNull.Value or by using SqlDataReader.IsDBNull(). Here’s an example showing these two ways of checking if a column is null: After checking if the column is … Read more

C# – Use StringAssert when testing a string for substrings

When you’re testing if two strings are equal, you can simply use Assert.AreEqual(). When you’re testing if a string contains a substring or a pattern, typically developers use Assert.IsTrue() with a substring method or regex. You should use StringAssert instead, because it gives better failure messages. Note: StringAssert is nice because it’s a built-in class. … Read more

C# – Using XmlSerializer to serialize

Here’s how to serialize an object into XML using XmlSerializer: You must add the [Serializable] attribute to the class you want to serialize: Here’s an example of creating an Author object and feeding it to the serializer: This outputs the following XML: This example showed how to use XmlSerializer with all the default settings. In … Read more

C# – Serialize a tuple to JSON

When you serialize a tuple to JSON, it uses the the underlying ValueTuple’s field names – Item1 and Item2. It doesn’t matter if you’re using a named tuple, it won’t use the names you specified in the tuple declaration. This behavior is the same with Newtonsoft and System.Text.Json. Here’s an example of serializing a named … Read more