Saturday, February 11, 2017

Use Moment.js with angular2 application

Recently i was developing an application in angular2 where i had to use a calendar which shows the results for this month, this week and this weekend. I was finding a solution in pure javascript but it was time consuming. I decided to go on with moment.js , this is how i have embedded moment with angular2 application.

Step 1 : npm install moment --save

Step 2 : In your systemjs.config.js file's map array add:

'moment': 'node_modules/moment'

to packages array add:

'moment': { defaultExtension: 'js' }

Step 3 : In your component.ts use: import * as moment from 'moment/moment';

and that's it. Now you should be able to use moment with your application.

Example:
public setDate(term: string) {
    var status: string;
    status = term;
    switch (status) {
      case "today":
        this.fromDate = moment().toDate();
        break;
      case "tomorrow":
        this.fromDate =  moment(new Date()).add(1,'days').toDate();
        break;
      case "weekend":
        this.fromDate = moment().startOf('week').add('days', 6).toDate();;
        this.toDate = moment().startOf('week').add('days', 7).toDate();
        break;
      case "thisweek":
        this.fromDate = moment().startOf('week').toDate();;
        this.toDate = moment().startOf('week').add('days', 7).toDate();
        break;
      case "nextweek":
        this.fromDate = moment().startOf('week').add('days', 7).toDate();
        this.toDate = moment().startOf('week').add('days', 14).toDate();
        break;
      case "thismonth":
        var date = new Date(), y = date.getFullYear(), m = date.getMonth();
        var firstDay = new Date(y, m, 1);
        var lastDay = new Date(y, m + 1, 0);
        this.fromDate = moment(firstDay).toDate();
        this.toDate = moment(lastDay).toDate();
        break;
    }

Monday, January 30, 2017

AngularJS directive to allow only specific numbers in input

I came across this question on stackoverflow to allow the user to type only specific numbers such as 3,6,9,12 and so on. You can use the following directive which checks for the key and allows as input.

Directive Code
 angular.module('demo').directive('restrictTo', function() {  
   return {  
     restrict: 'A',  
     link: function (scope, element, attrs) {  
       var include = /3|6|9|12/;  
       element[0].addEventListener('keydown', function(event) {  
         if (!include.test(event.key)) {  
           event.preventDefault();  
         }  
       });  
     }  
   }  
 });  

Demo:

https://plnkr.co/edit/oogjTylyl2MTS91nFyxk?p=preview

Also we can use the ng-pattern as follows,

 input name="numberField" type="number" data-ng-model="model.number" data-ng-pattern="/^(3|6|9|12|15)$/"/>  

Friday, January 27, 2017

Shift from Angular1 to Angular2 if you are an Angular 1.x fan

I am a big fan of AngularJS over the years and involved in developing enterprise applications using Angular1. To all the angular1.x developers out there, am going to write about my experience on migrating from Angular 1.x to Angular 2.

Let's find out the differences ,

(i) To those who think Angular2 is the updated version of Angular1, No it is not . Only the names are same,  Angular 2 is completely rewritten.



(ii) Angular1 is using javascript whereas Angular 2 is using Typescript which is super set of javascript



(iii) Most of us are familiar with the $scope in Angular1, one core concept was $scope, and you the saddest part is we don't find $scope in angular 2. Angular 2 use  zone.js to detect changes.



(iv) If you are a mobile developer Angular1.x does not provide much, where Angular 2 is mobile oriented.



(v) Angular 1.x use controllers to handle the logic part, which are gone. And  controllers are replaced with “Components” in Angular 2.


////Angular 1.x using Controller and $scope.........
var myApp = angular .module("myModule", [])
var prods = { name: "Prod1", quantity: 1 };
.controller("productController", function($scope) { $scope.products = prods;
});
///Angular 2 Components using TypeScript........
import { Component } from ‘angular2/core’;
template: `{{prods.name}}`
@Component({ selector: ‘prodsdata’, })
prods = { name: ‘Prod1’, quantity: 1 };
export class ProductComponent {
}

(vi) One of the favourite directive for generating elements was ng-repeat with Angular 1.x
ng-repeat is replaced with *ngFor.
///Angular 1.x structural directives:........
<ul>
{{item.name}}
<li ng-repeat="item in items">
///Angular 2 structural directives:.............
</li> </ul> <ul>
{{item.name}}
<li *ngFor="#item of items"> </li>
</ul>

(vii) Declaring the local variables also changed with angular2  using hash(#) prefix.


(viii) Even though most of the concepts remains the same Two-way data binding: ng-model replaced with [(ngModel)] in angular 2.


(ix) Concept of bootstraping has changed too.Angular 1.x has 2 ways to bootstrap angular. One using ng-appattribute and other via code. In Angular 2, The only way to bootstrap angular is via code.
 import { bootstrap } from 'angular2/platform/browser';  
 import { ProductComponent } from './product.component';  
 bootstrap(ProductComponent);  


(x) Apart from all the above, main concepts such as ways of Routing and Depdency injects has been changed drastically with angular2.


In Angular 1.x, we use $routeProvider.when() to configuring routing. Where in Angular 2, @RouteConfig{(...}) is used. ng-view present in Angular 1.x is replaced with


One of the advantages of Angular1 Dependency Injection. In angular 2 everything is ‘class’ , so DI is achieved via constructors.


To begin with Angular 1.x you should be well versed with java script. Angular 1.x is simpler and easy to learn/coding based on Javascript, whereas Angular 2 just got released LIVE version and it is easy for Java developers to grasp the concepts of Angular 2.To begin with Angular 2 first start with the basic concepts of AngularJS to understand things in Angular 2 better. Happy Learning!


Monday, January 2, 2017

Look Back 2016 and Happy new year 2017

Year 2016 turned out to be awesome for me! A very slow start of the year with lot of challenges somehow accelerated into very convenient series of events.

Top 3rd user in Sri lanka on Stackoverflow:



I’m an addict about Stack Overflow for an year now. Before I start my work at office,or before i goto bed,or on a break,during lunch, Stack Overflow comes to my mind. I have few reasons because,

Willigness to learn:
Learning never stops, for sure. Every day, a new way to solve a problem coming out and Stack Overflow is a great way to be informed about them.
Willingess to teach:
It also increase your “writing” ability and teaching you better about the information that you think you already know.
Reputation and moderation:
Stack Overflow's model has made answering interesting with reputation, badges, privileges, leagues and stuff. And the community is too good. The people I know from Stack Overflow, are real good and are very friendly.

All the above reasons made me to be an addict on stackoverflow and made me to the top 3 users in srilanka with the reputation over 30k.

Became a lead and product owner
One of the life time achievement during the year was becoming an product owner and a tech lead. I got an opportunity to build a product of my own and leading a team of 10 members, and the things i learnt were countless. Working on a distributed team has many challenges but it's a very rewarding experience.

Got married to the person i truly loved
It feels amazing when you get married to the same person you loved for 10 years. But  it didn't come without some degree of effort, empathy, compromise, and sacrifice. Now, it's nice when the love and sacrifice comes easy, because you're so enamored and amazed by the person you are with, falling in love. It takes little effort. But the real rewards come from fighting through the tough times.  It's actively building something together, something you can be proud of, and want to protect. That happened to me during the year 2016.


Got National level award for the product
There is a top-secret recipe for success. Keep this secret mantra: "Work Hard".Another best thing that happened to me during 2016 was getting the merit award from NBQSA. It feels great when your hard work has been paid off. Later, the appreciation from the company and the CEO was one of the highlights of the year.


Finally, I could write a book on the year 2016 . The most of the good things had happen to me.Something I have prayed about all my adult life . I feel am so blessed and the search is over  for the year 2016.Now, the new year 2017 has arrived. Wishing all of you a very happy and prosperous New Year 2017. May this year bring joy, happiness and peace to all of you.All excited and looking forward to another challenging year of good work, positive vibes and exclusives



Saturday, December 31, 2016

Big Data Architecture - a walkthrough

Let me start this blog with a little example. Assume, Sachin have a leak in a water pipe in his garden. He takes a bucket and a some sealing material to fix the problem. After a while, he see s that the leak is much bigger that and he needs a specialist  to bring bigger tools. Meanwhile, he still uses the bucket to drain the water. After a while, he notices that a massive underground stream has opened and he needs to handle millions of liters of water every second. 

He does n't just need new buckets, but a completely new approach to looking at the problem just because the volume and velocity of water has grown. To prevent the town from flooding, maybe he needs his government to build a massive dam that requires an enormous civil engineering expertise and an elaborate control system. To make things worse, everywhere water is gushing out from nowhere and everyone is scared with the variety.

Welcome to Big Data.


Key elements of Big Data:

  1. There are over 600 million tweets every day that is flowing every second which tells about the High Volume & Velocity
  2. Next  need to understand what each tweet means - where is it from, what kind of a person is tweeting, is it trustworthy or not which tells about the High Variety
  3. Identify the sentiment - is this person talking negative about iPhone or positive? which describes about the High Complexity
  4. And finally need to have a way to quantify the sentiment and track it in real time which tells about High Variability
Traditional architecture of any Big Data solution would look something like below,




Data is collected from various sources such as Content management system, software application and then transferred to relational database management systems such as mssql,postgresql etc. 
In order to analyse these data which are being collected , ETL part is done using a single machine most of the times and the necessary data is being transfered to some of the OLAP data warehouses  for analyzing data. The data which is analysed finally is archived data which is not live/real time data. Which in terms refered as Death of data.  Data which is finally analysed is only 10%. 


Big Data,  is massive data that cannot be stored and processed by a single machine. Having understood the basics of Big Data, it is important to learn how it can prove helpful in enhancing business opportunities. Given the massive volume of Big Data, it is logical that only some of it would be of extreme importance. It is this small percentage of data which when analyzed and used in the right manner can prove quite advantageous for promoting business online. 
A modern Architecture:
I have transformed the above architecture inorder to support large volume of data with the modern tools and technologies, A Modern BI architecture will be cooked by using the recipe as below:


Sunday, December 18, 2016

Am I really a developer or just a nethead?

It has been 6 years since i entered into programming field, and 18 years since i started using a computer, Everyone things i am a computer geek. Some times in my mind sounds come that Is that I am really a developer or just a good nethead?.

It's because there has not been a single day i coded without using Google search and Stack Overflow.


My Experience

When I was 15, I wrote my first program.  That was a long time ago now.  And it was in pascal language. During my university days i had more interest on gaming and animation rather than programming. When i got my first job, i struggled to code in c# with the dot net platform  during the initial days. With the help of google and stack overflow, now i would rate myself 8 on c# and i have experience of various open source technologies. But still i felt i was a better googler , not a good programmer. 

What made me to think I am a really bad programmer?
(i) Choosing workarounds over doing the right thing.
(ii)Used Ctr+c and Ctr+v more than normal keys
(iii)When things went wrong, i asked who is at fault rather than what the problem was. 


Mistakes to avoid to become a better programmer
In the year 2016, i started to avoid above practices and i would say programming is the first step to solving problems using technology. My tips that i followed during the year to be a better programmer as follows,



  1. Every day find a small challenge that can  be done in an hour.
  2. Read code. There is a plethora of freely available code for applications. There are tons of free projects by others on github.
  3. Make small projects to build experience.  Make it an open source project and if you can encourage collaboration if your project is compelling enough.
  4. Try programming for a day without googling. continue it for two days, maybe a week. See how it feels.
  5. Go to Meetups, Workshops, meet with others who feel the same way you do about technology.


anyone can become a good developer if he/she is passioned about it and practice a lot, preferably daily."In order to remain at the same level you have to spend at least two hours daily programming.". There will be many programmers out there who would think the same! What do you think?