Wednesday, 14 March 2018

Create filter Pipe in Angular5

dfAngular Pipe:-

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's Array of object data into filterd Array order (ascending /descending).

Create pipe using cli

ng g pipe filter-data

write below code in filter-data.pipe.ts file


import { Pipe, PipeTransform } from '@angular/core';
import { retry } from 'rxjs/operator/retry';

@Pipe({
name: 'filterData'
})
export class FilterDataPipe implements PipeTransform {

transform(items: any[], f: any, key?: string, keyF?: string): any[] {
if (items && Array.isArray(items)) {
if (Array.isArray(f)) {
let allFilter = [];
if (keyF) f.forEach((obj) => { allFilter.push(obj[keyF]); });
else allFilter = f;

if (key) {
return items.filter((it) => {
return allFilter.includes(it[key])
});
}
else {
return items.filter((it) => {
return allFilter.includes(it)
})
}
}
else {
if (key) {
return items.filter((it) => {
return it[key] === f
});
}
else {
return items.filter((it) => {
return it === f
})
}
}
}
return [];
}
}

Write below code where you want to sort data(In component html)


  1. Filter in Array of string:- e.g. var arr=['om', 'prakash', 'pandey']
<div class="mdl-cell mdl-cell--4-col">
<mat-form-field class="mat-form-field-custom">
<input matInput placeholder="Search by Audit Name" [(ngModel)]="searchText">
<mat-icon matSuffix>search</mat-icon>
</mat-form-field>
</div>

<div class=" mdl-cell mdl-cell--3-col mdl-cell--8-col-tablet
mdl-cell--12-col-phone matrix-names"
*ngFor="let name of (arr | filterData : searchText)">{{ name }}
</div>
  1. Filter in Array Of Objects:-  e.g. var userList=[{name:'om'}, {name: 'prakash'} , {name: 'pandey'}]
<div class="mdl-cell mdl-cell--4-col">
<mat-form-field class="mat-form-field-custom">
<input matInput placeholder="Search by Audit Name" [(ngModel)]="searchText">
<mat-icon matSuffix>search</mat-icon>
</mat-form-field>
</div>

<div class=" mdl-cell mdl-cell--3-col mdl-cell--8-col-tablet
mdl-cell--12-col-phone matrix-names"
*ngFor="let user of (userList | filterData : searchText : 'name')">{{ user.name }}
</div>
  1. Filter in Array Of Objects:-  e.g. var userList=[{name:'om'}, {name: 'prakash'} , {name: 'pandey'}] and input filter is object then in last parameter define the KEY by which you want to search
  2. Filter in Array Of Objects:-  e.g. var userList=[{name:'om'}, {name: 'prakash'} , {name: 'pandey'}] and input filter is also an array of object(for multi select dropdown) then second parameter is an Array of Object andn last parameter defined the KEY by which you want to search........



Create Sorting Pipe in Angular5

Angular Pipe:-

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's Array of object data into sorting order(ascending/descending).

Create pipe using cli

ng g pipe order-by

write below code in order-by.pipe.ts file


import { Pipe, PipeTransform } from '@angular/core';
import { retry } from 'rxjs/operator/retry';

@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
transform(items: any[], key?: string, order?: string, typeOf?: string): any[] {

if (items && Array.isArray(items)) {

let asc = (order != 'dsc') ? -1 : 1, c, d;//c,d update only value not reffrence
return items.sort(function (a, b) {
if (key)
c = a[key], d = b[key];
else
c = a, d = b;

if (typeOf === 'date') {
c = typeof (c) === 'string' ? new Date(c) : c;
d = typeof (d) === 'string' ? new Date(d) : d;
}
else if (typeOf === 'number') {
c = parseFloat(c);
d = parseFloat(d);
}
return (c > d) ? (asc * -1) : (c < d ? asc : 0);
});
}
return [];
}
}


Write below code where you want to sort data(In component html)


<div *ngFor="let detail of auditSiteData | orderBy:'audit_date':'asc':'date'">
{{detail.audit_date }}
</div>

Friday, 7 July 2017

Difference Between event.preventDefault(), event.stopPropagation() and return false

  1. event.preventDefault() – It stops the browsers default behaviour.
  2. event.stopPropagation() – It prevents the event from propagating (or “bubbling up”) the DOM.
  3. Stops callback execution and returns immediately when called.
Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

Example:- It's tested on W3School

<div onclick='executeParent()'>
  <a href='https://www.w3schools.com' onclick='executeChild()'>Click here to visit w3schools.com</a>
</div>

<script>
  function executeChild() {
   //event.preventDefault();  
   // event.stopPropagation();// stop event bubbling
    event.currentTarget.innerHTML = 'Click event prevented'
    alert('Link Clicked');
    if(event.currentTarget.innerHTML==='Click event prevented'){
    event.preventDefault(); // stop default behaviour of browser means href won't be call
    }
    //return false// it is used for exit from function/ callback at any where
  }

  function executeParent() {
    alert('Div Clicked');
  }
</script>

Wednesday, 14 June 2017

OOPs in JavaScript

JavaScript supports Object Oriented Programming but not in the same way as other OOP languages(c++, PHP, Java, etc.) do. The main difference between JavaScript and the other languages is that there are no Classes in JavaScript whereas Classes are very important for creating objects. However, there are ways through which we can simulate the Class concept in JavaScript.
Another important difference is Data Hiding. There is no access specifier like (public, private and protected) in JavaScript but we can simulate the concept using the variable scope in functions.

Object Oriented Programming Concepts

1) Object
2) Class
3) Constructor
4) Inheritance
5) Encapsulation
6) Abstraction
7) Polymorphism

Preparing the workspace

Create a new file "oops.html" and write this code on it. We will write all our JavaScript code on this file.
<html>
  <head>
    <title>JavaScript Object Oriented Programming(OOPs) Tutorial
    </title>
  </head>
  <body>
    <script type="text/javascript">
      //Write your code here.....
    </script>
  </body>
</html>

1) Object

Any real time entity is considered as an Object. Every Object will have some properties and functions. For example, consider a person as an object, then he will have properties like name, age, etc., and functions such as walk, talk, eat, think, etc. now let us see how to create objects in JavaScript. As mentioned previously there are so many ways to create objects in JavaScript like:
//1)Creating Object through literal
var obj = {};
//2)Creating with Object.create
var obj = Object.create(null);
//3)Creating using new keyword
function Person() {}
var obj = new Person();
We can use any of the above ways to create Object.

2) Class

As I said earlier there are no classes in JavaScript as it is Prototype based language. But we can simulate the class concept using JavaScript functions.
function Person() {
    //Properties
    this.name = "aravind";
    this.age = "23";
    //functions
    this.sayHi = function() {
        return this.name + " Says Hi";
    }
}
//Creating person instance
var p = new Person();
alert(p.sayHi());

3) Constructor

Actually, Constructor is a concept that comes under Classes. The constructor is used to assign values to the properties of the Class while creating an object using the new operator. In above code we have used name and age as properties for Person class, now we will assign values while creating new objects for Person class as below.
function Person(name, age) {
    //Assigning values through constructor
    this.name = name;
    this.age = age;
    //functions
    this.sayHi = function() {
        return this.name + " Says Hi";
    }
}
//Creating person instance
var p = new Person("aravind", 23);
alert(p.sayHi());
//Creating Second person instance
var p = new Person("jon", 23);
alert(p.sayHi());

4) Inheritance

Inheritance is a process of getting the properties and function of one class to other class. For example, let’s consider "Student" Class, here the Student also has the properties of name and age which have been used in Person class. So it's much better to acquiring the properties of the Person instead of re-creating the properties. Now let’s see how we can do the inheritance concept in JavaScript.
function Student() {}
//1)Prototype based Inhertance
Student.prototype = new Person();
//2)Inhertance throught Object.create
Student.prototype = Object.create(Person);
var stobj = new Student();
alert(stobj.sayHi());
We can do inheritance in above two ways.

5) Encapsulation

Before going on to Encapsulation and Abstraction first we need to know what Data Hiding is and how can we achieve it in JavaScript. Date hiding is protecting the data from accessing it outside the scope. For example, In Person class, we have Date of Birth (dob) properties which should be protected. Let's see how to do it.
function Person() {
    //this is private variable
    var dob = "8 June 2012";
    //public properties and functions
    return {
        age: "23",
        name: "aravind",
        getDob: function() {
            return dob;
        }
    }
}
var pobj = new Person();
//this will get undefined
//because it is private to Person
console.log(pobj.dob);
//Will get dob value we using public
//funtion to get private data
console.log(pobj.getDob());
Wrapping up of public and private data into a single data unit is called Encapsulation. The above example is the one that best suites Encapsulation.

6) Abstraction

Abstraction means hiding the inner implementation details and showing only outer details. To understand Abstraction we need to understand Abstract and Interface concepts from Java. But we don't have any direct Abstract or Interface in JS.
Ok! now in order to understand abstraction in JavaScript lets takes an example from JavaScript library Jquery. In Jquery we will use
$("#ele")
to select select an element with id ele on a web page. Actually this code calls negative JavaScript code
document.getElementById("ele");
But we don't need to know that we can happy use the $("#ele") without knowing the inner details of the implementation.

7) Polymorphism

The word Polymorphism in OOPs means having more than one form. In JavaScript an Object, Property, Method can have more than one form. Polymorphism is a very cool feature for dynamic binding or late binding.
function Person() {
    this.sayHI = function() {}
};
//This will create Student Class
function Student() {};
Student.prototype = new Person();
Student.prototype.sayHI = function(l) {
        return "Hi! I am a Student";
    }
    //This will create Teacher Object
function Teacher() {};
Teacher.prototype = new Person();
Teacher.prototype.sayHI = function() {
    return "Hi! I am a Teacher";
}
var sObj = new Student();
//This will check if the student
//object is instance of Person or not
//if not it won't execute our alert code.
if (sObj instanceof Person) {
    alert("Hurry! JavaScript supports OOps");
}

Conclusion

JavaScript supports Object Orientezd Programming(OOP)Concepts. But it may not be the direct way. We need to create some simulation for some concepts.
<html>
  <head>
    <title>JavaScript Object Oriented Programming(OOPs) Tutorial
    </title>
  </head>
  <body>
    <script type="text/javascript">
      //1)Creating Object through literal
var obj = {};
//2)Creating with Object.create
var obj = Object.create(null);
//3)Creating using new keyword
//function Person() {}
//var obj = new Person();

function Person1() {
    //Properties
    this.name = "aravind";
    this.age = "23";
    //functions
    this.sayHi = function () {
        return this.name + " Says Hi";
    }
}
//Creating person instance
var p1 = new Person1();
alert(p1.sayHi());



function Person(name, age) {
    //Assigning values through constructor
    this.name = name;
    this.age = age;
    //functions
    this.sayHi = function () {
        return this.name + " Says Hi";
    }
}
//Creating person instance
var p = new Person("aravind", 23);
alert(p.sayHi());
//Creating Second person instance
var p = new Person("jon", 23);
alert(p.sayHi());


function Student() { }
//1)Prototype based Inhertance
//Student.prototype = new Person("Om Prakash", 23);

//2)Inhertance throught Object.create
//Student.prototype = Object.create(new Person("Om", 23));

Student.prototype = function write(name) {
    alert(name);
}

var stobj = new Student();
console.log(stobj,"ok")
alert(stobj.Test("omdsfdgfhfg"));


function Person2() {
    //this is private variable
    var dob = "8 June 2012";
    //public properties and functions
    return {
        age: "23",
        name: "aravind",
        getDob: function () {
            return dob;
        }
    }
}
var pobj = new Person2();
//this will get undefined
//because it is private to Person
console.log(pobj.dob);
//Will get dob value we using public
//funtion to get private data
console.log(pobj.getDob());

    </script>
  </body>
</html>

Tuesday, 13 December 2016

Connection Pool in MongoDB

As your application grows in functionality and/or usage, managing resources becomes increasingly important. Failure to properly utilize connection pooling is one major “gotcha” that we’ve seen greatly impact MongoDB performance and trip up developers of all levels.

Connection Pools

Creating new authenticated connections to the database is expensive. So, instead of creating and destroying connections for each request to the database, you want to re-use existing connections as much as possible. This is where connection pooling comes in.
A Connection Pool is a cache of database connections maintained by your driver so that connections can be re-used when new connections to the database are required. When properly used, connection pools allow you to minimize the frequency and number of new connections to your database.

Connection Churn

Used improperly however, or not at all, your application will likely open and close new database connections too often, resulting in what we call “connection churn”. In a high-throughput application this can result in a constant flood of new connection requests to your database which will adversely affect the performance of your database and your application.

Opening Too Many Connections

Alternately, although less common, is the problem of creating too many MongoClient objects that are never closed.  In this case, instead of churn, you get a steady increase in the number of connections to your database such that you have tens of thousands of connections open when you application could almost certainly due with far fewer. Since each connection takes RAM, you may find yourself wasting a good portion of your memory on connections which will also adversely affect your application’s performance.
Although every application is different and the total number of connections to your database will greatly depend on how many client processes or application servers are connected, in our experience, any connection count great than 1000 – 1500 connections should raise an eyebrow, and most of the time your application will require far fewer than that.

MongoClient and Connection Pooling

Most MongoDB language drivers implement the MongoClient class which, if used properly, will handle connection pooling for you automatically.
The syntax differs per language, but often you do something like this to create a new connection-pool-enabled client to your database:
mongoClient = new MongoClient(URI, connectionOptions);
Here the mongoClient object holds your connection pool, and will give your app connections as needed. You should strive to create this object once as your application initializes and re-use this object throughout your application to talk to your database. The most common connection pooling problem we see results from applications that create a MongoClient object way too often, sometimes on each database request. If you do this you will not be using your connection pool as each MongoClient object maintains a separate pool that is not being reused by your application.

Example with Node.js

Let’s look at a concrete example using the Node.js driver.
Creating new connections to the database using the Node.js driver is done like this:
mongodb.MongoClient.connect(URI, function(err, db) {
  // database operations
});
The syntax for using MongoClient is slightly different here than with other drivers given Node’s single-threaded nature, but the concept is the same. You only want to call ‘connect’ once during your apps initialization phase vs. on each database request.
Let’s take a closer look at the difference between doing the right thing vs. doing the wrong thing.
Note: If you clone the repo from here, the logger will output your logs in your console so you can follow along.
Consider the following examples:
var express = require('express');
var mongodb = require('mongodb');
var app = express();

var MONGODB_URI = 'mongo-uri';

app.get('/', function(req, res) { 
  
  // BAD! Creates a new connection pool for every request
  
  mongodb.MongoClient.connect(MONGODB_URI, function(err, db) {
  if(err) throw err;
  
  var coll = db.collection('test');

    coll.find({}, function(err, docs) {
      docs.each(function(err, doc) {
        if(doc) {
          res.write(JSON.stringify(doc) + "\n");
        }
        else {
          res.end();
        }
      });
    });
  });  
});

// App may initialize before DB connection is ready

app.listen(3000);
console.log('Listening on port 3000');
The first (no pooling):
  • calls connect() in every request handler
  • establishes new connections for every request (connection churn)
  • initializes the app (app.listen()) before database connections are made
  • var express = require('express');
    var mongodb = require('mongodb');
    var app = express();
    
    var MONGODB_URI = 'mongodb-uri';
    var db;
    var coll;
    
    // Initialize connection once
    
    mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
      if(err) throw err;
     
      db = database;
      coll = db.collection('test');
    
      app.listen(3000);
      console.log('Listening on port 3000');
    });
    
    // Reuse database/collection object 
    
    app.get('/', function(req, res) { 
      coll.find({}, function(err, docs) {
        docs.each(function(err, doc) {
          if(doc) {
            res.write(JSON.stringify(doc) + "\n");
          }
          else {
            res.end();
          }
        });
      });
    });
      
The second (with pooling):
  • calls connect() once
  • reuses the database/collection variable (reuses existing connections) waits to initialize the app until after the database connection is established
If you run the first example and refresh your browser enough times, you’ll quickly see that your MongoDB has a hard time handling the flood of connections and will terminate.

Further Consideration – Connection Pool Size

Most MongoDB drivers support a parameter that sets the max number of connections (pool size) available to your application. The connection pool size can be thought of as the max number of concurrent requests that your driver can service. The default pool size varies from driver to driver, e.g. for Node it is 5, whereas for Python it is 100. If you anticipate your application receiving many concurrent or long-running requests, we recommend increasing your pool size- adjust accordingly