Saturday, July 15, 2017

Angular 4.3 Now released

Angular version 4.3 has been released. This is a very minor release.

What’s new?
  • It has HttpClient, a smaller, easier to use, and more powerful library for making HTTP Requests. Learn more about it from the docs
  • New router life cycle events for Guards and Resolvers. Four new events: GuardsCheckStartGuardsCheckEndResolveStartResolveEnd join the existing set of life cycle event such as NavigationStart
  • Conditionally disable animations via a new attribute, [@.disabled]
  • Support for the emulated /deep/ CSS Selector (the Shadow-Piercing descendant combinator aka >>>) has been deprecated to match browser implementations and Chrome’s intent to remove. ::ng-deep has been added to provide a temporary workaround for developers currently using this feature. 
Wondering what have changed ? For the complete list of features and bugfixes check the changelog.

Sunday, June 11, 2017

Build a select dropdown with *ngFor in Angular 2

One of the most repeated questions with angular2 i have come across Stack overflow is "how to generate a select dropdown with an array or object". Hence, i decided to write a sample post with sample code to ease the search.

I will be posting two samples with one simple array and other with object.

Assume you want to generate a dropdown select by having an array with years.

  years = ['2016','2015','2014'];  

The app.component.ts code will look like,

 import {Component} from '@angular/core';  
 import {Http} from '@angular/http'  
 import {bootstrap} from '@angular/platform-browser-dynamic';  
 import { Component } from './Component';  
  selector: 'material-app',  
  templateUrl: 'app.component.html'  
 export class AppComponent {  
  years = ['2016','2015','2014'];  
  selectedyear = '2015' ;  
  onChange(year) {  

In the above cocde selectedyear indicates the default value of the dropdown whenever the app is loaded.  onChange is the event gets fired whenever a option is changed, you can capture the selected value with the event.

And the template  app.component.html will look as follows,

*ngFor is being used to repeat the items as options. It's simple as above.


Next we will see how to bind a object using *ngFor . Assume  if you have a object and want to bind the keys as drop down values,

 currencyList = {  
 "USD": {  
 "symbol": "$",  
 "name": "US Dollar",  
 "symbol_native": "$",  
 "decimal_digits": 2,  
 "rounding": 0,  
 "code": "USD",  
 "name_plural": "US dollars"  
 "CAD": {  
 "symbol": "CA$",  
 "name": "Canadian Dollar",  
 "symbol_native": "$",  
 "decimal_digits": 2,  
 "rounding": 0,  
 "code": "CAD",  
 "name_plural": "Canadian dollars"  

to get the keys of object you can use  Object.keys(this.currencyList); and the rest is same as above sample.


Sunday, June 4, 2017

ESLint with Visual Studio Code (vscode)

Poor code quality application can lead to many serious problems when the size of code grows. Linting is the process of checking the source code for Programmatic as well as Stylistic errors. This is most helpful in identifying some common and uncommon mistakes that are made during coding. To do this process many linters are out there like eslint, jshint, jslint etc.  

All the above helps us to be consistent in semicolons, quotes & code formatting etc. In this blog post i will be showing you how you can setup ESLint with visual studio code which is my favorite code editor.

Install ESLint global

Install it globally by using NPM by this command:

 npm install -g eslint  

Download ESLint extension 

Install the ESLint by downloading the extension, as shown below,

After downloading we need to initialize the ESLint.

Initialize ESLint in project

Next is to initialize ESLint by using Ctrl + ` to open the terminal in Visual Studio Code

That's all folks, now your project is setup with ESLint, from now on it will be very easy to catch lint errors and fix them even if you had missed it. Let's see ESLint in action.

And if you want to explore more on ESLint you can explore it on the website

Saturday, June 3, 2017

How to copy a Database from a MongoDB instance to another?

While recently i was working in an application i had to copy the database from a mongoDB  hosted in an mlab instance to my local. I will share an easy step in MongoDB Shell which support to copy database from remote instance to current one with a single command.

DEMO with steps :

I made  two instances of MongoDB from following commands.
 //Instance 1  
 mongod --port 9998 --dbpath /data/db1  
 //Instance 2  
 mongod --port 9999 --dbpath /data/db2  

In instance 1 there is a database called "dsampledb1".
and i started the instance with the following command,

 mongo localhost:9998  

I create a database with one collection with the following command,
 use dsampledb1{id:1, name:"sample name"})  

Then I log in to next MongoDB instance using MongoDB Shell.
 mongo localhost:9999  

Now to copy the database from the instance 1 to instance 2 , we can simply use the following command,

Syntax is as follows,
 db.copyDatabase(sourcedb, destinationdb, fromhost, username, password)  

A first-timer’s experience of Microsoft’s MVP Community Connection (MCC)

It was my first ever experience to participate in Microsoft's event outside Sri Lanka. My experience as a “first-timer” attending the South East Asia's MVP community connection, along with few other MVPs from my country. MVP Community Connection is a day to connect, learn, inspire and celebrate the local MVP community and MS employees.

It was an exclusive event especially organized for Asia pacific MVPs. The intention is to have all MVPs from different region join there and have a great time with others. There were some interesting sessions and networking between each other. 

From the moment I got off the plane at the Soekarno–Hatta International Airport Airport, I was very excited about the event. I was the first to arrive AYANA Midplaza JAKARTA 2 hours prior to the event. From the registration, greeted by Microsoft mvp tshirt and  I was escorted to pick up my personal registration badge and Wahoo!. 

First day started with lunch at the Hotel. Everyone had a very good time introducing ourselves in 1 minute with other MVPs.  There were totally around 50 MVPs from various countries in south east Asia and we were snuffled and divided into 7 teams for various activities and sessions. It was really awesome to meet with other MVPs and get some inputs, their works and other things related to personal and professional life. Later with a key note from Soyoung Lee, Community Program Manager on "MVPs for the year 2017 and latest updates". Then we had  hack a plan session on  various topics such as "Emerging Technologies", "Developer Field Presentation" etc andone of the best moment was the group photo .

 Later in the evening we were out for dinner where we had Indonesian varieties of food and MVPs were involved in presenting their culture in various ways.  Finally everyone had a great time and fun on the first day.  Second day, it started with a fantastic breakfast and a team activity , later there were  very productive intense discussions to improve MVP engagement within the Partner network. The day ended with a award ceremony where everyone who attended the session was given away with a cool gift. It was a tremendous experience I had at MVP community connect event at Jakarta,Indonesia. There were lots of things that i could learn from various MVPs. Also it created a very good channel with all other MVPs.  

Saturday, March 18, 2017

Microsoft - A Big Thank You

1/03/2017 was a huge day in my career as I was awarded my first (and hopefully not the last) Microsoft Most Valuable Professional award under the category Visual Studio and Development Technologies. It was such a  Indescribable honor, and i have to give a shout out here to the Microsoft community for their support. There have been so many great mentors/supporters in my career over the past 6  years.Thank you  MVP Community Program Manager, my friends, colleagues, my company,followers and supporters for helping me to get my Microsoft  MVP Award for this year.

I hope this marks only the beginning of this new phase of my professional life and I feel so very lucky to be among the 6 technology leaders under the same category in Sri Lanka. Microsoft has always been a great supporter of the community, and a real partner in our ongoing efforts. I will make sure to work extra hard to give back (even more) to the community and I will be more glad to do it every day! Thank you Microsoft!Thank you to the MVPs who welcomed me and others have helped me throughout the years!

Sunday, March 12, 2017

Visual Studio 2017 has landed!

It has been an amazing journey for Microsoft Visual studio , Recently marking 20 years of software development tool in the industry. Tech giant Microsoft has introduced the discharge of Visual Studio 2017. Users can obtain visual Studio 2017 by visiting

Every Visual studio fan would have been excited about the release of Visual Studio 2017. Let's see what Visual Studio 2017 offers us ahead of the previous versions.

In one sentence, The builders can use Visible Studio 2017 to create purposes for Android, iOS, Home windows, internet, and cloud. “Code fast, debug and diagnose with ease, test often, and release with confidence".

Productiveness and efficiency , Developers life made easy:

Working with your team with one repository has never been easier. Now we can use the new 'Open Any Folder' feature to immediately open and work with virtually any code file without a formal project or solution around it.

Codebase Navigation:
Visual Studio 2017 refreshes the navigation experience with the following features,

Go To Implementation (Ctrl+F12) – navigate from any base type or member to its various implementations.

Go To All (Ctrl+T or Ctrl+,) – navigate directly to any file/type/member/symbol declaration. You can use the icons along the top of the feature to filter your result list or use the query syntax (e.g., “f searchTerm” for files, “t searchTerm” for types, etc.).

Find All References (Shift+F12) – now with syntax colorization, Find All Reference results can be custom grouped by a combination of project, definition, and path. You can also “lock” results so that you can continue to find other references without losing your original results.

Indent Guides ­– dotted, gray vertical lines act as landmarks in code to provide context within your frame of view. You may recognize these from the popular Productivity Power Tools.

With Visual studio 2017 there has been fre tweaks and additions to make the common
tasks more productively

IntelliSense – User can filter necessary completion list by category by clicking on the icons in the tray or by hovering over them to learn the keyboard shortcut.

Refactorings – use ‘Ctrl+.’ to access all the refactorings and quick actions we’ve added in VS.

Add using/Imports for types in reference assemblies/NuGet packages

Code Suggestions – code suggestions lee the user hint best practicess.

Mobile Support:
Mobile developers favourties both Xamarin and the amazing Visual Studio Tools for Apache Cordova are included in this 2017 release.  Xamarin integration in Visual Studio 2017 is a huge plus.

Testing and Debugging:

Visual Studio 2017 gives the developers debugging experience to identify the source of an issue faster with the following things,

The new Exception Helper

Run To Click

XAML Edit and Continue

Reattach To Process

Open for everyone:

Last but not the least, there is a FREE community version that everyone can try. Also
if you get  60 days of Xamarin University free if you download before 14 March 2017.

Here's a quick rundown of all the features that have arrived on the Visual Studio 2017:

Better startup and load time
Modified navigation with new features
Visual C++
Extended support for C# 7.0 and Visual Basic
Support for F# 4.1 language
Live Unit Testing
Introduction of Git features
Enhanced Visual Studio Feedback Workflow
Inclusion of .NET Core and ASP.NET Core libraries
Xamarin 4.3 support
NuGet support
Azure SDK for .NET
Office Developer Tools for Visual Studio
Developer Command Prompt
Installation Nickname, and other IDE improvements

So, what you are waiting for? Start to download Visual Studio 2017 and check out what's new? You will feel glad  as how i am. Cheers!

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.

public setDate(term: string) {
    var status: string;
    status = term;
    switch (status) {
      case "today":
        this.fromDate = moment().toDate();
      case "tomorrow":
        this.fromDate =  moment(new Date()).add(1,'days').toDate();
      case "weekend":
        this.fromDate = moment().startOf('week').add('days', 6).toDate();;
        this.toDate = moment().startOf('week').add('days', 7).toDate();
      case "thisweek":
        this.fromDate = moment().startOf('week').toDate();;
        this.toDate = moment().startOf('week').add('days', 7).toDate();
      case "nextweek":
        this.fromDate = moment().startOf('week').add('days', 7).toDate();
        this.toDate = moment().startOf('week').add('days', 14).toDate();
      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();

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)) {  


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: `{{}}`
@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:........
<li ng-repeat="item in items">
///Angular 2 structural directives:.............
</li> </ul> <ul>
<li *ngFor="#item of items"> </li>

(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';  

(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