ASP.NET – Async SSE endpoint

Server-Sent Events (SSE) allow a client to subscribe to messages on a server. The server pushes new messages to the client as they happen. This is an alternative to the client polling the server for new messages. In this article I’ll show how to implement the messaging system shown in the diagram below. This uses … Read more

C# – Async Main

The Async Main feature was added in C# 7.1 and works with all overloads of the Main() method. To make the Main() method async, add async Task to the method signature, like this: This is syntax sugar that compiles down to calling GetAwaiter().GetResult() on whatever you’re awaiting. In other words, it’s equivalent to doing the … Read more

C# – How to consume an SSE endpoint with HttpClient

Server-Sent Events (SSE) allow a client to subscribe to messages from the server. It creates a one-way stream from the server to the client. When the server has new messages for the client, it writes them to the stream. This is an alternative to the client polling the server for updates. Use the following to … Read more

Error: Cannot convert null to type parameter ‘T’

Problem You’re trying to return null from a generic method and you’re getting the following compiler error: Cannot convert null to type parameter ‘T’ because it could be a non-nullable value type. Consider using ‘default(T)’ instead You can’t return null because the compiler doesn’t know if T is nullable. Solution There are a few options … Read more

C# – Can’t pass decimal parameter in DataTestMethod

I have a parameterized unit test with decimal parameters. When I run the test, I get the following exception: System.ArgumentException: Object of type ‘System.Double’ cannot be converted to type ‘System.Decimal’. Solution Change the parameters to doubles and convert them to decimals inside the test method. Why is it throwing an exception? You have to pass … Read more

C# – Parameterized tests with MSTest v2

There are two steps for parameterizing a unit test when using the MSTest v2 framework (built-in default): Here’s an example: Parameterized unit tests are useful because you only need one test method for multiple test cases instead of one test method per test case. It’s a simple way to declutter your unit tests and make … Read more

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 check if a type has a default constructor

A default constructor is a constructor that doesn’t have parameters. Therefore, to check if a type has a default constructor, you can use reflection to loop through the constructors and see if there are any with no parameters, like this: In this article I’ll show an example of loading types that implement a specific interface … 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

PowerShell – Saving SQL query results to a CSV file

With PowerShell, you can execute a SQL query with Invoke-Sqlcmd. If you want to save the query results to a CSV file, you can use Export-Csv. Here’s an example: If Invoke-SqlCmd is missing, install the SqlServer module If it’s complaining about not having Invoke-SqlCmd available, you will need to install the SQL Server PowerShell module. … 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

Categories C#

Moq – Return different values with SetupSequence

When you’re mocking a method that’s called multiple times, you may want to change the behavior of the method each time it’s called. The way you do this with Moq is by using SetupSequence(), like this: Note: You can also make it throw an exception in the sequence. Example of code I want to test … Read more

C# – How to sort by multiple fields (Linq)

Use the OrderBy() and ThenBy() Linq methods when you want to sort a list by multiple fields, like this: Ascending vs Descending order By default, OrderBy() and ThenBy() sort in ascending order. If you want to sort by descending order, use the Descending version of each method. For example, if I want to sort NFL … 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 unit test async methods

Let’s say you have the following async method you want to test: Here’s how to unit test this: This is awaiting the method you’re testing. To await it, you must make the unit test method return async Task. This example is a bit simplistic. In the real world when you are working with async methods, … Read more

SQL – Filtering GROUP BY with HAVING and WHERE

There are two ways to filter GROUP BY results: In other words, WHERE controls which rows will be considered for grouping, GROUP BY groups the filtered rows, and then HAVING filters the groups. I’ll show examples below. Example – Using WHERE with GROUP BY Let’s say you have the following table and you want to … Read more

C# – Get all classes that implement interface

You can use reflection to get all classes in the current assembly that implement a specific interface. Here’s how: To create instances of these types, loop through them and use Activator.CreateInstance(), like so: Example – Auto-wire a command routing table Let’s say we want to build a command routing table. We have commands and want … 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

WinForms: How to handle DataGridViewButtonColumn click event

Here’s how to handle the DataGridViewButtonColumn button click event: In this article I’ll show a step-by-step example of how to handle the button click. Example DataGridView with a button column When I click the button I want it to say Hi to the person. 1 – Set the DataSource to BindingList<Person> 2 – Add ClickHandler(Person … 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