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.

ASP.NET Core Basics: React with an API

In the past, I have done some exploration on Aurelia and Angular via the ASP.NET Core Basics series. This post is going to take a similar approach as I start doing some exploration with React. 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 React project can be found here.

This post is going to cover adding a React project to the existing using the React template that is now built into Visual Studio. The same thing can be accomplished using the .NET CLI so don’t feel like Visual Studio is required. The goal for the React project in this initial post will be to connect to the contacts API and download a list of contacts and render that to the screen. In future posts, I hope to expand this functionality to match that of the Aurelia and Angular projects.

Project Creation

Right-click and select Add > New Project.

In the Add New Project dialog select the ASP.NET Core Web Application. In the case of the sample, the project will be named React. Click OK to continue.

On the next screen make sure and select ASP.NET Core 2.0 and the React.js template. Then click OK.

The following is the resulting React project in the context of the full solution.

Next, make sure and run npm install from a command prompt in the React project’s directory to ensure all the npm packages get restored.

Adding the Contact List

Inside the  ClientApp/components/ directory add a file name  ContactList.tsx. TSX is the TypeScript version of the React JSX file type. The official docs on JSX can be found here. Since this is my first time working with React I took the  FetchData.tsx file and copied the contents and used that as the starting point for my contact list. To lead with there is an interface for what should define a contact.

Next, we have an interface for the state of this component with contains a loading flag and an array of contacts.

In the constructor for the component is where the data is pulled from the API using  fetch. The data from the API is then saved to the state of the component using the  setState function.

Next, the component has a function named  renderContactsTable which takes an array of contacts and returns how they should be rendered. In this case, the contacts are rendered to a table that displays the contact ID and Name.

Finally, there is the render function. As you can guess this is what gets called to render the component. In this case, either “Loading” or the contact list gets displayed depending on if the contact list data has been loaded or not.

The following is the full file for reference.

Add Contact List to Navigation

Now that we have the contact list component it needs to be added to the navigation menu. The first step is to add it to the application’s router. This can be found in the  routes.tsx file. The file is short so I am going to include the full content. Lines 7 and 13 are the ones added to handle our contact list.

The last change is to add a navigation link to the  NavMenu found in the  NavMenu.tsx file. As I am sure most of us are used to adding an item to the nav menu is just adding a new li, but with the React specific  NavLink bit.

Wrapping Up

React is different than both Aurelia and Angular. Don’t take that as a good or bad thing. I don’t plan to pick on a side on the Angular vs React debate I just want to get a good feel for the different frameworks. So far the React experience has been pretty nice and I look forward to doing more exploration.

You can find the finished code for this post here.

Hitting a wall

I have had a very frustrating week. I got sick, failure on two different blog posts, basically no progress on any project. I hit walls on everything I attempted.

Everyone has bad weeks and if you look back I am sure you will find I have made a couple of posts along these same lines. I don’t post this type stuff to complain, but instead to be clear that this isn’t easy and at times is a struggle. I share this so that it can be an encouragement when you hit your own walls. Everyone faces struggles. Pick your hero and I can promise that they struggle.

We tend to see only the positives from the lives of other people which makes what we are going through feel worse and unfair. Comparing the full depth of yourself to the public face of others is an easy way to head down a very negative path. A path I have struggled with at times.

If you struggle with some of the same things I recommend that you check out the content of John Sonmez and Gary Vaynerchuk. Both of them have helped me push through some of the walls I have hit. The Energy Bus by Jon Gordon has also been helpful for staying positive.

Whatever wall you are hitting keep working and push through. You can do this.

Identity Server: Migration to ASP.NET Core 2

The Identity App that is part of my IdentityServer sample project is the last application I have on GitHub (of the ones that will get upgraded) that needs an upgrade to ASP.NET Core. The starting point of the project before any changes can be found here. This post assumes that you have already followed my generic ASP.NET Core 2 migration post, which can be found here, on the project you are migrating. One final note of caution this post has been written using the RC1 version of the Identity Server NuGet packages and then moved to the final version so there will be two different related pull requests that will have to be looked at to get the full picture of all the changes.

Package Changes

The first change is to get a version of the Identity Server packages what will work from ASP.NET Core 2.

Database Initialization

I wasted a lot of time on finding out this was an issue when I was trying to create Entity Framework migrations and kept getting Unable to create an object of type ‘ApplicationDbContext’. Add an implementation of ‘IDesignTimeDbContextFactory‘ errors. The gist is database initialization needs to be moved out of  Startup and context constructors.

Let’s start with the  ApplicationDbContext and remove the following code from the constructor as well as the associated property.

Next, in the  Configure function of the  Startup class remove the following line.

We still need the database initialization code to run, but where should that be done? In the  Main function of the  Program class seems to be the new recommended location. The following is the new  Main function.

InitializeDatabase now needs to take an  IServiceProvider instead of an  IApplicationBuilder. This forced a lot of lines to change so the following is the full class.

Startup Changes

Most of the changes to the  Startup class are in the  ConfigureServices function, but some cross with the  Configure function as well. The existing AddIdentityServer extension has multiple changes especially if you are using Entity Framework for your configuration data.  AddTemporarySigningCredential is now  AddDeveloperSigningCredential. The following is the new version including configuration data.

The way to handle registration of external authentication has changed as well. For example, this application uses Twitter. The  UseTwitterAuthentication call in the  Configure function needs to be removed. The following added to the bottom of the  ConfigureServices is now the proper way to add external authentication providers.

Entity Framework

The new changes in Identity from the ASP.NET Core team included a new foreign key which is one of the things that Sqlite migrations can’t actually do. Since I don’t really have any data I care about I just deleted the database and the existing migrations and snapshots and regenerated everything. If you are using Sqlite and this isn’t an option for you check out this post for some options. If you aren’t using Sqlite then the migrations should work fine. The following are the commands to generate migrations for the 3 contexts that the Identity Application uses.

Quick Start UI Changes

As part of going from the RC1 version to the Final version, the Identity Server team updated the UI and related bits to be in line with the new features added in the ASP.NET Core 2.0 release. Turns out that resulted in a lot of changes. Since I haven’t done any custom work in this area of my Identity Application I deleted the related files in my local project and pulled from the ASP.NET and Entity Framework Combined sample. I am going to give a good idea of all the files I replace, but in case I miss something GitHub will have the full story.

In the Controllers folder replace  AccountController.cs and  ManageController.cs. Add or replace the following folders:   ExtensionsModelsQuickstartServices, and  Views.

Application Insights Error

I ran into the following error.

System.InvalidOperationException: No service for type ‘Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet’ has been registered.

You may or may not see it, but if you do open the  _Layout.cshtml and remove the following two lines.

Wrapping up

If you hit any issues not covered above make sure and check out the breaking changes issue. The completed code can be found here for part 1 and here for part 2.

Identity Server: Deploy to Azure

This post is going to cover taking the existing set of applications we have been using to learn about Identity Server and deploying them to Azure. The starting point of the code can be found here.

Prep Work

The applications as they stand from the link above are not ready to be pushed to Azure most due to some configuration changes that are needed. We will go through each of the applications and take the hard-coded values and move them to  appsettings.json.

API Application Configuration

The API application needs two configuration values for the address of the Identity Application and the address of the Client Application. The following two lines need to be added to the application’s  appsettings.json file.

Then in the  Startup class, the values need to be used. The Identity Server address is used in the JWT Bearer setup.

Then the Client address is used in the CORS setup.

Identity Application Configuration

The Identity application needs a configuration value for the address of the address of the Client Application. The following line needs to be added to the application’s  appsettings.json file.

Next, the  Config class needs a reference to configuration passed into the  GetClients function.

Next, the references to  http://localhost:5002 need to be replaced with the value from the configuration. The following is one example.

Identity Application Entity Framework

As part of publishing this set of applications, this example is going to use Azure SQL and right now the application is set up to use SQLite. In the  Startup class replace  UseSqlite with  UseSqlServer. The following is an example of one of the needed replacements.

When switching database providers make sure to delete and recreate your database migrations. I didn’t to begin with and it cost me a lot of time in changing down a strange error which this post covers.

Client Application Configuration

The Client application needs two configuration values for the address of the Identity Application and the address of the API Application. The following two lines need to be added to the application’s  appsettings.json file.

Then in the  Startup class, the Identity Server Address needs to be used in the  AddOpenIdConnect call.

Next, the configuration values need to be passed to the Angular application. This process ended up being harder to figure out that I had anticipated and turned into a full blog post on its own. See this post for the details. The code for all the changes will also be on GitHub in case you need to the the diff for the client application.

Publish to Azure

Right-click on the Identity Application and select Publish.

This will show the Publish screen which provides the option to publish to Azure. We don’t have an existing App Service so we are going to create a new one. This page in the official docs explains all the options available on the publish screen. Click the publish button to continue.

The next screen that shows is the Create App Service Screen. I used all the default values and created a new Resource Group and App Service Plan. Keep in mind that the resource group and plan will be reused for the remaining two applications we are looking deploy. The only thing that will change between the applications on this screen will be the App Name.

The services tab looks like the following.

Next in the additional resources box lets hit the plus button next to SQL Database since our group of applications is going to need somewhere to store data. This will take us to the Configure SQL Database screen.

Since I don’t already have a SQL Server setup I am going to hit the New button to add one. That results in the next screen where you enter a name for the server as well as a username and password. After entering the required information click OK.

This will put you back on the configure database screen with most of it filled out. Make sure to set the database name you want to use.

Finally back on the Create App Service screen, you will see all the resources that you selected and configured. When you are satisfied with what you see click the Create button and let Azure do its magic.

When it is done you will see the profile now listed on the Publish page.

The above needs to be repeated for both the API and Client Applications, but using the Resource Group and App Service plan created above. Each profile should use a unique application name.

Identity Application Azure Configuration

The Identity Application needs access to the database that we created above. This means we need to set the  DefaultConnection. The first step is to determine what the connection string should be. On the Azure Portal in your list of resources select the SQL database that we created above.

On the next page copy the provided connection string. Now navigate to the Identity App Service and under the Settings section select Application settings. Scroll down and find the Connection strings section and enter the copied value as the DefaultConnection.

Just above the Connection strings section we also need to enter a few values in the App settings section. For the Identity Application, we need the Twitter key and secret as well as the address of the client application. The following is a screenshot minus the actual values.

For the ClientAddress use the URL found in the Overview of the Client App’s App Service page.

API Application Azure Configuration

From the list of resources select the API App’s App Service page and in the Settings section select Application settings. In the App settings section add values for  IdentityServerAddress and  ClientAddress. As with the  ClientAddress above the URLs for each application can be found on their respective App Service pages.

Client Application Azure Configuration

From the list of resources select the Client App’s App Service page and in the Settings section select Application settings. In the App settings section add values for  IdentityServerAddress and  ApiAddress.

Wrapping Up

At this point, you should be able to load up the application at the client address provided by Azure and have a working application. Overall the deployment to Azure was pretty easy. Getting the applications prepared to be deployed was a bit more challenging and sent me down a couple of rabbit holes. The code in its final state can be found here.

Pass ASP.NET Core Appsettings Values to Angular

As part of getting my set of Identity Server 4 sample applications to run in Azure, I needed a way in the Client Application to pass some configuration values from  appsettings.json to the Angular front end that could be used both during server-side rendering and client-side rendering. This application is using JavaScriptServices. This solution may need tweaking if your application isn’t using JavaScriptServices. The code for the client application can be found here.

Settings

In this example, we need to pass the address of our Identity Server and API from  appsettings.json to Angular. The following is the settings file for this example.

Providing Configuration Data to Angular

In this application, Angular is loaded from the index action of the home controller. This view can be found in the  Views/Home folder in the  Index.cshtml file. The following is the file before any changes.

The first change needed is to inject the configuration data using ASP.NET Core’s DI system. Add the following two lines at the top of the file.

Now the configuration data from the application is available to this view. Next, we need to pull a couple of values out of the configuration data and pass it to the Angular application. To do this we are going to use the  asp-prerender-data tag helper. You can read more about it in the official docs. The idea is you construct an object which is then serialized and stored in  params.data. In our example, we are passing the URLs for the Identity and API Applications.

The above is creating a new object with an  apiUrl property and an  identityUrl property. The following is the full completed view for reference.

Angular Server-Side Boot

When Angular gets prerendered on the server-side it runs the code in the  boot.server.ts file. This is where we will set up the providers needed on for the server side prerender. This is the bit that I missed for the longest time when trying to get this example going. I kept trying to find a way to add the providers in the  app.module.server.ts file. Add any providers you need to the  providers constant. For example, the following is passing URLs for an API and Identity Server in addition to the defaults provided by JavaScriptServices.

Lower in the same file we can pass through the configuration values to the client side render as globals on the window object. To do this add a  globals property to the object being passed to the  resolve call.

The above will have the URLs as part of a single object, but you could have each URL as its own property if you prefer.

Angular Client-Side

Now that the server-side has providers for API URL and Identity URL we need to provide the client-side with the same capabilities. These changes will be in the  app.module.browser.ts file. The first step is to add providers for each.

Next, we need functions to return the URLs from the  url_Config property of the window object which the following two functions do.

Wrapping Up

With the above, you can now use your configuration values from ASP.NET Core and pass them through to your Angular application. In hindsight, the process is pretty simple, but getting to that point took me much longer to figure out than I would like to admit. I hope this post saves you some time!

Swagger and Swashbuckle: Disable Try It Out

In last week’s post, I walked through adding Swagger support to an ASP.NET Core 2 API using the Swashbuckle. One of the awesome things about Swashbuckle is it provides an integration with swagger-ui.

Try it out!

One of the features of the UI integration is the ability to invoke an end point using the “Try it out!” button. This feature is awesome during development but may not be something you want to allow, depending on the use case, for a production end point.

Disable Try it out!

I tried googling lots of different things to find the option to disable the “Try it out” button and had a really hard time finding an answer. It didn’t help that I want the button text to be “Try it now” for some reason. Thankfully it truly was a failure on my part and there is a provided way to disable “Try it out” and it is much more flex able than what I was initially looking for.

In the  Configure function of the  Startup class find the call to  app.UseSwaggerUI. Adding  c.SupportedSubmitMethods(new string[] {}); will completely disable “Try it out”. The following is the full call to  app.UseSwaggerUI just to provide context.

The great thing about the way this is set up if you can allow some actions and not others. For example, say you wanted to allow get actions but disable the rest. The following would allow for that.

One word of caution the above is case sensitive and if you use  Get instead of  get “Try it out” will remain disabled.