Monday, November 21, 2016

Angular 2 Part 3.1 - Splitting to Two Components (Exporting & Importing)

In part 3, we are going to split our code (Component, HTML, CSS, Model and Mock) into different files. Splitting our code into different file allow our code easy to maintain as well as easy to scale.

In this section, we are going to split our component into multiple files.
  • main.ts - where we'll bootstrap our application to load first component.
  • app.component.ts - This component contains our page header.
  • car-parts.component.ts - This component contains list of car parts.
Here is app.component.ts.
import {Component} from '@angular/core';

// This is component declarator, we called it metadata.
@Component({
  selector: "my-app",
  template: `
    <h1>{{title}}</h1>
    <car-parts></car-parts>
  `
})

export class AppComponent{
  title = "Ultra Racing"  // Example of property 
}
  • Added "export" in-front of class, so it can be import into main.ts.
  • Added custom selector "car-parts", this is to display our car parts using car-parts.component.ts.
Here is car-parts.component.ts.
import {Component} from '@angular/core'; @Component({   selector: "car-parts", // Display in selector defined in app.component.ts   template: ` <p>There are {{totalCarParts()}} total parts in stock.</p>     <ul>       <!-- carParts in an array object defined in AppComponent Class. -->       <!-- carPart is a local variable. -->       <li *ngFor="let carPart of carParts">         <h2>{{carPart.name | uppercase}}</h2>         <p>{{carPart.description}}</p>         <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>         <p *ngIf="carPart.inStock === 0">Out of stock</p>       </li>     </ul>   ` }) export class CarPartComponent { carParts = [{       "id":1,     "name":"Super Tires",     "description":"These tires are the very best",     "inStock":5   },   {     "id":2,     "name":"Reinforced shocks",     "description":"Shock made from krytonite",     "inStock":4   },   {     "id":3,     "name":"Padded Seats",     "description":"Super soft scats for a smooth ride.",     "inStock":0   }] // Example of object   
  totalCarParts(){     let sum = 0; for (let carPart of this.carParts) {   sum += carPart.inStock; } return sum; } }
Here is main.ts.
import {NgModule, Component} from '@angular/core';
import {AppComponent} from './app.component';
import {CarPartComponent} from './car-parts.component';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

@NgModule ({
  imports:      [ BrowserModule ], // List down all component will be used.
  declarations: [ AppComponent, CarPartComponent], // Import dependencies.
  bootstrap:    [ AppComponent ] // Indicate first component to launch.
})

class AppModule {}

// Start the application in web browser.
platformBrowserDynamic().bootstrapModule(AppModule);
  • Added import AppComponent and CarPartComponent.
  • Added CarPartComponent into NgModule's declarations.
In this section, I didn't add any new functionality, just split the component into different file.

Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 2.2 - Pipes & Methods

We use Pipes to transform data. A Pipes takes in data as input and transforms it to a desired output. Similar to Unix Pipe, if you are familiar with it.

Below example is to write car part names in capital letter.
@Component({
  selector: "my-app",
  template: `
    <h1>{{title}}</h1>
    <ul>
      <!-- carParts in an array object defined in AppComponent Class. -->
      <!-- carPart is a local variable. -->
      <li *ngFor="let carPart of carParts">
        <h2>{{carPart.name | uppercase}}</h2>
        <p>{{carPart.description}}</p>
        <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
        <p *ngIf="carPart.inStock === 0">Out of stock</p>
      </li>
    </ul>
  `
})
Here are the additional Pipes to use.
  • lowercase - Well, lowercase...
  • date - Format dates, how you like them...
  • number - Format numbers.
  • decimal - Format decimal.
  • replace - Create a new string, replacing specific character.
  • slide - Create a new list or string containing a subset of the element.
  • json - transform any input to a JSON formatted string.
  • * You also can create a custom pipe.
Next example is to add a total car part using method() - totalCarParts().

First create totalCarParts() method in AppComponent class.
class AppComponent{
  title = "Ultra Racing",  // Example of property
  carParts = [{ ... }], // Example of object
  totalCarParts(){
    let sum = 0;
    for (let carPart of this.carParts) {
      sum += carPart.inStock;
    }
    return sum;
  }
}
Second display total car parts in template.
@Component({
  selector: "my-app",
  template: `
    <h1>{{title}}</h1>
    <p>There are {{totalCarParts()}} total parts in stock.</p>
    <ul>
      ...
    </ul>
  `
})
Enter command "npm start" to run the application.




















Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 2.1 - Structure Directive

A directive (within Angular) is how we add dynamic behavior to HTML.

There are 3 different kinds of directives
  1. Component - Directive with a template.
  2. Structure - Alters layout by adding, removing or replacing DOM HTML elements. Example: ngFor and ngIf.
  3. Attribute - change the appearance or behavior of an element.
Below code is an example how we add a property and array object into Component and display in index.html using selector.
  • ngFor is structure directive. Loops through an array.
  • ngIf is another structure directive. It allows us to evaluate conditionals, show content conditionally.
@Component({
  selector: "my-app",
  template: `
    <h1>{{title}}</h1>
    <ul>
      <!-- carParts in an array object defined in AppComponent Class. -->
      <!-- carPart is a local variable. -->
      <li *ngFor="let carPart of carParts">
        <h2>{{carPart.name}}</h2>
        <p>{{carPart.description}}</p>
        <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
        <p *ngIf="carPart.inStock === 0">Out of stock</p>
      </li>
    </ul>
  `
})
class AppComponent{   title = "Ultra Racing",  // Example of property   carParts = [{       "id":1,     "name":"Super Tires",     "description":"These tires are the very best",     "inStock":5   },   {   "id":2, "name":"Reinforced shocks", "description":"Shock made from krytonite", "inStock":4 }, {     "id":3,     "name":"Padded Seats",     "description":"Super soft scats for a smooth ride.",     "inStock":0   }] // Example of object }
Enter command "npm start" to run the application.



















Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Friday, November 18, 2016

Angular 2 Part 1 - My First Component

Angular is a framework for dynamic web application. Angular has 2 versions and both version works very different. In this article, I am going talk about Angular 2.

Angular 2 can be written in JavaScript, TypeScript or DART. I am using TypeScript on all my examples.

TypeScript is Microsoft extension of JavaScript. It allows to add powerful type check and object-oriented features. TypeScript is superset of JavaScript and importantly, Angular 2 source is programmed with TypeScript.

Prerequisite on Angular 2 with TypeScript is to install npm. Because node.js installer come with npm, so we are using it to install npm. Take note that we don't code node.js.

npm is JavaScript package manager to share, reuse JavaScript. We use npm to download Angular 2 source files. To download and install Angular 2 with TypeScript, please follow the prerequisite in Angular 2 Quickstart page - https://angular.io/docs/ts/latest/quickstart.html#!#prereq.

You should have below folder structures after install Angular's sources.
- node_modules (folder to store Angular 2 source.)
- package.json (identifies npm package dependencies for the project)
- systemjs.config.js (defines how the TypeScript compiler generates JavaScript from the project's files.)
- tsconfig.json (provides information to a module loader about where to find application modules, and registers all the necessary packages.)

Now we going to create our first component.

First, we create index.html.
<html>
  <head>
    <!-- Angular 2 libraries -->
    <script>
      System.import('app')     // This piece is calling app/main.ts where we write our application code.
        .catch ( function(err){ console.error(err);} );     // We also include error checking.
    </script>
  <body>
    <!-- This custom tab is where Angular 2 application will load. -->
    <my-app>Loading...</my-app>
  </body>
  </head>
<html>
Second, we code Angular 2 on app/main.ts.
import {NgModule, Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';

// This is component declarator, we called it metadata.
@Component ({
  selector: 'my-app',  // Custom tab in index.html that will load the component code.
  template: '<h1>Hello Angular 2!</h1>'  // HTML code going to load in selector.
})

class AppComponent { }

@NgModule ({
  imports:      [ BrowserModule ], // List down all component will be used.
  declarations: [ AppComponent ], // Import dependencies.
  bootstrap:    [ AppComponent ] // Indicate first component to launch.
})

class AppModule {}

// Start the application in web browser.
platformBrowserDynamic().bootstrapModule(AppModule);

Enter command "npm start" to run the application.







BrowserModule - Module needed for running angular Website.
platformBrowserDynamic  - Angular library needed to run the application.
NgModule - Group Angular code into blocks of functionally.
Component - Building block of Angular 2 Application and can be nested to one inside the other. Each component may have its own class file, html file and css file.

Follow the example, you should see Loading... then change to Hello Angular 2!.

Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Tuesday, October 25, 2016

Advertising Networks


HRSifu.com reached 20k page view per month. I'm looking for an Advertising Networks to monetize the website traffic. Here are some of the Ad Networks for Publisher:

Google AdSense – Rejected because Policy does not allow computer code generated page website.

Google AdMob – Unfortunately it is a platform for Mobile App, not Web App.

Media.net – Powered by Yahoo and Bing. Rejected because Policy does not allow computer code generated page website.

Infolinks – Approved, low CPM for Asia Website. Only display Facebook Advertisement at the moment.

Adroll - Not working with Publisher.

Quantcast – Not working with Publisher. It has a traffic measurement tool for publisher. Generally it provide information such as visitor gender, age, country and etc., similar to Google Analysis.

Adsoptimal –Approved, low CPM for Asia Website. Only display Jitta Investiment advertisement.

No doubt, Google AdSense is a great Advertising Networks. However, it is difficult to get approved. They are looking for quality content and high traffic website.

Infolinks and Adsoptimal is best alternative for Google AdSense and Media.net. However, CPM is really low because they don’t have quality advertiser. Most of the time only display 1 advertisement.

Wednesday, October 12, 2016

Amazon Web Services (AWS) Free Online Training


  1. Our quick introductory videos on each AWS service.
    https://aws.amazon.com/training/intro_series/
  2. Our ten minute, hands-on tutorials.
    https://aws.amazon.com/getting-started/tutorials/
  3. Our Qwiklabs, which is an in-depth, hands-on simulation training.
    https://run.qwiklab.com/lab_catalogue
  4. Our free online courses on Security in the Cloud and Big Data in the Cloud.
    https://aws.amazon.com/training/course-descriptions/security-fundamentals/
    https://aws.amazon.com/training/course-descriptions/bigdata-fundamentals/
  5. Our monthly webinar series which goes into much more detail on different services.
    https://aws.amazon.com/about-aws/events/monthlywebinarseries/
  6. Our AWS Youtube Webinar channel for past talks and presentations.
    https://www.youtube.com/user/AWSwebinars/feed

Tuesday, February 23, 2016

Open Source Anti Virus - ClamAV

ClamAV is an open source (free) anti-virus engine, support stream scanning using Java API. It’s come with an advanced tool such as online virus pattern database update.

ClamAV supports in Unix, Linus, MaxOS and Window. ClamAV is under Cisco Systems and can be reliable.

In this article, I am going to demonstrate how to install ClamAV in Window and write a sample java application to send a file for scanning.
  1. Download and install ClamAV.
    • Download "clamav-0.99-x64.msi" at http://www.clamav.net/documents/installing-clamav.
    • Double click on "clamav-0.99-x64.msi" to start the installation by selecting default options.
    • ClamAV is installed in folder C:\Program Files\ClamAV-x64 if you follow default options.
  2. Configure ClamAV.
    • Copy clamd.conf.sample and freshclam.conf.sample from C:\Program Files\ClamAV-x64\conf_examples\ to C:\Program Files\ClamAV-x64\.
    • Rename clamd.conf.sample to clamd.conf.
    • Rename freshclam.conf.sample to freshclam.conf.
    • In clamd.conf, 
      • comment "Example" in line number 8.
      • uncomment "TCPSocket" in line number 101.
      • uncomment "TCPAddr" in line number 109.
    • In freshclam.conf,
      • comment "Example" in line number 8.
    • Run freshclam using command prompt to download antivirus database.
    • Start ClamAV by run clamd using command prompt.
  3. Test ClamAV
    • Go to folder C:\Program Files\ClamAV-x64.
    • Run clamscan and scan all files in the directory.
  4. Write a sample JAVA Program
    • Download clamavj-0.1.jar and org.apache.commons.logging.jar at http://soniyj.altervista.org/blog/free-solution-for-check-infected-files-with-java-and-clamav/?doing_wp_cron=1456213243.7796299457550048828125
    • Create Test.java and copy below code:
      import com.philvarner.clamavj.ClamScan;
      import com.philvarner.clamavj.ScanResult;
      
      import java.io.*;
      import java.io.FileInputStream;
      
      public class Test {
       
       public static void main(String args[]) {
        System.out.println("Start");
        ClamScan clamScan = new ClamScan("127.0.0.1", 3310, 20);
        
        try {
         ScanResult result = clamScan.scan(new FileInputStream("D:\\14k.png"));
         System.out.println(result.getStatus());
        } catch (FileNotFoundException e) {
         e.printStackTrace();
        }
        
        System.out.println("End");
       }
       
      }
      
    • Compile Test.java using the command:
      javac -cp clamavj-0.1.jar;org.apache.commons.logging.jar Test.java
      
    • Run Test.java using the command:
      java -cp .;clamavj-0.1.jar;org.apache.commons.logging.jar Test
      
    • The code actually sending "D:\14k.png" to scan and return pass. Passed means the file is clean.
References: