Category Archives: HTML&CSS

flex layout

vary good source for flex layout
https://codepen.io/anon/pen/VKxRoE?editors=1100

Advertisements

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:

home

create.PNG

added

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';

@Injectable() 
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
            .catch(this.handleError);
    }


    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)               
                .map(this.extractData)
                .catch(this.handleError);
    }

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

    private handleError(error: Response) {
        console.error(error);
        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

angular2_injection

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';

@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 {
        this._movieService.getMovies()
            .subscribe(
            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';
@Component({
    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;
    }
}

star.component.htmlstar.PNG

css:

star_css

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

passing_data_down.PNG

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

inData

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';

@Component({
    templateUrl: 'app/movies/create/movie-create.component.html'
})

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

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

    ngOnInit() {
        this.newMovie = new Movie;
    }

    createMovie(event) {
        let _this = this;

        this._moviesService.createMovie(this.newMovie)
            .subscribe(function () {
                _this._router.navigate(['Movies']);
            });
    }

    cancelCreate(event) {
        this._router.navigate(['Movies']);
    }

}angular2_form.PNG
Router:
route.PNG

In the index.html page, put the baseurl:
baseUrl.png

Done, have fun!

Overlay screen with transparency achieve by using position: relative and absolute

New trick learned by doing build this layout, have transparent under my two foundation columns. The looking is like this:

transparent wrap under two columns

The div layout is like this:

<div class=”clearfix blueWrap”>
<div class =”orangeWrap”></div>
<!– below two columns is the purple wrap in the picture –>
<div class=”medium-6 columns”></div>
<div class=”medium-6 columns”></div>
</div>

 just few line of css:
  .blueWrap{position:relative;}
  .orangeWrap{
        background-color: rgba(68, 68, 68, 0.47);
	position:absolute;
	top:0;
	left:0;
	width:100%;
	height:100%;
       }
 

then just use the foundation media query to make sure when it was in the big screen don’t display that transparent overlay screeen.

@media only screen and (min-width: 64.063em) {
.orangeWrap {
width:70%;
}

Create marquee news in front page and the news is read from the database with expired data,also included management page to insert news

My boss just saw other company website has a marquee new on the front page, so she asked me if I could make one and arrow her to insert news and the news will dispear at the expired data.

For achieve that task, first I create a table in my database table, here is my table:

breadNewTable

then I write a store proceedure, a little tip for fresh guy, alway use store preceedure to insert data for security reasons.

breadNewStoreProceedure

Now, We could start the front end job. I create a user control:marquee.ascx(so you could put it in anyway you like), to display the new, here is my html code:

frontUCmarquee

here is the backcod, I used ado.net to open the database and qurery what I need, and bind it to my BulledtedList:

databasereadertomarquee

See the code this if(!IsPostBack) is not neccessary, but I use web froms so it wil inherit maintain state so I don’t need retrieve database everytime postback.

here I am also happy to share the css file for style this unorder list to display inline:

MarqueeCssStyle

A tip for fresh guy, put this in the page your use control will stand it.

Now, you just need drag the usercontrol to any page you want it with this css style in top of the header it. You coud see it.

Then We could start create a page to arrow my boss to insert the bread news, I used boostrap format so it save my time to write css. here is the front page look like:

addNews

here is the html code:

htmlCodeAddnews

The form use jQury Validate, the jquery-ui.js, is for my boss click then will pop up the jQuery calender to arrow her to put the expired date. So simple isn’t, I am love JQure very much, save a lot of time. It remind me when I first time write javascript over 10 years ago, for every simply function I need write a lot codes.

Finally I just need write a event could be fired by this button.

storeIntodatabase

Ok, That’s all. Have fun!

Using c# code to force bootstrap modal stay open after page postback

Recently I write a small function into my asp.net application.To enable the driver to input the time the submit the pick up client and drop off the client time.
My boss like the pick up time and drop off time should been populate by just click.so I write a code on the back of page to retrive the time every time the driver click the button.
But the dropoff button driver me to nuts,Because When the dropoff button click I pop out the bootstrap modal.But the problems came out this button need make page postback to retrive the current time and after postback my modal need stay open.
It take me a while to fix out this.
Here is my solution.
first, I need write javascript like this is for to open the modal: #dropoffModal is my hidden modal.

 function openModal() {
$('#dropoffModal').modal({ show: true });
}
 

Second I have the the button is like this(See the button click will fire a event named:”Button_DropOff_Click” behind it):

 button_click_event_fire_javascript

Finally, just write your event on the page behind file:


protected void Button_DropOff_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}

here just a solution. by the way, You could use ScriptManager.RegisterStartupScript() this command call another function in your frond page javascript.

How You Can Draw Regular Polygons with the HTML5 Canvas API

How it is look likes goes to here:

http://www.sandywebdesigner.com/canvas/canvas.html

  • 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;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.moveTo(radius,0);
for (var i = 1; i < sides; i++) {
ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
}
ctx.closePath();
ctx.restore();
}

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

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

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

context.beginPath();
polygon(context, 120,120,100,5);
context.stroke();
}
window.addEventListener(“load”,doFirst,false);

And You could use below code generate different shapes.

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

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

context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle=”rgba(227,11,93,0.75)”;
context.fill();
context.stroke();

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

context.beginPath();
polygon(context,350,125,100,6,-Math.PI/2);
context.fillStyle=”rgba(51,128,255,0.75)”;
context.fill();
context.stroke();

context.beginPath();
polygon(context,125,350,100,7,-Math.PI/2);
context.fillStyle=”rgba(11,227,93,0.75)”;
context.fill();
context.stroke();

context.beginPath();
polygon(context,350,350,100,8,0,false);
polygon(context,350,350,60,8,0,true);
context.fillStyle=”rgba(227,11,93,0.75)”;
context.shadowColor = ‘rgba(0,0,0,0.75)’;
context.shadowOffsetX = 8;
context.shadowOffsetY = 8;
context.shadowBlur = 10;
context.fill();
}
window.addEventListener(“load”,doFirst,false);

Create a video in your HTML5 page, here is the javascript code you needed it

Here i put the java script source code make your video work.

here the final file you needed it.

function doFirst(){
    barSize=600;
    myMovie=document.getElementById(‘myMovie’);
    playButton=document.getElementById(‘playButton’);
    bar=document.getElementById(‘defaultBar’);
    progressBar=document.getElementById(‘progressBar’);
    
    playButton.addEventListener(‘click’,playOrPause,false);
    bar.addEventListener(‘click’,clickedBar,false);
}
function playOrPause(){
   if(!myMovie.paused && !myMovie.ended ) {
       myMovie.pause();
       playButton.innerHTML=’Play’;
       window.clearInterval(updateBar);
   }else{
       myMovie.play();
       playButton.innerHTML=’Pause’;
       updateBar=setInterval(update,500);
   }
}

function update(){
    if(!myMovie.ended){
        var size=parseInt(myMovie.currentTime*barSize/myMovie.duration);
        progressBar.style.width=size+’px’;
    }else{
         progressBar.style.width=’0px’;
          playButton.innerHTML=’Play’;
          window.clearInterval(updateBar);
    }
}

function clickedBar(e){
    if(!myMovie.paused && !myMovie.ended){
        var mouseX=e.pageX-bar.offsetLeft;
        var newtime=mouseX*myMovie.duration/barSize;
        myMovie.currentTime=newtime;
        progressBar.style.width=mouseX+’px’;
        
    }
}
window.addEventListener(‘load’,doFirst,false);

Then here is your css code for add video to your html5 page–continue

Here I put the css style for mark up your video appearance. not very beautiful, but it works, you could change this to what you like.

Css3 style below: (next post is the javascript file, you need add to make the video works.)

body{
text-align:center;
}
header,section,footer,aside,nav,article,hgroup{
display:block;
}
#skin{
width:700px;
margin:10px auto;
padding:5px;
background:red;
border:4px solid black;
border-radius: 10px;
}
nav{
margin:5px 0px;
}
#buttons{
float:left;
width:70px;
height:22px;
}
#defaultBar{
position: relative;
float:left;
width:600px;
height: 16px;
padding:4px;
border:2px solid black;
background-color:yellow;
}
#progressBar{
position: absolute;
width:0px;
height:16px;
background:blue;
}

Create a video in your HTML5 page–continue

Here I am going to continue my post. HTML5 page added video is much easy now.

put below source code in your html body ,next post is the css style.

<section id = “skin”>
<video id=”myMovie” width=”640″ height=”360″>
<source src=”videos/movie.mp4″ type=’video/mp4′ >
</video>

<nav>
<div id=”buttons”>
<button type=”button” id=”playButton”>Play</button>
</div>
<div id=”defaultBar”>
<div id=”progressBar”>
</div>
</div>
<div style=”clear: both;”>

</div>

</nav>

</section>