C# – Deserialize JSON to dynamic object

If you want to deserialize JSON without having to create a bunch of classes, your best option is to use Newtonsoft.Json. Here’s an example. Let’s say you want to deserialize the following JSON: To deserialize this to a dynamic object with Newtonsoft, use JsonConvert.DeserializeObject<dynamic>: This outputs the following: Deserialize to ExpandoObject in older versions of … Read more

C# – Case insensitive dictionary

If you want a case insensitive dictionary, use: In the Dictionary constructor you can specify how keys are compared. For string keys, the default is a case sensitive comparison. To make it case insensitive, you can pass in StringComparer.InvariantCultureIgnoreCase. Example I have a table that maps users to devices. The user-to-device mapping gets cached in … Read more

How to modify app.config at runtime

When you try to modify the app.config at runtime, if you don’t do it right, you’ll run into a few problems: System.Configuration.ConfigurationErrorsException: The configuration is read only. This article will show you how to update the app.config the right way to avoid these problems. This shows three different scenarios: inserting a new connection string, modifying … Read more

How to use relative paths in a Windows Service

Relative paths are resolved relative to the current working directory. When you’re running a Windows Service, the default working directory is C:\Windows\system32 or C:\Windows\SysWOW64. Therefore relative paths are resolved from these system folders, which can lead to problems when read/writing files. Here are the most common problems you’ll run into: System.IO.DirectoryNotFoundException: Could not find a … Read more

C# – Fixing the Sync over Async antipattern

The Sync over Async antipattern is when you’re using a blocking wait on an async method, instead of awaiting the results asynchronously. This wastes the thread, causes unresponsiveness (if called from the UI), and exposes you to potential deadlocks. There are two causes: In this article I’ll show an example of the Sync over Async … Read more

SqlTypeException: SqlDateTime overflow

Problem I am executing a SQL query and trying to set a datetime column to DateTime.MinValue. I’m getting the following exception: System.Data.SqlTypes.SqlTypeException: ‘SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.’ The problem is that DateTime.MinValue is 1/1/0001 12:00:00 AM and the SQL Server DateTime minimum value is 1/1/1753 12:00 AM. Solution … Read more

Primitive Obsession code smell

The primitive obsession code smell means you’re using primitive types (ex: string, int) excessively instead of encapsulating them in objects. This leads to sloppy code that’s error prone, such as when you have very long parameter lists full of primitives. I’ll show an example of this problem and how to fix it. Here’s a simple … Read more

C# – Log every method call

I want to log method calls, including their parameter names and values, and what called the method. I want to minimize the amount of coding involved. For example: What options are available? In this article I’ll explain how to use the simple built-in approach. 1 – Create LogMethodCall() utility method The System.Diagnostics.StackFrame class gives us … Read more

Class Diagrams missing in Visual Studio

Problem The Class Diagram item is missing in Visual Studio. Note: I ran into problem starting in VS2019. Solution For some reason this is not installed by default in Visual Studio, so we simply need to install it. 1. In Visual Studio click Tools > Get Tools and Features… 2. Close Visual Studio. 3. In … Read more

Refactoring the Large Class code smell

The Large Class code smells refers to a class that has too many responsibilities. It’s doing too much. Ideally a class should only have one responsibility (Single Responsibility Principle). Code Smell: Large Class Definition: A class has too many responsibilities. Solution: Large Class code smell example Here’s an example of the Large Class code smell … Read more

The referenced component could not be found

Problem When I open a C# project in Visual Studio, none of the references are loading. In the error list it says “The referenced component could not be found” for several references. Here’s a snippet showing just a few of the reference errors: The referenced component ‘System’ could not be found.The referenced component ‘Microsoft.CSharp’ could … Read more

Auto-increment build numbers in Visual Studio

You need to auto-increment your build numbers in order to easily tell which code you’re working with. In this article I’ll explain how to auto-increment your build numbers in Visual Studio. I’ll be using text templating to generate the Assembly Version. 1 – Choose a versioning scheme I’m going to be using the version scheme: … Read more

How to mock static methods

The need to mock static methods in order to add a unit test is a very common problem. It’s often the case that these static methods are in third-party libraries. There are many utility libraries that are completely made up of static methods. While this makes them very easy to use, it makes them really … Read more

C# – Example of using BlockingCollection

The BlockingCollection class is a blocking concurrent queue. It provides an implementation of the producer-consumer pattern. There are two parts to this pattern: BlockingCollection is thread-safe, which means it’s designed to be used by many threads at once. Here’s an example of using BlockingCollection with one consumer and two producers: Note: BlockingCollection.IsCompleted means the queue … Read more

‘CREATE/ALTER’ must be the first statement in a query batch

Problem When you’re executing a CREATE/ALTER statement to create a procedure/view/function/trigger, you get one of the following errors: ‘CREATE/ALTER PROCEDURE’ must be the first statement in a query batch ‘CREATE VIEW’ must be the first statement in a query batch. ‘CREATE FUNCTION’ must be the first statement in a query batch. ‘CREATE TRIGGER’ must be … Read more

Error: chromedriver.exe file does not exist in the current directory

Problem I’m trying to use Selenium with the ChromeDriver and I’m running into the following exception: Unhandled Exception: OpenQA.Selenium.DriverServiceNotFoundException: The chromedriver.exe file does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at http://chromedriver.storage.googleapis.com/index.html Solution The simplest solution is to install the Selenium.Chrome.WebDriver package: … Read more

C# – Example of using events

Events are an implementation of the observer pattern and consists of two parts: There are three simple steps to using events, which I’ll show below. 1 – Add an event field The first step is to add an event field to a class with the event keyword and a delegate type (such as the generic … Read more