C# – How to use Polly to do retries

Whenever you’re dealing with code that can run into transient errors, it’s a good idea to implement retries. Transient errors, by definition, are temporary and subsequent attempts should succeed. When you retry with a delay, it means you think the the transient error will go away by itself after a short period of time. When … Read more

How to do retries in EF Core

EF Core has built-in retry functionality. To use it, you can call options.EnableRetryOnFailure(), like this: The retry logic is contained in execution strategy classes. The above code is using the default execution strategy class (SqlServerRetryingExecutionStrategy). When you execute a query, it goes through the execution strategy class. It executes the query and checks for transient … Read more

PowerShell – How to use Select-String to search files for a pattern

In this article, I’ll show how to use the Select-String PowerShell command to search files in a directory with a regex pattern. I’ll first explain the basic syntax, and then I’ll show a few common search scenarios. Pattern, path, and alias Select-String has two main parameters: Note: The command name is not case-sensitive. You can … Read more

C# – Using the is operator

You can use the is operator to check if an object is a certain type. Here’s an example: You can also use the is operator to declare a variable of the target type, like this: Note: The employee object is only available in the if block, but IntelliSense shows it out of its scope. If … Read more

C# – Pad a 2D array on all sides

Padding a 2D array on all sides means adding new rows on the top and bottom, new columns on the left and right, and then copying the original elements to the center of the padded array. It looks like this: There are two approaches for copying the elements. You can either copy individual items in … Read more

C# – How to supply IOptions

The options pattern is an indirect way to dependency inject settings into a registered service. If you’re using code that implements the options pattern, then you’re required to supply an IOptions<T> object. For example, let’s say you’re using the MovieService class and it has the following constructor: This requires you to supply the IOptions<MovieSettings> parameter. … Read more

Calling BuildServiceProvider from application code results in an additional copy of singleton services being created

When you try to call BuildServiceProvider(), you get the following warning: Warning ASP0000 Calling ‘BuildServiceProvider’ from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to ‘Configure’. There are two scenarios where you may be calling BuildServiceProvider() because you want to resolve services … Read more

C# – Dependency inject BackgroundService into controllers

Let’s say you have a hosted BackgroundService called DatabaseLoggerService. It runs in the background and logs messages to the database. It has the following definition: You want your controllers to use this for logging. In other words, you want them to depend on ILoggerService, not the concrete DatabaseLoggerService class. First, constructor inject ILoggerService into your … Read more

Complex DataBinding accepts as a data source either an IList or an IListSource

If you try to set a list control’s DataSource to a type it can’t handle, then you’ll get the following exception: System.ArgumentException: Complex DataBinding accepts as a data source either an IList or an IListSource. (Parameter ‘value’)at System.Windows.Forms.ListControl.set_DataSource(Object value) Note: This applies to all controls that subclass ListControl, such as ComboBox and ListBox. This is … Read more

How to use NLog in ASP.NET

When you want to use NLog in ASP.NET, the first step is to install and configure NLog. Then you can either use it directly or fully integrate it and ASP.NET. Use NLog directly if you prefer to have static ILogger properties, instead of using dependency injection. The downside of this approach is that you’ll have … Read more

ASP.NET Core – How to unit test your middleware class

There are three requirements for unit testing a middleware class: Here’s an example: This is a simple test that only checks the response status code. By passing in DefaultHttpContext, you have control over the request and response objects. You can set the request to whatever you need, and then verify the response. I’ll show examples … Read more

ASP.NET Core – How to add custom middleware

The ASP.NET Core request pipeline has middleware components (classes or lambdas) for processing requests. There are many built-in middleware components, such as AuthorizationMiddleware and HttpsRedirectionMiddleware. You can create custom middleware. I’ll show how below. 1 – Create middleware class In this example, I’ll show how to create a middleware class which is based on the … Read more

ASP.NET Core – Configure JSON serializer options

ASP.NET Core uses System.Text.Json as the default JSON serializer. To configure the JSON serializer options, call AddJsonOptions() in the initialization code: Calling AddJsonOptions() gives you access to the global JsonSerializerOptions object. This is used for all requests / responses. You can configure the options and add converters (including your own custom JSON converters). ASP.NET Core’s … Read more

How to use Newtonsoft in ASP.NET Core

By default, ASP.NET Core uses System.Text.Json for JSON serialization. If you want to use Newtonsoft instead: Note: Before .NET 6, do this in Startup.ConfigureServices(). Install the right package Microsoft packaged up Microsoft.AspNetCore.Mvc.NewtonsoftJson based on the framework version, so you can’t just install the latest package. You have to find the latest one for the framework … Read more

C# – Newtonsoft extension methods for HttpClient

System.Net.Http.Json provides extension methods that simplify getting and sending JSON with HttpClient. Internally, it uses System.Text.Json for serialization. What if you want to use Newtonsoft instead of System.Text.Json? You can use the following extension methods for that: These are modeled off of the extension methods in System.Net.Http.Json. HttpClient is used to fetch the JSON content … Read more

C# – Get and send JSON with HttpClient

The simplest way to get and send JSON with HttpClient is to use the GetFromJsonAsync() and PostAsJsonAsync() extension methods (in System.Net.Http.Json), like this: Note: You have to install the System.Net.Http.Json package if you’re using a framework version before .NET 5. These extension methods use System.Text.Json for serialization. They simplify things by abstracting away the common … Read more