Unit Testing C# Async Methods

This time I have a C# async method that should be tested. As you remember, async method must return Task or Task<>.  You can declare an async void method, but this should be used only for event handlers because you have no control on method execution and, the most important, its failure. Beside that, async void method is hard to test.

I have a simple async method that returns Task<int> instead of int in synchronous method (look at my previous post Unit Testing C# Synchronous Methods).

We must be happy that modern unit test frameworks allow to write async unit test where an async method is called asynchronously.

1. Check successful result

The async method being tested is called via await operator. This makes the code being executed in true asynchronous mode.

2.1. Check failure with ThrowsAsync<>

Unit test is awaiting for result from Assert.ThrowsAsync, that is awaiting for result from the method being tested. If you delete the inner async/await, the method would be executed in synchronous mode. If you omit the first outer await, the unit test method might finish before the code in NumberAsync would fail. So you will get wrong results!

2.2. Check failure with Record.ExceptionAsync

ASP.NET Identity. Part 2 – Customizing Entities

ASP.NET Identity gives a class ApplicationUser for storing data about users. It has a lot of properties defined in base class IdentityUser, such as Id, UserName, Email, PhoneNumber, etc. But when you need to add some extra properties, it becomes more complicated.

Entity Framework creates a database only once at first use. It does not recreate, nor modify it. We should use EF migrations to add new fields. Also it gives the possibility to change table names.

1. Add new properties in file Models\IdentityModels.cs

2. Open Package Manager Console and run command

EF will create folder Migrations and a couple of files: Configuration.cs and <timestamp>_InitialCreate.cs with code to create a default database structure.
3. Create new migration and give it a name

Visual Studio will open a file with two method to add and drop columns defined in step 1.
4. Apply EF migration to database.

Now I have the following database structure:

5. I want to enter first and last names during the registration process. So I’ll add two properties to class RegisterViewModel in file Models\AccountViewModels.cs

6. Add code to Views\Account\Register.cshtml file to display these them.

7. Change Register method in Account controller (file Controllers\AccountController.cs) to store them.

8. Also I want to display user’s first name on the top bar of the web application instead of his/her email. To do this we need to modify file Views\Shared\_LoginPartial.cshtml to get ApplicationUser via current user’s Id with the help of Owin context, then to show property FirstName. The final code looks like this:

ASP.NET Identity. Part 1 – Changing Default Database

When you create MVC project in Visual Studio 2017, you can use individual user accounts authentication that is shipped with MVC template. This implementation uses Entity Framework. By default, EF creates a database in SQL Server LocalDB with a name like aspnet-WebApp-<timestamp>.

To change the connection to database:
1. Open Web.config file
2. Find section <connectionStrings>
3. Modify the attribute connectionString in element with name DefaultConnection. Element will look like the following:

<add name="DefaultConnection" connectionString="Data Source=(local);Integrated Security=SSPI;Initial Catalog=AspNetIdentityDB;" providerName="System.Data.SqlClient"/>

If you dislike the name DefaultConnection, you should change it in Web.config file and in the constructor of ApplicationDbContext class (file Models\IdentityModels.cs).

Creating GitHub Project In Visual Studio 2017

My goal is to create a new solution and place it in GitHub. This can be done in few steps:

1. Create a GitHub account.
2. Install a GitHub extension for Visual Studio. I’ve downloaded it from https://visualstudio.github.com/
3. Start Visual Studio, open Team Explorer and connect to GitHub.

4. Create a new GitHub repository.

Click link, and enter data in the next form.

5. Switch back to Team Explorer. Click Create a new project or solution link.

6. Choose project type, give it a name. Step forward on wizard steps.

After that you will have the following structure in Visual Studio

and in a disk folder

Now you can write code, commit changes and push them to GitHub.

Finding All Controls In ASP.NET Page

When you work with ASP.NET page, you might need to enumerate all controls of a specific type, i.e. text boxes, dropdown list, or table cells. All these controls derive from System.Web.UI.Control class.
To find all controls you need to iterate them recursively from the top one, i.e. Page, or any element that is located on a page (panel, table, etc.). One of the solution is to write an extension method like this.

Also you can use a generic version.

When I need to find all table cells with a specific ID, I can write the following LINQ query:

In C# 6.0 and later you can use Elvis operator in Where clause.

Converting List To DataTable

In my previous post SqlBulkCopy I wrote about how to load data from .NET code into SQL Server database using efficient BULK INSERT command. This class needs a DataTable or IDataReader instance as a source. I’ve collected a couple of examples how to convert List to DataTable.

1. Variation of Marc Gravell solution.
Source: https://stackoverflow.com/a/14548027

2. Solution created by Jennifer Hubbard, Bill Wagner, etc.
Source: How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRow


SQL Server have great commands like BULK INSERT or OPENROWSET(BULK…) to insert a huge amount of data into a database. .NET Framework has a class SqlBulkCopy that provides similar capabilities in C#. Full documentation is available on MSDN article SqlBulkCopy Class. But SqlBulkCopy has some restrictions on input data. It can read from:

  • DataRow[] array;
  • DataTable;
  • IDataReader.

A simple example of usage can be as follows:

SQL Server Profiler shows that the correct command was really executed.

In order to use SqlBulkCopy class elegantly, it would better to have a method or extension to convert a generic list to DataTable or IDataReader. But it’s a topic for my next post.

Offline Installer For Visual Studio 2017

Microsoft does not offer an ISO image for Visual Studio 2017, we need to make it ourselves by running web installer with some command-line arguments. Here are the links to official pages:

Create an offline installer for Visual Studio 2017

Visual Studio 2017 workload and component IDs

Example to grab community edition:

Layout parameter is mandatory, it points to a folder where the downloaded files would be saved.
Workload_id_list is a list of component IDs, separated by space. If you skip it, all components will be downloaded.

[UPDATE 2017-06-21]
Workloads contain only the recommended components. As mentioned by geoyar, you need to include optional components manually.

Component ID Description
Visual Studio core editor (included with Visual Studio Community 2017) Microsoft.VisualStudio.Workload.CoreEditor The Visual Studio core shell experience, including syntax-aware code editing, source code control and work item management.
Azure development Microsoft.VisualStudio.Workload.Azure Azure SDK, tools, and projects for developing cloud apps and creating resources.
Data storage and processing Microsoft.VisualStudio.Workload.Data Connect, develop and test data solutions using SQL Server, Azure Data Lake, Hadoop or Azure ML.
.NET desktop development Microsoft.VisualStudio.Workload.ManagedDesktop Build WPF, Windows Forms and console applications using the .NET Framework.
Game development with Unity Microsoft.VisualStudio.Workload.ManagedGame Create 2D and 3D games with Unity, a powerful cross-platform development environment.
Linux development with C++ Microsoft.VisualStudio.Workload.NativeCrossPlat Create and debug applications running in a Linux environment.
Desktop development with C++ Microsoft.VisualStudio.Workload.NativeDesktop Build classic Windows-based applications using the power of the Visual C++ toolset, ATL, and optional features like MFC and C++/CLI.
Game development with C++ Microsoft.VisualStudio.Workload.NativeGame Use the full power of C++ to build professional games powered by DirectX, Unreal, or Cocos2d.
Mobile development with C++ Microsoft.VisualStudio.Workload.NativeMobile Build cross-platform applications for iOS, Android or Windows using C++.
.NET Core cross-platform development Microsoft.VisualStudio.Workload.NetCoreTools Build cross-platform applications using .NET Core, ASP.NET Core, HTML, JavaScript, and CSS
Mobile development with .NET Microsoft.VisualStudio.Workload.NetCrossPlat Build cross-platform applications for iOS, Android or Windows using Xamarin.
ASP.NET and web development Microsoft.VisualStudio.Workload.NetWeb Build web applications using ASP.NET, ASP.NET Core, HTML, JavaScript, and CSS.
Node.js development Microsoft.VisualStudio.Workload.Node Build scalable network applications using Node.js, an asynchronous event-driven JavaScript runtime.
Office/SharePoint development Microsoft.VisualStudio.Workload.Office Create Office and SharePoint add-ins, SharePoint solutions, and VSTO add-ins using C#, VB, and JavaScript.
Universal Windows Platform development Microsoft.VisualStudio.Workload.Universal Create applications for the Universal Windows Platform with C#, VB, JavaScript, or optionally C++.
Visual Studio extension development Microsoft.VisualStudio.Workload.VisualStudioExtension Create add-ons and extensions for Visual Studio, including new commands, code analyzers and tool windows.
Mobile development with JavaScript Microsoft.VisualStudio.Workload.WebCrossPlat Build Android, iOS and UWP apps using Tools for Apache Cordova.
Unaffiliated components Component.GitHub.VisualStudio GitHub extension for Visual Studio
Unaffiliated components Microsoft.Component.Blend.SDK.WPF Blend for Visual Studio SDK for .NET
Unaffiliated components Microsoft.Component.HelpViewer Help Viewer
Unaffiliated components Microsoft.Net.Component.3.5.DeveloperTools .NET Framework 3.5 development tools
Unaffiliated components Microsoft.VisualStudio.Component.DependencyValidation.Community Dependency Validation
Unaffiliated components Microsoft.VisualStudio.Component.LinqToSql LINQ to SQL tools
Unaffiliated components Microsoft.VisualStudio.Component.TestTools.Core Testing tools core features
Unaffiliated components Microsoft.VisualStudio.Component.TypeScript.2.0 TypeScript 2.0 SDK
vs_community__1238641179.1486458197.exe –layout C:\VS2017 –lang en-US –add Microsoft.VisualStudio.Workload.CoreEditor Microsoft.VisualStudio.Workload.Azure Microsoft.VisualStudio.Workload.Data Microsoft.VisualStudio.Workload.ManagedDesktop Microsoft.VisualStudio.Workload.NetCoreTools Microsoft.VisualStudio.Workload.NetWeb Microsoft.VisualStudio.Workload.Node Microsoft.VisualStudio.Workload.Office Microsoft.VisualStudio.Workload.VisualStudioExtension Component.GitHub.VisualStudio Microsoft.Component.Blend.SDK.WPF Microsoft.Component.HelpViewer Microsoft.Net.Component.3.5.DeveloperTools Microsoft.VisualStudio.Component.DependencyValidation.Community Microsoft.VisualStudio.Component.LinqToSql Microsoft.VisualStudio.Component.TestTools.Core Microsoft.VisualStudio.Component.TypeScript.2.0

Useful NLog Targets

NLog has many targets to which it can save log entries. Here are some that I consider quite useful.


I’ve added some parameters to archive log on everyday basis.


NLog will create custom application log MyAppLog.

Visual Studio Debug window

Also NLog allows to save log in a database table, but it needs more efforts and lines of code to setup it. You can read more in the article Database target in NLog project documentation.

Reloading Configuration In NLog

When you use NLog in your C# project, its configuration is loaded once on the application startup. Now I want to change the configuration (targets, rules, levels) while application is running. It’s easy – just edit NLog.config file.

That’s not enough. Application should notice that changes and reapply them. This can be triggered by re-reading NLog.config again at some point, by pressing the button or calling Web API, i.e. you or your application should initiate reloading.

As for NLog, reloading is implemented by 3 lines of code.