Digital logic gates

Digital logic gates is an electronic component which results perticular ouput after implementing its logic on the input signals. Digital logic gates are the basic building block of any digital circuits. It can have one or more than inputs and exactly one output. Inputs or outputs signals are two types of voltage – High(1) voltage and Low(0) voltage, it can also be represented as On(1) and Off(0) or True(1) and False(0). Logic gate’s inputs and output represented using Truth table. Truth table helps us to understand the behaviour of logic gates. Truth table shows all possible input combinations and resultant output on each input combinations. For example a 2-input logic gates will have four(22) input combinations – (0,0), (0,1), (1,0), (1,1). Therefore, 3-input logic gate will have eight(23) input combinations.

Basic gates:

AND gate:

AND gate is an electronic circuit where output will be 1 when all its inputs are 1 otherwise 0. A 2-input AND gate can be represented as:-

Truth Table:

Input-1 Input-2 Output
0 0 0
0 1 0
1 0 0
1 1 1

Using this Truth table we can easily perform AND operation on two binary numbers. If we want to perform AND operation on numbers with different base e.g. Octal, Decimal or Hex then, we can first convert the number to binary number and then do the AND operation. We can use online Any base converter tool to convert numbers to binary equivalent. For example, if we want to do AND on two decimal numbers 17 & 45 :-

17 (decimal) = 010001 (binary)
45 (decimal) = 101101 (binary)
-----------------------------------
        (AND)  000001 = 1 (decimal)

We can use online AND calculator tool to calculate AND on Octal, Decimal, Hex or Binary numbers.

OR gate:

OR gate is an electronic circuit where output will be 1 when any one inputs are 1 otherwise 0. A 2-input OR gate can be represented as:-

Truth Table:

Input-1 Input-2 Output
0 0 0
0 1 1
1 0 1
1 1 1

Using this Truth table we can easily perform OR operation on two binary numbers. If we want to perform OR operation on numbers with different base e.g. Octal, Decimal or Hex then, we can first convert the number to binary number and then do the OR operation. We can use online Any base converter tool to convert numbers to binary equivalent. For example, if we want to do OR on two decimal numbers 18 & 46 :-

18 (decimal) = 010010 (binary)
46 (decimal) = 101110 (binary)
-----------------------------------
         (OR)  111110 = 62 (decimal)

We can use online OR calculator tool to calculate OR on Octal, Decimal, Hex or Binary numbers.

NOT gate:

NOT gate is a single input electronic circuit where output will be 1 when input is 0 and output will be 0 when input is 1. A NOT gate can be represented as:-

Truth Table:

Input Output
0 1
1 0

Using this Truth table we can easily perform NOT operation on binary numbers. If we want to perform NOT operation on numbers with different base e.g. Octal, Decimal or Hex then, we can first convert the number to binary number and then do the NOT operation. We can use online Any base converter tool to convert numbers to binary equivalent. For example, if we want to do NOT on decimal number 46 :-

46 (decimal) = 101110 (binary)
-----------------------------------
        (NOT)  010001 = 17 (decimal)

We can use online NOT calculator tool to calculate NOT on Octal, Decimal, Hex or Binary numbers.

Universal gates:

NAND gate:

NAND gate is an electronic circuit where output will be 1 when any of the inputs are 0 otherwise 1. NAND gate is just opposite of AND gate, it can be created using AND gate followed by a NOT gate. A 2-input NAND gate can be represented as:-

Truth Table:

Input-1 Input-2 Output
0 0 1
0 1 1
1 0 1
1 1 0

Using this Truth table we can easily perform NAND operation on two binary numbers. If we want to perform NAND operation on numbers with different base e.g. Octal, Decimal or Hex then, we can first convert the number to binary number and then do the NAND operation. We can use online Any base converter tool to convert numbers to binary equivalent. For example, if we want to do NAND on two decimal numbers 17 & 45 :-

17 (decimal) = 010001 (binary)
45 (decimal) = 101101 (binary)
-----------------------------------
       (NAND)  111110 = 62 (decimal)

We can use online NAND calculator tool to calculate NAND on Octal, Decimal, Hex or Binary numbers.

NOR gate:

NOR gate is an electronic circuit where output will be 1 when both the inputs are 0 otherwise 0. NOR gate is just opposite of OR gate, it can be created using OR gate followed by a NOT gate. A 2-input NOR gate can be represented as:-

Truth Table:

Input-1 Input-2 Output
0 0 1
0 1 0
1 0 0
1 1 0

Using this Truth table we can easily perform NOR operation on two binary numbers. If we want to perform NOR operation on numbers with different base e.g. Octal, Decimal or Hex then, we can first convert the number to binary number and then do the NOR operation. We can use online Any base converter tool to convert numbers to binary equivalent. For example, if we want to do NOR on two decimal numbers 17 & 45 :-

17 (decimal) = 010001 (binary)
45 (decimal) = 101101 (binary)
-----------------------------------
        (NOR)  000010 = 2 (decimal)

We can use online NOR calculator tool to calculate NOR on Octal, Decimal, Hex or Binary numbers.

XOR gate:

XOR gate is an electronic circuit which will give output 1 if either, but not both, of its two inputs are 1 otherwise 0. A XOR gate can be represented as:-

Truth Table:

Input-1 Input-2 Output
0 0 0
0 1 1
1 0 1
1 1 0

Using this Truth table we can easily perform XOR operation on two binary numbers. If we want to perform XOR operation on numbers with different base e.g. Octal, Decimal or Hex then, we can first convert the number to binary number and then do the XOR operation. We can use online Any base converter tool to convert numbers to binary equivalent. For example, if we want to do XOR on two decimal numbers 17 & 45 :-

17 (decimal) = 010001 (binary)
45 (decimal) = 101101 (binary)
-----------------------------------
        (XOR)  111100 = 60 (decimal)

We can use online XOR calculator tool to calculate XOR on Octal, Decimal, Hex or Binary numbers.

XNOR gate:

XNOR gate is an electronic circuit which will give output 0 if either, but not both, of its two inputs are 1 otherwise 1. XNOR gate is just opposite of XOR gate, it can be created using XOR gate followed by a NOT gate. A XNOR gate can be represented as:-

Truth Table:

Input-1 Input-2 Output
0 0 1
0 1 0
1 0 0
1 1 1

Using this Truth table we can easily perform XNOR operation on two binary numbers. If we want to perform XNOR operation on numbers with different base e.g. Octal, Decimal or Hex then, we can first convert the number to binary number and then do the XNOR operation. We can use online Any base converter tool to convert numbers to binary equivalent. For example, if we want to do XNOR on two decimal numbers 17 & 45 :-

17 (decimal) = 010001 (binary)
45 (decimal) = 101101 (binary)
-----------------------------------
       (XNOR)  000011 = 3 (decimal)

We can use online XNOR calculator tool to calculate XNOR on Octal, Decimal, Hex or Binary numbers.

Configure Ivy to dynamically download and install Ant extensions

We all know that Apache Ant is a popular Java build management system. But, in many cases Ant alone is not enough for extended build tasks and we have to install Ant extensions or plugins. For example, tasks like – “loop through all the files available in a directory”, can be done quite easily using Ant-Contrib extentions. For this, we have to download ant-contrib.jar to a directory, say /usr/share/ant-extensions/lib and create a task definition in the Ant project file.

<taskdef resource="net/sf/antcontrib/antlib.xml">
    <classpath>
        <pathelement location="/usr/share/ant-extensions/lib/ant-contrib.jar"/>
  </classpath>
</taskdef>

Complete Ant project file may look like:-

<project name="List files" default="list-files" basedir=".">
    <property name="ant-contrib-file" value="/usr/share/ant-extensions/lib/ant-contrib-1.0b3.jar"/>
    <property name="dir-to-list" value="/usr/share/libs"/>
 
    <target name="load-ant-contrib" description="Load ant-contrib Ant tasks">
        <taskdef resource="net/sf/antcontrib/antlib.xml">
            <classpath>
                <pathelement location="${ant-contrib-file}"/>
            </classpath>
        </taskdef>
        <property name="ant.contrib.loaded" value="true"/>
    </target>
 
    <target name="list-files" depends="load-ant-contrib" description="List jar files in a directory">
        <for param="file">
            <fileset dir="${dir-to-list}" includes="*.jar"/>
            <sequential>
                <echo message="@{file}"/>
            </sequential>
        </for>
    </target>
</project>

In the above example, we have to manually manage the dependencies and their versions. Well, there is a better solution using Apache Ivy dependency manager wherein Ivy can automatically download Ant dependencies from maven repository. We just have to specify the name of the dependency along with it’s version in the Ant project file.

Ivy module dependencies can be described in an xml file called ivy.xml. ivy.xml file contains the description of the dependencies of a module, its published artifacts and its configurations. Sample ivy.xml file with only ant-contrib dependency may look like:-

<ivy-module version="2.0">
    <info organisation="my-org" module="my-module1"/>
    <dependencies>
        <dependency org="ant-contrib" name="ant-contrib" rev="1.0b3"/>
  </dependencies>
</ivy-module>

We can also create this xml using echoxml Ant task:-

<echoxml file="ivy.xml">
    <ivy-module version="2.0">
        <info organisation="my-org" module="my-module1"/>
        <dependencies>
            <dependency org="ant-contrib" name="ant-contrib" rev="1.0b3"/>
        </dependencies>
    </ivy-module>
</echoxml>

We can specifiy multiple dependencies in ivy.xml and Ivy will make that dependencies available in the Ant task. The only jar file we have to include in the Ant task is ivy.jar, all other dependencies will be managed automatically by Ivy. We can also download ivy.jar dynamically using the Ant get Task:-

<get src="http://repo1.maven.org/maven2/org/apache/ivy/ivy/2.4.0/ivy-2.4.0.jar"
     dest="${user.home}/.ivy2/jars"
     usetimestamp="true"/>

At this point Ivy module dependencies has been configured. Ivy provides retrieve task, which then reads from ivy.xml and copies resolved dependencies in configurable file system location. Configure artifactproperty followed by retrieve task which then sets loaded dependency in Ant property, which will be required to load dependencies using taskdef Ant task. retrieve and artifactproperty task can be configured as:-

<ivy:retrieve/>
<ivy:artifactproperty name="[module].[artifact]" value="lib/[artifact]-[revision].[ext]"/>

The ant-contrib jar file will be loaded in Ant property ant-contrib.ant-contrib. Ivy not needed after this, now you can just load ant-contrib task using taskdef Ant task like this:-

<taskdef resource="net/sf/antcontrib/antlib.xml">
    <classpath>
        <pathelement location="${ant-contrib.ant-contrib}"/>
    </classpath>
</taskdef>

With all the above things tied in together, the complete Ant(v1.9.4) project file looks like:-

<project name="Ivy dependency example" default="list-files" basedir="." xmlns:ivy="antlib:org.apache.ivy.ant">
    <property name="ivy.install.version" value="2.4.0"/>
    <property name="ivy.jar.dir" location="${user.home}/.ivy2/jars"/>
    <property name="ivy.jar.file" location="${ivy.jar.dir}/ivy-${ivy.install.version}.jar"/>
    <property name="dir-to-list" value="/usr/share/libs"/>
 
    <target name="download-ivy" unless="ivy.downloaded" description="Download Ivy jar files">
        <mkdir dir="${ivy.jar.dir}"/>
        <get src="http://repo1.maven.org/maven2/org/apache/ivy/ivy/${ivy.install.version}/ivy-${ivy.install.version}.jar"
             dest="${ivy.jar.file}"
             usetimestamp="true"/>
    </target>
 
    <target name="check-ivy-downloaded" description="Check if Ivy is already downloaded">
        <condition property="ivy.downloaded">
            <and>
                <available file="${ivy.jar.file}"/>
            </and>
        </condition>
    </target>
 
    <target name="load-ivy" depends="check-ivy-downloaded,download-ivy" unless="ivy.loaded" description="Load Ivy Ant tasks">
        <path id="ivy.lib.path">
            <fileset dir="${ivy.jar.dir}" includes="*.jar"/>
        </path>
        <taskdef resource="org/apache/ivy/ant/antlib.xml" uri="antlib:org.apache.ivy.ant" classpathref="ivy.lib.path"/>
                <echoxml file="ivy.xml">
                        <ivy-module version="2.0">
                                <info organisation="my-org" module="my-module1"/>
                                <dependencies>
                                        <dependency org="ant-contrib" name="ant-contrib" rev="1.0b3" transitive="false"/>
                                </dependencies>
                        </ivy-module>
                </echoxml>
        <property name="ivy.loaded" value="true"/>
    </target>
 
    <target name="retrieve" depends="load-ivy" description="Retrieve dependencies">
        <ivy:retrieve/>
        <ivy:artifactproperty name="[module].[artifact]" value="lib/[artifact]-[revision].[ext]"/>
    </target>
 
    <target name="load-ant-contrib" depends="retrieve" unless="ant.contrib.loaded" description="Load ant-contrib Ant tasks">
        <taskdef resource="net/sf/antcontrib/antlib.xml">
            <classpath>
                <pathelement location="${ant-contrib.ant-contrib}"/>
            </classpath>
        </taskdef>
        <property name="ant.contrib.loaded" value="true"/>
    </target>
 
    <target name="list-files" depends="load-ant-contrib" description="List jar files in a directory">
        <for param="file">
            <fileset dir="${dir-to-list}" includes="*.jar"/>
            <sequential>
                <echo message="@{file}"/>
            </sequential>
        </for>
    </target>
</project>

Adding Bower to ASP .NET Project – Visual Studio Code

This is the third article in my series of using Visual Studio Code to create ASP .NET MVC Projects. Here we will be adding support for bower packages.

The default code generated by dotnet new mvc makes use of the following JavaScript libraries:-

Recall, from my previous article on adding the files to Git that I ignored these files via .gitignore. But, when you run your application in production by compiling the source, packaging it and deploying it, these files will be missing as they were not committed to Git. Instead, these must be downloaded from the Bower repository.

So, let us add a bower.json to the root first.

{
  "name": "hello-world-project",
  "private": true,
  "dependencies": {
    "bootstrap": "3.3.7",
    "jquery": "2.2.0",
    "jquery-validation": "1.14.0",
    "jquery-validation-unobtrusive": "3.2.6"
  }
}

Normally bower installs the packages to bower_components folder. But, in ASP .NET Core these static files should go inside wwwroot/lib so that they are publicly available. So, we need to create a .bowerrc file in the root with the following content:-

{
  "directory": "wwwroot/lib"
}

Let us test out now that bower is able to install these pacakages we declared as dependencies for our project.

So, first delete all files & folders under wwwroot/lib. Now, go to the terminal Ctrl + ` and do a bower install.

bower : The term 'bower' is not recognized as the name of a cmdlet, function, script file, or operable program.

This is because we don’t have bower installed on this virgin Virtual Machine (VVM, that sounds like a genre for something).

Trying to install bower using npm would fail as well because we don’t have NodeJS installed. Should I have mentioned this in the pre-requisites category? Nah, sometimes I like things to fail so that you get a deeper understanding of the inner workings.

So, why do we need bower? Because we are building an ASP .NET application which will have some frontend JavaScript libraries. Bower is a repository/package manager for frontend JavaScript libraries. Bower itself is written in NodeJS so we need that too.

This is key here. We have chosen ASP .NET Core for building our Web Application, yet we need the alternative to it – NodeJS (which by the way we are not going to use to run our web application). I hope the dependency is clear.

So, head over to NodeJS’s website and download the latest stable version. Once you have installed it, restart VS Code because even though NodeJS has been installed and added to the path, the commands node and npm will not be available to you until you reload VSCode.

Again go back to the VSCode terminal and try executing npm -v. This time your command should succeed and you should get an output such as 5.6.0, depending upon your version of node.

Install bower globally using npm install -g bower. You will get an output such as this:-

npm WARN deprecated bower@1.8.2: ...psst! Your project can stop working at any moment because its dependencies can change. Prevent this by migrating to Yarn: https://bower.io/blog/2017/how-to-migrate-away-from-bower/
C:\Users\Administrator\AppData\Roaming\npm\bower -> C:\Users\Administrator\AppData\Roaming\npm\node_modules\bower\bin\bower
+ bower@1.8.2
added 1 package in 12.109s

Now do a bower install to see if the JavaScript libraries we deleted from wwwroot/lib can now be installed by bower.

You will get an output like this.

PS C:\Users\Administrator\hello-world-project> bower install
bower jquery-validation-unobtrusive#3.2.6           cached https://github.com/aspnet/jquery-validation-unobtrusive.git#3.2.6
bower jquery-validation-unobtrusive#3.2.6         validate 3.2.6 against https://github.com/aspnet/jquery-validation-unobtrusive.git#3.2.6
bower bootstrap#3.3.7                               cached https://github.com/twbs/bootstrap.git#3.3.7
bower bootstrap#3.3.7                             validate 3.3.7 against https://github.com/twbs/bootstrap.git#3.3.7
bower jquery#2.2.0                                  cached https://github.com/jquery/jquery-dist.git#2.2.0
bower jquery#2.2.0                                validate 2.2.0 against https://github.com/jquery/jquery-dist.git#2.2.0
bower jquery-validation#1.14.0                      cached https://github.com/jzaefferer/jquery-validation.git#1.14.0
bower jquery-validation#1.14.0                    validate 1.14.0 against https://github.com/jzaefferer/jquery-validation.git#1.14.0
bower jquery-validation#1.14.0                     install jquery-validation#1.14.0
bower jquery-validation-unobtrusive#3.2.6          install jquery-validation-unobtrusive#3.2.6
bower bootstrap#3.3.7                              install bootstrap#3.3.7
bower jquery#2.2.0                                 install jquery#2.2.0
 
jquery-validation#1.14.0 wwwroot\lib\jquery-validation
??? jquery#2.2.0
 
jquery-validation-unobtrusive#3.2.6 wwwroot\lib\jquery-validation-unobtrusive
??? jquery#2.2.0
??? jquery-validation#1.14.0
 
bootstrap#3.3.7 wwwroot\lib\bootstrap
??? jquery#2.2.0
 
jquery#2.2.0 wwwroot\lib\jquery

If you go back to the wwwroot/lib folder, you should see the bootstrap, jquery, jquery-validation and jquery-validation-unobtrusive packages again.

Let’s commit the two files bower.json and .bowerrc now with a message like Added Bower.

Adding Git to Visual Studio Code ASP .NET MVC Project

This post shows you how to start version controlling (via Git) your ASP .NET project created using dotnet new. Read my previous post on how to create an MVC Project using Visual Studio Code first. Recall that I mentioned Git as a recommended pre-requisite.

If you go to the Source Control Tab (Ctrl + Shift + G) you will see that it says there are no active source control providers

Click the Initialize Repository button on the toolbar.

From the dialog that pops up, again click on Initialize Repository with your project folder currently open in it.

You will see a lot of changes being shown in Git. This is because we do not have a .gitignore file yet which ignores a lot of files & directories which are either compiled binaries, minified versions of scripts or downloaded packages from bower.

Let us create a .gitignore file in the root directory.

Now add the following lines to it:-

# Build results
bin
obj
 
# Bower libraries
wwwroot/lib
 
# Minified Scripts
*.min.js
*.min.css

Now you will see that the list of pending changes has gone down considerably.

Commit these files now with the message Initial Commit

You will be asked for a confirmation whether you want to stage all files and commit them. I prefer hitting Always because most of the times I am making small atomic changes and committing everything. If not, I am quite mindful of the files I need to commit and stage them first. So, this extra confirmation dialog is just an annoyance.

When I do this, I get an error that says:-

*** Please tell me who you are.
 
Run
 
  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"
 
to set your account's default identity.
Omit --global to set the identity only in this repository.
 
fatal: unable to auto-detect email address (got 'Administrator@EC2AMAZ-0IJRVME.(none)')

This is pretty self descriptive. Since this is a brand new Virtual Machine on AWS, I have’t configured my Git identity yet. So, I’ll go back to the Terminal and run the following:-

git config --global user.email "partho@maxotek.com"

Yeah, I put my real email address there. Go ahead, all you spam bots, send me some spam. Nobody emails me anyways. Or maybe, I am just giving Gmail more sample data to improve their SPAM filters!!!

git config --global user.name "Partho Sarathi"

Now, when I hit the commit button. All my changes are committed to Git.

Creating ASP. NET Core MVC Project Using Visual Studio Code

This post shows you how to get started with an MVC project using Visual Studio Code – the lightweight IDE by Microsoft.

Pre-requisites

Steps

  1. Open Visual Studio Code

    I am doing this on a brand new Virtual Machine on AWS. The only thing that it has installed on it is Chrome (apart from the Windows Server 2016 defaults ).

    So, as you can see VS Code is asking me to install Git for version control. It is not required, but I highly recommend that you install and use it for all your projects.

    Once, I have Git installed, re-opening VS Code looks like this

  2. VS Code has a Terminal built in. Open it by clicking on the Terminal tab at the bottom. Alternatively you could use the shortcut Ctrl + `

  3. Create a new directory for your project.

    mkdir hello-world-project

  4. Change to the newly created project directory

    cd hello-world-project

  5. Create a new .NET Core project of type mvc

    dotnet new mvc

    You should get an output like this:-

        PS C:\Users\Administrator\hello-world-project> dotnet new mvc
     
        Welcome to .NET Core!
        ---------------------
        Learn more about .NET Core @ https://aka.ms/dotnet-docs. Use dotnet --help to see available commands or go to https://aka.ms/dotnet-cli-docs.
     
        Telemetry
        --------------
        The .NET Core tools collect usage data in order to improve your experience. The data is anonymous and does not include command-line arguments. The data is collected by Microsoft and shared with the community.
        You can opt out of telemetry by setting a DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 using your favorite shell.
        You can read more about .NET Core tools telemetry @ https://aka.ms/dotnet-cli-telemetry.
        Getting ready...
        The template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.
        This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.
     
        Processing post-creation actions...
        Running 'dotnet restore' on C:\Users\Administrator\hello-world-project\hello-world-project.csproj...
            Restoring packages for C:\Users\Administrator\hello-world-project\hello-world-project.csproj...
            Generating MSBuild file C:\Users\Administrator\hello-world-project\obj\hello-world-project.csproj.nuget.g.props.
            Generating MSBuild file C:\Users\Administrator\hello-world-project\obj\hello-world-project.csproj.nuget.g.targets.
            Restore completed in 7.85 sec for C:\Users\Administrator\hello-world-project\hello-world-project.csproj.
            Restoring packages for C:\Users\Administrator\hello-world-project\hello-world-project.csproj...
            Restore completed in 1.36 sec for C:\Users\Administrator\hello-world-project\hello-world-project.csproj.
     
        Restore succeeded.

    If you get the following error then you don’t have .NET Core SDK installed. Install it from here. Make sure you restart VS Code after installing it because the changes to path settings will only apply on re-launch of VS Code.

    dotnet : The term 'dotnet' is not recognized as the name of a cmdlet, function, script file, or operable program.
  6. Now you can open this project folder using the Open Folder menu

    Alternatively, you can type code . from the terminal which will open up a new Visual Studio Code Window with the project directory. After this, close the previous VS Code window.

  7. Part of the reason why VSCode is so light is that support for various features have been moved into extensions. In order to support C# projects you will need to install the C# extension for VSCode.

    Opening up any C# code file, will automatically show this suggestion if you do not have the plugin installed.

    Alternatively, you can go to the Extensions Tab (Ctrl + Shift + X) and search for C# and from there install the one from Microsoft

    You will see it being Installed briefly.

    Then hit the Reload button to restart VS Code with the extension enabled.

    VS Code will automatically install C# dependencies such as: OmniSharp & .NET Core Debugger.

    After this you will get another warning that says that the required assets to build & debug this project are missing.

    If I don’t install it and hit F5, VS Code asks me to select the environment to start debugging with.

    So, when you install the missing assets, VS Code creates a .vscode directory with two files – launch.json & tasks.json which allow you to run/debug your project.

    Now, Hit F5 to start debugging your ASP .NET Core application.

    In the Terminal you will get an output like this:-

        > Executing task: C:\Program Files\dotnet\dotnet.exe build C:\Users\Administrator\hello-world-project/hello-world-project.csproj >
     
    Microsoft (R) Build Engine version 15.5.180.51428 for .NET Core
    Copyright (C) Microsoft Corporation. All rights reserved.
     
        Restore completed in 1.51 sec for C:\Users\Administrator\hello-world-project\hello-world-project.csproj.
        Restore completed in 368.92 ms for C:\Users\Administrator\hello-world-project\hello-world-project.csproj.
        hello-world-project -> C:\Users\Administrator\hello-world-project\bin\Debug\netcoreapp2.0\hello-world-project.dll
     
    Build succeeded.
            0 Warning(s)
            0 Error(s)
     
    Time Elapsed 00:00:10.24
     
    Terminal will be reused by tasks, press any key to close it.

    In the Debug Console you will see something like this:-

        info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
      Sending file. Request path: '/favicon.ico'. Physical path: 'C:\Users\Administrator\hello-world-project\wwwroot\favicon.ico'
    Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware:Information: Sending file. Request path: '/favicon.ico'. Physical path: 'C:\Users\Administrator\hello-world-project\wwwroot\favicon.ico'
    info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 10.8591ms 200 image/x-icon
    Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 10.8591ms 200 image/x-icon
    The thread 2408 has exited with code 0 (0x0).
    The thread 1224 has exited with code 0 (0x0).

    In the Threads pane you will see a lot of threads running for your Kestrel web server.

    And finally, your ASP .NET Core MVC Application will run inside the browser:-

Generating GitHub Access Tokens

To generate an access-token follow these steps:-

  1. Goto GitHub and login with your account
  2. Click on your Avatar at the top right corner of Github

  3. Select Settings from the drop down menu

  4. Goto Developer Settings from the side menu (bottom left)

  5. Goto Personal access tokens from the side menu

  6. Click on the Generate new token button on the top right

  7. Enter your Github password (if prompted)

  8. Give the token a description such as (Repository Seeder)

  9. From the Select scopes section check public_repo under repo. This allows access to your public repositories – listing them and creating new ones.

  10. Scroll down and click on Generate token

  11. You will be taken back to the tokens page. The newly created token should be highlighted in green. Copy that. This is your access token that you must use in APIs that let you interact with GitHub.

MAMS – Seeder for AngularJS Modules

This is my new project which creates a new AngularJS module project using a seed project.

The project is hosted on GitHub and published on npm

It uses my AngularJS Module Seed Project

Install

$ npm install -g mams

It is best to install it globally as you would be using it to create new projects and you want the command to be available anywhere.

Usage

Usage: mams [options]
 
Options:
 
  -V, --version               output the version number
  -p, --project <value>       The name of the project
  -d, --desc [value]          The description of the project
  -o, --output-file [value]   The otuput file
  -g, --create-github-repo    Creates a GitHub repository
  -t, --access-token <value>  The GitHub access token
  -h, --help                  output usage information

Examples

Basic Usage

This just creates a new project directory, clones the seeder project & updates the metadata of package.json, bower.json, build.conf.js.

mams -p mx-angular-notify -d "AngularJS module for showing toast notifications"

You will get an output like:-

Maxotek Angular Module Seeder v 1.0.3
Created project directory: mx-angular-notify
Seeder repository: https://github.com/maxotek/mx-angular-module-seed.git
Seeder repository cloned at: mx-angular-notify
Project: mx-angular-notify
Description: AngularJS module for showing toast notifications
Output File: mx-angular-notify.js
Project URL: null
HTTPS URL: null
SSH URL: null
mx-angular-notify/package.json updated
mx-angular-notify/bower.json updated
mx-angular-notify/build.conf.js updated
Renamed project file to: mx-angular-notify/src/mx-angular-notify.js
mx-angular-notify/src/mx-angular-notify.js updated
Updated project name in: mx-angular-notify/src/mx-angular-notify.js

Advanced Usage (Also creates GitHub Repository)

mams -p mx-angular-notify -d "AngularJS module for showing toast notifications" -g -t 72a8a3e2b8374bcb8acaf0d0f7f4a708

In addition to the stuff the Basic Usage does, this also creates a GitHub repository using your GitHub access token. Click here to know how to generate one.

Maxotek Angular Module Seeder v 1.0.5
Creating GitHub Repository
Listing repositories
Found: 31 repositories
Created project directory: mx-angular-notify
Seeder repository: https://github.com/maxotek/mx-angular-module-seed.git
Seeder repository cloned at: mx-angular-notify
Repository created at: https://github.com/maxotek/mx-angular-notify
Project: mx-angular-notify
Description: AngularJS module for showing toast notifications
Output File: mx-angular-notify.js
Project URL: https://github.com/maxotek/mx-angular-notify
HTTPS URL: https://github.com/maxotek/mx-angular-notify.git
SSH URL: git@github.com:maxotek/mx-angular-notify.git
mx-angular-notify/package.json updated
mx-angular-notify/bower.json updated
mx-angular-notify/build.conf.js updated
Renamed project file to: mx-angular-notify/src/mx-angular-notify.js
mx-angular-notify/src/mx-angular-notify.js updated
Updated project name in: mx-angular-notify/src/mx-angular-notify.js
mx-angular-notify/.git/config updated

Common errors

Error: 401 error making request GET https://api.github.com/user/repos: "Unauthorized"

Check that your access token passd after -t is correct.

The repository: mx-angular-notify already exists

The GitHub repository already exists under your account. If you want to start afresh, delete the repository and try again. Otherwise manually update the Project, Clone & SSH URLs

Building a AWS Serverless Web Application

This article will show you how to quickly create a AWS Serverless Web Application and deploy it. If you don’t know what a Serverless application is, read my article that talks about the history of web development and how Serverless application are the future.

The application in this example is just a Hello World REST API.

Table of Contents

Pre-requisites

The Stack

  • The stack comprises of NodeJS which is what our REST API is going to run on.
  • AWS the cloud solution which automatically scales up and down based on the load on the web application

Alrighty, let’s get started.

Sign Up for Serverless

The first thing we need to do is Sign Up for Serverless. I signed up with my GitHub account. It asks for some basic permissions:-

Personal user data
Email addresses (read-only)
This application will be able to read your private email addresses.

Hit Authorize serverless. That redirects you to the Getting Started page with the fancy looking console that shows the basic steps.

Creating a Project

Just following along their steps here.

  1. Open up your favorite terminal
  2. Navigate to your projects folder (assuming, you keep all your projects in a directory). I keep mine in C:\Projects.

    cd C:\Projects.

  3. Create a new folder for your Serverless project.

    mkdir hello-world

  4. Go to the newly created project directory.

    cd hello-world

  5. Verify that you have NodeJS installed with the minimum version. node --version

    Mine’s v6.10.3. Quite old considering 8.9.4 is their LTS release at the point of writing this article. But, this should work considering v6.5.0 or later is their pre-requisite.

    If you do not have NodeJS installed and get an error. Go to Node’s website and install the latest stable version.

  6. The next step is to globally install the npm package Serverless on your system.

    npm install serverless -g

    This takes a while so you might want to grab a coffee in the meantime.

  7. Now, lets login to our serverless account.

    serverless login

    This opens up your browser from where you can login using the method you chose to create your account with. Since, I used GitHub, I’ll sign in using it.

    If this is the first time you used serverless you might get an EULA. Read it (always do it, unless you agree to handover your first born to them for deployment on the Cloud!!) and click on I accept.

    After this, you are asked to close the browser window and go back to the terminal. You will see logs such as this in the terminal:-

    Serverless: The Serverless login will open in your default browser...
    Serverless: Opening browser...
    Serverless: Waiting for a successful authentication in the browser.
    Serverless: Waiting for a successful authentication in the browser.
    Serverless: Waiting for a successful authentication in the browser.
    Serverless: Waiting for a successful authentication in the browser.
    Serverless: Waiting for a successful authentication in the browser.
    Serverless: You are now logged in
  8. Now, let us create a serverless function using a built in template

    serverless create --template hello-world

    You get an output like this:-

        Serverless: Generating boilerplate...
     _______                             __
    |   _   .-----.----.--.--.-----.----|  .-----.-----.-----.
    |   |___|  -__|   _|  |  |  -__|   _|  |  -__|__ --|__ --|
    |____   |_____|__|  \___/|_____|__| |__|_____|_____|_____|
    |   |   |             The Serverless Application Framework
    |       |                           serverless.com, v1.26.0
     -------'
     
    Serverless: Successfully generated boilerplate for template: "hello-world"
    Serverless: NOTE: Please update the "service" property in serverless.yml with your service name

    Let us look at what files were generated. So, open this up in your favourite IDE. I prefer Visual Studio Code.

    code .

    Here’s the structure of the generated files:-

    • .gitignore
    • .handler.js
    • .serverless

Deploying

If I try to deploy the application now using the following command:-

serverless deploy

I get the following error:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
 
    Serverless Error ---------------------------------------
 
    ServerlessError: AWS provider credentials not found. Learn how to set up AWS provider credentials in our docs here: http://bit.ly/aws-creds-setup. 
    Get Support --------------------------------------------
         Docs:          docs.serverless.com
         Bugs:          github.com/serverless/serverless/issues
         Forums:        forum.serverless.com
         Chat:          gitter.im/serverless/serverless
 
    Your Environment Information -----------------------------
         OS:                     win32
         Node Version:           6.10.3
         Serverless Version:     1.26.0

Basically, Serverless does not have access to my AWS account and cannot create resources on my behalf. I followed along their guide and came up with these steps:-

  1. The first thing we need to do here is log into our AWS Console.
  2. Next, got to Identity and Access Management or IAM
  3. From there go to Users
  4. Then click on Add User
  5. Give it a name such as Serverless
  6. Select Programmatic access from Access type
  7. On the next screen go to Attach existing policies directly
  8. Select AdministratorAccess from the policies listed below
  9. Click on Next: Review and verify the details
  10. Click on Create User
  11. Keep a note of the Access key ID and the Secret access key. Alternatively, you can also download the credentials in CSV format from the Download .csv button.
  12. Go back into your terminal and save these credentials permanently using an AWS Profile.

    serverless config credentials --provider aws --key <PUT_YOUR_ACCESS_KEY_HERE> --secret <PUT_YOUR_SECRET_KEY_HERE>

    You will get an output like this:-

    Serverless: Setting up AWS...
    Serverless: Saving your AWS profile in "~/.aws/credentials"...
    Serverless: Success! Your AWS access keys were stored under the "default" profile.

    On Windows the profile is saved at the following path:-

    C:\Users\<YourUsername>\.aws\credentials

    [default]
    aws_access_key_id = ABCDEFGHIJKLM
    aws_secret_access_key = ABCDEFGHIJKLMNOPQRSTUV

    Now we have an AWS user setup with the proper permissions set and the credentials are saved in our local configuration. Let us try to deploy our application again.

    serverless deploy

    This step takes a while as the AWS stack is being created. You can go inside AWS’s Cloud Formation and then take a look at your Stack.

    You will see new files in your project folder now under the directory .serverless

    • .serverless
      • cloudformation-template-create-stack.json
      • cloudformation-template-update-stack.json
      • serverless-hello-world.zip
      • serverless-state.json
    • .gitignore
    • .handler.js
    • .serverless

    If everything goes properly you will get a log such as this:-

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    
    Serverless: Packaging service...
    Serverless: Excluding development dependencies...
    Serverless: Creating Stack...
    Serverless: Checking Stack create progress...
    .....
    Serverless: Stack create finished...
    Serverless: Uploading CloudFormation file to S3...
    Serverless: Uploading artifacts...
    Serverless: Uploading service .zip file to S3 (404 B)...
    Serverless: Validating template...
    Serverless: Updating Stack...
    Serverless: Checking Stack update progress...
    .................................
    Serverless: Stack update finished...
    Service Information
    service: serverless-hello-world
    stage: dev
    region: us-east-1
    stack: serverless-hello-world-dev
    api keys:
        None
    endpoints:
        GET - https://2rsm3t4w53.execute-api.us-east-1.amazonaws.com/dev/hello-worldfunctions:
        helloWorld: serverless-hello-world-dev-helloWorld
    Serverless: Publish service to Serverless Platform...
    Service successfully published! Your service details are available at:
    https://platform.serverless.com/services/maxotek/serverless-hello-world

    So, our service is deployed at: https://2rsm3t4w53.execute-api.us-east-1.amazonaws.com/dev/hello-world

    Also, there seems to be a nice dashboard at Serverless which shows the service details:

Resources

You can goto the newly created AWS stack to take a look at the resources that were created for your Serverless application.

Lambda Function

This is the core of the scaling aspect of a serverless application. You can read more about Lambda by going to AWS’s documentation page.

But, basically it allows you to run code without worrying where it is deployed. The deployment can scale up and down automatically to meet the incoming requests.

Lambda supports a lot of programming languages. In this case it is NodeJS which is also their preferred language because it has very fast startup times and is currently the fastest rising language/platform.

Our Lambda function is basically defined inside the handler.js function.

'use strict';
 
module.exports.helloWorld = (event, context, callback) => {
  const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*', // Required for CORS support to work
    },
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };
 
  callback(null, response);
};

There isn’t a lot going on in here. But, basically we are defining a handler for our helloWorld Lambda function. It recives an event object which contains the details of the request.

The context parameter contains various information regarding the incoming request. You can read up more on it by going here.

The callback parameter is optional and it depends on whether you want to return something back to the caller of our lambda function.

In this case we are returning a JavaScript object called response which is just an HTTP response. In it, we set the status code of 200 to say that the request succeeded. We are allowing Cross Origin Requests on this request by adding a Access-Control-Allow-Origin header. Finally, in the body of the response we are sending a JSON object with a Hello Worldish message and passing along the event parameter received in our handler.

API Gateway

In order for our Lambda function to be accessible over HTTP an API was created. Thus, hosting our web application on the cloud and making it accessible for everybody.

The API gateway itself defines which endpoint in the URL calls which Lambda function. Passing over any input parameters to our Lambda function’s event parameter.

CloudWatch Log Group

Next a CloudWatch log group was created so that all incoming requests and any console.log messages our Lambda function emits is automatically saved as a Log Stream.

IAM Roles

Appropriate roles are also created so that logs can be written by our Lambda Function onto CloudWatch.

Cloud Formation Template (#cloud-formation-template}

Finally, all of these were defined in a cloud formation template and published on S3 so that our stack can be created.

Output

The most important aspect of the output is the final endpoint through which our URL can be publicly accessed.

Undeploy

To remove your stack and all the resources Serverless created on AWS for you just run the following command :-

serverless remove

You will get an output like this:-

1
2
3
4
5
6
7
Serverless: Getting all objects in S3 bucket...
Serverless: Removing objects in S3 bucket...
Serverless: Removing Stack...
Serverless: Checking Stack removal progress...
...........
Serverless: Stack removal finished...
Serverless: Successfully archived your service on the Serverless Platform

Now, if I go back to the Endpoint URL:-

https://2rsm3t4w53.execute-api.us-east-1.amazonaws.com/dev/hello-world

I get a Bad request error.

The stack on AWS Cloud Formation is also no more.

However, the application service page is still available on the Service Page of Serverless.com.

To delete this I went to the Settings page and from there clicked on the Delete serverless-hello-world button at the bottom. This is followed by a confirmation page after which the application is no more.

Why Serverless Web Applications

Everybody is talking about Serverless these days. What is it and what’s all this buzz about? In order to properly understand what it brings to the table, you would have to look back into the history of web development.

Table of Contents

History

During the dotcom bubble (1997-2001) a lot of people saw business opportunities on the internet. Suddenly you could reach customers all across the world and enter markets you never thought you could get into without enormous capital and power. The internet was for everybody and it did not take a lot of capital to start your own business. It was a Get big fast kind of business that anybody could jump into. As a result of this, thousands of .com websites (hence the name dotcom bubble) popped up.

Websites in those days were created using plain old HTML which was created in 1993 and CSS which came 3 years later in 1996. Some websites used JavaScript to bring some dynamic nature to the webpages. Even fewer but fancier websites made use of Flash to give their sites an interactive feel.

While, HTML, CSS & JavaScript have since evolved and stayed relevant, Flash is almost dead. Part of the reason for it is that you haad to create Flash files in another application which was radically different from the coding feel of HTML, CSS & JS. Also, it has been marred by all kinds of vulnerabilities to the point that most browsers block it by default these days. Microsoft made a lame attempt at the market of Flash with Silverlight but it did not gain any momentum either.

Coming back to the topic, enterpreneurs were creating (or getting them created by someone) websites of all kinds and putting them on the internet so people could use them. In order for people across the world to get to see their website with their fancy products, the HTML, CSS, JS & Flash files needed to be hosted somewhere. That is, they must be put on a server that always runs and serves these files to the users’ browsers.

Deployment

Typically, one would log into the server using FTP and copy their files to make the website run.

Domains

A server just has an internet connection and a dedicated IP address that it’s Internet Service Provider has assigned to it. How do people reach your website? They can’t remember the IP address of each and every website to reach them.

You would register a domain name from a domain registrar. Something like, mysuperawesomewebsite.com and confgure it’s DNS to point to the IP address of your server. So now, anybody can reach your website by going to http://mysuperawesomewebsite.com using their browser.

You might ask, how does one know the name of the website either. For that we had search engines like (Google, Yahoo, etc). But, that’s a totally different topic and I’ll cover it later.

Scaling

While most of these dotcom websites died out as the funding ran out. Some, with good quality products or services did survive and started earning enormous profits.

But, they faced challenges of their own. As the website became more and more popular, the always online hosting server was no longer able to handle the volume of users it was getting.

The solution – get a bigger/badder machine with better hardware. So, you increased the CPU and RAM on your server. This is called vertically scaling up. But, there are limitations to it. You can only add so many CPUs and RAM to a single server. Well, unless you have a factory of your own to build totally custom hardware. In which case, go build your damn supercomputers that do a lot of good (think weather prediction) for the world.

Another problem is scaling up Input & Output. Most problems these websites solved were not compute intensive and mostly limited by I/O. Adding more I/O to a single machine is not as straight forward as adding CPU and RAM. You need multiple network cards (which is easy). But, you also need multiple internet connections. And these connections were not your then typical dialup lines that people used at homes. These were expensive and hard to get.

Clustering

To solve the scaling problem you create a cluster of servers. That is, instead of one server running your website, you put the HTML, CSS & JS on two or more servers and they distribute the load between them.

Each server would have a differnt IP address and a dedicated internet line to handle the I/O problem. With DNS, you specify multiple IP addresses against your domain (mysuperawesomewebsite.com) so that requests are distributed between the servers. This is a very basic way of distributing load between servers. Most DNS servers support Round-robin which shuffles the list of IP addresses that the user’s computer get when they are trying to go to your website. Browsers try the IP addresses in that order to load your website. So, users in the US might get the first IP address as the primary for your domain and connect to Server 1. While users in India might get the second one as the primary IP and connect to Server 2.

This is an over simplification and the actual order depends on your DNS server and stuff (DNS is after all hierarchical).

You get some sort of fault-tolerance too. As, if the server with the primary IP address is down, the browser will attempt to connect to the secondary server using it’s IP and load your website.

There are much better solutions to these problems of load balancing & fault tolerance which I’ll discuss below. But, this is how websites used to run back then. Infact, a lot of extremely popular websites still run in this fashion and do quite well.

The Problems

The main problem with this approach is that you have to manage your servers manually. If the volume of users suddenly increased you would have to buy or lease a new one from your hosting provider (which itself takes time). Then you would have to deploy your HTML, CSS & JS files on it. Add the new IP address to your DNS and wait for the change to propagate across the world (which could take upto 48 hours). Until then, requests wouldn’t even be coming to your new server and it would just be sitting idle, thus not really helping out with balancing load.

There is another factor here and that is the database. Typically your website is storing some user information or showing some dynamic data that is being stored in the database. This database needs to be scaled up too. But, the principle behind it is largely the same.

The New Way – Serverless

The idea behind Serverless computing is that you worry about what your application does and not how or where it is deployed, how it is scaled up or down.

It takes care of spawning new containers when the requests grow and then deleting them when the requests come down. You pay for the usage your website incurs because of others using it. When nobody is using it, you pay nothing (well you pay a nominal amount, but it is miniscule compared to what you would pay for a normal server).

There is however a hidden cost to it. A big part of Serverless is AWS Lambda which again is extremely cheap for low usage. However, it is a layer that Amazon built on top of EC2 and containers. As such the added cost of developing and maintaining it is passed on to your Lambda costs. Same goes for EC2 which is costlier than a dedicated instance. It is imperative from a business point of view that this be done. Besides, there pricing is very fair. Having said all that it will always be cheaper for a website/application that gets a lot of traffic to be hosted on a dedicated machine. The performance will also be much better that what you get on a shared tenant instance in EC2. But, then you pay for that machine even if nobody is using it.

In my opinion it is best to start a new application on AWS Lambda/Serverless platform and then migrate to a dedicated instance if the application becomes very popular. But, then again, maybe you can spend the time wasted in managing those servers on building another cool serverless application. Remember, life is short and we only get one shot at it. The choice is yours.