Component based Approach using Typescript

At the end of September 2016, I started learning Typescript.Being a Javascript Engineer,I can digest the fact that Javascript will be replaced by superset “Typescript” and finally I moved to Typescript.

I used to write javascript and use extensibly some of libraries like jquery and underscore.It have three years journey with Backbone.js with four different projects and the way it is written to use DOM manipulation,I just love it.But as the project size,maintaining codebase becomes an issues and to maintain each and every views life-cycle is an overhead to developers,so most of time i have explicitly write code to maintain life-cycle of a view.Then came Typescript,initially for me,it look like java and I was like “Dude,Am I writing backend code in UI ?”,but as time passed i started liking it and now i prefer typescript more over vanilla javascript.

But why there was a need of migrating towards typescript ?

Answer I found after some days : Components

Ok,Components,but that can be achieved with backbone also,but why typescript?

So,you can still use backbone and write a wrapper over it and extend the base class.Inheritance was missing in vanilla javascript that Typescript filled the gap.

Lets go and have a real use case.As the project size increase it is hard to maintain code-base they are likely chances of code duplication.So there was need of generic things that can be included in file to be use and instrument.For example write a generic view component with strictly typed variables so that the contract is not validated and that component can be used widely to maintain life-cycle of a component.


class BasicView {
/** this is generic component that have basic life cycles of a component

public render(){
}

public preRender(){
}

public destroy(){
}
}

Now,with typescript you can include basic component to every component.


class Component1 extend BasicView{

constructor(options){
super(options);
}

/** over-ride basic view methods in child view

public render(){
/** over-ride render method here in child view */
}
}

With Component base approach,component behave as individual identity that can be plug and plug.Component accepts a set of data and returns a set of data.So writing test cases also become easy with component based approach.

So,if you see frontend end trends for last two decades,the world is moving towards components.It has add-on features as code re-usability easy debugging and neat and clean files.It becomes really very easy to debug and enhance a product feature.The main advantage component based approach gives ,it makes the complete product loosely coupled.So extending it become too easy and migration is smooth.If you look at all recent frontend framework,they exhaustibly use component based approach.

I have now become huge fan of component based design,now any feature that i need to plug in my system,the first thing comes to mind,how i can follow component based approach and make it re-usable at other places.

Modern Frontend Technology Stack- An Overview

As javascript is expediting at an aggressive rate.Every six month new framework come into existence and popularity and it has become very difficult for a front-end developer to keep himself updated on day to day basis.

Now,with new framework and features,everyone want to exhaust those library for better and user-friendly interfaces are in demand.When it comes to development of web app,so many conditions comes into picture.Customers are looking for interactive design and value of product.So,to deliver a seamless running webapp it has become more challenging for a frontend Developers.

In the era of smartphones, web developers are expected to develop UI/UX that is responsive and user-friendly. If the web applications frustrate users, then it is difficult to maintain the customer’s loyalty on your website. Website navigation is another part often neglected by developers. Intuitive navigation creates a better user experience for the website visitor.

Slow web applications are a failure and as a result, customers abscond your website, thus damaging your revenue as well as reputation. Some of the performance issues developers’ faces are Poorly written code, Un-Optimized Databases, Unmanaged Growth of data, Traffic spikes, Poor load distribution, Default configuration, Troublesome third party services, etc.

Security is something the web developers need to consider at every stage of SDLC (software development life cycle). There are many things to consider when it comes to web application security such as denial of service attacks, the safety of user data, database malfunctioning, unauthorized access to restricted parts of the website, etc.

Frameworks are boost performance, offer libraries of coding and extend capabilities, so developers need not do hand-coding web applications from the ground up. Frameworks offer features like models, APIs, snippets of code and other elements to develop dynamic web applications.

In the current scerinio when the market is flooded with so many frontend framework.It become hard to figure out which one will best fit the requirement of the product.So Engineer struggle to learn and implement the best way.Just for example Angular 2.x is much more better than angular 1.x .React native is popular among mobile app developments.Ionic…NativeScript and other else.So now the questions arises do the developers need to master one of them or all at a go .

My approach,I write modular code.I write an layer of code to use any framework.Suppose right now for an application i am using backbone .I have written wrappers over backbone as base components.My code interacts with base components.So What is the advantage ? In near future If i wish to replace my framework with angular 2.x / React Native .So i have to make changes in Base Wrapper and my whole application logic and code will remain the same.This is the need of current front-end stack.You can change the framework and use the underlying features with minimal efforts.

Configure UI Layer on apache2

What is Apache2 ?

Apache is the most popular web server on the internet.It is used to serve more than half of all active websites.So lets configure it for our local development.

Installing Apache2 or httpd on Ubuntu or Debian

Open Terminal and run the following commands
    $ sudo apt-get update
    $ sudo apt-get install apache2

Assuming your workspace is in /home/user/workspace/UI directory
    $ cd /var/www
    $ sudo ln -s /home/user/workspace/UI UI
The second command creates a symbolic link to your repository.

Now, we will configure our apache server to serve static contents so that 
we can run our code locally.

Configure Apache2

$ cd /etc/apache2/conf-available

Create a file fqdn.conf inside conf-available directory containing following text:
ServerName localhost

and then again create a symbolic link to fqdn.conf file
$   cd /etc/apache2/conf-enabled
$   sudo ln -s ../conf-available/fqdn.conf fqdn.conf

Add UI workspace files and ProxyPass settings to apache2 server 
Before that let us take a backup of our setting file 000-default.conf.
Backup file name is 000-default.conf.bak

$   cd /etc/apache2/sites-available
$   sudo cp 000-default.conf 000-default.conf.bak

Now modify file 000-default.conf as the following:

Change DocumentRoot to:
DocumentRoot /var/www/UI

Add the following lines towards the end of the file, just before closing </VirtualHost> tag

        ProxyRequests Off
        <Proxy *>
                Order deny,allow
                Allow from all
        </Proxy>

        ProxyPass /api http://IPAddress
        ProxyPassReverse / http://IPAddress

        <Location />
                Order allow,deny
                Allow from all
        </Location>     

After making above changes,
Enable proxy module and restart apache2 server.


    $   sudo a2enmod proxy
    $   sudo a2enmod proxy_http
    $   sudo service apache2 restart
Open up your favorite browser and type localhost
This is all about configuring UI on your local Machine for development.
The same UI can be configured and run on node server.
 


Parameters to measure the peformance of a web App ( Frontend Applications)

I personally thing that anyone comparing to two front end Applications built with two different stack.Performance of any app depends upon various parameters and most importantly it depends upon the Project Requirement.
As far as my experience with building application,I will try to list some of these parameters.
a) Quality of the test/benchmark code : Writing any application/module/function but writing a test case for these are comparatively more tougher.
b) Application Type : The main stack is choose on the basis of application type ,whether is data driven, small application or SPAs .The choice of framework all depends upon on requirement of the product.
c) Server load and Server performance : whether the server is able to handle multiple request .it all depends upon optimizing the server to its best .
d) Quality of Internet Connection at end user and client Side
e) Memory usage by the client Browser and type of Browser used. Resource utilization (CPU/memory/network)
f)Dom Manipulation : DOM manipulation should be very less and it is not good for performance.
g)Garbage Collection by the Browser.

In a nutshell ,no library or framework is good or bad .All we need to learn its pros and cons and best way to exploit it to get our purpose done,be in Backbone, Angular ,Ember or React.

My Experience with Angular Js

I started working on angular late 2015 and I think I have written my share of Code in Angular Js.
In the year 2015, angular and React was popular. Fast.Fast Development and less code base
for a larger application become a requirement .performance was also a factor.The last project was in Backbone and Due to its bad design we have serious issues like sync calls
and large number of HTTP calls .So we decided to move to Angular .
After going through few blogs and articles we decided to use Angular + D3 + NVD3 and
for Development and RequireJs for Dependency and Grunt for Task Manger.The best Tool
was Chrome Dev Tool which helped us throughout our development process .

As we were new to Angular and Product need to be delivered in less than 3 months (90 days ) we were little bit scared.Angular as a steep Learning Curve. The greatest pain is setting the project and once project is setup development usually becomes fast.
As I was from jquery+Backbone background, initially I find it difficult to adjust to two way data binding and few lines of code doing miracles and inbuilt directives support.Later I become fan of Angular .As the project was huge, I keep performance issues also in mind.
Performance really matters a lot as users never waits for more than 5 seconds.if you are slow you will loose the business.
My experience in building a product with Angular stack was awesome and I enjoyed it that I was able to deliver and ultra fast application with more features, custom directives.custom filters and so on.
In my application we have lots of charting libraries ,but High-charts were not supported by Angular so ,I moved to NVD3 and D3 for more user interaction.Initially due to less support I faced certain issues with NVD3 but Later I found hacks and tricks to tackle with it.

With Angular my current application become 2x times faster than previous with more efficiently managing data at front-end side.

Comparison between Apache and Nginx

Both Apache and Nginx are popular and are used in wide variety of applications .
Most of the time it become an important decision to choose between Nginx and Apache for their application .Apache is more popular than Nginx because it covers more use cases and it has been around much longer, hence more people know about it .

Say for example :
With Apache, you just need to run/maintain/configure a single software that handles everything you might need like static files (css/js/images), PHP , Python, etc. It supports a lot of configuration options that cater to various use cases but is a little resource heavy (i.e. uses more CPU/RAM).

Nginx, on the other hand, just serves static files and also allows you to load balance (transfer your incoming request to one among a set of servers, depending on load), and some other stuff too. But it is much lighter on resources. Moreover, you would have to use something else to handle your dynamic content (PHP (programming language)/Python). Thus, you would have to run/maintain/configure multiple pieces of software.

Apache makes copies (process forks) of itself for every request, be it PHP or a css file. Each running version eats up more RAM. So you have a very low limit on the number of things it can do at one time.

Nginx on the other hand uses a fixed amount of RAM because it is event driven. So you can use your RAM for other things, like PHP

So from my side a piece of advice ,Use Apache if you just want to manage one thing and don’t mind resource usage and use nginx if you have lots of static content or are resource constrained or you like to use “the right tool for the right job”!

Why nginx is good at serving static files?

It’s not any better/worse at serving static files than Apache. However, the big difference is that nginx can serve a lot more users without using up additional resources.

Apache makes copies (process forks) of itself for every request, be it PHP or a css file. Each running version eats up more RAM. So you have a very low limit on the number of things it can do at one time.

Nginx on the other hand uses a fixed amount of RAM because it is event driven. So you can use your RAM for other things, like PHP.

Why nginx + apache?

nginx is configured to serve the static (js, css, img) files. So you have a fixed amount of ram handling all the regular files. No need to use up a fat copy of apache to serve something simple.

apache+mod_php, can just focus on creating dynamic HTML. Which means more effective use of your precious RAM.

For more details please go through these links :

Apache vs nginx – WikiVS
Nginx Vs Apache in AWS – Updated
Web Server Performance Comparison
Nginx overtakes Apache as the server of choice for the top 1000 trafficked sites
Apache vs nginx {performance comparison}
Apache2 vs Nginx for PHP application

I use both on a few projects. Apache for the main web server and nginx as a caching server only sitting in front of Apache.I use Nginx for static content and caching.
Apache remains better for production as it provides an important range of handful plugins.

Android :Learn to make your own Android App

Android applications are in great demand in the market ,and that how it attarcts more freaky programmers to develop apps for Android. Today ,I am going to demonstrate how to display any text in the Android App .

If you are newbie to Java,then this is not the right place for you,just brush up Java before you start here.At first you need to install Android SDK as per your system.For installation help click here http://developer.android.com/sdk/installing/index.html

NOW FOLLOW THE FOLLOWING STEPS
STEP 1: Start Eclipse.Once it is started.Go to File

File->New->Android Application Project.

android1

A dialog box will appear ,name is whatever you wish like i have given it name as Android_1
If you are asked to select a build target,and if you have installed Android API,choose API level as shown in the picture below.
android 4
Once selected click Next.
NOTE: The name of the package should be unique as once you will upload this app to Google Android marketplace.You Android App will be recognized with unique package name.

STEP 2: Now we need to create an activity.Activity is basically the layout structure that we want to display in our App.
Select Blank Activity on clicking next after Step 1.
Give the name of the Activity as I have given the name of the activity as Android_test
and click Finish
a6-03-15 12:03:36

FInally go to Window->AVD Manager and start your target emulator( An emulator is a virtual Android device to run Android Apps ).

STEP 3: Go to ECLIPSE  and see the Project Explorer ,and you will see all the files  listed in your project like the following image.

a7

Now open AndroidManifest.xml and you will find the codes as

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android_1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.android_1.Android_test"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Second_activity" android:label="@string/app_name"/>

    </application>

</manifest>

Brief Explanation about AndroidManifest.xml:-

AndroidManifest.xml file contains app specific settings such as app version and minimum SDK version.The different permissions required,activities that can be run,services,broadcast receives and more.
Once open,it will open in default graphical view,change it into AndroidManifest.xml view at the bottom right of your view of the manifest .
At the top level under application you are specifying icons and label.The main function of intent filter stuff is that it specifies what should launch when an App runs.

And again go to project Explorer and search for “res” folder and res->values>string.xml and the string.xml will open like shown below .

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">android_1</string>
    <string name="hello_world">Hello world! THIS IS MY ANDROID TUTORIAL</string>
    <string name="menu_settings">Settings</string>
     <string name="test_one"> THIS IS MY FIRST ANDROID PROGRAM</string>
     <string name="click_me">Click Me</string>

</resources>

you will see that two strings are already created.If you look at the AndroidManifest.xml file ,you will find
@String/app_name.It is referring to the app_name string seen here.This string.xml is basically a resource file.These are heavily used in Android to make it easier to localize your application.
Again move on to res/layout/activity_android_test.xml.You will see a file a like this

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@string/click_me"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Android_test" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        android:id="@+id/lblTextViewOne" />


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginLeft="64dp"
        android:layout_marginTop="39dp"
        android:onClick="@string/test_one"
        android:text="CLICK ME" />
</RelativeLayout>

Relative Layout is the way of containing and organizing element inside of it.The Relative Layout is used to display a block of text.

STEP 3: Now go to src->com.Example.Android_1
and open the Android_test.java file once there.And write the code as given given:

package com.example.android_1;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Android_test extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_android_test);

		final TextView TextViewOne = (TextView) findViewById(R.id.TextViewOne);
		TextViewOne.setText(R.string.test_one);

		}

}

Explantation of Android_test.java
Android_test class is extending the Activity class (which is part of Android SDK).We are only overriding one method from the Activity subclass,the “onCreate” method .This method is called when the activity is created and also when the screen is rotated.We call super.onCreate method so that the Activity subclass can handle its plumbing and then we call setContentView .This method is passed R.Layout.main .R is a way to refer to res folder and is how we pro-grammatically access the items in that folder.

STEP 4:
All we need to do is to create a new string and then use your TextView to use that String in the onCreate method.
let’s add an string to string.xml

<stringname="test_one">This is my first App</string>

Screenshot from 2013-03-15 12:25:29
then go back to activity_android_test.xml/main.xml

and add an id to it like

android:id="@+id/newtext"

again go to Android_test.java and write the following code

 TextView newtext=(TextView)findViewById(R.id.newtext)

if there is an error coming just import “TextView” or (android.widget)
again set the property of the Textview as

TextViewOne.setText(R.string.test_one);

Now your app is ready is ready to run.Just clean and build and RUN AS ANDROID APPLICATION
You will see an updated text.