Saturday, 10 December 2016

How to create angularJs 2 project using angular-cli

Prerequisite -
Install nodejs and npm

1.Install angular-cli
npm install -g angular-cli

2.Create new Project using  angular-cli
ng new ProjectName
It will angular project skeleton with all config files such as tsconfig.json, typings.json and package.json,
 
3. cd to new Project 
cd  ProjectName

4. run created app
ng nerve

Now , This project will be setup using Webpack bundle.
You can see Webpack bundle is valid as successful message.

Now,
http://localhost:4200  to load app component.

Issues -
Experimental-decorators warnings in AppComponent and other Components.
This is due to typescript version mismatch.
TS build uses v1.8.10 and tsconfig(ts compiler) uses v2.0.0

Hence we correct this conflict  in setting.json file.
We set node Module ts version for ts compiler to avoid conflict.
add below property -
"typescript.tsdk": "./node_modules/typescript/lib"



Friday, 9 December 2016

How to create angularJs2 Project

Main Configuration Files -

1. tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

2. typings.json
{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160317120654",
    "jasmine": "registry:dt/jasmine#2.2.0+20160505161446",
    "node": "registry:dt/node#4.0.0+20160509154515"
  }
}


3. package.json 
{
  "name": "angular2-Sample",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common":  "2.0.0-rc.1",
    "@angular/compiler":  "2.0.0-rc.1",
    "@angular/core":  "2.0.0-rc.1",
    "@angular/http":  "2.0.0-rc.1",
    "@angular/platform-browser":  "2.0.0-rc.1",
    "@angular/platform-browser-dynamic":  "2.0.0-rc.1",
    "@angular/router":"3.0.0-alpha.7",
    "@angular/router-deprecated":  "2.0.0-rc.1",
    "@angular/upgrade":  "2.0.0-rc.1",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2-in-memory-web-api": "0.0.10",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^1.0.4"
  }
} 


4. systemjs.config.js

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Add package entries for angular packages
  ngPackageNames.forEach(function(pkgName) {
     //Router has no "bundel" folder
    if (pkgName == "router"){
       packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
    }else{
    packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
    }
  });
  var config = {
    map: map,
    packages: packages
  }
  System.config(config);
})(this); 


5. index.html

<!DOCTYPE html>
<html>
    <head>
        <!-- 1.For HTML 5 Browser PushStart  -->
        <base href=".">
        <!-- 2.Add Default Css at project root -->
        <link  rel="stylesheet"  href="base.css">
         <!-- 3.Load Polyfill(s) for older browsers -->
        <script src="node_modules/core-js/client/shim.min.js"></script>
        <script src="node_modules/zone.js/dist/zone.js"></script>
        <script src="node_modules/reflect-metadata/Reflect.js"></script>
        <script src="node_modules/systemjs/dist/system.src.js"></script>
        <!-- 4.Add Configure SystemJS -->
        <script src="systemjs.config.js"></script>
        <script>
          System.import('app').catch(function(err){ console.error(err); });
        </script>
    </head>
   <body>
       <!-- 5. Main Container to hold view -->
       <myApp>Hello Ang2-startup</myApp>
   </body>
</html> 


6.typings folder 
It contains global dependencies like core-js, jasmine, node inside globals folder.  

 7.app folder

Note*- All folders must be kept in root 

 

Saturday, 3 December 2016

AJAX Basics

AJAX is Asynchronous JavaScript and Xml

AJAX allows you to send and receive data asynchronously without reloading the web page. So it is fast.
           AJAX allows you to send only important information to the server not the entire page.
So only valuable data from the client side is routed to the server side. It makes your application interactive and faster.

Why used (advantages)-
1.User is not blocked
2.Faster

What is XmlHttpResuest  ?
This Object is used to communicate between client and server.

Main Functions -
1. sends data from client in the background
2. receives data from server
3. updates webpage with new data without reloading it.


XmlHttpRequest Properties - 
readyState - State of request
                   0 - un-opened
                   1 - opened but send() not called
                   2 - send() called
                   3 - downloading data and responseText holds data
                   4 - request completed fully (response ready)

responseText -   returns response as Text
responseXML - returns response as XML

              
XmlHttpRequest Methods - 
1 .void open(method,URL,sync)  
                method - get or post  
                Url - url to be hit
                Sync - synchronous or asynchronous call

2. send(String) 
                 With String - post request
                 Without String - get request 

When is response received ?  
request.readyState == 4 

How to connect with DB ?
Use Scriplate Tag  <% %> to connect with Db and fire query.

link --> http://www.javatpoint.com/ajax-example-with-database
 

Why not to use(Disadvantage) -
1. makes jsp's complex by using a lot of script code.
    Eg.
   In case of database interaction.
2. difficult debugging
3. security issues  (AJAX source code is readable and also scripts can be changed)         
                

How to call AJAX using jQuery:
1.$.get(url,data,callback(result));
   $.post(url,data,callback(result));

2.$.ajax(url.data).done(callback(result))
 


HTML 5 Basics

New Features in Html 5 -

1.<audio>           -To play audio file directly.
2.<canvas>         -To draw graphics/canvas.
3.<article>          -To display document/article/magazine
4.<video>           -To play video file directly.
5.<svg>               -To display shapes
6.<nav>               -To show navigation link
7.<section>          -To define section in document.
8.<Footer>           -To define section inside a footer.
9.<Header>          -To define header inside Section
10.<dialog>          -To show window/dialog directly
11.<progress>       -To show progress bar.

12. Local Storage - Alternative to Cookies. 

All above is shown inside DOM document .

What is <!DOCTYPE html>  ?
It is mandatory to convey browser t. hat this is HTML 5 document.
If <!DOCTYPE html> is not mentioned, will not make HTML 5 tags function properly. Im[

Validation  Update -
1.required field is used in input tags for form validation.
Eg.     Name: <input type="text" name="name" required>

2. new <input> type -> email
Eg.    <input type="email">

What is Local Storage ?
Its an alternative to Browser Cookies.
           With local Storage, Web application can store data locally within user's Browser.
Before HTML5, application data had to be stored in cookies, included in every server request.

Advantages -
1.More secure than cookies.
Because Cookies is sent with all the future HTTP request to the server,
But Local-storage data resides with browser only.It is never sent to Server with HTTP request. 

2.Hold more data than cookies(upto 4KB) without compromising web application performance.(> 5 MB)
Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.


Local Storage is Global Object.
It can be accessed as below -
window.localStorage 
 
 

jQuery Basics

jQuery is small, light-weight,fast javaScript library.

 Application -
1. Html manipulation
2. Dom manipulation
3. Css manipulation
4. Html Animation
5. Ajax calling
6. Json parsing 
7. Handling Html events 

How to use - 
1. can be used in .js file or <script> tag inside HTML page
2. use jquery.min.js file or absolute url http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js

$(document).ready()   vs  Window.onload() -
$(document).ready()  is as same as $() 

           $() is jQuery event and called before Window.onload().$() gets called as soon as the DOM is ready (which means that the browser has parsed the HTML and built the DOM tree). This allows you to run code as soon as the document is ready to be manipulated.  
            Window.onload() is javaScript event.It called when complete (DOM + images+ frame )is loaded.
Also,$() can be called any number of time but Window.onload() can be called only once.
$() cannot access images and frames .Window.onload() can be used to access the same.

jQuery Selector -
1.By element  -     $(" element ")
2.By element Id -  $(" #id ")
3.By Class -          $(".className")

jQuery Effects -
Display effects - hide()   - hide selected elements
                            show()  - display selected elements
                            toggle() - switches between Hide() and Show()
Sliding effect -    slideDown() - shows element with sliding down.
                            slideUp() - shows element with sliding up.
                            slideToggle() - switches between slideUp() and slideDown()

animate()
delay() - delay showing of element.



 
 


 

Sunday, 20 November 2016

AngularJS2

Basics -
I. AngularJS2 is framework to build heavy javaScript applications.
It is mainly used to create SPA(Single Page Application.)
AngularJS2 is completely independent of AngularJS framework.

SPA vs MPA (Multi Page Application)
In multi page app each time a request is submitted a new page is served by the server and rendered.
This approach is OK for simple applications.
           But in case of rich use interface page becomes complex and to be loaded with a lot of  data.
Generating complex pages on server and transferring them to client over internet and rendering them in browser takes time and degrades user experience.
           Introduction of AJAX  improved MPA by refreshing a part of page( not full page) but increased page complexity.
SPA is a evolution of MPA+AJAX pattern,where only shell page is generated on the server and  UI is rendered by browser javaScript Code. SPA requests markup (HTML) and data separately and renders page directly in browser. 
In SPA only a part of shell page changes instead whole page.
eg. Gmail is SPA


SPA Advantages :
1.Faster page loading
2.Improved user interface because data is loaded in the background from server.
3.No need to write code to render page on server.
4.decoupling of Front end and Back end Development
5.can use same back end code(Web development) for Mobile development.

SPA Disadvantages :
1.Heavy frameworks to be loaded in browsers
2.UI code is not compiled hence its harder to debug.
3.search engine optimization problems

II. Typescript is used to develop angularJS2 app.
     TypeScript is a super set of javaScript. (Any valid JavaScript code is TypeScript code).
     TypeScript = JavaScript + additional Features
      
    Why to use TypeScript instead of JavaScript?
     These additional features are --> (modules,classes,interfaces,access  modifiers, intellisense, compile Time checking)

III.Ang2 Architecture -
    Main parts of  ng2 are -
    1.Component  - View Part
    2.Directive
    3.Router
    4.Service       -Service Part
 Component - {} encapsulates template,data and behavior (properties and methods) of view. (Is a class)
Main Component is called as Root Component.
Root Component has many sub components which help to divide app into smaller parts.
Components are completely decoupled from DOM .
In JavaScript we first select DOM element and then modify it.
In Ang2 we bind DOM element with component.
    Eg. component class variable - DOM element
          Component class method - DOM event  

Service - {} A class, which holds non-view logic like Business logic, Data Access , Logging  etc.
Router -  {} For navigarion
Directive -{} which  modifies DOM (like Component)
Unlike Component, it does not have html markup for view. 
 

 

 

Wednesday, 16 November 2016

What happens (Steps) when an URL is requested from address bar in Browser.(Eg.www.facebook.com)

Steps-
Suppose we type www.facebook.com in address bar of browser.

Whenever we want to connect to "facebook", we want to reach to the server where google web service is hosted. Each host name (facebook.com) has IP associated with it.
Eg. Say www.facebook.com has IP of 74.125.236.65.
        If we type http://www.facebook.com or http://74.125.236.65 we expect facebook server to show homepage. But both addresses may not be same.
But in real scenario facebook has multiple servers at multiple locations to cater huge volume of request they get per second. Hence we should let facebook decide which server is best for my response. Hence using host name solves the problem of typing actual facebook server IP.
        
              DNS (Domain Name System) resolves the problem of mapping URL with IP.
  
  1. First browser checks DNS records in its own cache for IP of requested server.
  If not found ,
  2. Browser checks DNS records in OS cache for IP of requested server.
  if not found,
  It decides to contact ISP.
  3. A request is sent to DNS server, that has the database of IP address and Host Names.
      DNS server tries to identify IP address for queried hostname.(It searches in DNS hierarchy until topmost DNS server).If found the requested IP , It is returned. Otherwise server not found message is sent.
 4. Since browser knows IP of server to contacted, Now browser initiates a TCP connection with server.
 5. Browser assembles http request which consists of header and optional content. 
     Request header has below content -

    
Where,
GET - http request type (always GET)
Accept - http response type expected
User Agent - Browser details
Connection - Asks connection server to keep TCP connection established for response.
Host - Host Name
Cookie - sent server cookie for previous browser session. Cookie has map with KV for user and Facebook

6. Browser receives the response in return.




where,
OK - http response status.
Content Type
Connection -asks browser to keep TCP connection open
Content -length - No of bytes

7. Browser renders HTML content.
    HTML rendering is also done in phases.
    7.1 - First HTML bare bone structure.
    7.2 - Then sends multiple GET request to get resources like images, JavaScript files, CSS files for HTML rendering.
   Now these images will be stored in the browser cache, so that next time it does not have to send    GET request to server for HTML rendering resources.