C# – How to unit test a model validation attribute

You can unit test a validation attribute by creating an instance of it and then testing the two methods: In this article, I’ll show examples of unit testing these methods in a custom validation attribute and in a built-in validation attribute (i.e. [Range]). Unit testing a custom validation attribute Consider the following custom validation attribute … Read more

C# – Round up to the nearest 30 minutes

Here’s how to round a DateTime up to the nearest 30 minutes: When the time is 3:38 pm, it rounds to 4:00 pm. When it’s 5:03 pm, it rounds to 5:30 pm. When it’s exactly 2:00 pm, it’ll round up to 2:30 pm (note: see the What if you’re at the start of a 30 … Read more

NLog – Log to console

There are two configuration options for logging to the console when you’re using NLog: 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 programmatically. Console target Add a Console target and a rule that writes to that target in nlog.config, like … Read more

C# – SQL Bulk Insert with SqlBulkCopy

When you need to insert multiple rows into the database, consider doing a Bulk Insert instead of inserting one row at a time. Bulk Insertions are up to 20x faster than executing SQL Insert repeatedly. The simplest way to do a SQL Bulk Insert is by using the built-in SqlBulkCopy (from System.Data.SqlClient) with a DataTable. … Read more