Wednesday, December 27, 2017

JavaScript : Callback and Promise

Callback

1. JavaScript statements execute line by line without waiting for previous async statements to finish.
2. Callback place vital role to execute required code after async code completes.
3. Callback is a function that is passed to another function as a parameter, and Callback function gets called inside the another function

different ways to call Callback functions

1. Passing anonymous function as callback function

$("#btnhome").click(function() {
  alert("Home Clicked");
});

Here, click method expecting function as parameter. So, anonymous function passing as a parameter

2.  Passing named function as callback function

function displayalert(){
alert("Home Clicked");
}
$("#btnhome").click(displayalert);

Here, click method expecting function as parameter. So, named function passing as a parameter

var displaymessage=function()
{
alert("message display");
}
var showAlert=function(callback)
{
console.log("showing alert message");
callback();
}

// calling function
showAlert(displaymessage);

3. Callback function with parameters

var add=function(a,b)
{
return a+b;
}
var calculate=(num1,num2,callback)
{
Console.log("adding numbers");
var result=callback(num1,num2);
Console.log(result);
}

// calling function
calculate(2,5,add);

Promise

1. Promise are next version of Callbacks
2. It avoids nesting Callback and multiple try/catch
3. It represent asynchronous operations as a sequence
4. It is a different syntax for achieving the same effect as callbacks. The advantage is increased readability
5. A promise represents the result of an asynchronous operation. It is a placeholder into which the successful result value or reason for failure will materialize
6. A promise contain callback function two arguments, resolve and reject , which are both functions. All your asynchronous code goes inside that callback. If everything is successful, the promise is fulfilled by calling resolve() . In case of an error, reject() is called with an Error object. This indicates that the promise is rejected

Example:
var p= new Promise(function(resolve, reject) {
  if (true) {
    resolve("successfull");
  }
  else {
    reject(Error("failed"));
  }
});

// calling Promise
p.then(function(response) {
  console.log("Success!", response);
}).catch(function(error) {
  console.log("Failed!", error);
})

Promise Chaining : It is used to call multiple async operations one after another

asyncThing1().then(function() {
  return asyncThing2();
}).then(function() {
  return asyncThing3();
}).catch(function(err) {
  console.log('error occured',err);
})

Callback with Nesting

api(function(result){
    api2(function(result2){
        api3(function(result3){
             // do work
        });
    });
});
     
Promise with Nesting

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
}).catch(function(error) {
     //handle any error that may occur before this point
});
        
Happy Coding :)


Tuesday, October 10, 2017

Git - Most Useful/Commonly Used Git commands

  1.  It is a distributed version control repository and it has source code management (SCM) functionality.
  2. It offers more features like bug tracking, task management, markdown format’s, graphs, email notifications, Gist code snippets and wiki for every project
  3. It offers both private and public repositories on same account.
  4. Un-track the specific files/folders by creating a file with “.gitignore”
Git Commands 
  • git init 
          Initialize current directory as a Git Repository
  • git clone <url> 
          download complete repository from the specified git url
  • git status 
          It shows all the files which are added/modified and ready to commit
  • git add <filename> (or) git add . 
          Either add single file or complete folder directory to the staging area to track the changes
  • git commit –m “<commit message>” 
          commit changes to staging repository
  • git remote add <alias> <git-url> 
          add GitURL as alias name. So it can be used easily for push and pull content
  • git remote remove <remote alias name> 
          delete remote alias name of Git-URL
  • git remote set-url <remote alias name> <new-git-url> 
          update remote alias name with new Git-URL
  • git push –u <remote –alias-name> <branchname> 
         push/move the content to remote git url with specific branch. Default could be <master> branch
  • git push –u <remote –alias-name> <branchname>:<newbranch> 
         creates new remote branch and push/move the content to that new branch.
  • git pull <remote-alias-name> <branchname> 
          fetch and merge all the files from the specified git remote repository/branch
  • git pull <remote-alias-name> <branchname> --allow-unrelated-histories 
          merge unrelated histories to local branch
  • git checkout –b <new-branch-name> 
          create new duplicate branch from master branch
  • git branch 
          It display all the available branches and * indicates current active branch
  • git checkout <branch-name> 
          Switching between the branches
  • git branch –d <branch-name> 
          delete the specified branch name
  • git stash 
          discard all local changes, but save them for later use
  • git checkout -- <file>
          discard local changes permanently for the given file and updated with new data from Git Repo
  • git reset --hard
          discard all local changes permanently 

Regular Branch Create/Push Steps :

  1. Go to command prompt ( ex:  D:\abc-development> )
  2. Create branch ( i.e. abc-task1 ) from “Develop” remote repo
>git checkout -b  abc-task1 origin develop
  1. Make required changes in abc-task1
  2. Adding all modifications to local repo
         >git add .
  1. Commit/stage all modifications to local repo
         > git commit -m “first commit”
  1. Push all changes to remote repo
          >git push -u origin abc-task1


Feature Branch Create/Push Steps :

  1. Go to command prompt ( ex:  D:\abc-development> )
  2. Create branch ( i.e. abc-task1 ) from “feature/abc-task1” remote repo
>git checkout -b  abc-task1 origin/feature/abc-task1
  1. Make required changes in abc-task1
  2. Adding all modifications to local repo
          >git add .
  1. Commit/stage all modifications to local repo
          > git commit -m “first commit”
  1. Push all changes to remote repo

         >git push origin HEAD:feature/abc-task1


Happy Coding :)

Sunday, September 17, 2017

Knex.js with Azure SQL/MSSQL Server

Knex.js is a SQL query builder for MSSQL, Oracle, MySQL, Postgres and SQLite3. It supports both callbacks as well as a promise interface for streaming data.

The following features are supported by knex.js
a) SQL Query builder
b) Schema builder
c) Joins, Groping, Select, Where and etc
d) Transactions & Savepoint
e) Schema Migrations
f) SQL Raw query
g) Batch Insert

You can find complete details about knex.js @ http://knexjs.org/

Steps to connect to Azure SQL / SQL Server

1. Install Node.js from https://nodejs.org/en/download/
2. Create folder “Knexmssql”
3. Navigate to folder “knexmssql”
     Ex: d:\knexmssql >
4. Install following npm modules
         a) d:\knexmssql > npm install –save express
         b) d:\knexmssql > npm install –save body-parser
         c) d:\knexmssql > npm install –save knex
5. Install “mssql@3.3” node module
         a) d:\knexmssql > npm install –save mssql@3.3
6. see the following knex mssql configuration for Microsoft azure
1.      var knex = require('knex')({
2.      client: 'mssql',
3.      connection: {
4.        server : 'xxxx.database.windows.net',
5.        user : 'xxxx',
6.        password : XXXX',
7.        options: {
8.            port: 1433,
9.            database : 'xxxx',
10.          encrypt: true  // mandatory for microsoft azure sql server
11.      } 
12.    }
13.  });

7. create server.js file under d:\knexmssql and copy following code

 var express=require('express');
 var bodyParser=require('body-parser');
 var port=process.env.PORT || 8100;
 var knex = require('knex')({
    client: 'mssql',
    connection: {
      server : 'xxxx.database.windows.net',
      user : 'xxxx',
      password : xxxx',
      options: {
          port: 1433,
          database : 'xxxx',
          encrypt: true  // mandatory for microsoft azure sql server
      } 
    }
  });
 var app=express();
 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({extended:false}));
 app.get('/getdata',function(req,res){
    // knex.raw('select * from Users').then(function(todos){
    //     res.send(todos);
    // })
    knex.select().table('Users').then(function(todos){
            res.send(todos);
        })
})
app.listen(port,function(){
    console.log("listen to port:",port);
});

8. Start node server using following command
    d:\knexmssql> node server.js
9. Go to Browser/Postmen with following url

You can download complete documentation from the link : Download

Happy Coding :)

Wednesday, July 26, 2017

Visual Studio Code – Popular Extensions

  • Visual studio code is a light weight, super-fast, free, open source and cross platform IDE developed by Microsoft
  •  It runs on windows, macOS and Linux operating systems.
  •  It has built-in support for JavaScript, Typescript and Node.js
  •  We can add wide range of extensions to VS Code for front-end development like C#, Java, Python, Angular, ReactJs, C++, PHP and etc.
  •  It has great in-built intellisence support for JavaScript, Typescript, CSS and HTML 
  •  It has in-built debug , attach process, breakpoints and watch mode inside editor 
  •  Built-in side bar with GIT commands 
  •  It has integrated terminal/command prompt to run any commands without moving out from editor 
  • We can import keyboard shortcuts from different editors using extensions 
  • Easy customization and support different themes 
  • Easy to export editor settings to make all developers to follow same standards in a team

Popular Extensions:

1. Debugger for Chrome :
It is built by Microsoft itself and used to debug JavaScript code in Google chrome without leaving the code editor. This extension has breakpoint settings, variable watching, stepping and debug console 

https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome

2. Angular Essentials:
It has packed with multiple extensions for complete Angular development.

https://marketplace.visualstudio.com/items?itemName=johnpapa.angular-essentials

3. HTML Snippets :
It gives great support for HTML with intellisence and syntax colouring.

https://marketplace.visualstudio.com/items?itemName=abusaidm.html-snippets

4. HTML CSS Class Completion:
It fetches name of all CSS classes in the current workspace and display complete list while typing

https://marketplace.visualstudio.com/items?itemName=Zignd.html-css-class-completion

5. TSLint:
It identifies issues in TypeScript code while writing and provide auto fixes too

https://marketplace.visualstudio.com/items?itemName=eg2.tslint

6. EditorConfig for VS Code:
It maintains consistent coding style for all developers. It makes easy while comparing files with equal indentation, spaces, tabs, line start and line end

https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig

7. C#
It allows writing C# code for .NET Core framework. It supports debugging, syntax highlighting, intellisence, Go to Definition, Find All reference and etc.

https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp

Learn more about VS Code from https://code.visualstudio.com/

Happy Coding :)

Tuesday, July 25, 2017

Angular CLI – Speed up Angular2/4 development

 Angular Team has re-branded the names from “Angular 2” to “Angular” and “Angular 1.x” to “AngularJS” which is now official names of these frameworks
  1. Angular CLI is a Command Line Interface to build, deploy and test angular applications. 
  2. It automates lot of development activities to improve code quality and reduce development time. 
  3. Angular CLI helps us to create new angular application, run a development server with LiveReload, run unit test cases, run E2E test cases, build and deploy as per environment specific


You can download complete documentation from the link : Download

Happy Coding :)

Wednesday, July 5, 2017

C#.NET – String Interning

If there are two identical string literals in one compilation unit then the code we generate ensures that only one string object is created by the CLR for all instances of that literal within the assembly. This process know as “string interning

CLR keeps string storage by maintaining a table called the intern pool, which contains a single reference to each unique literal string declared or created programmatically in the program. Hence, an instance of a literal string with a particular value only exists once in the system

Advantage :
  1. It decreases memory consumption 
  2. It decreases time required to compare two strings 
Disadvantage :
  1. After declaring new string literal, It needs to search all strings objects in memory to check if any one matches with in assembly
Example 1 :
                string str1=”christopher”;
                string str2=”christopher”;
    Console.WriteLine(str1 == str2); // true
    Console.WriteLine(Object.ReferenceEquals(str1,str2); // true

Here both strings (i.e. str1, str2) are having same identical text/literals. So it creates only one memory location by CLR and both strings will be pointed to same memory location (This process known as string intern).

Example 2:
                string str1=”christopher nolan”;
                string str2=”christopher” + “nolan”;
    Console.WriteLine(str1 == str2); // true
    Console.WriteLine(Object.ReferenceEquals(str1,str2); // true

Here both strings (i.e. str1, str2) are having same identical text/literals. So it creates only one memory location by CLR and both strings will be pointed to same memory location (This process known as string intern).

Example 3:
                string lastname=”nolan”
                string str1=”christopher nolan”;
                string str2=”christopher ” + lastname;
    Console.WriteLine(str1 == str2); // true
    Console.WriteLine(Object.ReferenceEquals(str1,str2); // false

Here second condition returns false, because we are assigning string object instead of string text/literal.

   If we change str2 assignment as follows
string str2=string.Intern(”christopher ” + lastname);
Console.WriteLine(Object.ReferenceEquals(str1,str2); // true
Now it returns true.

Example 4:
                string str1=”christopher nolan”;
                string str2=new StringBuilder().Append(“Christopher “).Append(“nolan”).ToString();
string str3=String.Intern(str2);
Console.WriteLine((object)str1 == (object)str2); // false
Console.WriteLine((object)str1 == (object)str3); // true

Here first condition returns false, because we are assigning string object instead of string text/literal.

Example 5:
                string str1=””;
                string str2=””;
StringBuilder sb = new StringBuilder().Append(String.Empty);
str2 = String.Intern(sb.ToString());
Console.WriteLine((object)str1 == (object)str2); // sometimes true, sometimes false

Regard to interning empty string,
.NET Framework 1.0, 1.1, and 3.5 SP1 returns true
.NET Framework 2.0 SP1, 3.0 returns false

Happy Coding :)

Saturday, June 17, 2017

AngularJS - Recommended Folder Structure

Usually at starting of the project, we don’t spend much time for project folder structure. This scenario works nicely in short term for rapid development, but in long term it creates lot of duplicate code issue and maintainability issue.

See the following two different kinds of folder structures

Normal folder structure:

projectapp/                        è this is the root folder
………………… index.html    è used main landing page
………………… app.js   è used for loading angular module, configuration, routes and etc.
…………………. controllers/         è used for specifying application required controllers
…………………………… loginController.js
…………………………… signupController.js
……………………………dashboardController.js
………………….directives/                è used for creating all re-useable html directives
……………………………loginInfoDirective.js
……………………………menuDirective.js
……………………………headerDirective.js
…………………………… footerDirective.js
………………….services/       è used for creating data services
………………………… userinfoService.js
………………………… itemService.js
………………….js/                  è used for specifying all third partly libraries
…………………........ jquery.js
……………………… angular.js
……………………… ngstorage.js
……………………… lodash.js
………………….templatesè used for specifying all required html views
……………………….. logintemplate.html
……………………….. signuptemplate.html
………………………… dashboardtemplate.html

The above structure is very common and also has some amount of separation. Here mainly we kept all views in one folder, all external libraries in one folder and all controllers in one folder.
The above structure looks good for smaller project. But in larger application it is not developer friendly structure. Take a simple example for modifying login page; we need to find out login controller, directive, service and login view to make necessary change.

Recommended folder structure:

projectapp/                         è this is the root folder
………………… index.html       è used main landing page
………………… app.js                è used for loading angular module and configuration.
…………………. app.routes.js  è used for specifying angular routes/states
…………………. app.constants.js è used for specifying application constants
…………………. app.messages.js è used for specifying validation messages, alerts
…………………. components/      è used for specifying page components
…………………………. login/
……………………………… loginController.js
……………………………… loginService.js
……………………………… loginTemplate.html
…………………………. dashboard/
…………………………………… dashboardController.js
…………………………………… dashboardService.js
…………………………………… dashboardTemplate.html
………………….shared/                        è used for creating all re-useable components
…………………………. header/
……………………………….. headerDirective.js
.................................................. headerController.js
……………………………….. headerTemplate.html
…………………………. menu/
………………………………. menuDirective.js
………………………………. menuTemplate.html
………………….assets/                 
…………………………… img/          è used for specifying application images
…………………………………. favicon.png 
…………………………… css/           è used for specifying application styles
…………………………………. site.css
…………………………………. bootstrap.css
…………………………… libs/          è used for specifying all third partly libraries
…………………………………. jquery.js
…………………………………. angular.js
…………………………………. ngstorage.js
…………………………………. lodash.js
………………………….. js/               è used for specifying custom JavaScript files 

The above structure shows modularized approach to build angular application. Here, we kept all routes in app.routes.js, all constants in app.constants.js, all login related functionality into login component.

Happy Coding :)