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.

Startup

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.

Run Multiple Projects in Visual Studio Code

While expanding the sample used in the Electron.NET post to include an API I hit a snag with Visual Studio Code. I have used multiple projects with Visual Studio Code before, but never two distinct applications that I need to run at the same time.  Sample code that contains the two projects, but before any modifications covered in this post can be found here.

Building Multiple Projects

The first issue to tackle was getting both projects to build since they are technically independent. As I’m sure you are aware VS Code doesn’t need a solution file like full Visual Studio does. What I learned during this process was that while a solution file isn’t required once can be used to ensure multiple projects all get built. Using VS Code’s Terminal I ran the following commands to create a new solution and add my two projects to that solution.

With the solution file in place, I then opened the tasks.json file found in the .vscode directory. In the build task, I removed the path to a specific csproj file and just used the workspace folder.

This is just one option on how to handle the builds. I believe another way would be to have two build tasks (one for each project) and use the individual build task in your launch configurations (which we are going to talk about next).

Debugging Multiple Projects

Open up your launch.json file in the .vscode directory. By default you will see a couple of configurations more than likely you will see one named .NET Core Attach and another named .NET Core Launch (web). It is the .NET Core Launch (web) configuration that we are interested in. This configuration controls how our application is launched. If you notice the program property points to the dll created during the build process, in the sample code this is  ${workspaceFolder}/src/ElectronTest/bin/Debug/netcoreapp2.0/ElectronTest.dll. This is all fine but doesn’t give us a way to run both of our projects. Let’s tweak the env property to set the ASPNETCORE_URLS which will control the URL the application is launched with.

Now that the original application’s launch configuration is set we need to add a second launch configuration for our second application. The following is the full configuration section for my second application (the API).

I started with a copy of the original application and just modified a couple of things. First, the name property is now .NET Core Launch (API) which will help us know which application we are launching later. In the launchBrowser section, I set enabled to false since this is an API and I don’t need to launch the browser when the application starts. The final difference is in  ASPNETCORE_URLS to make sure the URLs of the two applications are different. I used http://localhost:5000 in this example.

Now that all our configurations are good to go hop over to the debug section in VS Code.

On the debug you will notice that both of our launch configurations are listed. If you select the API one and hit the green play button it will start the API. With the API running you can then select the web configuration and hit the green play button and you will have both of your applications running in debug mode.

Wrapping Up

While it is not obvious at all how to get multiple applications to run in a single instance of VS Code the process isn’t hard after you do it the first time. I think my Visual Studio experience made figuring this out harder than it should have been. My key to learning how to get this going was on this GitHub issue.

Hopefully, this saved you some of the struggles I went through. Please leave a comment if there are different ways to accomplish this. The code with the final configuration can be found here.

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.

Refit Basics

A few weeks ago I was watching this episode of the ASP.NET Community Standup and they had Ryan Nowak on to talk about the new HttpClientFactory coming in the 2.1 release and a question came up about compatibility with Refit. I had been meaning to check out Refit but had honestly forgotten about it. This post is going to be a very basic introduction to Refit.

What is it?

In the author’s (Paul Betts) words, Refit is the automatic type-safe REST library for .NET Core, Xamarin and .NET. Cool, but what does that mean? Basically, Refit allows you to define an interface for an API that your application wants to call and using that is hides way all the HTTP and JSON serialization/deserialization bits.

Sample project creation

To test Refit out I created a very simple .NET Core console application. To do the same open a command prompt in the directory you want the project using the following command.

For this project, I am using Visual Studio Code as my editor. Since VS Code doesn’t have a NuGet UI build in (maybe there is an extension?) I used the following command to add Refit to the project.

Or if you prefer you can add the following to your csproj file.

The API

Instead of creating an API I searched the internet for a free one I could use. I ended up using CountryAPI. The following is a sample of what a response from the API looks like.

Classes

Now that we know what the API response looks like classes can be created to match its structure. In this case, I have two classes one for response and one for the actual country data.

API Interface for Refit

With the classes for the response setup, we can now define the interface that will be used by Refit when calling the API. The following interface defines a function to get all countries and another function that gets countries that speak a specific native language.

The attributes on the functions are part of the magic of Refit. In the cases above both of the calls are HTTP Get requests which is why they are using the  Get attribute. Refit does support other verbs as well.

The other thing of note here is the  AliasAs on the parameter of the second function call. This attribute can be used to control what gets put in the query string and keeps cryptic names from the API from spreading to other places in your code.

Calling the API

The following is the full code from my Program class that shows the usage of Refit with both of the API calls defined above.

The following line is defining a call to a rest API for a specific interface.

Now that we have a reference to the API it can be called asynchronously to get the data from the API.

The rest of the app is more of the same just using the other API call.

Gotchas

In order to use  async Task Main a change is needed to the project file to set the  LangVersion. I just set it to latest, but I believe the minimum for this feature is 7.1.

If you are using VS Code and are using  Console.ReadLine() like I am above then a change will be needed for the  launch.json file found in the  .vscode directory. Look for the  console property and set the value to either  integratedTerminal or  externalTerminal otherwise, the app will be connected to the debug console which will show the output of the application, but doesn’t allow for input.

Wrapping up

Using Refit to makes using APIs super simple. There is a level of magic that I would like to dig into more. I would also like to see how it handles issues and what sort of hooks are provided to address those issue. Based on the Github page Paul has addressed a wide range of the challenges faced with dealing with an API.

As part of writing this posts, I came across two other posts on Refit that might be helpful, one by Jerrie Pelser and the other from Scott Hanselman.

 

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.

 

Three Years of Blogging

This Thursday will be the third anniversary of my first post to this blog. This post is going to be similar to the post I did last year in the form of a retrospective.

Positives

Most of my positive points are the same as last year. I guess I shouldn’t be surprised as these are the reasons I spend my free time working on the blog.

  • Driver for learning new things
  • Opportunity to use new/different technology outside of my normal work
  • Helping others learn new concepts
  • Helping others overcome problems
  • Made my first contributions to open source
  • Comments from readers letting me know posts were helpful
  • No big hosting issues this year (thank you NodeHost!)

Challenges

Again most of the challenges are in line with what they were last year. I guess I should take that as a red flag and focus on solving some of my challenges instead of living with them.

  • Learning new things on a deadline
  • Self-applied pressure to meet my goal of a post a week (increasing my stress level)
  • Not focusing on stats, shares, comment, etc.
  • Picking the right things to learn
  • Time requirements taking away from other projects I would like to do

Top posts of the year

I was a little surprised at the makeup of this list. I expected to have more than a single repeat from last year’s list.

I did a series of posts looking at Identity Server 4 this year that didn’t make the above list individual, but as a total, the series was huge for me last year. If you are interested you can check out all the posts here.

Resources

There are a couple of resources that I want to point out.

ASP.NET Weekly is a weekly digest of all the best ASP.NET related news and blog post run by Jerrie Pelser. Jerrie does a lot of good work in addition to ASP.NET Weekly including a blog and a book.

ASP.NET Community Standup is straight from the team at Microsoft who is responsible for ASP.NET Core. These videos are a great way to get the scoop on what is in the works. Also, note that if you have watched in the past this show has moved from Scott Hanselman’s YouTube channel to .NET Foundation’s channel so update your subscriptions.

John Sonmez’s free blogging course is what finally pushed me over the edge to start blogging. It is a great resource to help get you moving.

NodeHost is my hosting provider. They provide super simple and cheap hosting. If you are looking for a place to host your own blog check them out. Combine them with Cloudflare and Let’s Encrypt and you are all set if you are going to WordPress route.

The next year

As usual, I am looking forward to seeing where ASP.NET Core goes next. Things like SignalR Core, HttpClientFactory, Entity Framework Core improvements are going to be great to explore.

Outside of ASP.NET Core, I am looking at putting out a very basic Xamiran app. Based how that goes you may see a few posts related to Xamiran in the next year.

If there is a topic you would like to see covered leave me a comment and I will add it to my list of things to look at.

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.

Setup PostgreSQL on Windows with Docker

Over the weekend I finally got the chance to start reading A Curious Moon by Rob Conery which is a book on learning PostgreSQL by following the fictional Dee Yan as she is thrown into database administrator role at an aerospace startup.

I have a lot of experience using Microsoft’s SQL Server, but up until now, I haven’t touched PostgreSQL. For personal projects SQL Server’s cost and be prohibitive and the release of Rob’s book added up to a good time to give PostgreSQL a try.

Install Directly or not?

On the download section of the official Postgres site, there is an option to download an installer. This is the route I was going to at first, but in Rob’s book, he suggests using a VM for Postgres installation on Windows. This kicked off a lot of searching on my part and didn’t find a good definitive answer on why that is or isn’t the way to do.

In the end, I decided to try and run the Postgres process using Docker instead installing directly on Windows or dealing with a full VM.

Installing Docker

Head to this link and click the Get Docker link to download the installer. After the install is complete you will have to log out and back in. When I logged back in I got a message about Hyper-V not being enabled.

After logging back in I then got the following message about hardware-assisted virtualization not being enabled.

After tweaking my BIOS settings and logging back in I was greeted by the Docker welcome screen.

Open a command prompt and run the following command.

You should output that starts with the following if your installation is working.

Hello from Docker!
This message shows that your installation appears to be working correctly.

What about Postgres?

Getting up and going with a container running Postgres was pretty simple and could be done with the following command which will create a container and expose the port used by Postgres so it can be accessed from the host.

The problem with this approach is if you ever need to rebuild the container for some reason, like a new version of Postgres is released, your data will be lost. Thankfully I found this blog post which shows how to use a secondary container for the data leaving the Postgres container able to be destroyed and recreated as needed. The following is the command I used to create my data container.

The above creates a container named PostgresData based on the Alpine image. It is important that the  -v parameter matches the path that Postgres expects.

Now that we have a container that will keep our data safe let’s create the actual Postgres container with the following command.

The only difference from the first example run command is the addition of  --volumes-from PostgresData which tells the container to use the PostgresData container.

If you run the  docker ps -a command it will show you all your containers.

As you can see in my example I have two containers only one of which is actually running. Make sure you don’t remove the data container just because it will never show as running.

Connect to Postgres

To verify all was working I downloaded pgAdmin from here. Run the installer and then open the application. Right-click on Server and click Create > Server.

On the Create Server dialog enter a Name for your server and then switch over to the Connection tab.

On the Connection tab for Host use localhost and in the Password field use the password you used for POSTGRES_PASSWORD on the docker run command.

Click Save to close the dialog and connect to the server. The following is an example screenshot of what you will see showing the available databases on the server, which is just the default database in this case.

Wrapping Up

Make sure to check out the official docs here for more information as needed.

Other than the storage portion getting Postgres up and running in Docker was pretty simple. I hope like me this will give you a good jumping off point to learn more about both Docker and Postgres.

If anyone has any alternate ways to deal with persistent storage please leave a comment.