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.

Installation

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.

Conversion

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.

Welcome to 2018

This isn’t the post I had planned for this week, but thanks to a failed automatic upgrade of one of the WordPress plugins this site uses I had to restore a back up of the site which destroyed a lot of the post meant for this week. Thankfully NodeHost does automatic backups every day and the restore process is super simple.

On the positive, it gives me a chance to try out something new. I am going to list the books that I read last year. For the ones that are available on Amazon, I am using affiliate links just to see what happens. A lot of these books come from John Sonmez’s book reviews playlist. Without further adieu here is the list broken out by rough category.

Biographical/Entertaining

Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Living with a Seal (I laughed a lot on this one)

Business

EntreLeadership (Free gift from CodeStock 2 years ago)
The Phoenix Project

Health

The Obesity Code (Very informational if you struggle with weight read this one)

Parenting

The Kazdin Method for Parenting the Defiant Child

Personal Development

Think and Grow Rich
Boundaries
Triggers: Creating Behavior That Lasts
Never Split the Difference: Negotiating As If Your Life Depended On It
Banish Your Inner Critic
The Energy Bus
Eat That Frog!
The 10X Rule
Peak Secrets from the new Science of Expertise
Moonwalking with Einstein
Deep Work

Software/Career

SOLID Principles Succinctly
.NET Core Succinctly
Little ASP.NET Core Book
The Imposter’s Handbook
The Complete Software Developer’s Career Guide

Top Picks

The Phoenix Project is at the very top of my list from 2017 it uses a story to teach lean concepts from an IT perspective. I which I could get everyone in my company to read this book.

The Energy Bus helped me adjust my perspective and have a more positive outlook on life. If you have any issues with negativity check it out.

The 10X Rule is pretty high on my list as well. This book will get you taking action toward your goals if you follow its advice.

If you have any recommendations leave a comment as I am always looking to add new books to my backlog.

Auth0: Introduction and Initial Project Setup

As I started my exploration of Identity Server I listed a few alternatives that provided the same type of functionality, but as a Software as a Service. This series of posts will be covering one of the options I mentioned, Auth0.

The big selling points for Auth0, and other services like it, are that it removes you from having to worry about Auth/User Management and get to the part of your applications that bring value to your customers. As with Identity Server, Auth0 can use OpenID Connect (as well as a lot of other protocols), single sign-on and API Access Control.

Sign-up

The first step in getting started is to sign up for a new account. Here is a link to the sign-up page (not an affiliate link). You can use a username and password or a social login. I’m going the social route using GitHub.

After user creation then there are a couple of setup steps. The first is to choose a tenant domain and region.

Click next and on the second step, there are questions about what the account is going to be used for. In my case, it is a personal, developer, who is just playing around.

Click Create Account to finish the creation of your account which will then land you on the account dashboard page.

Auth0 Setup

Client

From the Auth0 Dashboard click the New Client button. Give the client a name, TestMvc in my case, and select Regular Web Applications as the type.

In a follow-up post I will be covering the Single Page Web Application, but for this post, we are going to be using MVC since it tends to be simpler. The next page defaults to a framework selection which seems to be a guide to getting going for the framework you select. We are going to skip that and click on the Settings tab.

On the settings page, we need to fill in a value for Allowed Callback URLs. The sample client should use  http://localhost:50774/signin-auth0. Click the Save Changes button.

API

While we are doing some setup on the Auth0 site we are going to go ahead and set up our API as well. Click the APIs menu option on the left menu.

Then click the Create API button. In the dialog enter a Name and Identifier and click the Create button.

Sample Solution Structure and Setup

The sample solution for this post has two projects.

  • ApiApp – Backend application and is a resource that is will require authorization to access. The API is an ASP.NET Core Web API.
  • ClientApp – Frontend application that will be requesting authorization. This is an ASP.NET Core application that is hosting an Angular (4) application. Note for this post we will be using MVC and not Angular. A future post will deal with the Angular side.

The sample solution with the two projects already added can be found here. If you are using the sample solution feel free to skip the next two sub-sections as they are going over how the projects were created.

To start, add a directory to contain the solution.

API Application

Inside the solution directory, create an  ApiApp directory. From the command line in the  ApiApp directory run the following command to create a new ASP.NET Core application using the Web API template.

Client Application

Inside the solution directory, create a ClientApp directory. From the command line in the  ClientApp directory run the following command to create a new ASP.NET Core application using the Angular template which as of this writing outputs an Angular 4 application.

After generation is done run the following to make the all the NPM packages that are required get installed.

Solution

Inside the solution directory, let’s create a solution file for use with Visual Studio. Run the following command to create a solution file named  AspNetCoreAngularAuth0.sln.

Next, run the following two commands to add the API and Client projects to the solution.

Securing the API Application

Open the  appsettings.json file and add a section for Auth0. We are going to need to store the Auth0 domain (tenant domain from sign up) and API Identifier (from the creation of the API at Auth0).  The following is the full file from the API project with the new Auth0 section.

Next, in the  ConfigureServices function of the  Startup class add the following to add authentication using the JWT Bearer scheme to the DI system.

In the  Configure function add the following line before  app.UseMvc() to add authentication to the HTTP pipeline for the API application.

The last step in the API for this post is to add a controller that will require authentication. The following is the full code for the  AuthTestController that was added to the  Controllers directory.

Client Application

In the Client Application open the  appsettings.json and add the following setting related to Auth0. This is the full file so the logging section was existing.

If you are going to be checking in your code into a publically accessible source control I recommend you use user secrets instead of  appsettings.json. You can read more about user secrets here.

Next, in the  ConfigureServices function of the  Startup class add the following. I’m not going to go over this code line by line the gist is it is setting up the application to using cookies and Open ID Connect for authentication.

Note that the  OnRedirectToIdentityProvider bit is related to getting access to the API.

In the  Configure function add the following line before  app.UseMvc to add authentication to the HTTP pipeline.

Testing Setup

In order to provide a way to test login, logout, and API access without using the Angular portion of the client app, remember that will be a future post, I add an  AuthTestController to the  Controllers directory with the following.

Sorry for the formatting, but that sample has long of verbose statements. Nothing crazy going on in this file. There is an  Index action that attempts to call the API and then returns a view. The  Login and  Logout functions do what they say and were pull right from the official docs.

The associated  Index.cshtml file was added to the  Views/AuthTest directory with the following.

This view just shows a link to login or logout and shows the results of the API call. It is ugly but is enough to prove the setup is working.

Wrapping Up

Getting up and running was much fast with Auth0 and would be true of any SASS option I’m sure. It also helped that I have more of an idea of what is going on after all the posts I did on Identity Server. Another positive is Auth0 has some great docs. I used the ASP.NET Core and Web API ones a lot to get this sample application up and running.

Next steps are to get this setup running in the Angular client which should be my next post. The finished code for this post can be found here.

 

ASP.NET Core Basics: Razor Pages

As part of the ASP.NET Core 2.0 release, a new feature called Razor Pages was added to better handle page-focused scenarios. This post is going to cover adding usage of Razor Pages to an existing ASP.NET Core MVC application. This is part of the ASP.NET Core Basics series and the repo before any changes for this post can be found here. All the changes will be in the Contacts project if you are using the sample repo.

Add the end of this post the Razor Pages example will have the same level of functionality as the existing Razor example in the project.

Setup

To follow the conventions of a new Razor Pages project add a  Pages directory to the root of the project. As another level of grouping add a ContactsRazorPages directory under the  Pages directory. The strange name of the directory is just to make it super clear this is different than the existing Contact List already in the application.

Scaffolding

Razor Pages supports the same level of scaffolding as the existing Razor/MVC setup we are all used to in Visual Studio. To start, right-click on the  ContactsRazorPages directory and select Add > Razor Page.

This will open the Add Scaffold dialog. We are using entity framework and want to generate a full set of CRUD operations so select Razor Pages using Entity Framework (CRUD) and click Add.

Next, we have to select the Model and DB Context. We want to use the same model and context as our existing Razor/MVC setup so we are going to select the Contact class and the ContactsContext DB Context. Finally, since this is part of an existing application make sure and check the Use a layout page and use the existing  _Layout.cshtml page used by the rest of the application. Click the Add button and hang out while the magic happens.

After a couple of minutes, the directory will be filled with a set of pages to do contact CRUD operations. Since this is a page-centric method of working all the files you need are in this one directory. No separate controller and views as in traditional MVC. By default, routing is handled via the folder structure.

View Imports

I had to a  _ViewImports.cshtml file to the  Pages to get things working. I tried adding the needed imports to the existing import, but it didn’t work for some reason. Here are the contents of the file.

Add to the Navigation Menu

Our last step is going to be to add the new contact list to the site’s navigation menu. Open the  _Layout.cshtml file in the  Views/Shared directory and a link to the new contact list.

Notice that the link uses the  asp-page tag helper instead of  asp-controller.

Wrapping Up

The above covers adding Razor Pages to an existing MVC application and rounds out the all the major UI options for the ASP.NET Basics series. Keep in mind that Razor Pages functionality is fully on par with tradition MVC and has been recommended by Microsoft as the way to do when page-centric work. If you haven’t check out the getting started docs to get a better feel for how to use pages.

The completed code can be found here.

Identity Server: Upgrade Client to Angular 5

I have been working a lot on my basics sample project to explore some new client-side frameworks (React and Vue if you are interested). Since I have been away from the Identity Server sample for a while I thought it would be good to see what updates the project might need. It turns out that Angular was the big thing that was out of date. This post is going to cover the changes to get the project updated to Angular 5.

Package.json

In the Client App project open the  package.json file and update the version of the  @angular packages to at least the following version, and of course feel free to pin the exact version. I don’t just because of the nature of this sample.

At this point, I tried to run and got an error about the version of  rxjs being used. Instead of just blindly going package by package and seeing which versions were required I installed the Angular CLI and created a new Angular 5 application and used it as an example of what version I needed. Use the following commands if you would like to follow the same process since the current versions have changed by the time you are reading this post.

The above led me to the following version changes.

Attempt 2

At this point, I tried running the application again and received the following error.

Error: Version of @angular/compiler-cli needs to be 2.3.1 or greater. Current version is “5.0.1”.

As you can imagine I was surprised that 5.0.1 < 2.3.1. Turns out this is related to the version of @ngtools/webpack. This package deals with ahead-of-time compiling which my sample application uses, but the application I generated using the Angular CLI doesn’t. Updating to the following version cleared up the issue.

Open ID Connect Client

There was a much new version of the Open ID Connect Client that the Angular application is using so I upgrade it as well to the following version.

This version dropped the  startup_route so the following line had to be removed from the  AuthService class.

Final Steps

Now that the package versions are sorted run the following commands from a command prompt to make sure that all the new version are installed and in the proper places.

Wrapping Up

I am glad to have this upgrade done. It seems that every time I do one of these upgrades I end up down some rabbit hole. On the plus side, I seem to be getting faster at resolving the rabbit hole issues, or the frameworks have made a lot of progress on making sure the upgrade processes are simpler than they used to be. Either way, I get to expand my knowledge. I just need to schedule a bit more time before attempting upgrades.

The code in its finished state can be found here.

Vue: Contact Detail

Last week’s post covered adding a Vue project to the ASP.NET Core Basics example solution. This post is going to cover adding a read-only view of a contact’s detail to being the Vue sample a step closer to being in line with the Angular, Aurelia and React samples. The code before any changes can be found here.

Contact Class

The  Contact interface in the  contactlist.ts file should be deleted. Add a  contact.ts file to the  ClientApp/components/contacts/ directory. This will hold the replacement for the interface we just deleted. The full class definition follows.

This class is very simple and will be used later to show how a function call can be used as part of a view.

Contact Service

Since the application will now have two places that need to access the ASP.NET Core API lets to refactor the API access into a service. This is the same style used by the Aurelia, Angular and React applications. Add a  contactService.ts file to the  contacts directory. The service will provide functions to get all contacts or a single contact an ID. The following is the full class.

Now the API access in the  ContactListComponent can be refactored to use the service. First, add imports for contact and service.

Next, replace the fetch call with a service call.

Contact Detail Component

Add a  contactDetail.ts which will be the backing component for the contact detail view. The following is the full class. Pretty much all it is doing is using get contact service to get contact detail by ID when it is mounted.

Now add a  contactDetail.vue.html file for the UI bits of the contact detail. This is basically just HTML with the same binding syntax as before. Notice that the binding of address is a function call. The other Vue things to note are that the details will only show if contact is truthy using the v-if.

Routing with a Parameter

Finding the proper way to route with at parameter in Vue was not easy. The way it is done has evolved over time making find the right way a little challenging. The first step is to add a route for the contact detail by adding a new item to the  routes array in the  boot.ts file.

The  :id in the path denotes a parameter. The  props: true bit is also key to getting the ID when in the contact detail component. The  contactlist.vue.html needs to be updated to link to the contact detail route.

Finally, in the  ContactDetailComponent we need to use the ID. To do so we need an import to allow the use of the Prop decorator.

Now all that is needed is to apply the decorator to a property of the class that matches the name of the parameter in the route.

Now the ID can be used to get the proper contact from the contact service. The following is code that was already shown, but the full context of how the prop decorator is used is important so I am repeating it here.

Wrapping Up

This brings the projects one step closer to being on the same level feature-wise. Look for one more post to get the Vue project features lined up with the other samples in the solution.

Keep in mind that this is my first look at Vue and my examples may or may not be idiomatic.

The code in a finished state can be found here.

ASP.NET Core Basics: Vue with an API

In the past, I have done some exploration on AureliaAngular and React via the ASP.NET Core Basics series. This post is going to take a similar approach using Vue. The code for the project will be in the same repo as the previous basics examples and will be utilizing the same API to pull data. The code before adding the Vue project can be found here.

Project Creation

There is not a template for Vue built into Visual Studio, but there is a set of templates that can be used via the .NET CLI with the  dotnet new that includes Vue (as well as Aurelia and Knockout). A full list of available templates can be found here. The template we need is Microsoft.AspNetCore.SpaTemplates and can be installed using the following command from a command prompt.

Create a Vue folder at the same level as the other projects, for the samples this would be in the  src folder. In the command prompt navigate to the  src/Vue/ directory. Run the following command to create the Vue project.

After the project generation completes run the following to get the needed npm packages installed.

The last step is to get the new project added to the existing solution. Navigate the command prompt to your solution file. For the sample project, this is the root of the repo. Then run the following command (this could also be done through Visual Studio instead of using the CLI).

Adding the Contact List

In the  ClientApp/components directory add a new  contacts directory to house all the awesome contact related functionality we will be adding. Next, add a new  contactlist.ts. To this new file add the interface which defines what a Contact looks like.

Above the contact interface, add the following imports needed to create a Vue component.

Finally, add the contact list component. This component maintains a list of contacts which gets filled from our existing API when the component is mounted (see the docs for more information on Vue’s lifecycle hooks).

The following if the full component just to provide full context.

Next up is the UI for this contact list component. In the same directory add  contactlist.vue.html.  The following is the full file.

All of the above is pretty straightforward. All the Vue specific items have a  v- prefix.

Add the Contact List to Navigation

The last bit needed to have a working contact list is adding it to navigation so the user can get to the list. The routes are defined in the  boot.ts file in the  routes array. Add the following line to the array to handle our contact list.

Now that the router knows to handle the contact list it needs to be added to the navigation UI. Open the  /navmenu/navmenu.vue.html file and find the unordered list that is the navigation menu. Add a new list item to provide a link to the contact list.

Wrapping Up

Vue reminds me a lot of Aurelia in its simplicity so far which is awesome. Look for the same progression of posts for Vue that happened with React over the last few weeks.

The code in its final state can be found here.

React: Form for Contact Add

Last week’s post covered adding a read-only view of a contact’s details. As before the goal is to get the React project’s features in line with the Aurelia and Angular samples. This week we will be adding a form to all addition of a new contact. The code before any changes can be found here.

Contact List

On the contact list page, we need to add a link to create a contact. This will be added just after the header in the  ContactList.tsx file.

Routing

In order to stay in line with the other sample, the  ContactDetail component is going to be handling both the read-only view and the view to add a contact. This means the ID that is currently part of the contact detail needs to be optional. The following is the change to make ID optional by adding a question mark.

Contact Service

In the  ContactService class, we need to add a  save function. This new function will make a post request to the contacts API and return the new contact with the ID from the API to the caller.

Contact Detail

The  ContactDetail class is where most of the changes are. I had some trouble getting React’s forms to work directly with the instance of the contact class and ended up just storing the parts of a contact directly in state instead of as an object. I expect this is a failure on my part and not an issue with React. I may revisit this in the future. Below is the new structure of the state used by contact details.

Next, the  constructor needed to be changed to handle the new state structure and to handle being called without an ID.

Again, this is way more code than it would be the contact class were being used. Next, the render function needs to be adjusted to render the UI for the read-only view or the contact creation. The decision is based on the ID being set or undefined.

The render of an existing contact needs to be changed to use state instead of an instance of a contact.

The following is the render of the add contact UI. I will call out a couple of parts after. The bulk of the code is just rending of the form.

The following is the input for the contact’s name.

Since I decided to go with the controlled component route React will be responsible for being the source of truth, not the form its self. To accomplish this it is important that the input has a  name and an  onChange event handler set up. The following is the  handleChange function which uses the name from the on change event to update the proper property in the component’s state.

The following line is the reset button which will reset the state to blank out all the fields in the form.

<button className="btn btn-danger btn-lg" onClick={() => this.reset()}>Reset</button>

The  reset function just uses  setState to blank out all the fields.

Not surprisingly the submit button triggers a submit of the form. What happens on submit is defined in the opening form tag.

The  handleSubmit function takes the contact information in state and uses it to create a new instance of a  Contact which is then passed to the  ContactService to be saved. The service returns a new contact object from the server and the ID is stored to state.

If the server does return an ID for the new contact then the  redirect is set to true. Then will case the following code to run in  renderNewContact which will redirect the user back to the read-only view of the new contact.

Wrapping Up

This pretty much gets the React application in line with the Aurelia and Angular sample applications. It has been fun getting a handle on the very, very basics of React. While I am back in the basics sample projects I may go ahead and tackle a Vue sample next.

The finished code can be found here.

React: Contact Detail

Last week’s post covered adding a React project to the ASP.NET Core Basics solution. As I stated last week the goal is to get the React project’s features in line with the Aurelia and Angular samples. This week we will be adding a read-only view of a contact’s details. The code before any changes can be found here.

Contact Class

The  Contact interface in the  ContactList.tsx should be deleted and in its please we will add a  Contact class. As part of this change, I also moved the contact related items to a contact directory. Add a  contact.ts file to the  ClientApp/components/contacts/ directory with the following contents.

This class is very simple and will be used later to show how a function call can be used as part of rendering.

Contact Service

Since the application will now have two places that need to access the ASP.NET Core API I decided to refactor the API access behind a service. This is the same style used by the Aurelia and Angular applications. Add a  contactService.ts file to the  Contacts directory. The service will provide functions to get all contacts or a single contact using its ID. The following is the full class.

The final step in this refactor is to use the new service in the  ContactList class. First, add imports for the service and  Contact class.

Then, replace the fetch call with the service.

Contact Detail Component

Add a  ContactDetail.tsx file which will be used to show the details of a contact including using the  getAddress function of the  Contact class. The following is the full contents of the file.

This is all very similar to the things I have covered before. Now that we have a contact detail component we need a way to display it.

Routing with a Parameter

Import the contact detail in the  route.tsx file.

Next, add a route path for contact detail that expects an ID.

Back in the  ContactList component change the ID to be a link to the new contact detail route using the ID of the contact.

The code for pulling the route parameter was in the  ContactDetail component above, but I am going to show it again just so all the route with parameter information is together. The route parameters can be accessed using  props.match.params.{parameter name} which in this case ends up being  props.match.params.id. The following is the constructor of the  ContactDetail component which is using a route parameter.

Wrapping Up

This brings the projects one step closer to being on the same level feature-wise. I expect at least one more post to get the project features lined up so make sure and keep a lookout for the next post.

Keep in mind that this is my first look at React and my examples may or may not be idiomatic. So far I am really enjoying working with React.

The code in a finished state can be found here.