Electron.NET with a Web API

This post will be expanding on the introduction to Electron.NET that I did here to add in a Web API hit to pull some data as well as the UI on the Electron side to use this data. The code before any changes can be found here.

API Creation

To create the API I used the following from the command prompt in the folder where I wanted the new project to be created.

API Data

Now that the API project is created we need to add in the ability to interact with a database with Entity Framework Core. Adding in Entity Framework Core ended up turning into a post of its own when you can read here.

The model and DB Context of the API project match what was in the blog post I linked above, but I am going to include them here. The following is the model.

Next, is the DB Context, which is empty other than the DB Set for the contacts table.

With our model and context setup, we can run the following two commands to add the initial migration and apply the migration to the database.

API Endpoints

The API is just going to handle the basic CRUD (create, read, update, delete) operations for contact. Instead of hand coding the controller we are going to use some code generation provided by Microsoft. First, we need to add the  Microsoft.VisualStudio.Web.CodeGeneration.Design NuGet package to the API project using the following command in a command prompt set to the root of the API project.

Now with the above package installed, we can use the following command to generate a controller with the CRUD operations already implemented.

There is a lot of switches when using  aspnet-codegenerator. The following is a rundown of the ones used above.

  • controller tells the code generator we are creating a controller
  • name defines the name of the resulting controller
  • model is the model class that will be used for the generation
  • dataContext is the DB Context that will be used for the generation
  • outDir is the directory the output will be in relative to the current directory of your command prompt
  • api tells the code generator this controller is for a REST style API and that no views should be generated

With the code generation complete the API should be good to go.

Electron Model

Over in the Electron project, we need a model to match the data the API is returning. This could be the point where a third project is added to allow the API and the Electron app to share common items, but just to keep the example simple I’m just going add a copy of the contact model from the API project to the Electron project.  The following is the full contact model class.

Electron Views

Now that we have a model in our Electron project we need to create the views that go along with it. Start by adding the code generation package like we did above using the following command.

Unfortunately, controller generation needs a DBContext to work which our project doesn’t have, so we have to take the long way about to generate our views and then manually create a controller to go with them. In order to get view generation to work, I had to add references to the Entity Framework Core Tools package using the following command.

In the  csproj file add the following .NET CLI tool reference.

Now the project is ready to use the command prompt to generate the views we will need for our CRUD operations related to our contacts. Use the following commands to create the full range of views needed (Create, Edit, List, Delete, Details).

Again there is a lot of switches when using  aspnet-codegenerator. The following is a rundown of the ones used above.

  • view  tells the code generator we are creating a view
  • the next two items are the name of the view and the name of the view template
  • model is the model class that will be used for the generation
  • useDefaultLayout uses the default layout (surprise!)
  • outDir is the directory the output will be in relative to the current directory of your command prompt

The Index.cshtml generated above comes with links for Edit, Details, and Delete that won’t work as generated. Open the file and make the following changes to pass the key of the contact trying to be opened.

Electron Controller

With the views complete let’s add a  ContactsController.cs to the  Controllers directory. The code for the controller follows, but I’m not going to go into the details. I took a controller from another contact base project and just replaces all the Entity Framework stuff with calls to the API we created above. Please don’t use this as an example of how something like this should be done it is just quick and dirty to show that it can work.

Electron Add Link To Navigation

The final step to add a link to the list of contacts to the navigation bar of the application. Open the  _Layout.cshtml and in the unordered list for the nav bar add the following line.

Wrapping Up

That is all the changes to get the application up and running. If you run the API and then use  dotnet electronize start from a command prompt in the ElectronTest project root all should be good to go.

The completed code can be found here.

Add Entity Framework Core to an Existing ASP.NET Core Project

I had a Web API application that I was using to test something that had no database interaction at all that I needed to add database interaction too. Going through my posts I didn’t find a guide to add Entity Framework Core to an existing project, so that is what this post is going to cover. We will be using SQLite for our database.

Project Creation

The project we are starting with is just a new ASP.NET Core Web API created using the .NET CLI using the following command from a command prompt.

This gives us a new Web API with no database interaction and makes sure we are all on the same page for the rest of the post.

Project File Changes

Open the  csproj file associated with your project. First, we need to add a package reference to the Entity Framework Core tools.

Next, we need to add a reference to the Entity Framework Core Tools for the .NET CLI.

The final change to the project file is only needed if you are using SQLite and it is to keep the database file from showing up in the file list. Add the following and adjust  app.db to match your database name.

App Settings

Now we need to store the database connection string. Again we are using SQLite in this example so if you are trying to use SQL Server (include LocalDb) your connection string will look much different. This is also a place where you need to replace  app.db with the database name you want to use.

Open the  appsettings.json file and add a  ConnectionStrings section similar to the following.

The following is my full settings file after the change just to make sure the context is clear.

Model and Db Context

If you are a long time reader it will be no surprise that the model we will be using is that of a contact. The following is my full contact model.

Now that we have a model we need to add a DBContext.


Now that we have the application settings, model, and context from above open up the  Startup class and in the  ConfigureServices function add the following code to get the  ContactsDbContext into the container.

Initial Migration

Now that the project is all set to go let’s add an initial migration that will get the table for our contacts set up. From a command prompt in the project directory run the following command.

This will add a Migrations directory to the project with the code needed to add the contacts table. If you want to go ahead and apply the migration to the database run the following command.

Since we didn’t have a database yet the above command creates one which will show up in the root of our project with a name that matches our application settings since we are using SQLite.

Wrapping Up

Adding Entity Framework Core to a project is pretty easy, but not something I do a lot, so this will serve as a good reminder of the steps. Hope it helps you out as well.

Create a Desktop Application using ASP.NET Core and Electron.NET

Electron is a cross-platform (Windows, Linux, and Mac) library for building desktop applications using JavaScript, HTML, and CSS. Even if you have never head of Electron I’m sure you have used some of the desktop applications it has been used to build such as Visual Studio Code, Atom, Slack.

Electron.NET provides a wrapper around Electron with an ASP.NET Core MVC application in the mix. Here is the reason why this was done from the creates of the project.

Well… there are lots of different approaches how to get a X-plat desktop app running. We thought it would be nice for .NET devs to use the ASP.NET Core environment and just embed it inside a pretty robust X-plat enviroment called Electron. Porting Electron to .NET is not a goal of this project, at least we don’t have any clue how to do it. We just combine ASP.NET Core & Electron.

Project Creation

Seems only fitting to use VS Code for this post since it is built using the same base library. From the command line create a new ASP.NET Core MVC application using the following command.

Make note that it is important at this time that you use the MVC template when attempting this and not a Razor Page application. This is more of a warning if you are using Visual Studio to do your project creation and not the CLI command above.

Next, we need to reference the ElectronNET.API NuGet package which can be added using the following command.

Then, open the csproj and add a reference for the Electron.NET CLI tool which should match the following.

After that make sure and restore packages using the following command.

Wire-up Election.NET

Open Program.cs and add UseElectron(args) to the WebHost builder chain.

Net, open Startup.cs and add the following line to the bottom of the Configure function. This is what will open the Electron window on startup.

Finally, run the following from the command prompt to get the project ready to run under Electron. This should only need to be done once.

Run the application

At this point, the application is ready to go. The neat part is you can just hit F5 and it will run like any normal ASP.NET Core application (this would change when you get into Electron specific calls I’m sure) or if you run the following command it will run inside of the Electron shell.

Wrapping up

It was surprisingly simple to get a new application up and running, of course so far the app isn’t anything other than a web site hosted in Electron. My plan is to take this base application and create my normal basic contacts application, which will be the next post. From there I may look into layering in some Electron features.

The completed code can be found here.

Two-factor Authentication in ASP.NET Core 2

This post was going to be an update of the SMS using Twilio Rest API in ASP.NET Core post a made a year or so ago, but once I got the example project created I noticed that the default template has removed SMS as an option for two-factor authentication in favor of authenticator auth support.

This post is going to explore the setup of this new two-factor authentication style. In a follow-up post, I may look at adding back support for SMS as the second factor as that seems like a more common scenario albeit a less secure one.

Project Setup

To create a new Razor Pages application using individual authentication I used the following command from a command prompt. Make sure you are in the directory you want the files to end up. The only reason I mention this is I just spend the last 5 minutes cleaning up my user directory because I forgot to change directories.

Next, I move up a directory and used the following command to add a new solution file.

Finally, I used the following command to add the new project to the solution file. If you aren’t using Visual Studio then you don’t have to have the solution file.

The project after the above can be found here.

Add a QR Code

Strictly speaking, a QR code isn’t required, but it is much better for users so they don’t have to enter a 32 character key into their authenticator application manually. I followed the official docs to enable QR code generation.

The first step is to download a Javascript QR Code library. I just used the one recommended in the docs, but any would work. This link will take you to a zip download. Open the download and copy  qrcode.js and  qrcode.min.js into a new  qrcode directory inside of your project’s  wwwroot/lib/ directory.

Next, find your project’s  EnableAuthenticator.cshtml file and update the scripts section at the bottom of the page to the following.

Enabling Two-Factor Authentication

The above changes are all that is required, and now we are going to walk through what it looks like for the user. Once logged in click on your user in in the upper right after of the site to open user management.

Next, click the Two-factor authentication link.

Then, click Configure authenticator app link.

This will land you on the page with the QR code.

Now using the authenticator application of your choice you can scan the QR code. Once scanned your authenticator application will display a code. Enter the code in the Verification Code box and click Verify. If all goes well you will be taken to a page that lists a set of recovery code for use if you can’t use your authenticator application for some reason.

Wrapping Up

I think it is awesome how easy the ASP.NET Core team has made the use two-factor authentication. With this being built into the templates it pushes all in the right direction. I do wish they would have left SMS as an option, but hopefully, it wouldn’t be hard to put back in.

The code in the final state can be found here.

ASP.NET Core 2 Fails to Publish With Angular 5

I had an issue opened on my Identity Server GitHub repo saying that publishing the client application fails with something like the following error when using server-side rendering.

Can’t resolve ‘./../$$_gendir/ClientApp/app/app.module.browser.ngfactory’

This was only an issue after moving the project to target Angular 5. After some research, it turns out that Angular tools for Webpack has to use a different plugin for ahead of time compiling for Angular 5+. I ended up finding a fix in this issue.

The Fix

In order to resolve the issue, I made the following changes in the  webpack.config.js file. The first change is in the require statements at the top of the file.

Next, make the following replacement in the rest of the file, which should only be two places.

Wrapping Up

Most of the projects I reference on this blog are written to specifically target the topic I am trying to cover and as such I miss things like testing publish since I’m never going to production with these applications. I really appreciate those of you who find issues and take the time to open an issue on GitHub. Keep them coming, and if you find a solution before I do feel free to submit a pull request.


Entity Framework Core with Postgres

With last week’s post, I now have Postgres running in a Docker container. This post is going to cover using Entity Framework Core with Postgres which will happen to be running in the Docker container from last week, but that bit isn’t a requirement for this post. This post is going to be very similar to this one which covered Entity Framework Core with SQLite.

Starting Point

Using Visual Studio 2017 I started with a new ASP.NET Core project using the Web Application template with Individual User Accounts for Authentication. Using Individual User Accounts is an easy way to get all the Entity Framework Core stuff setup.

Add Postgres Nuget Package

Right-click on the project file and click Manage NuGet Packages.

On the Browse tab search for  Npgsql.EntityFrameworkCore.PostgreSQL and then click install.

Configuration Changes

Open the  appsettings.json file and change the  DefaultConnection in the  ConnectionString section to a valid Postgres connection string as in the following example.

Not that a user ID and password are needed. If you are going to be checking your project into source control I recommend in addition to the above you only store the connection string with the real user ID and password in user secrets which don’t get checked into source control. You can find more information on user secrets here.

Startup Changes

The final change needed before running the application is in the  ConfigureServices function of the  Startup class to switch out SQL Server for Postgres. The following shows an example of the change for the  ApplicationDbContext.

Run the App

Running the application at this point will work fine until you hit a function that wants to talk to the database. For example, attempting to register a user would result in the following error.

If you see this error don’t panic just follow the instructions and they will get you going. The simplest solution is to just click the blue Apply Migrations button and continue your testing.

Wrapping Up

The application is now ready to go using Postgres. The Entity Framework Core team, as well as the Postgres Entity Framework Core Provider team, have done a great job making everything work with no pain.

The official docs for the provider can be found here. I would love to offer some tooling recommendations for working with Postgres, but I haven’t been working with it enough yet to provide any. If you have any Postgres tools you recommend please leave a comment.

The code in its final state, which has been expanded to include my standard contacts example, can be found here.

Trying the New ASP.NET Core Angular Template with CLI Support

I got hit by the flu that has been going around and now that the fever has passed I thought it would be a good time to try out the new version of the Angular template for ASP.NET Core that works well with the Angular CLI.

Template Installation

Note that at the time of this writing the templates are in the release candidate stage and a new version could be available by the time you are reading this so make sure and check this page for potential updates.

Running the following command from a command prompt will install the RC version of the templates.

Project Creation

Create a directory for the project and navigate to it in a command prompt. Run the following command to create the new Angular project.

Next, if you have a solution you want to add the new project to that can be done with the following command adjusting for the naming of your project and solution.

Installation of Angular CLI

From the command prompt run the following command to install the Angular CLI globally.

After the above, I got the following error trying to run any Angular CLI commands.

You seem to not be depending on “@angular/core”. This is an error.

The problem ended up being that I had not installed all the packages for the project. The issue was cleared up by the following command.

Angular CLI Usage

Navigate to the ClientApp directory and you can then use all the Angular CLI commands as you would in a stand along Angular application. Some of which can be found here. If you are looking for a quick command to verify all is work the following command works well by running a linter on your project.

Wrapping Up

Having templates that are compatible with the Angular and React CLI is a big step forward. The CLIs provide a lot of functionality and by having a setup that doesn’t restrict their usages is a great move. Make note that server-side rendering is no longer enabled by default, but can still be enabled for Angular projects, but not React based projects.

I recommend you check out the official documentation which can be found here.

I hope we see these functionality moves to the other templates that are outside of the templates in this package in order to support Aurelia and Vue.

Identity Server: Migration to version 2.1 and Angular HTTP Changes

Version 2.1 of Identity Server 4 was released a few weeks and this post is going to cover updating my sample project to the latest version. The starting point of the code can be found here. We are going to tackle this in sections as there are updates needed for an ASP.NET Core Update, Identity Server Update, and some broken bits in Angular.

ASP.NET Core Update

The sample projects were all on ASP.NET Core version 2.0.0. For each project right-click and select Edit ProjectName.csproj. Make the following change.

Identity Server Update

Right-click the Identity App project and select Edit IdentityApp.csproj. Next, make the following changes.

Next, need to add a couple of Entity Framework migrations to see if there were any data changes with the following commands from a command prompt in the Identity App project directory.

Turns out that there were no data changes for this version so if you are on version 2.0.0 you can skip this step.

Angular Issues

I’m not sure how I didn’t hit this issue on the last update post, but the Client App needs to be changed to use the new Angular HttpClient. I got the following error when trying to run the client application.

An unhandled exception occurred while processing the request.

NodeInvocationException: No provider for PlatformRef!
Error: No provider for PlatformRef!
at injectionError
After some digging, I tracked the issue down to using HttpModule instead of HttpClientModule. To make this transition we need to make a few changes. In the app.module.shared.ts make the following changes to the imports section.

Next, in the imports array make the following change.

Next, in the webpack.config.vendor.js fille add the following to the vendor array.

The last changes are to the auth.service.ts and they are extensive so instead of going through them I’m just going to post the full class after all the changes.

With all those changes made run the following two commands in a command prompt in the Client App project directory.

Wrapping up

This post ended up being more about Angular than Identity Server, but it is nice to have everything upgraded to the latest and working.

The files in the completed can be found here.

Change ASP.NET Core from npm to Yarn

Over the past couple of months, I have been having some issues with npm. Between the upgrading of npm Windows begin a pain and a version incompatibility with node I have just gotten frustrated with it. This post is going to cover the steps to use Yarn as a replacement for npm in an ASP.NET Core application.


The first step is to get Yarn installed. Head over to this site and download and run the installer for your operating system.

For Visual Studio, Mads Kristensen created an extension for Yarn that makes the integration much better. The installer for the extension can be downloaded from here.


Open a command prompt in the same directory as your project’s  package.json file and run the following command.

This will create a  yarn.lock and lay out the  node_modules folder using Yarn’s resolution algorithm.

I did hit the following error when I did the  yarn command. I left out the specific file that it had an issue with because I am sure yours would be different.

To clear the issue I just deleted the  node_modules directory and let Yarn recreate it. It might also work to use a command prompt with administrator privileges.

Visual Studio

With the Yarn extension installed there are a couple of settings that are helpful to change. All the setting we will be changing can be found under the Tools > Options menu. The first is to have  yarn install run when the  package.json is saved. Look under  Web > Yarn Installer for this option.

The second setting is to turn off automatic NPM restore so packages are restored twice. This requires the options under NPM to be set to false. The options can be found in  Projects and Solutions > Web Package Management > Package Restore.

The extension helps with Yarn integration, but the integration still isn’t as full-featured as using NPM. At my current level of frustration having to manually restore package when I open a project on a new PC is totally worth it.

Wrapping Up

So far Yarn has been great and I have not hit any issues, but my usage has also been limited. It seems like a solid alternative to NPM.

Make sure and check out Yarn’s official post on migrating from NPM which can be found here. Of specific interest will be the CLI command comparison which can be found here.

Auth0: Usage from Angular

This post is a continuation of my exploration of using Auth0 with ASP.NET Core with an API and an Angular front end. I recommend you start with the first post if you are new to Auth0.

This post is going to add a login from Angular in the Client Application as well as accessing the API once logged in. The starting point of the code can be found here.

API Application

To give us an endpoint in the API to call let’s move the  SimpleDataController class from the  ClientApp/Controllers directory to  ApiApp/Controllers directory. Also, remember to adjust the namespace to reflect this move.

To remove some complication we are going to add a CORS policy to the API Application to allow all CORS request. This wouldn’t necessarily something I would recommend for a production application. For more information on CORS check out this post.

To add the CORS policy open the  Startup class and add the following to the  ConfigureServices function which adds a CORS policy to DI that allows all calls through.

Next, in the  Configure function, CORS needs to be added to the HTTP pipeline with the policy added above. The following is the full function body for reference, but only the CORS line is new.

Note that the API isn’t currently using Authorization at all and won’t be for this post.

Client Application

Instead of redoing a lot of the same work that I covered in some of my posts on using Identity Server and Angular together I decided to copy the ClientApp directory and use it as a starting point. The rest of the client changes are going to assume the same starting point which means we will be using angular-auth-oidc-client instead of the Auth0 client to do the Open ID Connect bits.

Configuration values from appsettings.json

We need some setting from the ASP.NET Core part of the client application. First, add the following new settings to the  appsettings.json file.

Next,  Index.cshtml needs to be changed to provide some prerender data. The following shows the new data being passed into the Angular application (this post covers this in detail).

Now that the prerender values are being passed in we need to handle them in the  boot.server.ts file in the  createServerRenderer export. The following is the full list of values.

Down a bit in the file, the  setImmediate call needs to be changed to the following.

Next, in the  app.module.browser.ts file we need functions for getting the config values as well as the associated providers. The following is the full file without the imports.

Finally, in the  auth.service.ts file we need to inject the new configuration values. The following is the constructor that takes in the new values as well as uses them in the set up of the  OpenIDImplicitFlowConfiguration.

Make sure in the Auth0 client setup you allow the callback listed above or you will run into issues.

Wrapping Up

Working on this post further convinced me that Open ID Connect is the way to go. I basically took an implementation that was meant for Identity Server and used it with Auth0.

Make note that the reason the API is unsecured at this point is that I had an issue getting angular-auth-oidc-client to play nicely with Auth0 for some reason. I doubt it is an issue with either product just some sort of missing configuration on my part. This is the part of the post that I sunk so much time on. In the end, I decided to just skip it for now. If anyone does get that setup work I would love to see the sample so I know what I was doing wrong.

The completed code can be found here.