Tech Junkie Blog: 2018

Tuesday, August 14, 2018

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







































2. After you download the file extract the file with the tar command

tar -zxvf mongodb-linux-x86_64-rhel70-4.0.1.tgz










3. Create a new folder in the /opt/ directory call mongodb with the command mkdir /opt/mongodb
4. Copy the extracted files to the newly created folder with the command

cp -R -n mongodb-linux-x86_64-rhel70-4.0.1/ /opt/mongodb

5. Type mongod to verify that MongoDB has been installed

















































You will noticed that MongoDB tries to start itself but shut itself down because there's no data 
folder that it expects.  That's easy enough to fix.  All you have to do is type in the following
command in the terminal

mkdir /data
mkdir /data/db/

Now you can type mongod to start MongoDB.







































Monday, August 13, 2018

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>

Friday, August 10, 2018

Linux installation comes with OpenJDK, but you want to use the official JDK from Oracle instead to run most of the software.  This post will show you the steps to install the Oracle JDK

First let's check to see what version of JDK we have installed by running the command

java -version










As you can see Fedora installs the OpenJDK library by default.  What we want to do is replace it with the Oracle version instead.

Type the address http://www.oracle.com/technetwork/java/javase/downloads/index.html
into Firefox in the Fedora VM and click on the "JDK" download button


































Thursday, August 9, 2018

One of the most useful feature in Azure is the ability to reset your virtual machine's password.  There will be times when you create a virtual machine that you put aside for a long time and you forgot the password for the machine.

To reset your password do the following:

1.  Log into Azure by typing the URL https://portal.azure.com
2. Click on the "Virtual Machines" link






3. Select the virtual machine you want to reset your password on










4. Click "Start" to start the machine, your machine must be running before you can reset your password











5. Under "SUPPORT + TROUBLESHOOTING" select "Reset Password"












6.  Select the "Reset Password" radio button, enter the username and password you want to reset to.  Then click "Update" when you are finish




















Surprisingly the reset password function takes a long time to apply. So you have to wait for a while before you can use your virtual machine again.




Wednesday, August 8, 2018

An ASP.NET MVC can get big, and it could be overwhelming.  Areas are a way to break up the application into smaller segments,  A perfect candidate for an Area is the Administrative features of the site because it has multiple pages, and functionalities.  So it is a good idea to segment off the Administration area to its own area (no pun intended).

To add an Area to your MVC application right-click on the project and click "Add", then select "Area..."


















Type in the word "Admin" in the "Add Area" dialog










Make sure AreaRegistration,RegisterAllAreas method is called in the Global.asax.cs file so that your "Admin" area is registered















The Areas folder structure should look like this.















Now we want to create a controller for the Admin Area, right-click "Controllers" folder under "Admin" and click "Add", then select "Controller"








Select and empty controller










Call the controller "HomeController", then click "Add"










Open the HomeController.cs file under the "Contollers" folder in the "Admin" folder, right-click on the "Index" method, then click "Add View"

















Except the default options for the view and select "Add"






















Open the Index.cshtml and type in the following code

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<h1>This is from the Admin Area</h1>

Now if you type in the route /Admin/Home/Index you see the message "This is from the Admin Area"























Now comes the annoying part about Areas, when you type in the route /Home/Index you will get an error that the Home controller is not unique.  That is because the MVC framework puts all controllers in finds in the application into a flat list regardless of namespace.





























In order for us to fix this issue we need to specify the namespace in both the "AdminAreaRegistration.cs" file and RouteConfig.cs file

First let's fix the AdminAreaRegistration.cs file, open the file and type in the following code in the RegisterArea method


        public override void RegisterArea(AreaRegistrationContext context) 
        {

            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                new string[] { typeof(NorthwindCafe.Areas.Admin.Controllers.HomeController).Namespace }
            );
        }


Notice in the last line new string[] { "NorthwindCafe.Areas.Admin.Controllers" } we set the namespace for the Admin Area controls so that MVC looks for the controllers that are only in that namespace









Now let's do the same thing for the RouteConfig.cs file. Open the RouteConfig.cs file and change the routes.MapRoute method to the following


            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                namespaces: new string[] {typeof(NorthwindCafe.Controllers.HomeController).Namespace}
            );

Now when you type in the route /Admin/Home/Index you see the Admin Index.cshtml page













And when you type in the /Home/Index route you see the application home page



















Tuesday, August 7, 2018

Monday, August 6, 2018

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>

The code above basically intialize the counter functionCount property and calls the function ten times and then output the counter property directly through the functionCount object, which is ten.


Friday, August 3, 2018

In our previous series we've gone over how to install Ubuntu Server on Oracle VirtualBox to use it as a server.  In this series we will go over how we can use the Fedora desktop as your developer's machine/virtual machine.  Having a Linux developer machine is great because a lot of the more expensive Windows developer's program are expensive.  There's usually a Linux equivalent application that is comparable to their Windows big brother that are usually free or a lot less expensive.  Also most Java technologies work better on Linux than Windows.  So let's begin on journey into the Linux desktop experience.















Thursday, August 2, 2018

In this tutorial we will add icons to your navbar.  In the previous tutorial we added a responsive layout with bootstrap.  In this post we will add some icons to your navigation.  Font-Awesome gives you professional looking vector graphics, which are implemented using CSS.  Bootstrap 4 uses Font-Awesome as it's icons. Glyphaicons will goes away. So we might as start using it.

Just to review this is how our layout looks like in our previous post.























Wednesday, August 1, 2018

With Azure, any developer can easily add a membership service immediately when you are ready to use it.  In my other tutorials we started to create the "Northwind Cafe" sample application.  Traditionally, we would store our user information in an SQL Server database.  While that would be the easiest place to store user information.  There are many downsides to doing that, for instance you have to lock down the SQL Server so that hackers are not able to hack into the database.  You also have to worry about network security and so forth.  The beauty of Azure |AD is that you let Azure take care of all of that.  It also comes with many services already built-in like OAuth, and two-factor authentication.

Before we go on, we need to make the distinction that Azure AD is not the same thing as your on-premise AD.  Your on-premise machines will still be managed by your on-premise Active Directory.  Azure AD is designed to scale your internet-based applications and APIs.

So let's get on with it!

To create a new Azure AD in Azure log into the Azure portal at https://portal.azure.com

1. Now click on the "Create a resource" link in the Azure Portal

Tuesday, July 31, 2018

In our previous blog post we installed CentOS on our local virtualization software call VirtualBox.  In this blog we are going to go through how we are going to do the same in Azure, and host our CentOS server on the cloud.

People often get confused when they work with Azure because there are two versions of Azure.  Most people call it the classic mode and the new portal Azure or the more official term is ASM vs ARM.  In this post we will create a CentOS Linux virtual machine in the new Azure portal.

Follow the steps below create a new Azure portal:

1. Go to the URL : https://portal.azure.com
2. Log in with your Azure credentials
3.  Click on "Virtual Machines" make sure it doesn't say classic on the link





















Monday, July 30, 2018

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.

The following is the formula for a radius according to Google












Here is the code to calculate the radius of a circle in JavaScript


    <script>

        var r = radius;

        function radius(circumference) {
            return circumference / (2 * Math.PI);
        }

        console.log(r(10));

    </script>

The code above returns a value of the radius by dividing the circumference by 2*Math.PI and outputting the result to the console log.  Notice once we assign the function to the radius to variable r, we can use the variable r in place of the function radius.

Here is the result:









Sunday, July 29, 2018

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


Oh, before I forget the grid system needs to be wrapped around by a .row CSS class.

1. First let's create our small columns, with this code


<body>
    <br/>
    <blockquote>
        <div class="container-fluid">
            <div class="col-sm-12">
                <div class="row">
                    <div class="col-sm-1 font-weight-bold bg-success border border-dark">col-sm-1</div>
                    <div class="col-sm-2 font-weight-bold bg-success border border-dark">col-sm-2</div>
                    <div class="col-sm-3 font-weight-bold bg-success border border-dark">col-sm-3</div>
                    <div class="col-sm-4 font-weight-bold bg-success border border-dark">col-sm-4</div>
                    <div class="col-sm-5 font-weight-bold bg-success border border-dark">col-sm-5</div>
                    <div class="col-sm-6 font-weight-bold bg-success border border-dark">col-sm-6</div>
                    <div class="col-sm-7 font-weight-bold bg-success border border-dark">col-sm-7</div>
                    <div class="col-sm-8 font-weight-bold bg-success border border-dark">col-sm-8</div>
                    <div class="col-sm-9 font-weight-bold bg-success border border-dark">col-sm-9</div>
                    <div class="col-sm-10 font-weight-bold bg-success border border-dark">col-sm-10</div>
                    <div class="col-sm-11 font-weight-bold bg-success border border-dark">col-sm-11</div>
                    <div class="col-sm-12 font-weight-bold bg-success border border-dark">col-sm-12</div>
                </div>


The resulting visual looks like this in the browser. As you can see col 1 to 4 can fit into one line.  As the columns increase in size it takes up more space. 5+6 = 11 so it can fit in one line.  However, anything after 6 will only fit into one line if it's in the same row.  It's gets simple if you just add everything to 12 so 7+4+1 = 12, or 7+3+2 = 12 would be okay.


















Tuesday, July 24, 2018

In most environments you are not allowed to have direct access to the Linux server.  The most common way to gain access is through a secure shell connection or SSH.  The most common tool that is used on a Windows environment to connect to Linux is a utility software call Putty. In this post we are going to connect to our CentOS instance that we've installed on VirtualBox.

First let's setup our CentOS on VirtualBox for client connection.

1.  Click on "Settings"


















2.  Now choose "Network",  make sure "Enable Network Adapter" is checked, then select "Bridged Adapter".  The bridge adapter option allows your virtual machine to use the host's network adapter as if its own network adapter.



























3.  Expand the "Advanced" section and select "Allow All"  for "Promiscuous Mode", not sure why it's called Promiscuous Mode



























4.  Now log into your CentOS instance and type ifconfig into the terminal






















Record the "inet" IP Address because this is the address that you will use in Putty

5.  Now launch Putty and put the IP address in the Host Name (or IP Address) field, then click "Open"





































6. When prompted for a login, type "root" and then enter the password for root










That's it, now you are connected to your Linux instance that is hosted on VirtualBox using SSH.



Monday, July 23, 2018

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>








The code above encapsulates the copyAll function inside the copyNumbers function, which performs a for loop to copy an array of numbers.  Since the arguments object is an object, it can have properties.  So we pass in properties instead of parameters to make the code more readable.  However, the code is not as efficient as a direct call to the function.  Just like anything in programming there's a trade-off.  It's up to you, whether you are willing to make that trade-off.


Sunday, July 22, 2018

In older versions of SQL Server, the "sa",  System Administrator account is given a blank password by default.  In SQL Server 2014, that is no longer the case.

To set the "sa" account's password, perform the following steps:

Connect to SQL Server instance using by clicking on "Connect" then select "Database Engine"




Saturday, July 21, 2018

In this tutorial we will add the INSERT functionality to our GridView control.

Follow the steps below to enable insert on our GridView control.

1. Open the source view in the .aspx page and add the ShowInsertButton attribute to the <asp:CommandField element inside the <asp:GridView element

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:CommandField ShowInsertButton="True" />
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
                <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
                <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
                <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
                <asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" />
                <asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel" SortExpression="ReorderLevel" />
                <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" />
            </Columns>
        </asp:GridView>

2. Click on the ">" icon on the SqlDataSource control to configure the datasource, then click on the "Configure Data Source" link

3.  Click next twice until you see the "Configure the Select Statement" screen, click on the "Advanced.." button.  Then check the "Generate INSERT, UPDATE, and DELETE statements" and the "Use optimistic concurrency" checkboxes. Then click "OK"





Monday, July 16, 2018

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>







If you remember our previous addNumbers function it only takes two numbers and and add them.

With no parameters specified we can specify as many parameters as we want and add the numbers based on the number of parameters to get the total.  The draw back with this approach is that we don't have any named parameters, which means that we can only to the parameters via the arguments object like this argument[i].  However, we don't have to know the exact number of parameters ahead of time for our function.  So there is a trade-off.




Tuesday, July 10, 2018

In previous blog we've installed the CentOS operating system on VirtualBox however, when we reboot, it takes us to a text prompt.  In this blog we will be installing a graphical desktop environment to our operating system using "yum".  Follow the steps below to get the Gnome desktop in your CentOS.

1.  Make sure you have internet connection
2.  Click "Start" on your "CentOS" VM










Monday, July 9, 2018

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.

The following code is a simple function that adds two numbers together


            
<script>
        function addNumbers(x, y) {
            return x + y;
        }

        console.log("The sum of 1 + 3 is " + addNumbers(1, 3));
</script>






The code above creates a function called addNumbers with two parameters and returns the sum of the two numbers


Tuesday, July 3, 2018

If you are a startup or an entrepreneur, learning Linux is essential. Most of the open source and latest innovations starts out with Linux such as Docker.  That's because Linux is for the most part free and has a great community of techies supporting it.  Even Microsoft loves Linux now, it even made a commitment by releasing SQL Server on Linux.  Although it could  be a fling, instead of a long term engagement.  Also if you noticed the Virtual Machines on the clouds are cheaper if you choose the Linux version.  In this series on Linux I will go over what you need to do to get yourself started on Linux.  The best way to learn about Linux is to install it on a Virtual Machine.  We could host it on the cloud, but then we need to pay for it.  There are some free-tiers but they are limited.  So we are going to use VirtualBox from Oracle to host our CentOS instance.

On the previous blog we went over how to create a new virtual machine for CentOS in VirtualBox.  In this blog we will go over how to install the CentOS ISO file on the new virtual machine that we've just created. Below are the step by step instructions of how to install CentOS on VirtualBox.

Step-By-Step Instructions:

1. Launch VirtualBox, right-click then select "Settings"


2.  Click on "Storage", you will see the disc icon is "Empty"

Monday, July 2, 2018

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.