C# – How to make concurrent requests with HttpClient

The HttpClient class was designed to be used concurrently. It’s thread-safe and can handle multiple requests. You can fire off multiple requests from the same thread and await all of the responses, or fire off requests from multiple threads. No matter what the scenario, HttpClient was built to handle concurrent requests. To use HttpClient effectively … Read more

C# – How to use FileSystemWatcher

You can use the FileSystemWatcher class to detect file system changes, such as when a file is created, deleted, modified, or renamed. When a change happens, it raises an event that you can handle. This is an event-based alternative to polling for file changes. In this article, I’ll show how to use FileSystemWatcher to detect … Read more

C# – How to test that your code can handle another culture’s date format

Let’s say you have code that converts a string to a DateTime with DateTime.Parse(): By default, DateTime.Parse() uses CultureInfo.CurrentCulture to figure out the date format. The current culture ultimately comes from your OS settings. So when you run this code on a computer that is using the en-US locale, the current culture will automatically default … Read more

.NET – Signing code with a certificate

You’re given .PFX code signing certificate and told to sign your code. What does this mean, and how do you do it? What is code signing? Signing code means creating a digital signature on an executable file by using a code signing certificate. When your code is executed, your organization’s security software will check that … Read more

C# – Use Convert.ChangeType to convert string to any type

You can use Convert.ChangeType() to convert from a string to any type, like this: Normally you’d call the specific type converter method, such as when you’re converting a string to an int. However, sometimes it makes sense to use the generalized type converter method – Convert.ChangeType() – instead of hardcoding the calls to specific type … Read more

C# – How to implement the plugin pattern

In this article, I’ll explain how to implement the plugin pattern. This approach uses a generic plugin loader that solves many real world problems when loading plugins in .NET. Besides being generic, this plugin loader also solves the following real world problems when working with plugins: If you find that this generic plugin loader doesn’t … Read more

Error: Sequence contains no elements

Problem When you call .First() on an empty IEnumerable, you get the following exception: System.InvalidOperationException: Sequence contains no elements Solution Option 1 – Use .FirstOrDefault() instead of .First() When the IEnumerable is empty, .FirstOrDefault() returns the default value for the type. For reference types this returns null. For value types this returns 0 or that … Read more

C# – How to switch on type

Sometimes you may find it necessary to have conditional logic based on an object’s type. The simplest way to do this is to switch on the type, like this: This feature is called type pattern matching. Before this feature was added (in C# 7), you’d have to use a bunch of if-else’s and check the … Read more

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

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