Tech Junkie Blog - Real World Tutorials, Happy Coding!: 2019

Tuesday, September 24, 2019

In our last post we created our business entities, in this post we are going to use our business objects to display information to the users.  I this post we are going to show the accounts to the users.  In the previous posts we have been setting up the environment the plumbing sort of speak.  Starting now we are going to build the application.  The first thing we want to do is counter-intuitive, we are going to take the database out of the equation and start using mock data to get so that we can see how our application will run.

In our previous post we created some user stories.  In this post we are going to work on one of the stories:


  • As a user I should be able to view my accounts. (2 pts)

It's a simple process, but we know exactly what we have to do with user stories.  It's a different mindset than the traditional requirements.  The typical requirement that you are used to seeing is

1.1.1 System shall allow the user to view his/her accounts

It's basically saying the same thing, but the first one the user stories is in plain English and it's a lot easier to comprehend.  You can take it to the business user, the web designer, or the web developer and it's easily understood.  That's the benefit of Agile development. 

First let's take the Iffe out of the account.js file so that it's easier to work with and then we want to make changes to the bankController.js file

Here is how the account.js file should now look like.

function Account(balancetype) {
    this.balance = balance;
    this.type = type;
}

Account.prototype.deposit = function (d) {

    this.balance = this.balance + d;
    return this.balance;
}

Account.prototype.withdrawal = function (w) {
    this.balance = this.balance - w;
    return this.balance;
}


function inherits(baseClasschildClass) {
    childClass.prototype = Object.create(baseClass.prototype);
}

function Premium(balancetype) {
    this.balance = balance + (balance * .05);
    this.type = type;
}


inherits(AccountPremium);

Premium.prototype.transfer = function (fromtoamount) {
    from.balance -= amount;
    to.balance += amount;
    from.rebalance();
    to.rebalance();
}

Premium.prototype.deposit = function (d) {
    this.balance = this.balance + d;
    this.balance = this.balance + (this.balance * .05);
    return this.balance;

}
Premium.prototype.rebalance = function () {
    this.balance += this.balance * .05;
}

Here is the code we change in the bankController.js file


(function () {
    'use strict';

    angular.module('bankController', [])
        .controller('bankController', ["$scope"function ($scope) {
            $scope.accounts = [new Account(1000'Checking'), new Account(10000'Saving'), new Premium(100000'Premium Checking')];
            console.log($scope.accounts);
        }]);

})();

Wednesday, September 18, 2019

In our previous post we created some mockups, now we are going to create some user stories so that we can started development with some idea of what should be included in the application.  This is just a quick planning session.

We'll pretend like we are running a Sprint, we can think of this as a very loose Sprint planning.

Sprint 1 User Stories;

  • As a user I should be able to view my accounts. (2 pts)
  • As a user I should be view my user profile. (1 pt)
  • As a user I should be able to view my account details. (2 pts)
  • As a user I should be able to view my past transactions. (1 pt)
  • As a user I should be able to view my upcoming transactions ( 1 pt)
  • As a user I should be able to search my transactions (2 pts)
Sprint 2 User Stories:
  • As a user I should be able to transfer money from my account (1 pt)
  • As a user I should be able to withdrawal money from my account (1 pt)
  • As a user I should be able to deposit money from my account (1 pt)
  • As a user I should be able to withdrawal money from my account (1 pt)

Tuesday, September 17, 2019

In the previous post we created the JavaScript business objects in our AngularJS application.  While that's great and all we should we really take a step back create some rough mockups of our banking application so that we will know what we will be building.

First let's mock up the home page:

Home page mockup






















On our home page we have a profile section were we can access our account/profile. Then we have the ACME bank logo/branding, and finally the accounts that we have in the bank.

The next mock-up is the the Accounts Details page, when we click on one of the accounts:

Account Details page mockup




























As you can see from the mock-up it's pretty straightforward.  You have an identification of the account, then a display of upcoming  transactions, and past transactions.  There's also a search box for searching of transactions.

Finally we have the Money Transfer screen which enables the users to transfer money into and out of the account.  It just has the basic information, where the money is coming from, where it's going to, the transfer date, the amount and the transfer button.

Money Transfer mockup



















As you can see the mock-up is pretty simple and easy to change.  Actually it's just pen and paper.  I am a big fan of low-fidelity design.  Meaning simple and low effort.  We can change it anytime.

Previous: AngularJS SPA: Building The Bank Application JavaScript Objects (Business Entities)

In the last few posts we have been working with our models and retrieving the data natively in the application, but most of the project you will work with in real life will probably have you call some kind of api with an endpoint.  In this post we are going to substitute the products call what we made with an api.

Here are steps to create our first Api:

1. First we want to set up our application to use postman to test out our api. To do that right-click on the project and click on "Properties", in Properties screen click on "Debug" and uncheck "Launch browser" and make a note of the port number of the App URL.  We will make the api calls with postman initially to make sure that our api works.  Postman has become pretty popular with api development because it allows us to make api calls and see the results.  You can get postman here

https://www.getpostman.com/downloads/ I would get the desktop version because it's more robust.





















2. Now we are ready to create a ProductController to be our api controller, Asp.NET Core has the api control built-in so we don't have to do anything special for a controller to be a web api controller. So create a file call ProductController in the Controllers folder.  The ProductController should have the following code

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NorthwindCafe.Web.Data;
using System;

namespace NorthwindCafe.Web.Controllers
{
    [Route("api/[Controller]")]
    public class ProductController : Controller
    {
        private readonly  IProductRepository _repository;
        private readonly  ILogger _logger;

        public ProductController(IProductRepository repository, ILogger logger)
        {
            _repository = repository;
            _logger = logger;
        }

        [HttpGet]
        public IActionResult Get()
        {
            try
            {
                return Ok(_repository.GetProducts());
            }
            catch (Exception ex)
            {
                _logger.LogError($"Get products failed {ex}");
                return BadRequest("Get products failed");
            }
        }
    }
}

The code above is pretty straightforward.  You have the define private variables _repository and _logger for the repository to hold the injected objects in the constructor. Then you define a method call Get with the decorator [HttpGet] to handle get requests.  The Get() method returns the list of products and retruns Ok = 200 status code if everything is ok and returns a 400 error status code if there's an exception.  The other important thing is the [Route("api/[Controller]")] decorator.  This is what you typed into the browser.  So for this route you would type http://localhost:50051/api/product into Postman.

3. So now we are ready to test our code in Postman, first we need to run our code, press CRTL+F5
Then select "GET" method on Postman call, type in the URL localhost:50051/api/product and you will see the list of products returned in Json, usually the resource in this product should be pluralize, but I forgot the s.  So the URLs should be localhost:<port>/api/products but since it's just development we can let it slide.  However, if you work with other people you might want to pluralize it.


Sunday, September 8, 2019

The "Server Explorer" tool in Visual Studio 2013 is a good tool at your disposal if want to interact with the database in GUI environment.  To create a new data connection to the database in the "Server Explorer" perform the following actions:

  1. Click on "Server Explorer" tab in the left hand side, then click on "Add Connection"

2.  In the "Data source" list box, select "Microsoft SQL Server", for data provider select ".NET Framework Data Provider for SQL Server", then click "Continue"


Saturday, September 7, 2019

There are times when you are handed over an .mdf file and are tasked to create a new database out of it.  There's no log just an .mdf file.  The easiest way to create a new database is to use the query editor in SQL Management Studio type the following into the Sql Query window

CREATE DATABASE Northwind
 ON (name= 'Northwind',
 filename = 'C:\Northwind.mdf')
FOR ATTACH_REBUILD_LOG;

The query above will create a new database for you call "Northwind", all you have to do is specify the location of the .mdf file and the "FOR ATTACH_REBUILD_LOG" will rebuild the log for you. You might run into a "Access denied" error but it's a permissions issue. Make sure the user that is running the query has permission to the file.


Saturday, August 31, 2019

When you need to do an insert into multiple database table you need to the get the ID of the insert so that you could use that ID for the next insert. Here is how you would do that with the Scope_Identity()which gets the last inserted ID back to you if you execute your query with the ExecuteScalar() method.

                SqlCommand cmd = new SqlCommand("INSERT INTO Users (" +
                    "LoginName," +
                    "FirstName," +
                     "LastName," +
                     "Password," +
                     "Email," +
                     "DOB," +
                     "Sex" +
                     ") VALUES (" +
                    "@Email," +
                    "@FirstName," +
                     "@LastName," +
                     "@Password," +
                     "@Email," +
                     "@DOB," +
                     "@Sex)" + 
                     " Select Scope_Identity();",conn);


Wednesday, August 28, 2019

A lot of examples on logging in ASP.NET Core shows you how to add console logging to your ASP.NET Core application.  But it's pretty useless in a real world application.  What you really want is to write to a file or a database.  There's a package called Microsoft.Extensions.Logging.Log4Net.AspNetCore that will make your application use log4Net.

Here are the steps to use log4Net:

1.  Right click on your NorthwindCafe.Web project and select "Manage NuGet Packages"

Managing Nuget Packages With Visual Studio





























Tuesday, August 27, 2019

In the previous post we successfully used the repository pattern to retrieve products from the database and set them to the Product objects.

In this post we are going to display those products in the Index.cshtml page

Here are the steps:

1. Open the Index.cshtml page in the Views/Home folder
2. Now declare a model of enumerable of products at the top of the page like this 

@model IEnumerable<Product>

You will noticed that the Product class has a red underline on it, when you mouse over Visual Studio will say that the Product reference is missing

Mouseover to find missing reference in Visual Studio











Monday, August 26, 2019

Now that we have our data in the database it is time for us to show the data to our users and we going to use the repository pattern to show our data.  A repository pattern is basically a conduit between the database and our business objects that has built in CRUD operations.  It is ideal for LOB applications.  There are many websites and books that explains the repository pattern better than I do.  Feel free to explore them.

Here are the steps to create a product repository for the products in the database:

1. Create a folder in the NorthwindCafe.Web solution call "Data"
2. Create an interface call IProductRepository in the "Data" folder, this will be the interface that we implement our repository from.

The code of the IProductRepository should look like this

using NorthwindCafe.Web.Models;
using System.Collections.Generic;

namespace NorthwindCafe.Web.Data
{
    public interface IProductRepository
    {
        IEnumerable<Product> GetProducts();
    }
}

Friday, August 23, 2019

In the previous blog we created the NorthwindCafe database with Entity Framework Core.  Now we are going to seed the database so that we can work with the data.

Here are the steps to seed the NorthwindCafe database:

1.  Create a file call DBInitializer in the NorthwindCafe.Web  "Models" folder, in the file type in the following code


using System.Linq;

namespace NorthwindCafe.Web.Models
{
    public class DbInitializer
    {
        public static void Initialize(NorthwindContext context)
        {
            context.Database.EnsureCreated();

            if(context.Categories.Any())
            {
                return;
            }

            var categories = new Category[]
            {
               new Category {Name = "Coffee", Description="Coffee", Products = new Product[] { new Product { Name = "Dark Roast", Description = "Dark Roast", Price = 2.0M } } },
               new Category {Name = "Tea", Description="Tea", Products = new Product[] { new Product { Name = "Chai", Description = "Chai", Price = 1.5M } } },
               new Category {Name = "Pastry", Description="Pastry", Products = new Product[] { new Product { Name = "Cupcake", Description = "Cupcake", Price = 1.25M } } },
               new Category {Name = "Food", Description = "Food", Products = new Product[] { new Product  { Name = "Hamburger", Description = "Hamburger", Price = 5.0M } } }
            };

            foreach (var c in categories)
            {
                context.Categories.Add(c);

            }

            context.SaveChanges();
        }
    }
}


Thursday, August 22, 2019

In this post will are going to finally create the database that we have been preparing for in the last previous blog posts.  It's a two step process, first you have to add the NorthwindContext to the application in the Startup class, then you have to run the Entity Framework migration tool.

Here are the steps to create your NorthwindCafe database:

1.  Open the Startup.cs file, then type the following lines in the ConfigureServices method
 
            var connectionString = Configuration["Data:NorthwindContextConnection"];

            services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(connectionString));

The line above gets the connection string from the appSettings.json file that we've created earlier. Then use the AddDbContext method in the services instance.  Dependency injection will take care of the plumbing for you.  Using lamba expression we tell the Entity Framework to use the Sql Sever provider for Entity Framework core.

Make sure you have the following namespaces in your Startup class

using NorthwindCafe.Web.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;


Wednesday, August 21, 2019

In our previous post we created the models for our Northwind Cafe application.  In this blog we will create the DbContext class which is the conduit between your entity classes and the database.  Think of it as a bridge that the database and the entity framework has to cross to get to each other.

Follow the steps below to create the NorthwindContext:

1. Create a class in Models folder call NorthwindContext

Tuesday, August 20, 2019

In the previous post we added a configuration file call appSettings.json file to store our connection string to the database that we are going to create through Entity Framework.  Even though Microsoft provides us with the Northwind database, we don't really want to use it because it's outdated.  We are going to modernize the database by rebuilding it from scratch with the code first approach with Entity Framework Core.  If you look at the existing Northwind database you will see that there's a lot of redundant data and tables.  For example there are tables for Customers, Employees, Suppliers and Shippers.  Those are basically roles, and we will take care of those roles later on in the series using the Identity framework.  What we are going to do is start out simple with just the Products, Categories, Orders, OrderDetails table and add on to those tables as we progress in building the application.

Wednesday, August 14, 2019

I believe the last iPhone I owned was an iPhone 3?  I don't remember, but it was a while back.  It was actually a very good phone.  I love Apple products, but the price just seems to increase on each iterations and the features were less and less with each upgrades.  I found myself with a life or death situation.  Should I go to the dark side (Darth Vader breathing) an "Andriod Phone".  Oh my god, stop it I said to myself...lol  But at the time the Android phones were getting good.  So I decided to take the plunge and never looked back.

Anyways back to the present day, I have Apple envy because it has this great ecosystem, that I can't tapped into because I don't have an iPhone.  That is until I got the new iPad, which is the cheaper version of the iPad, but it's not really cheap at all it's the best iPad out there for the price.  I got it so that I can watch movies and read magazines while I was commuting.  What I found surprising was that once again I am tapped into the Apple ecosystem with my iPad.  I can sign up to all the new services that Apple is touting.  I am currently subscribed to News+ because I am a news junkie.  But if you think about it most of the new Apple services are ideal for consumption on a bigger screen.

Since I have unlimited plan on my Android phone, I used it as a hotspot for my iPad.  Put my iPad in a stylish mini bag, and I am good to go.  My iPad became a substitute for an iPhone, for less than 1K that's not bad. I know what you are thinking an Android phone and an iPad working together?  That's like the rebellion working with the empire.  But that's the closest thing to world piece right now and we should take it :)



If you want to contribute to my retirement fund you can buy it here on Amazon, it's actually a really good tablet for the price.  I mean the screen is amazing.  I got the older model and I am still using everyday. iOS is awesome, that's the one thing I like about the empire's product (I mean Apple's product).



Monday, August 5, 2019

Now that we have most of our static contents taken care of for our application, meaning we did everything we could without a database.  It's time to create our database.  But before we can do that we need a place to store our connection string to the database.  Usually we just store the connection string in the web.config file in our web application.  However, since ASP.NET Core is trying to break free from the old way of doing things, there's a new way to store configuration information which is more flexible the old web.config way.  As usual it also requires more work.

Friday, August 2, 2019

In this post we will add Tag Helpers support for our application.  Tag Helpers are programmable attributes that you can use throughout the application.

Follow the steps below to enable tag helpers:

1.  Right-click on the "Views" folder and create a "View Imports" file

Thursday, August 1, 2019

In this tutorial we will add icons to your navbar.  In the previous tutorial we added a responsive layout with bootstrap.  In this post we will add some icons to your navigation.  Font-Awesome gives you professional looking vector graphics, which are implemented using CSS.

Wednesday, July 31, 2019

In our previous blog we created a simple _Layout.cshtml file that does not have any markup just to make things simple.  In this blog we will use Bootstrap to make the layout look more professional and responsive, so that it can be viewed in any screen size.  The previous layout looks like screenshot below.

Tuesday, July 30, 2019

In this blog post we are going to add the jQuery, and bootstrap libraries to our ASP.NET Core application.  Normally we will use NuGet to bring in these libraries but ASP.NET Core gives you the option to use bower.json file to configure the dependencies that you will need on the client-side using NPM in the backend.

Here are the steps to import the client-side dependencies into our project:

1. First let's add bower.json file of the "NorthwindCafe.Web" project, Right-click on the NorthwindCafe.Web project and add a file called bower.json in the project

2.  Open the bower.json file the markup should look like this

{
 "name": "asp.net",
 "private": true,
 "dependencies": {
 }
}

Monday, July 29, 2019

In ASP.NET MVC there is a default layout file that the application use when one exists.  If you look at the markup at the top of the "Index.cshtml" file you will see that there is a markup to specify the layout of the page in the code below.

@{
    Layout = null;
}

The code above tells ASP.NET MVC to not assign any layout to the page because it is being set to null. In this blog we will build on our existing NorthwindCafe.Web  project and add a default layout view to the project so that each page in the project will have a common layout.  This is similar what you would a master page for in web forms.

Friday, July 26, 2019

In the previous post we have enabled MVC on our application.  Now we want to add our first MVC controller and view to test out verify that MVC is working.  We also have to tell ASP.NET Core what pattern to look for when looking for our controllers and views.


Thursday, July 25, 2019

In this post we will go over the process of enabling ASP.NET MVC in our application.  Just like static files, in order for us to use MVC in our application we have to tell ASP.NET Core to use Mvc in the Startup.cs file.  We will continue to use the application "NorthwindCafe" that we used in our previous blog.

Here are the steps to add MVC to your application:

1.  Open the Startup.cs file, then in "Configure" method type in the following to enable MVC

       
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            app.UseMvc();
        }

Wednesday, July 24, 2019

As I have mentioned before ASP.NET Core decouples the application from the infrastructure as much as possible.  Therefore, you have to tell it exactly what you want in your project.  In this blog post we are going to tell ASP.NET that we want to serve static html files in our application.

Here are the steps to serve static files in our ASP.NET Core application.

1.  Open the "NorthwindCafe.Web" project, then click on the "Startup.cs" file in the project.  You will see the following markup in the Configure method

        public void Configure(IApplicationBuilder app)
        {
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

2.  Go into the Configure method, remove the existing code and type in the following code
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseDefaultFiles();
            app.UseStaticFiles();
        }

Monday, July 22, 2019

Technology has moved at a breakneck speed, after working with ASP.NET Core for a while, I realized that my ASP.NET MVC blog articles have become outdated.  Don't get me wrong, MVC is still a very big part of ASP.NET Core, but that's the thing it's just a part of it.  ASP.NET Core has decoupled the infrastructure from the application.  You can deploy your web app on Docker imagine that!  No longer is IIS your primary means of hosting your ASP.NET application.

However, with this new freedom comes added complexity.  No longer can you just drag and drop components into your design surface.  Those days are long gone.  This post ist meant to ease your way into ASP.NET Core.  I will using the release candidate version two of ASP.NET Core for this post and other subsequent posts.  I found out that I can't really follow my blog posts anymore to create the project with the latest version which is 2.1.  Don't use 2.2 for now because there's still not a lot of documentation on it.  So here is the updated version  I will be using Visual Studio 2017 for my development.  You can use the command line interface and notepad to develop your ASP.NET Core application.  But, I think that borders on insanity.

Wednesday, January 9, 2019

Up until this point all we did was take care of the plumbing, MongoDB for the database, AngularJS as the application framework, expressJS for hosting, and Heroku as deployment infrastructure in the cloud. Whew! It feels like I am spitting out development hastags and buzzwords.  But, you know what they always say "it takes a village to build a SPA application".  Well they didn't say that, but they should! Who are they anyways?  The software engineer gods?  Or god forbid the mythical "full stack developers!!  Fear them the full stack developers!  But I don't know who they are, you ask.  Well they are just awesome! God says.  They are 10x!  Wow 10x, you said to yourself.  They must be good!  Hahaha  I just love the buzzwords.  It's entertaining.  I would never say I am a full stack developer.  I am just a developer who knows a lot of stuff.

In this post we are going to take a step back and start working on the actual application and take the plumbing out of the equation for a while.

As with any application at the center of it all is the question.  What does the application do?
Since our application is banking application, we will create objects that are in the banking domain.  This is called a domain driven design.  We are not going to follow the domain driven design (DDD) to a T, but we will follow the spirit of it.

Tuesday, January 8, 2019

In this post we are going to install Ninject which is a lightweight IOC container.  You can think of an IOC container as a magic toolbox that gives you the tools that you need when you need it.  Hence its called dependency injection, meaning it injects the dependencies that you need.  As with any IOC container there needs to be a mapping between the interfaces and the implementation.  That's where Ninject comes in.

First let's install Ninject with Nuget. here are the steps:

1. Open the Nuget Management Console and type in the following command

Install-Package Ninject -Version 3.2.2
Install-Package Ninject.Web.Common -Version 3.2.2
Install-Package Ninject.Mvc3 -Version  3.2.1

Search This Blog