Sunday, February 12, 2017

Angular 2 Dependency Injection

What is dependency injection (DI)

Dependency injection is a feature of a dynamic language that we quite often use in JAVA web applications and .NET applications. This feature enables efficient re-use of code and instances thus making the programs more memory efficient and light weight, still at the cost of a few additional lines of code (CPU cycles). This could also in turn provide the programmer with the benefit of design patterns such as Singleton and Factory patterns without having to code them from scratch (We will discover how as we proceed). To conclude what is DI, it's a mean by which we inject an instance of an object (called services in Angular 2) to another Object (mostly to a component) in order to have clean code and reusable code.

Advantages of DI

Improved changeability

Since the object creation is taken away from the components that uses the object, we no longer worry about the object constructor. Which is great if we're to work in large teams, which might bring continuous changes in to services and components, not for DI would require changes at both ends making it difficult to maintain code.

Cleaner code

Using DI makes the code cleaner. This is because we just have to mention the required object and reference name. Programmer can directly use the instance without having to worry about creating the code with a messy set of constructor parameters and so on.

Object Re-use

Most of the Angular 2 UI's are interaction intensive and requires web requests to be sent often. The best example would be us typing in a text box with suggestions flowing seamlessly. If we are to initiate instances of a single service and keep sending requests there might be a race condition and can cause the TCP sockets to overwhelm. Also having concepts like ES7 Observables (Will be discussed in another blog post) which enables the components to observe services rather than update through call backs or promises, would not be useful if we are to replicate objects without a clear purpose. 

An example:
We have a userDataService to fetch the user profile. This update the users profile picture on the UI. If we are use use a separate services each time we update the profile there will be so many objects and all these will be reflected in your RAM usage. Also if there are repeated requests we cannot guarantee which request will be served last, which is the result that will cause the UI to reflect.

DI in action

Sample Service



It is required to use @Injectable() in order to make the injection possible.

Injecting the dependency


This demonstrate the use of the UserManagementService within AuthService. Which is quite simple. Just call the name of the method required to get the task done

Using Singleton and Different instances for DI

Singleton

If we are to use a singleton design pattern using the DI we should add the providers (Which is the injectable object class) within the angular 2 module. This will directly enable the injection of the dependency throughout the module without any clutter.

@NgModule({
    providers: [UserManagementService]
})
export class AppModule {
    ...
}

Non-singleton

If we are to use separate instances over different components we could declare the providers within their individual components

@Component({
    templateUrl: 'events-page.html',
    providers: [PostService]
})
export class EventsPage {
    ...
}









Sunday, February 5, 2017

AngularJS Vs ReactJS(FaceBook)

Overview


Before starting off with the article I'd like to provide some background as to why this article may be important to starting your next project. I have used AngularJS 2 with Ionic 2 in order to develop the Mobile Application for Reforest Sri Lanka which is available at PlayStore. I have been using ReactJS for about 6 months at CAKE LABS (PVT) LTD during my internship where I was able to clearly see pros and cons of the library.

Introduction




As I have mentioned ReactJS is a "library" it is basically a rendering engine. Whose primary focus is to render. It is build around the concept of the Virtual DOM and the component based architecture. When ever a change happens the Virtual DOM is completely rendered whilst only the tags having a net difference in the Real DOM are then updated. As the mechanism implies all the HTML tags are indexed by the library by injecting them with ID parameters, making it impossible for you to add ID's or rather unconventional if you do so. Due to the component based architecture this enables the reuse of components which makes the development quite easy. At the same time the framework uses JSX (Java Script XML) syntax which seems to be HTML but are not. Thus the styling of the component becomes a not so simple task in the right React way.




Angular JS is actually a framework which  provides all the required libraries off the shelf. This makes the development easy and at a mature level, this makes the size of the minified UI to be reasonably smaller in size since we are reusing the functions provided by the framework itself without having to install third party libraries such as Fetch, Isomorphic Fetch or request handling libraries such as JSONP. All the features are documented in the official website, which was quite not stable until recent. AngularJS 2 also comes with the component based architecture which makes the reuse of components possible but as not simple as in the case of ReactJS. I'd rather like to say its bit messy and not so straightforward with the concept of directives and modules.

Feature Comparison



Angular JS 2 React JS
Use the HTML DOM straightaway Uses a virtual DOM then updating the real DOM
Uses dependency injection model and some ECMA Script 7 features Still in ES 6
Uses components and modules Uses components
HTML/CSS styling can be applied straightaway Needs to use additional libraries such as Radium in order to reuse styles
Can use inline styles which is quite difficult
Styles are provided in the form of JSON objects since we use JSX



When to use what


This quite not straight forward. If the system is so large and there are components that are being heavily re used, the ReactJS might help. Still there might be many additional libraries required in order to handle the Data Architecture (Discussed later in a separate blog) such as Redux/Relay/Reflux. On the other hand the development effort of the React JS framework will be quite high since it is heavily typed and the task of the UI engineer is not just to style but he/she will have to consider the logic in a component. For an example simple expand collapse might require a change in the logic. See the below example.

Class Component1 extends React.Component {
    this.state = { menuOpen: true };

    hanldeOpenClick() { this.setState({ menuOpen: !this.state.menuOpen }); }

    ....

    render() { return <div style={{ LOGIC }}> <MENU_TO_OPEN/> </div> }

}

This would just be handled with CSS or with a lesser number of lines of code in Angular JS 2.

In the template

<div class="{ open ? 'open' : 'close' }">
    <MenuComponent></MenuComponent>
</div>

In the component class

export class ComplaintCard { 
    open: boolean;
    constructor() { this.open = false; } 
    openMenu() { this.open = !this.open } 
}

This might look quite simple but in React render its completely JS and in Angular template its pure HTML. With my experience Angular 2 did a great Job in the ionic application and ReactJS was OK at my internship, yet we had to go through difficulties when including external render component such as maps, color pickers and etc. We had to use raw HTML injections which was not quite a good thing in the library perspective, but after all served the purpose. It shall be noted that React Native and Angular JS with Ionic 2 are completely two different entities which are orthogonal to each other in fundamental terms.

Conclusion


If the system consists of a large number of Components that can be reused, and heavily interactive React JS is the choice. If the system is modular, with several big components, yet of lesser number of reusable entities Angular JS would be fine. Learning curve for React JS is lesser but the development effort will be greater. It also requires a full stack developer with good knowledge in JS + HTML + CSS to get the full use of it which can be easily segregated with Angular JS 2.

Sunday, September 4, 2016

Powering Up With Jax-rs and Angular!!

Some Past...


The web has become a place for more interaction rather than delivering static information. It has been a while since the web sites were build using pure html, with the new Social Networking era coming out the web was highly interactive and required to serve request in millions.

In order to cater the above requirements, the interactivity the systems were build on top of more powerful servers with different technologies. Other than the technologies being new, a more robust architecture was required enabling the developers to cope with the changing requirements and maintaining the systems for a long time with minimal downtime.

Talking about the legacy systems like CORBA (Common Object Request Broker Architecture) which was defined by the OMG (Object Management Group, well they define UML too) in a gist it was a platform which enabled different system to talk, a protocol indeed. It used interface definition language (IDL). This itself had a disadvantage on CORBA's life, interested? read,
https://en.wikipedia.org/wiki/Common_Object_Request_Broker_Architecture#Problems_and_criticism

There are other note worthy architectures such as SOAP (Simple Object Access Protocol), which used XML and our beloved REST which uses JSON. REST is request based and most often no sessions are kept, rather serve the request based on its content and headers. REST is fast because of the used frameworks and the simple object format JSON, which has stripped of lengthy XML tags which SOAP used.

Why Angular!

Most of us do love simple template based web frameworks such as Laravel, Symfony and even JSP with a bit of twisting tags. But every time a click is made the page loads, which means basically everything other than that is cached would be resend from the server. At least 304 (Not modified) checks would be performed at the server side for cached content.

Then comes AJAX (Asynchronous Javascript and XML, well we use JSON) for querying small chunks of data for search suggestions and form auto fills to make the user experience a little better. Based on the same concept we load views, using Angular. Angular provides a set of features which makes the life easy for the developer in terms of

  • Management of scopes, without having this dealing with var keyword (javascript variables) was a bit messy.
  • Routing being built in.
  • Easy to use templates using curly braces (handlebars).
  • Most beloved ng-repeat, find out you'll love it.
some stuff you won't like,
  • Use of hash bags
    • Urls are displayed as www.example.com/#/my-page/?request=name
    • This is used to block the request at the domain and handle the rest of the routing with hash bagged content, now we have HTML 5 and that's what I'll be talking today!
Let's make a handy angular application with pretty urls (www.example.com/my-page/anuradhawick).
We'll be using JAVA with Jax-rs for the REST API and Jersy Servelet for routing the API calls.

Steps and Sample Code!


  • MVN dependencies


  • Since we are planning to use HTML 5 we need to make our routes to point to a single JSP file.
All the requests are pinted to the app.jsp, in this jsp file we include the required html pages to be loaded <%@include file="index.html"%>

Within this HTML file we must define the base for all the routes, usually we define this in the header.

<html ng-app="app-name">
<head>
    <title>My App</title>
    
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="https://code.angularjs.org/1.5.8/angular-route.min.js"></script>
    <base href="/angular-app/">
</head>


  • Using the controller. This is placed inside the index.html file

<section class="content">
    <div ng-controller="MainController">
        <div class="box">
            // Your HTML components and stuff
        </div>
    </div>
</section>


  • Defining the controller

var app = angular.module('app-name', ['ngRoute']);

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider
        .when('/route-1', {
            templateUrl: '/route1.html',
        })
        .when('/route-2', {
            templateUrl: '/route2.html',
        });
    // This line will make our app HTML5
    $locationProvider.html5Mode(true);
});
// our controller
angular.module('app-name').controller('MainController', function ($route, $routeParams, $location) {
    this.$route = $route;
    this.$location = $location;
    this.$routeParams = $routeParams;
    // what ever the methods should go here

});

Special Notes

  • The routes and the folder structure must have different name, because the html content loaded by the angular app should be rendered with GET requests from the server and shall not be routed away, may cause recursive calls crashing the app.
  • Base URL must be define, this is where we get pointed when the page is reloaded from address bar.
  • Always use different names for api end points and folder structures. This masks our internal file structure and isolate the resource routes from api routes, good for security and application functionality will not be affected.
  • Use comments and code with good quality, don't be lazy to use a minifying/ uglifying framework to make your web application a bit more lighter.


References
https://angularjs.org
https://en.wikipedia.org/wiki/Common_Object_Request_Broker_Architecture

Sunday, March 6, 2016

Binary Search

Introduction

This is one of the simplest search techniques that involves a intuitive way of searching for an item in a sorted list. Yes the it requires to be sorted in some order that supports searching.

For an example you may look for a certain page in a book. First you get the page number from the index at the end of the book. Then you randomly open the book and see it's page number. Say you have opened page 250, out of 500 pages and what you really need is page 256. Now it's obvious that the required page is at the latter half of the book.

Lets make this more general to make an algorithm out of it.

Divide the data set into two components.
Compare the last component of the first set, if the required item is greater in value, search in the latter half.
Else search in the first half.

Pseudo code

function BinarySearch(array, key, start, end)
        if(start > end)
                return -1 // Item not found
        mid = ( start + end) / 2
        if(array[mid] == key)
                return mid
        else if(array[mid] > key)
                return BinarySearch(array, key, mid + 1, end)
        else
                return BinarySearch(array, key, start, mid - 1)


Java Code


Feel free to visit the original repository of algorithms at:
URL https://github.com/anuradhawick/Algorithms

Wednesday, December 30, 2015

Linked List Data Structure with JAVA iterator

Introduction

Linked list is a data structure where nodes are kept in sequence as in a graph but in a linear manner.
As in the above graph what we all keep is a pointer/reference to the head of the list. This data structure can be used to Implement a Stack or a Queue very easily. Because we always have a pointer to the end and the start of the chain. We may also access other elements but it'd need us to iterate thus giving O(n) time complexity.

JAVA Iterator/ Iterable Interface

JAVA provides us with a nice interface which is the Iterator interface which let us use foreach or enhanced for loops. This is very important if we are to use Lamda expressions which is a handy feature in JAVA 8 release. You may be familiar with these if you are already an expert in python programming, where we use these Lamda expressions frequently to make clean code.

Once Iterator interface is implemented methods hasNext() and next() should be implemented giving us the ability to use aforementioned looping. This will be more clear with the code. I have included the codes of two JAVA files LinkedList.java and LLMain.java. We should make sure that we keep track of the current location of the pointer to support iterator. Also I have used a variable to keep if the looping has started. This is just for the implementation of the iterator. What is important is the concept.

The Itarable interface is enables us to create an object iterable. Which means and Iterator object can be obtained. This is if we use the Iterator design pattern. Which is apparently not necessary for our job.

JAVA Code

Make sure you don't import the JAVA LinkedList class :) Then no point!


Feel free to visit the original repository of algorithms at:
URL https://github.com/anuradhawick/Algorithms

Tuesday, December 29, 2015

Detect cycles in a graph using DFS

Introduction

In this post I'm going to talk how to detect if there is a cycle in a graph. Which means can there be more than one way of reaching any node from any other node in the graph. This is completely implemented using the DFS which I have already talked about in a previous blog post. So this will be short blog with only the basics.

In DFS we are using a stack data structure. At the same time we keep track of visited nodes to be ignored in case we find them later in the algorithms. This ignorance is the key point in detecting a cycle. DFS yields a tree out of the graph. Thus there cannot be cycles. Hence we ignore repeated nodes when we go deep through the neighbouring nodes of a graph.

Algorithm and Implementation 
 

Let us consider the above directed graph. Starting from A in a typical DFS we move through nodes as follows.

A->B->C->E->F
since F is a terminal node we have again E at the node.
A->B->C->E
Now the stack becomes something like this
A->B->C->D (Pop out E and put D) and continuing
A->B->C->B
A->B->C->C
now we pop out C (Remember we shall mark what we pop as visited)
now we have 
A->B->C
Bingo, we again pop out C which has already been discovered. Here we conclude that there is a cycle. What really means here is that we have a path to C from A B C E and we again reach C which makes the cycle. This is simple and operates in O(n) time, where n is the number of nodes.

Java implementation is as follows:




Feel free to visit the original repository of algorithms at:
URL https://github.com/anuradhawick/Algorithms

Wednesday, December 23, 2015

Prims Minimum Spanning Tree (MST)

Introduction

This is one of the most commonly used greedy algorithms in many fields. This algorithm tries to make a minimum cost Tree out of a given connected graph, otherwise no tree would exist but a Forest. Following are some applications of Prim's algorithm. There can also be performed by using the Kruskal's algorithms. I'll be talking about the Kruskal's algorithm in a later post. You may also refer to the blog post http://binary-maths.blogspot.com/2015/05/minimal-network-euler-107.html for Kruskal's algorithms as well.

Let's see how it works.
Say we have a graph represented by the adjacency matrix as follows

Graph g = { {0, 2, I, 6, I},
                    {2, 0, 3, 8, 5},
                    {I, 3, 0, I, 7},
                    {6, 8, I, 0, 9},
                    {I, 5, 7, 9, 0},
                  }
where I stands for Infinity or non-edges.
Graph in pictorial view may look like this.

            2        3
      (0)----(1)----(2)
         |      /   \       |
       6| 8 /       \5   |7
         |  /           \   |
       (3)----------(4)
                 9


Algorithm

What happens in the algorithm is we take a vertex and try to set parent for each neighbour if that edge has a lesser cost than the one already have to visit that particular vertex. For an example from 0 we can set parents of 1 as 0 and 3 as 0 and so on. Eventually the algorithm will end up selecting minimum cost incident edge for each of the vertices.

To start with keep an array to save the minimum cost to incident on a given vertex. This array keeps track of the edge that has minimum cost to reach the vertex from all the valid neighbours. In the beginning the array would look like this. The value of index is the vertex id.
minTree = { I, I, I, I, I}
we maintain another array to store parent vertex's index and to check whether a given node is visited already.
The algorithm starts with any vertex say 0. So we make the minTree[0] as 0 and proceed.
Now out of the minTree array get the vertex with min value. Which is 0. Mark as visited by setting visited[0]=true. parent[1]=0, parent[3]=0, minTree[1]=2 (cost of incident edge) and minTree[3]=6. We continue untill there are no unvisited vertices. Ultimately our tree will lie in the parent array as index and value as the edge vertices of the MST.

Code





Feel free to visit the original repository of algorithms at: