C# – Circuit breaker with Polly

In an electrical system, a circuit breaker detects electrical problems and opens the circuit, which blocks electricity from flowing. To get electricity flowing again, you have to close the circuit. The same approach can be implemented in software when you’re sending requests to an external service. This is especially important when you’re sending lots of … Read more

C# – Global exception event handlers

There are two global exception event available in all .NET applications: FirstChanceException: When any exception is thrown, this event is fired before anything else. UnhandledException: When there’s an unhandled exception, this event is fired right before the process is terminated. You wire up these event handlers in Main() (before anything else has executed), like this: … Read more

C# – How to unit test code that reads and writes to the console

When you’re unit testing code that uses the console IO methods, you’ll need a way to automate the input and a way to capture the output. There are two ways to do this: Redirect the console IO. Wrap the console IO method calls and mock out the wrapper. In this article, I’ll show how to … Read more

ASP.NET Core – Self-hosted service stub with a command line interface

When you’re integrating with a third-party API, you may want to send requests to a service stub instead of sending them to the real API. The purpose of a service stub is to simulate the third-party API by returning hardcoded responses. This is similar to how mocks are used in unit testing – it helps … Read more

NLog – Log to console

There are two configuration options for logging to the console using NLog: Console target – uses the default text colors. ColoredConsole target – allows you to configure the color of logging messages. In this article, I’ll show how to configure these two targets using nlog.config. At the end, I’ll show an example of configuring NLog … Read more

C# – Parsing commands and arguments in a console app

In a console app there are two ways to get commands: Command line arguments passed into your program via Main(string[] args). User input from Console.ReadLine() (which you then split into a string[]). After getting a command, you have to parse it to figure out what code to execute. Typically commands have the following format: commandName … Read more

C# – Waiting for user input in a Console App

The following code shows how to wait for user input in a Console App: When the user types something in and presses the Enter key, Console.ReadLine() will return what they typed. Console.ReadLine() vs Console.ReadKey() Console.ReadLine() waits for the user to press Enter, and then returns everything they typed in. Console.ReadKey() returns individual key presses. It … Read more