Wednesday, 30 August 2017

Setup MEAN Stack with Angular 2 in Ubuntu 16.04

Steps to install and configure MEAN stack necessary application in Ubuntu 16.04

Install the following
1) MongoDB/NoSQL:              sudo apt-get install mongod

2) Express JS globally:            sudo npm install -g express

3) Angular CLI:                        sudo npm install -g angular/cli

4)Node JS and npm:               sudo apt-get install nodejs npm

To upgrade to latest NodeJS

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

sudo ln -sf /usr/local/n/versions/node/<VERSION>/bin/node   /usr/bin/nodejs

(NOTICE that the default installation for nodejs is in the /usr/bin/nodejs and not /usr/bin/node)

To upgrade to latest version (and not current stable) version, you can use

sudo n latest

Other useful nifty commands:

npm init
creates a package.json in root for you

npm list
lists all installed packages

npm prune
removes packages not depended on by your project according to your package.json

npm outdated
tells you which installed packages are outdated with respect to what is current in the npm registry but allowable by the version definition in your package.json

Friday, 12 May 2017

Convert your website into Android application using android studio

Converting your website to Hybrid android application using Android Studio

I am using android studio IDE to achieve the same. Get it from the below link:

To do this, in the first place the website should be responsive to android devices.

I followed the below tutorial to convert the website to android apk

1) Follow the tutorial to convert your site: (Thanks to the site!!)

   Basically the main changes required are from the below files:
   a. activity_main.xml
   c. AndroidManifest.xml

2) Once the changes are done, run the application in the studio.
     You should get Build Success!!

3) To generate an apk file and install it in your real device:
     Go to Build-> Select Build APK

     Once you get an option to open the build apk in the explorer, you can use the same in android devices!! And        I believe one need not learn android to create an apk for building Hybrid application..Cool ha :D !!

Now to change the default launcher ic_launcher icon of the android app:

* You can do this too almost easily: Head to
    Build your icons and download the zip package. (Note: Dont start your logo name with Caps!!!)

    Extract the zip package to the following path: 
     app\src\main\   into the 'res' folder.

Then in the AndroidManifest.xml file, change the  android:icon="@mipmap/my_icon" to match your icon name. 

Clean and build the app . Your new apk with custom icon is ready.

Monday, 17 April 2017

Configure Magento headers to call Rest API in Angular 2

Below are the steps to configure CORS (Cross Origin Resource Sharing) in the server(Magento) to call its API in frontend(Angular 2).

The below procedure is a fix for different CORS based error scenarios like:

1) Response for preflight has invalid HTTP status code 400

2) Response for preflight has invalid HTTP status code 405

3) No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.

4) Request header field authorization is not allowed by Access-Control-Allow-Headers

5) Request header field content-type is not allowed by Access-Control-Allow-Headers

Step 1: In the .htacess of Magento,under <IfModule mod_rewrite.c>  replace

                  RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
                  RewriteCond %{REQUEST_METHOD} OPTIONS

Step 2:
                  RewriteRule .* - [L,R=405]   with
                  RewriteRule ^(.*)$ $1 [R=200,L]

Step 3:
                  To the end of the page, there is another <IfModule mod_headers.c> (around line ~120)
                  Under this tag,add the below 2 lines:
                  Header always set Access-Control-Allow-Origin "*"

            Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization"

Note: Dont forget the word 'always'.

Step 4:
                 Make sure to activate the apache module headers:
        a2enmod headers

After changes my .htaccess looks like:

... ....
<IfModule mod_rewrite.c>
Options +FollowSymLinks
    RewriteEngine on
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    RewriteRule ^(.*)$ $1 [R=200,L]
#RewriteRule .* - [L,R=405]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule .* index.php [L]

ErrorDocument 404 /pub/errors/404.php
ErrorDocument 403 /pub/errors/404.php
<IfModule mod_headers.c>
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization"
Header always set X-UA-Compatible "IE=edge"
    <FilesMatch "\.(appcache|atom|bbaw|bmp|crx|css|cur|eot|f4[abpv]|flv|geojson|gif|htc|ico|jpe?g|js|json(ld)?|m4[av]|manifest|map|mp4|oex|og[agv]|opus|otf|pdf|png|rdf|rss|safariextz|svgz?|swf|topojson|tt[cf]|txt|vcard|vcf|vtt|webapp|web[mp]|webmanifest|woff2?|xloc|xml|xpi)$">
        Header unset X-UA-Compatible

My Frontend (Angular 2) logic looks something like:

import { Injectable } from '@angular/core';
import { Http, Response,Headers,RequestOptions,RequestMethod} from '@angular/http';

export class ProductService {
    public _productUrl = '';

    constructor(private _http: Http) { }

    getProducts(): Observable<IProduct[]>
let headers = new Headers({'Content-Type': 'application/json;charset=UTF-8',
'Authorization':'Bearer ntthnrbj1uam2tuv1ekva7n18mcnkby3'

 return this._http.get(this._productUrl,{headers:headers})
        .map(response => {
            return response.json();

The Authorization Bearer key was generated as below:

To get the bearer token:

1) Login to Magento admin, create a user role and a user in admin

2) To get bearer token :

    curl -X POST "http://<localhost/IP>/Magento2/index.php/rest/V1/integration/customer/token" -H "Content-Type: application/json" -d '{"username":"restuser_name","password": "restuser_password"}'

Explanation :

RewriteRule ^(.*)$ $1 [R=200,L] 
Apache will respond "200 OK" when the request method is OPTIONS

Header set Access-Control-Allow-Origin "*"
Giving global cross-origin access to Magento. Usually its a bad idea to give * from a security perspective. 
Suggested way is to give the the origin(domain+scheme+port number) site URL in place of *.
Eg: Access-Control-Allow-Origin:

ie) When Site A tries to fetch content from Site B, Site B can send an Access-Control-Allow-Origin response header to tell the browser that the content of this page is accessible to certain origins.
By default, Site B's pages are not accessible to any other origin; using the Access-Control-Allow-Origin header opens a door for cross-origin access by specific requesting origins.

Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization
 Each header must explicitly be listed and I added x-test-header to Access-Control-Allow-Headers

References which were very useful:

Monday, 13 February 2017

Creating custom theme in Magento 2

Hi Guys,

Here i will be providing explanation on how to create your own theme in Magento 2 so that you can play around with your design and look and feel :) 

Out-of-the-box Magento provides two default design themes:
        Luma, as a demonstration theme
        Blank as a basis for custom theme creation.

But if you want to customize the default design theme, you need to create a new theme as im going to show below:

1) Create your theme directory and declare your Magento2 theme: 

    Create a new Vendor folder(SachTheme) by navigating to:
    <your Magento 2 root directory>/app/design/frontend/SachTheme

   Create theme folder inside Vendor folder:  app/design/frontend/SachTheme/theme-new 

    Create theme.xml  under
   app/design/frontend/SachTheme/theme-new/theme.xml as

 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
<theme xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
   <title>Sach New Theme</title>

Copy the default media/preview.jpg from app/design/frontend/Magento/luma/media/preview.jpg
OR if the file is not found under the above path, use the one below:
Under :  vendor/magento/theme-frontend-luma/media/preview.jpg

2) Add registration.php to register your new custom Magento 2 theme

    To register your theme in the Magento system, you need to create registration.php file in your theme directory: app/design/frontend/SachTheme/theme-new/registration.php

 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.


3) Finally, clear var/cache and var/page_cache before logging into Magento 2 Admin.

     In the root of magento 2 in command prompt:  php bin/magento cache:flush

4) Navigate to:  Content-> Design-> Configuration and Select your newly created theme


Monday, 5 December 2016

Angular 2 Getting started

Angular 2 is one of the fastest web app java script framework for building our web application.
It can be added to our HTML page using the <script> tag.

1) Angular 2 application anatomy:



>These components can be pulled together to form an application by defining an "Angular Module".
>Every Angular application has atleast one Angular module called the "Angular root module"(app) and also an application can have any number of additional angular modules including Angular feature module that consolidates the components into specific application feature.

 2) Languages that can be used for developing Angular JS (Language Selection)

       a)    The JS Language specification feature is officially called the ECMAScript (ES).

               Different versions of ES:
               * ES 3 - Supported by older broswers
               * ES 5- Current version
               * ES 2015 (ES 6) - Must be Transpiled (compiled by a tool to ES 5) before the browser     executes it...

 3) Selecting an Editor :


4) Setting up Enviornment:

     npm  –  Is a CLI utility that interacts with the repository of open source projects.

--   Package manager for java script

--   To install all lib of angular
            --   Download from

   Setting up the Angular JS application manually: (Can be referred for documentation in


    Alternate steps:

                           a) Tooling :Angular CLI:
Its a CLI for generating the setup files and boilerplate code for A2 application (including Scaffolding unit and end to end test)

b) Starter files for building our application, i have referred from git hub

From the above github link, i have  downloaded and pasted the APM Start into my work space folder in my drive say and opened using my VS code editor.



Understanding the directory structure:

> All the files specific for our application are under the app folder.

> These are the setup files:


5) Now we have to install all the libraries required for running our Angular 2 application:

   * Open any terminal (i have used Babun tool) with the application root directory and type 'npm install'


   * This installs all the libraries we need and typescript. Ignore the warnings.

   * We get a tree structure in the end which shows the installation is complete.

  * We get a node modules folder and typings folder post npm installation:


   * Type npm start to start the application server.

   * Once the server is started hit the below URL:


   * Notice the code structure:



 For every .ts file we get .map file and .js file

Process: The start script started the TypeScript compiler, which transpiled all the .ts file to ES js file (.js file) that browser can understand.

.map file: is the source map generated by the compiler which helps debug .ts code

To stop the server: use Ctrl +C 

6) Modules

 * Modules are used to resolve namespace issue in Angular2 application.

 *  In ES 2015, a module is a file and vice versa.

 * We just create a file and write some code and import/export, the file becomes a module.

  * Angular 2 has something called Angular 2 modules.

7) Component:

    A component includes:

    a) A View defined in a template
    b) Its associated code defined within a Class (Properties, Methods)
         A Class becomes a function when we give a metadata.

    c) Metadata defined with a  Decorator (an angular component function)
             Decorator is a function that adds Metadata to a class, its members.
             Always prefixed with @


Example of a component in a TypeScript: