C# – Use SemaphoreSlim for throttling threads

When you have multiple threads trying to do work at the same time, and you want to throttle how many of them are actually executing (such as when you’re sending concurrent requests with HttpClient), you can use SemaphoreSlim. Example – a busy grocery store Grocery stores have a limited number of checkout lanes open. Let’s … Read more

C# – How to use IN with Dapper

Let’s say you have a SQL Query that uses IN and you want to execute it using Dapper. Your query looks something like this: Here’s how you’d execute that with Dapper: Then you’d call it like this: There are two key things to notice about this: Exclude the parentheses In a normal SQL Query you … Read more

C# – Pass in a Func to override behavior

If I want to change the behavior of a method from the outside, I can pass in a function pointer. This approach exists in every language, and is one way to implement the Strategy Pattern. In C#, function pointers are referred to as delegates, and the two most common ones are Action and Func. The … Read more

C# – Deserialize JSON to dynamic object

If you want to deserialize JSON without having to create a bunch of classes, you can either deserialize to a dictionary or deserialize to a dynamic object with 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 … Read more

C# – Case insensitive dictionary

Dictionaries with string keys are case sensitive by default. If you want a case-insensitive dictionary, use the Dictionary constructor that takes a string comparison option and pass in StringComparer.InvariantCultureIgnoreCase, like this: Note: There are other case-insensitive options you can pick from, such as OrdinalIgnoreCase. Example I have a table that maps users to devices. The … Read more

KeyNotFoundException: The given key was not present in the dictionary

Problem The following exception is thrown when you try to get a value from a dictionary using a key that doesn’t exist in the dictionary: KeyNotFoundException: ‘The given key was not present in the dictionary.’ Consider the following the example of initializing a dictionary with a few key/value pairs, and then trying to access non-existent … 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

Refactoring the Switch Statement code smell

The Switch Statement code smell refers to using switch statements with a type code to get different behavior or data instead of using subclasses and polymorphism. In general, it looks like this: This switch(typeCode) structure is typically spread throughout many methods. This makes the code difficult to extend, and violates the Open-Closed Principle. This principle … 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

Refactoring the Long Method code smell

In this article I’ll be walking through an example of how to refactor the Long Method code smell. Code Smell: Long Method Definition: A method has too many lines of code, making it hard to understand. Solution: Long Method code smell example Here’s an example of the Long Method code smell (source: GildedRose Refactoring Kata). … Read more

Set up a Spring Boot app with Amazon SQS

In this article we’re going to create a Spring Boot project using Spring Initializr that will allow us to interact with Amazon SQS queues. Amazon SQS and Spring Series This article is part of a series: Create a new Spring Boot project using Spring Initializr Dependencies Open the pom.xml file to review the dependencies. The … Read more