Created Bootstrap Dashboard in Angular

See: https://getbootstrap.com/docs/4.3/examples/dashboard/

I was able to recreate the get bootstrap dashboard example in Angular, the code can be found here: https://github.com/muncey/angular-bootstrap-admin

There were a few highlights:

  • The layout is broken down into header, nav (sidebar) and main components.
  • The feather.js and Chart.js scripts were not loading in time for the code to be available so I load these scripts in the app.component.
  • If creating again I would create a Resolve guard in future to wait for scripts to load.
  • If creating again I would call the nav component sidebar to be closer to what it does.

To load the scripts in the app.component I created a function loadScript.

  loadScript(src) {
    const script: any = document.createElement('script');
    script.src = src;
    return new Promise((resolve, reject) => {
        if (script.readyState) {
          script.onreadystatechange = function () {
              if (script.readyState === 'loaded' || script.readyState === 'complete') {
                  script.onreadystatechange = null;
                  return resolve(true);
              }
          };
        } else {
          script.onload = () => {
            return resolve(true);
          }
        }
        document.getElementsByTagName('body')[0].appendChild(script);
    });

This is based on the advice found here: http://www.lukasjakob.com/how-to-dynamically-load-external-scripts-in-angular/

I modify the ngOnInit as follows:

  ngOnInit() {
    this.loadScript('https://cdnjs.cloudflare.com/ajax/libs/feather-icons/4.9.0/feather.min.js')
      .then((result) => {
        console.log('feather loaded');
        this.scriptsLoaded++;
      });
    this.loadScript('https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js')
      .then((result) => {
        console.log('Chart loaded');
        this.scriptsLoaded++;
      })
  }

And wait for the scripts to load in app.component

<app-frontend-layout *ngIf="scriptsLoaded == 2"></app-frontend-layout>

I am pretty happy with this as it looks close to the example and didn’t take a long time to create. The next steps will be to look at creating an authenticated admin console.

Adding bootstrap to Angular

In todays article I am planning to show how to add the bootstrap CSS framework to Angular.

I am using the how to css example from w3schools as a starting point for my new web site.

https://www.w3schools.com/howto/howto_css_example_website.asp

To create the initial website I copy the HTML from the above example into the app.component.html file in my angular project.

Version 1 does not look that good because I have not at this stage applied any styles. To apply styles I go to the Bootstrap web site and follow instructions on the getting started page.

https://getbootstrap.com/docs/4.3/getting-started/introduction/

This is done by adding the CSS files and the Javascript files from the bootstrap web page into the index.html file in the Angular project.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<my-app>loading</my-app>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

The web site now looks a lot better.

But there are still some problems with the layout and the web site does not render as per the example from w3schools. To make it render more like the example I am using the Boostrap grid layout system and adding container to the top level components, plus using col-3 for the side column and col-9 for the main section.

This is using the grid system from boostrap

https://getbootstrap.com/docs/4.3/layout/grid/

The site is looking more like the example from w3schools and the next step is to setup the header section and the menu section.

The header section is easy to style as I simply reuse the .header styles from the w3schools example and paste these styles in to the app.component.css file.

/* Header/logo Title */
.header {
  padding: 80px;
  text-align: center;
  background: #1abc9c;
  color: white;
}

The original html already has the navbar class which is needed to generate a navigation bar in place.

<div class="navbar container">
  <a href="#" class="active">Home</a>
  <a href="#">Link</a>
  <a href="#">Link</a>
  <a href="#" class="right">Link</a>
</div>

There are some additional html tags that need to be added to be able to render a navigation menu similar to the example from w3schools.

The easiest way to do this is to copy the navigation structure from the Boostrap web site.

https://getbootstrap.com/docs/4.3/components/navbar/

<div class="navigation container">
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">My Site</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item active">
          <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#" tabindex="-1" aria-disabled="true">Link</a>
        </li>
      </ul>
    </div>
  </nav>
</div>

I also wrap the navbar in a div with classes of navigation and container. My website is now starting to look a lot more like the example.

I change the navbar to be bg-dark and then add in a background-color style for the navigation container that matches the navbar style.

  <nav class="navbar navbar-expand-lg navbar-light bg-dark">


/* Navigation */
.navigation, .navbar {
    background-color: rgb(52, 58, 64);
}

Finally I add in styles for the fakeimg and the footer as follows:

/* Fake image, just for this example */
.fakeimg {
  background-color: #aaa;
  width: 100%;
  padding: 20px;
}

/* Footer */
.footer {
  padding: 20px;
  text-align: center;
  background: #ddd;
}
Header, nav and main section
Footer section

This will create a starting point for developing websites using Angular and Boostrap. The code for this example can be found below:

https://github.com/muncey/angular-bootstrap-simple

Using Chart.js to display calculator results

In my last post I set up a calculator flow on an ASP.NET web page using Javascript to make an API call and to perform client side rendering, see: https://munceyweb.com/2019/06/06/using-javascript-to-invoke-an-api-in-asp-net-core/

What I want to show with this new post is how to take the results and to use Javascript in ASP.NET core to format and present the results as a stacked bar chart.

To do this I am using a javascript library called chart.js and you can find a link to Chart.js here: https://www.chartjs.org/

The first step then is to open the Index.cshtml page that I previously created and to add a reference to the chartjs javascript library.

Adding a reference to Chart.js

Once this is done I am then able to create the Javascript code to format and display the chart.

First add a canvas to the page to hold the chart.

Adding canvas

Next add in a generateBarChart function

generateBarChart function

Then enhance the onCalculate javascript method to generate the data needed for the bar charts.

So that should be it, so lets fire up the web site created in the last post, run dotnet run and then open https://localhost:5001 and put in my weekly rent.

Chart Generated

This generates a chart that displays the breakdown between repayments and expenses.

Using Javascript to invoke an API in ASP.NET core

I have used the dotnet command line to create a new ASP.NET core web site to host the customer portal which will allow for people to access the functionality of Get Homii via a web site.

dotnet new mvc -o GetHomii.CustomerPortal

This will generate a basic .net core web site with bootstrap and jquery and to get started I have created a form that renders as follows:

I am using the bootstrap library and it’s grid framework to render the form and I will be writing some javascript to process the click of the ‘Check your borrowing power’ button.

The first step is to open the page /Views/Home/Index.cshtml and just above the closing /div put the following code:

<script language="javascript">
/**
    Invokes the loanamount API to get a calculation response
    Returns a Promise
*/
const getCalculationResponse = (rent) => {
    const url = `https://gethomii-gateway.azurewebsites.net/api/v5/calculators/loanamount?rent=${rent}&isInvestor=N`;
    return window.fetch(url);
}
</script>

What the code is doing is creating a function called getCalculationResponse that will wrap the window.fetch that I setup in my previous post https://munceyweb.com/2019/06/06/using-the-javascript-console-to-test-a-api/. This function will return a promise which can be handled by the calling function. You can test the function operation at any stage by opening the developers console and typing the function name with a valid parameter. This is a good technique to remember as using the developers console in this way is a powerful way to debug any application that you are working on and to see what responses are coming back to API calls.

The other tab to be aware of is the Network tab as this will show you exactly what is being sent to and what is being retrieved from the API. This becomes very useful later on particularly when you are developing a new application and want to try out different scenarios without running the whole application. In the screen shot below I have invoked the API using the getCalculationResponse function and I am previewing the response to confirm operations.

The next step is to add a button handler for the check your borrowing power button. I have done this by adding the following code.

/**
    Button handler for the Check your borrowing power button 
*/
const onCalculate = () => {
    const rent = $('#rent').val();
    getCalculationResponse(rent)
        .then(response => response.json())
        .then(json => {
            console.log(json);
        })
}

This code will receive the response convert the response to json and will then write the response to the console.

Again this is a powerful programming technique and the approach I am taking is to build in a way where I test each step as I go rather than attempting to build the whole app first and then test it. I have found that this is the best way to build an app as it gives me an opportunity to test as much of the app as possible whilst building the application.

Now the next step is to add response handling code

        .then(json => {
            $('#results-PropertyValue').val(json.propertyValue);
            $('#results-InterestRate').val(json.interestRate);
            $('#results-Rent').val(json.rent);

            $('#calculateForm').addClass('d-none');
            $('#resultsForm').removeClass('d-none');
        })

Doing this will render the above form which will show the results of the calculation. There are a couple of additional steps that I want to take. The first is to implement the Check Again button and the second is create a Spinner to display when the calculation is taking place.

So lets go right ahead and do that. The Check Again button is easy to implement as it is simply a matter of hiding the results and showing the form again.

/**
    Button handler for the Check Again button
*/
const onGoBack = () => {
    $('#calculateForm').removeClass('d-none');
    $('#resultsForm').addClass('d-none');
}

For the Spinner I am using the boostrap spinner control https://getbootstrap.com/docs/4.3/components/spinners/

<div id="processing" class="d-none"> 
    <div class="spinner-grow" role="status">
        <span class="sr-only">Loading...</span>
    </div>
</div>

I have created a new element called processing when I want to show the element I use the removeClass jQuery function to remove the d-none class and to hide the element I add the d-none class back again. The onCalculate function now looks like the following:

/**
    Button handler for the Check your borrowing power button 
*/
const onCalculate = () => {
    const rent = $('#rent').val();
    $('#calculateForm').addClass('d-none');
    $('#processing').removeClass('d-none');
    getCalculationResponse(rent)
        .then(response => response.json())
        .then(json => {
            $('#results-PropertyValue').val(json.propertyValue);
            $('#results-InterestRate').val(json.interestRate);
            $('#results-Rent').val(json.rent);

            $('#calculateForm').addClass('d-none');
            $('#resultsForm').removeClass('d-none');
            $('#processing').addClass('d-none');
        })
}

Using the Javascript console to test a API

When I build a front end the first step is to test the API calls in the browser. The easiest way to do this is to use the google chrome developer tools and the window.fetch API.

The API I am using is the GetHomii API for calculating how much someone can borrow by using how much they believe they can pay each week or how much rent they are currently paying.

The API URL is:

https://gethomii-gateway.azurewebsites.net/api/v5/calculators/loanamount?rent=750&isInvestor=N

And the results are:

{"rent":750,"deposit":0,"monthlyRent":2860,"interestRate":4.865,"loanTerm":30,"propertyValue":493755,"LVR":0,"totalLoanValue":493755,"monthlyPayment":2610,"weeklyPayment":602,"minPrice":0,"maxPrice":493755,"adjustedRent":660}

The first step is to open google chrome and to put the url into the browser. This is to make sure that the API is available and ready to accept requests and return results.

As you can see the API is ready and the next step is to then press F12 to open the google developer tools and then to navigate to the Console tab on the developer tools.

First thing to do is to run the window.fetch('https://gethomii-gateway.azurewebsites.net/api/v5/calculators/loanamount?rent=750&isInvestor=N') command to make sure you can retrieve the information using Javascript. This will return Promise {pending} which is a Javascript promise that you will need to listen for in order to process the output of the API request. In order to make sure that I am getting a good result back, the last step in the developers console is to listen for and process the API response as follows window.fetch('https://gethomii-gateway.azurewebsites.net/api/v5/calculators/loanamount?rent=750&isInvestor=N').then(result => console.log(result))

This will result in the Response object being written to the Javascript console. What I am interested in is the body part of this object and the status as I can use these to prepare a response for the user based on the API request.

Installing Dot Net Core on a Mac

All the instructions for this can be found on the Microsoft web site at https://docs.microsoft.com/en-us/dotnet/core/tutorials/using-on-macos

I want to install dotnet core on my Mac so that I can perform development locally of an ASP.NET core web site and I am using Visual Studio Code and the command prompt.

First step is to go to this link https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/install and click download.

Once I clicked this link I then downloaded a .pkg file which I was then able to open to install and run the dotnet SDK. So to do that I opened a terminal prompt and run the dotnet command. I also ran the dotnet --help command so that I could see what options are available with the dotnet cli.

Getting Personal Access Tokens from Azure Dev Ops

This is a good article on how to use a Visual Studio Team System personal token with git. It basically functions as a password for accessing your git repositories if they are held in azure dev ops.

https://blog.velingeorgiev.com/vsts-personal-access-tokens-with-git-visual-studio-2017

And in good news, the menus for getting a personal access token work the same way in Azure Dev Ops.

Getting Personal Access Tokens from Azure Dev Ops

ASP.NET Core versus Spring Boot

I want to compare ASP.NET Core versus Spring Boot in order to see what the differences are between the two frameworks.

In order to do this I am creating a web app that will allow a user to log on via a web url and to then view and create users.

When users log on I want to generate a token which can be used to stay logged on and can be used to authenticate and authorise. I also want to generate a CSRF token to prevent CSRF attacks.