Tag Archives: Programming

Angular 2 Tutorial – movies App

Last time I wrote a blog created the MovieAPI and now I am using that API as back end services to create an angular 2 app.

the final source code could find at my github repository.  here is the link download

For the MovieAPI open it, build it will install the packages automatically, then run the service first.

After the service is done, go to the angular2 folder, open command window

–run npm install,

— npm start

It will look like this:




Step 1 : Setting up your angular 2 application, I already have a blog  click here to found it. Or also could download from the source file from https://github.com/angular/quickstart/blob/master/README.md but it add a lot of unnecessary setting, probably confuse for beginning learner.

It was better do few times manually setting it up to get understand all of the necessary for start anguar 2 application.

Step 2:  In angualr 2 everything is component, for me normally like to create the service first. I just create a file named movies.service.ts under folder movies

import {Injectable} from 'angular2/core';
import {IMovie} from './movie';
import {Http, RequestOptions , Response, Headers} from 'angular2/http';
import {Observable} from 'rxjs/Observable';

export class MovieService {   
    private _movieUrl = 'http://localhost:53871/api/movies';

    constructor(private _http: Http) { }

    getMovies(): Observable<IMovie[]> {
        return this._http.get(this._movieUrl)
            .map((response: Response) => <IMovie[]>response.json()) //arrow function, tranceform response to json object and is array of IMovie[]
            .do(data => console.log("All: " + JSON.stringify(data))) //for debug

    createMovie(movie: IMovie): Observable {
        let body = JSON.stringify(movie); 
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this._http.post(this._movieUrl, body, options)               

    private extractData(res: Response) {
        let body = res.json();
        return body.data || {};

    private handleError(error: Response) {
        return Observable.throw(error.json().error || 'Server error');

In there MovieService I have a IMovie here is my movie.ts I put it in the same folder with MovieService .

//interface won't compile to js file, it just for typescript do type checking
 export interface IMovie { 
    movieId: number;
    title: string;
    genre: string;
    classification: string;
    releaseDate: number;
    rating: number;
    cast: string[];


export class Movie implements IMovie {
    movieId: number;
    title: string;
    genre: string;
    classification: string;
    releaseDate: number;
    rating: number;
    cast: string[];

Step 3: Inject the services.
Go to the app.component.ts this is our container component, for anguar 2 only need inject once, then all of the nest container could using it ( by import it ).

Inject a service has two steps:

1) import the file into the app.component,

2) Inject it as providers

here is my app.component.ts


Step 4: Create the movies-list.component.ts

//for using component, simply import it into this file
import {Component, OnInit} from 'angular2/core';
import { ROUTER_DIRECTIVES } from 'angular2/router';

import {IMovie} from './movie';
import {MovieService} from './movies.service';
import {MovieFilterPipe} from './movie-filter.pipe';
import { StarComponent } from '../shared/star.component';

    selector: 'sz-movies',
    templateUrl: 'app/movies/movies-list.component.html',
    styleUrls: ['app/movies/movies-list.component.css'],  
    pipes: [MovieFilterPipe],
    directives: [StarComponent, ROUTER_DIRECTIVES]
export class MovieListComponent implements OnInit {
    pageTitle: string = 'Movie List';   
    listFilter: string;
    errorMessage: string;
    movies: IMovie[];

    constructor(private _movieService: MovieService) {

    ngOnInit(): void {
            movies => this.movies = movies,
            error => this.errorMessage = error);


here is the movies-list.component.htmlmovies_html


for this component I have a nested StarComponent.

Setp 5: create nested StarComponent, here is the star.component.ts under the share folder

import { Component, OnInit, Input} from 'angular2/core';
    selector: 'sz-star',
    templateUrl: 'app/shared/star.component.html',
    styleUrls: ['app/shared/star.component.css']
export class StarComponent implements OnInit {
    @Input() rating: number;
    starWidth: number;
    ngOnInit(): void {
        this.starWidth = this.rating * 86 / 5;




In angular 2: data flow is unidirectional, for passing data from view to the class

first: you passing data into the directive could bind it to the property


Second: need import the Input from angular2/core, and bind it to the property


Now, one nested movies-list.component and nested star.componet down.

Now using the same steps create the MovieCreateComponent

import {Component, OnInit} from 'angular2/core';

import {IMovie, Movie} from '../movie';
import {Router} from 'angular2/router';
import {MovieService} from '../movies.service';

    templateUrl: 'app/movies/create/movie-create.component.html'

export class MovieCreateComponent implements OnInit {
    title: string = 'Create New Movie';
    newMovie: IMovie;

        private _moviesService: MovieService,
        private _router: Router
    ) { }

    ngOnInit() {
        this.newMovie = new Movie;

    createMovie(event) {
        let _this = this;

            .subscribe(function () {

    cancelCreate(event) {


In the index.html page, put the baseurl:

Done, have fun!

Zend Framework2: Tutorial Part2: Hello World Module Application

The reason I start to write this post, because I read saw a lot video on youtube.com take hours to tell you how do it. And I also follow it but it is waste my time. Didn’t work for me. And I write this as my study record also hope that could help someone to start Zend Framework2.

Actually it is very simple,

First,copy the entire “Application file” and rename it to “Hello” (You could just rename the “Application” to “Hello” or any name you like, but under this file those three name must match )


Second, open the “Module.php”, the namespace Hello (this namespace should match your module name).

Continue reading Zend Framework2: Tutorial Part2: Hello World Module Application

Tips for use Drupal

Tip1: After install new module,should go Administration › People › Permissions, set permission, otherwise won’t work.

Tip2: Drupal built a lot of caching mechanism to improve performance, but in a development environment, it is best to turn off all to see the results of the fastest changes.

Into the background

administer -> configuration -> perfromance 


  • Cache pages for anonymous users
  • Cache blocks

Are unchecked.

In addition, to make the theme changes take effect immediately, you need to at the top of the theme template.php join


Tip4: Avoid modifying Drupal core files

In the file structure of Drupal modules and themes can be installed in drupal / modules , drupal / themes , it is also possible to install in drupal / sites / all / modules , drupal / sites / all / themes under. Recommended to choose the latter, which is the official recommended. Because this way, you can modify the project focused on the sites directory when upgrading Drupal version, you can cover all the core files directly without having to have another worry.

Of course, since the Drupal web root directory is set in the root directory of the code, from a security point of view, then pay attention to the library may be accessed files, so you can control what file permissions in addition to sites outside the directory.

Tip5:error when processing Drupal

Since  Drupal has error handling php, when there was error occurs, the screen will appear

The website encountered an unexpected error. Please try again later.

Generally , you can go Administration › Reports › Recent log messages, view the error message.

But sometimes occurred if the situation worse, such as the installation of some modules may report the above error and you can’t access the back control.

So then you can go check watchdog, variables field holds this error message, you can notepad to  open it to see the error details (which you need Database logging module).

How You Can Draw Regular Polygons with the HTML5 Canvas API

How it is look likes goes to here:


  • a circle is 2 * Pi
  • don’t know how to explain sine and cosine, but if you understand below is help you under stand my JavaScript code.
  • x = r * cosine(a)
    y = r * sine(a)

And here is the JavaScript code for you Polygons

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
for (var i = 1; i < sides; i++) {

When I need a pentagon,here is the code for get it.

function doFirst(){
var x = document.getElementById(“canvas”);

context= x.getContext(‘2d’);

polygon(context, 120,120,100,5);

And You could use below code generate different shapes.

function doFirst(){
var x = document.getElementById(“canvas”);

context= x.getContext(‘2d’);


// Draw a circle to encompass this polygon
context.arc(125, 125, 100, 0, Math.PI * 2);



context.shadowColor = ‘rgba(0,0,0,0.75)’;
context.shadowOffsetX = 8;
context.shadowOffsetY = 8;
context.shadowBlur = 10;

Cakephp Blog Tutorial 1 – Installation

1. download the latest version cakePHP,

2. copy into localhost root file, and I name it as “Blog”

3. There are 3 things need to fix it out:

First is connect to your databases:

A) Database configuration (make sure have a  database in your localhost)

B) use NetBeans to open your files,under the App file, under config file, you see a database.php.default,rename it and move .default, and open it

C) here you could set your database, there are class you should change it like this

public $default = array(
‘datasource’ => ‘Database/Mysql’,
‘persistent’ => false,
‘host’ => ‘localhost’,
‘port’ => ”,
‘login’ => ‘root’,//I use localhost, so I set it root
‘password’ => ‘*******’,//here put your password
‘database’ => ‘blog’,//choose your databases
‘prefix’ => ”,
‘encoding’ => ‘utf8’,

Second,config your salt

under app/config/core.php, open core.php file,find your Security.salt, then go to google type:random strings, click GRC,copy the string to replace it into your file,should look like below:

Configure::write(‘Security.salt’, ‘dVYSYFEl2wYaF5FXSKhFmhGSXBGLmFeyczLUaH4IX8qIKZqo03aasw2jTmcjRP7’);

Third, Debug is optional but I think that it is good have it.

Down load it from cakePHP website name debug_kit-master file put it under your plug file

open bootstrap.php uncommon this statement.

CakePlugin::load(‘DebugKit’); //Loads a single plugin named DebugKit



How to let your visual studio 2010 support HTML5?

Mircosoft won’t let code people use notepadd++ to write codes.Html5 is very popular,how can vs2010 won’t support html5? here I will teacher you how to let you vs2010 support html5.

all you need is vs2010 and a browser.

what do we need a browser? hehe,if you want you vs2010 support html5. first thing first is that you need update vs2010 to sp1.

How do we up microsoft Visual Studio 2010 to microsoft Visual Studio 2010 sp1?
There are two ways:
1.Go straight to microsoft website, download center download Microsoft Visual Studio 2010 Service Pack 1

2.open windows update, the system will automatically find vs2010 update file, size around 600MB

Once you finished update, then open you vs2010 goto tool->option->HTML->Validation


use php process a web form feedback-insert data-continue1

you already  had a page collect information from use input, and build a page connect to your serves databases, here is the page use for process the data, (insert the information to your databases)

here is your process_chinese_zodaic.php page sourse code;

$sender = trim($_POST[‘fname’]);
$feedback =trim($_POST[‘feedback’]);
$agree = $_POST[‘agree’];
$submit = $_POST[‘submit’];

echo “Your must write your first name,last name,feedback”;
if($agree == 1)
$agree = “N”;

$agree = “Y”;
if($error == 0)
$table = “zodiacfeedback”;
$data = date(“Y-m-d”);
$time = date(“H:i:s”);
$query = “insert into $table(message_date,message_time,sender,message,public_message)values(‘$date’,’$time’,’$sender’,’$feedback’,’$agree’)”;
$result = @mysql_query($query);
echo “<p>unable to insert the values “. mysql_error().”</p>”;
echo “<p>”.htmlentities($sender).”,Thanks you for giving us feedback.</p>”;
echo “<p><a href=’view_zodiac_feedback.php’>View all of the feedback</a></p>”;




use php process a web form feedback–continue

since you got a form collect your information , so now you need create a database

here it is , you could save this as inc_connect.php

$db_name = “chinese_zodiac_database”;
$DBConnect = mysql_connect(“severname”,”usename”,”password”);
if (!$DBConnect)
echo “<p>unable to connect to the database server “.mysql_error().”</p>”;
$db = mysql_select_db($db_name);
echo “<p>unable to connect to the database server “.mysql_error().”</p>”;
$DBConnect = false;




use php process a web form feedback….

use php process a web form feedback, and insert the information into your databases, and use php create a page to view the feedback.

here is the code.here is the html page collect the information;

<h2>Chinese Zodiac FeedBack</h2>
<form id=”form1″ method=”post” action=”process_zodiac_feedback.php”>
<label for=”fname”>Your Name:</label>
<input type=”text” name=”fname” id=”fname”>

<label for=”feedback”>Your FeedBack</label>
<textarea name=”feedback” id=”feedback” cols=”45″ rows=”5″></textarea>
<p><label>Are you agree to public your feecback?</label>
<input name=”agree” value=”Yes” type=”checkbox”></input></p>
<input type=”submit” name=”submit” id=”submit” value=”Submit”>


some useful function php with mysql

  • mysql_connect(‘servers’,’admin’,’password’)
  • mysql_select_db(‘name of databases’)
  • mysql_query(‘sql querys’)
  • mysql_num_row(‘my sql query result’)
  • mysql_affected_row() and mysql_info() return information on the records that were affected by an insert,update,or delete query.
  • mysql_fetch_array()
  • mysql_fetch_assoc()
  • mysql_fetch_row()
  • mysql_fetch_lengths()
  • mysql_free_result() This ensures that the resultset doesn’t keep taking up space in your Web server’s memory.
  • You can only use the mysql_free_result() function with SQL statements that return results,such as SELECT queries,and only when the SQL statement successfully returned results. If you attempt to use the mysql_free_result() function with SQL statements that do not return results, such as the CREATE DATABASE and CREATE TABLE statements, or on an empty resultset, you will receive an error.