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.

Creating C# website in github

These are my notes on C# which is Microsofts server side language. By server side language this is a programming language that you can use to create applications that run on a web server. There is more to C# than this but for the sake of the notes I am preparing I want to focus on using C# as a server side language.

When you build a web site it consists of two basic parts which are the front end screens and the back end code. The front end screens are the html and javascript and css which work together to produce the visual look and feel and user interface. The back end code is the smarts of the application and web site the part of the web site that performs actions on behalf of users such as logging users into a information system or ordering products on a users behalf. The back end code is typically written in what is known as a third generation language such as Java, C# or python and is normally developed using a well established framework. In the case of Java you might write back end code using the Spring framework or the Struts framework. In the case of C# you would write back end code using the .NET core framework or the ASP.NET framework.

The recommended or future approach is to use the .NET core framework for building applications if you are aiming to build a cross platform (runs on linux) web site. The .net core framework is the better way of building web sites as it is the latest iteration of the .net frameworks and has been written from the ground up to be specifically designed for web sites. The .net framework (not core) is designed for more general usages such as building desktop applications. It is possible to mix and match the two by using a microservices architecture and communicating between the two using RPC’s (remote procedure calls).

When learning a new technology stack my advice is to try and learn it from the ground up by reading examples and using the command line interface rather than using the Visual Studio IDE. The reason for this is that this will give you a much more comprehensive knowledge of the framework you are dealing with plus it should encourage you to automate as much of the development process as you can once and to automate these processes early.

What I would suggest you do first is to come up with a basic architecture for your web site and to then set up source code control and a build script to establish a development environment. Not forgetting of course the all important install.sh script that will set up the local development environment on another developers PC. In this case I am looking to setup a cross between a traditional n-tier architecture and a microservices architecture which will provide eventually an API for front end systems to consume. I want to develop the site in such a way that it could be re-used for different purposes and I also want to write a site that others could reuse.

[ Front End (Razor Pages ] - [ Back End (.NET CORE) ]
[ Front End (SPA) ] - [ Back End (API) ]

The above diagram shows the basic architecture. The Back End, .NET Core and API will serve two different purposes. The Razor Pages and .NET Core pages are used to provide the Admin, back office user interface and a reference implementation of the application. The SPA and API is used to provide a consumer view of the application and development of the SPA could be done by another team with the interface to our team being the API.

I am not a big believer in heavy architecture diagrams as you can see but if you needed to you could expand that diagram out and in fact if you were creating this application in a corporate environment you would need to. You probably noticed that I haven’t included a database. This is intentional as I want to keep this architecture database neutral so that you could implement the project using the database that your hosting provider, cloud platform or organisation provides. For the first iteration of this application I will use SQLite. SQLite is a small fast lightweight database which is available in mobile phones and can also be used to serve small websites. The database is held in files and can be easily copied from one system to another making it easier to set up a consistent development environment when working with multiple developers.

I am using github as the location for the source code. Creating a location for the source code is an important first step as this will let you keep a history of changes that you have made, will let other developers help you on the project and also will let you set up automation tools to perform tasks such as building and testing your code.

Showing how to create a new repository
Creating a new repository

Once I click Create repository I have then created a new github repository. A repository is a place that you can save code into. You save code by creating a branch and then making a merge request. I will explain this process later but the concept of branching and merging is one of the major concepts you will need to grasp when working with github and git. Other source code management systems such as subversion have a different system which is more based around merging at the end of a project. Git works best by letting you create small merge requests that are incremently merged into the main codebase.

The repository itself at the moment is small only containing two files. The .gitignore provides a list of files that should never be checked into the repository. This might be binary files or files that are specific to a developers environment. The README.md file is mini WIKI that you can use to provide instructions on getting started with the project. It is a good convention in setting up a development environment to provide comprehensive instructions on getting started for new developers in the README.md file.