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

Friday, December 31, 2021

The some() array works similar to the every() method, it also returns true or false when the condition is met.  some() needs to match just one element in the array that meets the condition to return true.  So lets run the same code that we ran for the every() method.  We will test to see if the array is greater than 50 for the first condition, and then we will test to see if the array is greater than 70 for the second condition.  For the every() method the first condition returns true, while the second condition returns false.  Let's see what happens with the some() method.


    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 76.99];

        var greaterThanFifty = oilPrices.some(function (value) { return value > 50; });

        var greaterThanSeventy = oilPrices.some(function (value) { return value > 70 });

        console.log("greaterThanFifty: " + greaterThanFifty);
        console.log("greaterThanSeventy: " + greaterThanSeventy);
    </script>

Thursday, December 30, 2021

If you come from C# or Java, JavaScript inheritance is a little different than what you are used to.  In JavaScript you don't inherit from a class, but you inherit the classes' prototype object.  In our previous post we created an Account class.  In this post we are going to inherit from the account class.  First let's recreate the Account class with the code below.


    <script>
    <script>
        function Account(balance, type) {
            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;
        }

    </script>


Wednesday, December 29, 2021

In the previous post we created arrays of different types, in this post we are going to read the values from our arrays.

Let's work with the following arrays
  1. var numbers = [1,2,3,4];
  2. var stringArray = new Array("USA", "Canada","China");
  3. var objectArray = [{firstName: "Jane", lastName:"Johnson", weight:"115lbs"},{firstName: "Jack", lastName:"Johnson", weight:"200lbs"}];
Let's start with getting a value from an array:

To get the second value of an array you would write the following code by using the :

console.log(numbers[1]);
console.log(stringArray[1]);
console.log(objectArray[1]);

Tuesday, December 28, 2021

Arrays in JavaScripts are a collection of values stored in what are called elements.  Each element is represented by a numeric index that is zero based, meaning the first element of an array starts at index zero.  JavaScript arrays are dynamic and can contain many types of objects including functions.  The useful thing about arrays is that they are a specialized object that contains a variety of built-in methods that are useful in the manipulation of the array.

First let's create an empty array, there are several ways to do this:


  1. var empty = [ ];
  2. var empty = new Array();
  3. var empty = new Array(0);

Monday, December 27, 2021

The Array.isArray() method is a useful method to determine object is of type array.  Let's demonstrate with some code.

    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 69.50, 76.99];
        var iamObject = new Object();

        console.log(Array.isArray(oilPrices));
        console.log(Array.isArray(iamObject));
    </script>

The code above tests to see if the oilPrices array is of type array which it is, and then it tests to see iamObject is an array.  The console.log out put should return true, and the second console.log should return false.

Friday, December 24, 2021

In JavaScript when you define a function you get a built-in Arguments object, this object is an array-like object that puts the arguments/parameters of the your function in an object which can be accessed via indexes much like an array.

This can be useful if you have a function that takes multiple parameters, but you don't know how parameters there will be.  Let's modify our addNumbers function so that it can add more than two numbers using the Arguments object.

    <script>
        function addNumbers() {
            var sum = 0;

            for (var i = 0; i < arguments.length; i++)
                sum += arguments[i];

            return sum;
        }

        console.log("The sum of the numbers are " + addNumbers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
    </script>

Thursday, December 23, 2021

A JavaScript class is different than classes in other languages like C# or Java.  A class in JavaScript means that the objects inherit properties from the same prototype object.  It is defined by using the function to initialize and return a new object.

First thing we have to do define the prototype object by creating a function constructor that initializes and creates a new object.  Let's say we have a bank account first we will create a constructor that will create a new account object.  We then define the class methods by defining the prototype methods.  After we do that all the new objects that created will inherit those prototype methods. Like the code below.


    <script>
    <script>
        function Account(balance, type) {
            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;
        }

        var a = new Account(100, "Checking");
        var bonus = 10;
        var fine = 20;

        console.log("Deposit " + bonus + " " + a.deposit(bonus));
        console.log("Withdrawal " + fine + " " +  a.withdrawal(fine))
        console.log("Account type " + a.type);
    </script>




Wednesday, December 22, 2021

The lastIndexOf() method searches for last appearance the element in the array that matches the passed in value. In this example we will search for the value 60.50 in the array.  The lastIndexOf() method takes two arguments.  The first argument is the value to search for, the second argument is optional and specifies the index to start the search at.  If the second argument is omitted the search will start at the first element of the array.

    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 69.50, 76.99];

        var searchAtBeginning = oilPrices.lastIndexOf(60.50);

        var searchAtIndex = oilPrices.lastIndexOf(60.50,2);

        console.log("searchAtBeginning: " + searchAtBeginning);
        console.log("searchAtIndex: " + searchAtIndex);
    </script>

Tuesday, December 21, 2021

The indexOf() method searches for the element in the array that matches the passed in value.
In this example we will search for the value 60.50 in the array.  The indexOf() method takes two arguments.  The first argument is the value to search for, the second argument is optional and specifies the index to start the search at.  If the second argument is omitted the search will start at the first element of the array.

    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 76.99];

        var searchAtBeginning = oilPrices.indexOf(60.50);

        var searchAtIndex = oilPrices.indexOf(60.50,2);

        console.log("searchAtBeginning: " + searchAtBeginning);
        console.log("searchAtIndex: " + searchAtIndex);
    </script>

Monday, December 20, 2021

The every() method is a method that tests a condition on every array element and makes sure that all the elements meets the criteria.  It returns true or false.

The code below test to see if the oil prices array is greater than $50 or greater than $70


    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 76.99];

        var greaterThanFifty = oilPrices.every(function (value) { return value > 50; });

        var greaterThanSeventy = oilPrices.every(function (value) { return value > 70 });

        console.log("greaterThanFifty: " + greaterThanFifty);
        console.log("greaterThanSeventy: " + greaterThanSeventy);
    </script>

Friday, December 17, 2021

A JavaScript function is a piece of code that is defined once and can be reused through your program.  A function can have arguments or parameters that you can pass into it and returns a value.  If an explicit return value is not specified the return value is "undefined".  During invocation of the function, the function returns the value of "this" keyword, which represents the context of the function.

As you can see a function is a lot like a method.  If a function is defined as a property of an object it is in fact called a method of the object.  It is import to keep in mind that functions in JavaScript are objects and they have the benefits of any objects, meaning they can be self contained, which provide them with a vast amount of flexibility.

Thursday, December 16, 2021

JavaScript does not have a built-in feature to define a namespace.  A namespace is basically a container of your code that it does not pollute the other codes that's on page.  Namespace allows you to play nice with people's code and other JavaScript libraries.

Fortunately, JavaScript functions have their own contexts and scope.  Therefore, we can use functions as a namespace so that it does not pollute the global scope.

The easiest way to create a namespace on a page is to encapsulate everything in an anonymous function like the code below.


    <script>
        (function () {
            // put your code here
        }());

    </script>

Another way of using namespace is to assign the anonymous function to a variable


    <script>
       var myNameSpace = (function () {
            // put your code here
        }());

    </script>

Wednesday, December 15, 2021

The filter() method returns the elements of the array that satisfies the function that is passed into the method.  If the function returns true the element is added to the filtered array, else it is ignored.

Let's say we only want to buy oil when the prices drops below $72, so we will only return an array element where the prices below $72


    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 76.99];

        var lowPrices = oilPrices.filter(function (value) { return value < 72 });

        console.log(lowPrices);
    </script>

Tuesday, December 14, 2021

The JavaScript array splice() method allows you to delete and insert array elements in one method
Before we get to the examples let's see how we would use the splice() method on an array first.

The splice method takes 1....n method parameters.  The first parameter specify the position of the array that will be deleted.  The second parameter specify the number of elements to be deleted after the first element's index position, or splice out.  Any subsequent parameters will be the elements that will be added to the array.  If there's only one parameter then all the elements before the first parameter's position will be deleted

For example let say we have the following array

    <script>
        var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9,10];
    </script>

Monday, December 13, 2021

In CSS you can group your selects into one declarations. For example you want to create a read alert text for your h2 HTML element tag.

You can define each property one at a time like so

<style>
        h2{font: bold 25px arial, verdana;}
        h2{color: red;}
        h2{background:black;}
</style>


When you type in <h2>Alert</h2> you will get this effect





Friday, December 10, 2021

Before we begin inserting data into mongoDB we need to understand the difference between Relational Database Management System (RDBMS) and mongoDB.  RDBMS is a database many of us worked with in the past.  You have tables and relationships between those tables.  We will use the ACME Bank that we were build our AngularJS SPA application as an example.

This is how the design would be on a RDBMS






























Thursday, December 9, 2021

JavaScript is a flexible language, and that flexibility extends to functions.  A JavaScript function are not just codes that you reuse and execute.  There are also values, values that you assign to a variable.  In the following example we are going to write a function that will calculate the radius of a circle.  But instead of invoking radius function like a normal function call, we are going to assign to a function to a variable first.

Wednesday, December 8, 2021

The Array.concat() method returns a array that is a concatenation of the original array and what what is being passed into the concat() method.  The concat() method can take either values or another array.

For example lets say you have an array of numbers from 1 to 3

var numbers = [1,2,3];

Now let's say you want to concatenate the numbers 4 and 5 into the array.  You would type in the following

numbers.concat(4, 5);

Tuesday, December 7, 2021

The Array.sort() methods sorts the array in alphabetical order by default, or you can pass in a custom sort function.

So let's say you have an array of names that's our of order that you want to sort.


    <script>
        var names = ["zack", "jim", "bob", "adam", "jason"];
    </script>

If we call the names.sort() method we would get resulting array in Alphabetical order

Monday, December 6, 2021

The Array.join() method converts all of the elements of an array into strings and concatenates the elements.  If no delimiter is defined it is separated by a comma.  The most common use for this is to convert an array into a comma separated list of strings.

For example let's say we want to convert an array of zip codes into a comma separated list.

    <script>
        var zipCodes = [90210, 90211, 90212, 90213, 90214];
    </script>

If we just call the zipCodes.join() method we will get a string of comma separated list

Friday, December 3, 2021

In JavaScript the DOM is an acronym for "Document Object Model" that's quite a mouthful.  Most people just refer to it as the DOM.  The DOM is basically a collection of objects/elements organized in the tree structure.  To perform any functions in JavaScript you first have to find a reference to the object or element you are working with.  Luckily, there are a few handy JavaScript methods that can help you find the elements in the DOM that you want.

Let's take a look at the methods:


  • getElementById - this method gets the element based on the unique id that is assigned to the                                   element
  • getElementByClassName - this method gets the elements that has the class name that is passed                               into the method
  • getElementByTagName - this method gets the elements that matches the tag name
  • querySelector - this method gets the first child element that matches the CSS selector being                                passed in
  • querySelectorAll - this method gets all the child elements that match the CSS selector

Thursday, December 2, 2021

To make your functions developer friendly it is sometime useful to define your a arguments as properties.  This way your code is self documented, instead of having the developers read documentation on the code you can just use the arguments to document the code so that it would reduce the confusion from the developer.

    <script>

        var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        var copiedNumbers = [];

        function copyNumbers(args) {
            copyAll(args.orignal,
                args.copy,
                args.size);

            function copyAll(original, copy, size) {
                for (var i = 0; i < size; i++) {
                    copy[i] = original[i];
                }
            }
        }

        copyNumbers({ orignal: numbers, copy: copiedNumbers, size: numbers.length });

        console.log("original " + numbers);
        console.log("copies " + copiedNumbers);

    </script>

Wednesday, December 1, 2021

One of the first thing you would do in web development is to link an external Cascading Stylesheet to an HTML document.  As a matter of fact bootstrap would not work if you didn't link the bootstrap.css file in your HTML document.  Linking an external document is easy enough you often see the link like this

    <link href="Content/bootstrap.css" media="all" rel="stylesheet" type="text/css"></link>
    <script src="Scripts/bootstrap.js"></script>

Now let's break it down link attributes, there are four possible attributes for the link tag.

They are the following:
  • rel (required) - Relations, relationship to this page.  For CSS stylesheets its "stylesheet"
  • type (optional) - is the type of the link, "text/css" is the type for CSS stylesheets
  • href (required) - is the location of the resource, it could a relative path or an actual URL like a CDN
  • media (optional) - with this attribute you can specify which media the stylesheet is meant for.  For example the media attribute can have the "projector" value.

Tuesday, November 30, 2021

Since JavaScript functions are objects they can have properties that belongs to the function itself.  For example this simple example counts the number of times the function is being called by incrementing the counter property that belongs to the function.


    <script>
        functionCount.counter = 0;

        function functionCount() {
            return functionCount.counter++;
        }

        for (var i = 0; i < 10; i++)
            functionCount();

        console.log(functionCount.counter);

    </script>

Monday, November 29, 2021

When you define an object as an Array in JavaScript you get the benefits of inheriting some useful methods with it.  Some of the common methods are those that allows you to add and delete elements from an array.  The .push() method adds an element at the end of the array, the unshift() method adds an element at the beginning of the array.  The delete keyword deletes an element at the specified index.

Let say you have an the following array:

var numbers = [3,4];

If you output the array in the browser console you will see that the array has two elements with the number 3 occupying index 0 and the number 4 occupying index 1.

Friday, November 26, 2021

The switch statement is there to make the code more readable if the if statements contains too many branches and becomes too hard to read.

Consider the code below

var x = 6;

if (x === 1)
{
     console.log("one");
}
else if (x === 2)
{
     console.log("two");
}
else if (x === 3)
{
     console.log("three");
}
else if (x === 4)
{
     console.log("four");
}
else if (x === 5)
{
     console.log("five");
}
else
{
     console.log("x is not 1-5");
}

Thursday, November 25, 2021

Since an array is a collection of elements of objects, values, etc.  The most common function performed on it is to iterate through each elements of the array.  The most frequent way to do that is with a for loop.

Let's say you have an array with the following:

var numbers = ["one","two","three","four","five"];

The numbers array above contains five string elements, which also has a indexes associated with the it.  There's also a length that is defined with each array that we will use for the for loop we are about to write.  So what do the you length of the numbers array will be?

If we output the array to the browser with the statement console.log(numbers.length) do you think we will get the length to be 5 or 4?

If you guess 5 you are correct because there are five elements in the array.  However, the arrays have zero based indexes therefore the index is always length -1

for(var i = 0; i < numbers.length; i++)
{
     console.log(numbers[i]);
}

Wednesday, November 24, 2021

JavaScript itself does not have multidimensional arrays, instead you can use an arrays of arrays instead.  Multidimensional arrays are basically arrays that you can reference by rows and columns.  The most obvious real world use is to store rows and columns of a database record.  Imagine if you have a row of the database product from the database from the table "Products".  Instead of storing each value in an individual variable you can store them in an arrays of arrays.

Let's say you have the following database Products table

Tuesday, November 23, 2021

In the previous post we installed MongoDB on Linux on this post we are going to install MongoDB on Windows.

Here are the steps:

1. Go to https://www.mongodb.com/download-center/community, then click on the "Download" button





















Monday, November 22, 2021

The Array.reverse() method reverses the order of the array elements.  The easiest way to demonstrate this is to have an array with the numbers 1 to 5.  If we call the Array.reverse() method we should get an array of 5 to 1.  The Array.reverse() does not create a new array, it simply rearranges the array into a new order.  Just keep that in mind when you are using this method.

So let's declare our array from 1 to 5


    <script>
        var numbers = [1, 2, 3, 4, 5];
    </script>

So if we call the numbers.reverse() method we should get an array of 5 to one in the reverse order

Friday, November 19, 2021

The for loop is a looping construct in JavaScript that are more simplistic than the while loop.   When writing the for loop there are three three parts they are


  1.  Initialize - a count variable is initialize, it's usually zero but it doesn't have to be
  2. Test - A test to see if the loop should continue
  3. Increment - finally the count is incremented, it doesn't have to be an increment it could be decrements as well

Let's use the JavaScript code to demonstrate:

If you execute the loop below you will bet a for loop that executes when i is less than 10


for (var i = 0; i < 10; i++)
{
    console.log("i is " + i);
}

console.log("i outside of for look is " + i);

Thursday, November 18, 2021

The forEach() method loops through an array, and performs a function on each element of the array.  The forEach() method can take three arguments, the first argument is a current value that you want to perform an action on.  The second argument acts as the "this" value within the scope of the function.  The third argument is the array itself.  Most of the time only the first argument is passed.  The code below passes in only one argument which is an anonymous function being performed on each element of the array using the forEach() method to calculate the oil prices in the last five days and prints it out in the console.


    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 76.99];
        var total = 0;

        oilPrices.forEach(function (value) { total += value });

        console.log(total);
    </script>

Wednesday, November 17, 2021

 In the previous post we created a load balancers with the target groups, rules, and instances to handle HTTPS traffic.  In this post we are going to set up our DNS records in Route 53. So go to the Route 53 dashboard, click on your domain

1. Click on "Create record"



Tuesday, November 16, 2021

In this post we are going to go over some basic commands that you can run on a machine that has MongoDB installed.

One of the first thing you want to do is to connect to MongoDB so that you can run more commands.
Here is the command to connect to MongoDB

mongo --host=localhost --port=27017

All you need is the name of the host and port number, 27017 is the default port number and since we running the command on the MongoDB host, the host is localhost
















Monday, November 15, 2021

The map() method is similar forEach() method which means that it performs a function, however it returns a new array with the returned values.  In this example we are going to perform the $1 discount of the oil prices using the map() method instead of the forEach() the difference here is that the map() method returns a new array instead of the original array, but the result will be the same.


    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 76.99];

        var discounted = oilPrices.map(function (value) { return value -1; });

        console.log(discounted);
    </script>


Friday, November 12, 2021

The conditional ?: operator in JavaScript has three operands the first part goes before ? the second goes between the ? and the : symbol and the third operand goes after the : symbol.  You can think of this operator as shorthand way of writing a an if statement.  The first operand evaluates to a boolean, if the first operand is true then evaluate the second operand else evaluate the third operand.

Let's say we want to want to see what the gender of the baby is and assign it a name, let's demonstrate it with code.

var gender = "girl";

var name = gender === "boy" ? "Julian" : "Julie";

console.log(name);

The code above assigns the variable gender to "girl" then it uses the conditional ?: to assign a value to the variable name if the gender is "boy" then assign the name "Julian" to name, else assign the name "Julie"

Thursday, November 11, 2021

JavaScript error handling is a lot like other languages where you have the try/catch/finally  statement that you can used.  The basic premise is

try
{
     // try some codes here fingers crossed that nothing bad happens
}
catch(ex)
{
     // oops something bad happened, this is where it gets handled or I tell the user
}
finally
{
    // I don't care what happens I am going to execute and get paid
}

Here is the error handling in action:

Wednesday, November 10, 2021

 In the previous post we created four instances with a Launch Template. In this post we are going to add DNS records in Route 53 and configure our Application Load Balancer with our certificates.

Before we start creating stuff let's take a step back and look at how we want to configure the website.  Let's say a bank wants to branch out into investing, so it wants to dedicate to instances to it's investing arm.  In our architecture we would have two target groups, one target group handling traffic for https://acmebanking.com and the other target group handling traffic for https://investing.acmebanking.com

We are going to register all four instances on the load balancer.

1. So now we ready to create an Application Load Balancer, give it a name and for the listener add an HTTPS listener to the existing one


Monday, November 8, 2021

The most common ways you see how objects are created in JavaScript is the object literal syntax.  The object literal syntax is the open { } with comma separated name: pair value lists.  The name: part is the name of the property.  The part after : is the property value which can hold a primitive value or another object.  It could even be a function.

Here is an example of an object literal:

var product = {
    name: "Chai",
    Category: "Tea",
    Country: "India",
    supplier: {
        name: "ACME Tea Of India",
        location : "New Delhi"
    },
    related: ["Earl Grey", "Green Tea", "Dark Tea", "White Tea"],
    display: function () {
        console.log(this);
    }
};

Friday, November 5, 2021

The eval() function in JavaScript provides the power of dynamic evaluation, it evaluates a strings of JavaScript codes and returns a value.  If you use the eval on pair of string numbers it will be forgiving and give you the number if it can.  For example if you type int

eval("4+5")  the result will be 9 even though it's a string

Thursday, November 4, 2021

In the previous post we visited how to create an object with an object literal.  In this post we are going to create the same object using the new keyword.  When creating objects using the new keyword it is required that the it is followed by a function call.  The purpose of this function call is the needs a way to call to the constructor of the new object.  A constructor is used to create or initialize the created object.

Here is the code to rewrite our literal object using the new keyword:

var product = new Object();

product.name = "Chai";
product.category= "Tea";
product.country= "India";
product.supplier= {
    name: "ACME Tea Of India",
    location: "New Delhi"
};

product.related = new Array("Earl Grey", "Green Tea", "Dark Tea", "White Tea");
product.display = function () {
    console.log(this);
};

Wednesday, November 3, 2021

 In the previous post we created our certificates in the Certificate Manager, in this post we are going to create four instances using a Launch Template so that we could use it in our load balancer.  

1. We are actually going to use "Launch Template" to create our instances, so click on "Launch Templates" under "Instances" in the EC2 Dashboard

2.  Click on the "Create launch template" button
3. Give your template a name, then scroll down to AMI type


Tuesday, November 2, 2021

In this post we are going to install MongoDB on a Linux operating system.

Here are the steps:

1.  Download the community edition of MongoDB from the page https://www.mongodb.com/download-center?jmp=nav#community click on the "Linux" tab is selected and select the Linux version that you want

Monday, November 1, 2021

Object.Create( ) is a static function which can take two arguments.  The first argument is the prototype of the object, while the second argument is the properties of the argument.  A prototype is a second object that is created with every JavaScript object.  It is like a blueprint, or the model that the object is built on.  Think of it as a car prototype.

So let's create an object with Object.Create( ) function:

var person = Object.create({
    name: "Tech Junkie",
    location: "Mars",
    hobbie: "Video Games"
});

console.log(person);

Friday, October 29, 2021

In JavaScript anything defined outside of a function is considered a global scope while anything that's defined inside a function is called a variable scope (local or function scope) meaning it exists inside the lifetime of the function.  Let's use code to demonstrate this point


var streetFighter = "Ryu";

function displayFighter()
{
    var streetFighter = "Ken";

    console.log(streetFighter);
}

displayFighter();


Thursday, October 28, 2021

In JavaScript there are two ways to access an object, first by dot notation like this

product.name

or with array notation

product["name"]

They both get the job done.   However with the array syntax [""] you access the object as if it's an array but instead of accessing it by numbers or index you access it by the property names.  That's because JavaScript objects are associative arrays.  They look like other objects in other languages such as C, C++, and Java.  However they behave very differently.

In other languages objects are defined in advance, their properties are methods are fixed.  To add a property or method to the object you have to change the class the object instance is created from.

Wednesday, October 27, 2021

 In this post we are going to set up our website to serve up https traffic so that our traffic can be encrypted.  In this post the first part of the series we are going to request a certificate from the Certificate Manager in AWS.

1. The first thing we need to do is create a certificate, In the AWS search field search for Certificate Manager then click on the drop down auto complete choice.



2. Click on "Get started" under "Provision certificates"

Tuesday, October 26, 2021

In a typical git scenario you would have a new branch for developers to work on, the when he or she is done. You do your code reviews and what not.  After you are satisfied with the results you would want to merge the new branch into the master branch.

In this post I am going to show you how to merge an existing branch into a master branch

Here are the steps:

1. First you want to checkout the master branch to work on it with the command git checkout master












Monday, October 25, 2021

Now that we've learned to create objects in all sorts of ways it's time to set and get the object properties that we've created.  In this blog we will go over how to access the object properties either to set them or get them.

First let's create an object that we can work with:

Type in the following code in the between the <script type="text/javascript"></script> tag in an html page.


        var product = new Object();

        product.name = "Chai";
        product.category = "Tea";
        product.country = "India";
        product.supplier = {
            name: "ACME Tea Of India",
            location: "New Delhi"
        };

        console.log(product);
If you run the page with the code above you will see the following in the browser console:

Friday, October 22, 2021

When the browser window opens and navigates to a webpage with your JavaScript code. A global object is created for your JavaScript program.

If you type the following line as the first line of code in your JavaScript file

var globalObj = this;

What do you think will get?  In this case you are referencing the Window object, which is JavaScript's object for the browser window.  As you can see there's a whole bunch of global properties and methods already defined at the global level.

Thursday, October 21, 2021

There are times when you will get an error when you tried to access a property in an object, sometimes you think a property exists in the object but it does not.  Let's use the product object from the previous blog post as an example.


        var product = new Object();

        product.name = "Chai";
        product.category = "Tea";
        product.country = "India";
        product.supplier = {
            name: "ACME Tea Of India",
            location: "New Delhi"
        };

Let's say another developer works on the project and he assumes that since there's a "country" property that there should be a "city" property.  If he tries to access the access the "city" property in the product object he will get an undefined, because the property does not exist.   If he types the following he will get the undefined message.

Wednesday, October 20, 2021

 In this pose we are going to implement auto scaling on our instances.  Auto scaling is a feature on AWS that automatically scaled horizontally either based on metrics or the health of an instance. In this post we are going to setup auto scaling on an Application Load Balancer.  

1. The first thing we have to do is setup an Auto Scaling Group under "Auto Scaling" click on "Auto Scaling Groups"

2. Click on the "Create Auto Scaling group" button

3. Give your auto scaling group a name, then click on the "Create a launch template"


Tuesday, October 19, 2021

In previous posts we created a new git repository locally and on github and then sync them up.  In this post we are going to create a new branch in the local git repository and push it to the remote repository.


First let's create a new branch with the following command in the local git repository

git checkout -b "Hour2"








Now following the tutorials in this post Hour 2: Enable ASP.NET Core to Serve Static Files

After you are done open the command line in the folder and type git add .

Monday, October 18, 2021

In JavaScript you can delete an object's property with the delete operator.  Let's use the product object again as an example.

Let say you have the following JavaScript code to create a product object.


        var product = new Object();

        product.name = "Chai";
        product.category = "Tea";
        product.country = "India";
        product.badProperty = "Bad Property";
        product.badProperty2 = "Bad Property 2";
        product.supplier = {
            name: "ACME Tea Of India",
            location: "New Delhi"
        };

console.log(product);

Friday, October 15, 2021

One of the most common task you have to do as a Linux administrator is to add a new user.  Especially developers who always wants root access. Docker needs root access, however the person who is administering Docker is probably not the system administrator.  Most likely it will be the application developer. To accomplish this task you can use the useradd command in the Terminal session then add the new user to the Docker group.  Follow the steps below to add a new user to CentOS.

Thursday, October 14, 2021

Most people don't realize JavaScript has object property setters and getters or accessor methods.  When an object has a setter only it is a write only property, when it has a getter only method that it is a read only property.  If a property has both then it is a read/write property.  A perfect example is if you are working with a private property in JavaScript which has the $ prefix in front of it.

Let's say you have an object with a private property $n like the example below:


        var game = {

            $n: "Awesome Game!",

            get name() { return this.$n}
        };

The code above only has a getter name that exposes the private property $n when you console.log you should get value of the $n like the code snippet below

Wednesday, October 13, 2021

 In the previous post we went over how to create a Application Load Balancer, based on routes in the URL.  In this post we are going to change the rules so that it directs traffic based on host names.  For example we could have acmebanking.com route to target group 1 and accounts.acmebanking.com route to target group 2.  It's the same concept as the previous setup but instead of routes, we are using hostnames instead.

In order to implement this solution we need to setup a record in Route 53, which is AWS domain registration service.  You can follow along with the DNS names, but if you have a hostname registered with AWS that's even better.

1. So the first thing you want to do is go to Route 53 dashboard, go to Hosted Zones

2. Click on the hosted domain


Tuesday, October 12, 2021

In the previous post we created a local git repository, in this post we are going to create a remote repository in github and link it to the local repository that we created.

Here are the steps to create a new repository in github:

1.  Log into your github account and click on the "New" button next to the text "Repositories"










Monday, October 11, 2021

One of the main concept of working with Bootstrap is the Grid system.  It could be intimidating at first to work with the Grid system.  But the system is quite elegant and simple solution.

The most important thing you have to remember about the grid system is that it divides the page into 12 columns, and it is responsive meaning it will adjust to the size of the client's screen.

You can control the size of the column with the .col-sm, .col-md, .col-lg, .col-xl, which translates to small, medium, large, and extra large screens.  In addition to the screen size you can also control the with of the column with the -n at the end of class attribute.  For example if you want a column for a small screen to span three columns it would be .col-sm-3.

Here is the cheat sheet, I am going to use color coding for the different sizes.

Small - Green
Medium - Orange
Large - Red
Extra Large - Blue


Friday, October 8, 2021

In our previous blog posts we ran containers with the Fedora and CentOS images.  In this blog we are going to run a command to see which containers are running in our host system.  To get a list of all the containers running on our host Ubuntu system we type in the command docker ps -a command.

Thursday, October 7, 2021

The while loop statement in JavaScript simply executes a statement block until a condition is not true anymore the syntax for the while loop is as follow

while (expression is true)
{
     execute these statements
}

The while loop is an iterative loop if the condition is true and the statements are executed, it starts at the top of the loop again and executes until the expression is false.  Therefore, there's a potential for an infinite loop.

Wednesday, October 6, 2021

 In the previous post we went over how to create a Network Load Balancer, in this post we are going to create one of types of load balancer AWS offers.  We are going to create a Application Load Balancer, this balancer  is designed to work best with the typical line of business web applications.  It deals mostly with the requests/response scenarios on the web, therefore it supports the HTTP, and HTTPS protocols exclusively.  It can be setup to respond to the routes that configured or the hosts.  It all depends on how your web applications serves the client.  In a way it's the easiest load balancer type to understand because it deals with headers, URLs,  routes,  parameters, query strings and etc.

Before we create the load balancer we need to create more than one instances with a web server because we need to test that the load balancer is able to switch.

1. Create four instances with the user data to create Apache Web Servers with these commands in the User Data for instance, if you need the full instruction on how to create instances with User Data you can read this post . 

#cloud-boothook
#!/bin/bash
#Use this for your user data (script without newlines)
# install httpd (Linux 2 version)

yum update -y 
yum install -y httpd.x86_64 
systemctl start httpd.service 
systemctl enable httpd.service 
echo "Hello world from $(hostname -f)" > /var/www/html/index.html
cd /var/www/html/
cp index.html contacts.html

We just created an index.html file to write out the hostname for testing later on, we also created a new file called contacts.html so that we can have different routes.

To create more than one instance at a time, type in the number of instances in the "Number of Instances" field.  Select no preferences for the subnets






Tuesday, October 5, 2021

In this blog post we will create a Git & Github repository for the Northwind Cafe application that we've been working on.

First let's create a git local repository

1. Follow the steps on this blog post to create an empty NorthindCafe in git repository using Visual Studio Hour 1: Create ASP.NET Core Project From Scratch




























Monday, October 4, 2021

The do/while loop is similar to the while loop.  The difference is that the first the loop expression is tested after the do statement block is executed at least once.  For example let's use our countdown example again.

If we have the code below the countdown displays the same results as the output.  However, the first iteration is performed without a evaluation of the expression.  It's not until the countdown is 9 that the while part of the loop kicks in.

Friday, October 1, 2021

The beauty of Docker is that you can run a very lightweight image of another Linux distro on your host system.  In this post we will be pulling the latest image of CentOS into our docker container on our Ubuntu server.

Thursday, September 30, 2021

The for/in loop is a for loop that is used to iterate through the variables in an object. It can iterate to through that anything that can evaluated on the left side of the assignment expression call the LValues.  Let's use the for/in loop to iterate through an object "person".

Here we created an object called "person" with three properties we are going to use the for/in loop to display the property names as well as the values of those properties

var person = new Object();

person.name = "Tech Junkie";
person.occupation = "Blogger";
person.location = "Mars";

for(var p in person)
console.log(p + ": " + person[p]);

Wednesday, September 29, 2021

 In the previous post we went over how to create a Classic Load Balancer, in this post we are going to create one of types of load balancer AWS offers.  We are going to create a Network Load Balancer, this balancer  is for websites that require high performance and low latency websites, think of streaming data.  If your website needs real time streaming data, this is probably the load balancer for you. It supports layer 4 protocols such as UDP, TLS and TCP protocols. If you need a static IP or Elastic IP assigned to your load balancer this is your only choice because the other two load balancer does not give you the option to assign Elastic IPs.

Before we create the load balancer we need to create more than one instances with a web server because we need to test that the load balancer is able to switch.

1. Create two instances with the user data to create Apache Web Servers with these commands in the User Data for instance, if you need the full instruction on how to create instances with User Data you can read this post

#cloud-boothook
#!/bin/bash
#Use this for your user data (script without newlines)
# install httpd (Linux 2 version)

yum update -y 
yum install -y httpd.x86_64 
systemctl start httpd.service 
systemctl enable httpd.service 
echo "Hello world from $(hostname -f)" > /var/www/html/index.html

We just created an index.html file to write out the hostname for testing later on


Tuesday, September 28, 2021

In the previous post we installed Git on Windows.  On this post we are going to set up Git with our user name and assign Bracks as our Git editor so that we don't have to edit git through the command line console all the time.

Here are the steps to setup your user name and editor for git:

1. First let's set our user name, with the command git config --global user.name "Your name goes here"









Friday, September 24, 2021

The beauty of Docker is that you can run a very lightweight image of another Linux distro on your host system.  In this post we will be pulling the latest image of Fedora into our docker container on our Ubuntu server.

Thursday, September 23, 2021

Sometimes you don't want to do everything with the root account.  So there are some super users who you trust as administrators.  For those users you want them to be able to run the sudo command.  A sudo command allows a user to run commands with root privileges without logging in as root.
For example something like this sudo yum update unlike the su command which prompts you for the root password.  The sudo command prompts you for the password of the logged in user.

In order for the sudo to work we have to configure the /etc/sudoers file.  There is a special command for editing the sudoers file and it's the visudo command.  This command should be used at all times when editing the sudoers file instead of a text editor.

Wednesday, September 22, 2021

 If your website starts to become popular, especially if it's not static you might noticed that the performance is starting to degrade.  The most logical step is to scale your architecture with a load balancer.  AWS offers three types of load balancers, there are:

  • Application Load Balancer
    • Protocols (HTTP, HTTPS)
    • Specializes in web applications, deals with traffic at the request level (layer 7)
      • Supports query strings, path routing, parameter routing, IP routing
    • Supports IP addresses, Lamda Functions (serverless, microservices), and containers
  • Network Load Balancer
    • Protocols(TCP, TLS, UDP, TCP_UDP) - Layer 4
    • When high performance and low latency is required
    • TLS offloading
    • Elastic IPs can be assigned
  • Classic Load Balancer
    • Protocols (TCP, SSL, HTTP, HTTPS) - Layer 4, 7
      • Old generation, not recommended unless you are running EC2-Classic instance

    In a nutshell a load balancer distributes the client's traffic among the many instances that are available in your architecture to offload the traffic so that more than one instance can share the burden of the traffic.  A health check is setup so that only the health instances can serve up traffic.




    Tuesday, September 21, 2021

    If you are developing Java EE applications, then WildFly is an excellent web application that you can set up easily.  In this post we are going to setup WildFly on a Windows machine.  The instructions should be similar for a Linux machine, it's just that the files ends with the .sh extensions.

    Here are the steps to setup WildFly on your machine:

    1. Go the WildFly website and download the latest version, https://wildfly.org/downloads/


















    Monday, September 20, 2021

     In the last post we created a new partition for a new disk that we've just added, in this post we are going to mount the partition and create a filesystem for the partition so that we can use it.  First lets check to see that we have a new partition by running the fdisk -l command














    As you can see a new partition called /dev/sdb1 has been created with 8 GB of disk space.  Now we all good to go.

    Here are the steps to mount and create a file system in Linux:

    1. First we need to create a filesystem so that the Linux system can read and write to it.  Linux uses the xfs filesystem so that's what we are going to use.  To do that we have to run the mkfs command. To make an xfs filesystem you simply type mkfs.xfs /dev/sdb1







    2. Now that we have a filesystem that Linux could understand, it is time to mount the partition so that we could use in our server.  It's a two step process to accomplish that, first you have to create a directory, type mkdir /data to create /data directory.  Then you are going to mount the partition to that directory with this command mount /dev/sdb1 /data now if you run the command df -h you will see the partition has been mounted to the /data director








    3. We still have one more step before we are finished.  Everything will work like it should, but once you reboot the settings will not persist in it's current state.  To make the settings persist we have to edit the fstab file.  So type the command vi /etc/fstab make sure you have your system backed up and you can revert back because if you messed up you will not be able to log in. When you are in the fstab file type in the following line at the end of the file

    /dev/sdb1               /data                   xfs     defaults        0       0

    The spaces are tabs, the 0s are options for file system checks on boot.  You probably don't want that, so just type 0s to skip it. Press esc and :wq! to write to the file.














    4. Reboot and run the df -h command again and you should see that the changes persist and you can use the new partition


    Friday, September 17, 2021

    One of the most common task you have to do as a Linux administrator is to add a new user.  Especially developers who always wants root access. Docker needs root access, however the person who is administering Docker is probably not the system administrator.  Most likely it will be the application developer. To accomplish this task you can use the useradd command in the Terminal session then add the new user to the Docker group.  Follow the steps below to add a new user to Ubuntu.

    Thursday, September 16, 2021

    In the previous post we created a user called "John Wallace", in this post we are going to add John and Jason into the developers group.  In any system you want to group users into groups so that you can easily assign constraints and privileges to a group of user instead of doing it one at a time.

    Wednesday, September 15, 2021

     In the previous post we went over what a load balancer is, in this post we are going to create one of types of load balancer AWS offers.  We are going to create a Classic Load Balancer, this balancer is not recommended by Amazon, you should only create this if you have to support EC2-Classic instances.

    Before we create the load balancer we need to create more than one instances with a web server because we need to test that the load balancer is able to switch.

    1. Create two instances with the user data to create Apache Web Servers with these commands in the User Data for instance, if you need the full instruction on how to create instances with User Data you can read this post

    #cloud-boothook
    #!/bin/bash
    #Use this for your user data (script without newlines)
    # install httpd (Linux 2 version)

    yum update -y 
    yum install -y httpd.x86_64 
    systemctl start httpd.service 
    systemctl enable httpd.service 
    echo "Hello world from $(hostname -f)" > /var/www/html/index.html

    We just created an index.html file to write out the hostname for testing later on


    Tuesday, September 14, 2021

    In order to host websites in Tomcat we need to create a project to host servlets.  In this post we are going to create Dynamic Web project in Eclipse.

    Here are the steps to create a web project in Eclipse:

    1. Right-click on "Servers" → "New" → "Other"

    2. Expand the "Web" node then select "Dynamic Web Project", then click "Next"→



























    Monday, September 13, 2021

     In the previous post we used the df and fdisk commands to gather storage information about our Linux system.  In this post we are going to add a new disk and partition to our system.  I am using VBox and you can create a new storage by going to settings and adding a new disk, it will be just like adding a real physical disk on a physical machine except it's virtual.  You can go to this post if you want to know how to do it

    Here are the steps to adding a new disk and creating a partition for the disk:

    1. First we want to see what the new disk is identified as in our Linux system, we can do that by typing the command fdisk -l








    As you can see the new disk is identified as /dev/sdb and it has 8 GB which is correct

    2. We want to go into the fdisk utility to work with our new disk, to do that you type fdisk /dev/sdb then press enter





    3. Press m to see all the options that are available





















    From the help menu we know that we have to use the n option to add a new partition

    4. Type n and then press Enter to get into the create partition steps

    5. You will be given a choice of the partition being a primary or extended, since this is a new disk we want to make it a primary partition, so press p and ENTER






    6. For the partition number accept the default 1 by pressing ENTER, once again it's a new disk so it's going to be the first partition on the disk

    7. Accept the default again for the first sector by pressing ENTER





    8. Accept the default again by pressing ENTER, if you want to create more than one partition and not use the entire disk you enter the size so that there's disk space left like this +4G, and it would use only 4 GB for the partition, but since we want to use the entire disk we just going to press ENTER







    A new partition has been created for the new disk.  Or have you? A lot of beginners forget to do the next step and the partition is not created even though they went to through all the steps. The final step to the process is that you have to type w to write your changes else nothing will happen.  It's just a confirmation that fdisk needs, for you to confirm that the changes are correct in the final step.





     In the next post we are going to mount the partition and create a filesystem for the new partition.

    Friday, September 10, 2021

    In the previous post we installed Docker on our Ubuntu server.  Now we are going to add the Docker repository to our local server so that we can get the latest version of Docker.

    Thursday, September 9, 2021

    In our previous post we type in the yum command yum update to update the entire CentOS server.  But the most common operation that you will perform with yum that you will perform is to install, update, and remove an individual package.

    In this post we will install, update and remove the php package.

    Wednesday, September 8, 2021

     In the world of AWS you have to be familiar with the different features and what they are called.  Well two very important building blocks of all the services that AWS offers are the S3 and the IAM Role.  S3 is basically an object storage repository that are called buckets, but it is more than just a storage, you can turn to the storage into a static website. We'll get into that later. It's public facing, so you can access it over the internet. 

    IAM Role is an identity that you can assign policies to and that role assumes the permission.  Therefore only instances with a role that has a policy to access S3 can assume that role and have access to the S3.


    So let's start creating the assets on the diagram above:

    Tuesday, September 7, 2021

    In this post we are going to set Tomcat as a server in Eclipse so that we can interact with Tomcat through Eclipse.

    Here are the steps to configure Tomcat to work with Eclipse:

    You have to download the zip file version of the install to make Tomcat work with the Eclipse.  I had no luck with the Windows Installer

    So go to https://tomcat.apache.org/download-90.cgi

    Then click on the .zip version of the download, and then extract the files into the





















    Now extract the content of the zip file into the folder C:\apache-tomcat-9.0.24

    Monday, September 6, 2021

     To simulate a real world scenario often times you have to add components to your virtualize Linux operating system.  In this post we are going to add a new disk to our virtual machine in Oracle's VirtualBox.  

    Here are the steps to adding a new disk to a VM:

    1.  Right click on your virtual machine and select settings then select "Storage", the power must be off.  Click on the second icon next to the "Controller: SATA" section








    2. On the next dialog click on the "Create" icon









    3. Click "Next"














    4. Click "Next"














    5. Type in a name for the disk and then click "Create"














    6. Select the disk under "Not Attached" and then click on "Choose"














    7. Now your new disk is attached to the Virtual Machine, click "OK"






    Search This Blog