How to detect “no internet connection” using ANGULAR JS

Today i need to show some message when internet connection lost. So I define this interceptor in httpProvider in my app.js file, so its return an error when a call does not happen successfully due to internet connection lost. This Interceptor return status= "-1" when ajax call is failed. So i set a variable online= true here and in my html i display a message if online=true. See below my html code as well


angular.module('YourAppName', []).config([
  '$httpProvider',
  function($httpProvider){
    $httpProvider.interceptors.push([
      '$q','$rootScope',
      function($q,$rootScope) {
        return {
            responseError: function(res){
                //Angular returns "success" by default, but we will call "error" if data were not obtained.
                if(res.data == null && res.status === -1 && res.statusText === ""){
      $rootScope.online = true;
                    return $q.reject(res) //callback error()
                }      
                return res //return default success()
            }
        };
      }
    ]);
  }
]);


Now i need to show some message when $rootScope.online = true;
Below i check that online variable is true then show a message "Your have lost your internet connection. Check your internet connection and reload your page again." other wise not.


<!--Below message is showing when internet connection is lost. --> 
<div class="alert alert-error" ng-if="online"><i class="btn-icon-only icon-warning-sign"></i>
 Your have lost your internet connection. Check your internet connection and reload your page again.<button ng-click="reloadRoute()"><i class="icon-refresh"></i> Reload</button>
</div>

If you see my above html there i also add a reload button to reload the page to do this i create a function and i call this on click of reload button Below is my function :

// This function Is use to reload the active page.
$rootScope.reloadRoute = function() {
   $route.reload();
}

Now in the last step you need to hide the above message automatically when internet connection is coming again to do this i just put $rootScope.online = false; when view content loaded like below :

// To set the view online message false.
$rootScope.$on('$viewContentLoaded', function() {
   $rootScope.online = false;
});

Preview :


If you like this post or you have any problem during implementation don't to leave a comment below i will definitely reply you back as soon as possible.


Chears :)
Happy coding..

How to remove html in angular js

Suppose you  have a textarea editor and you entered some text in it and making some formatting like change font or adding style etc . So now you want that when you are showing it you don't want to shown html you adding in it. See screenshot below.


Remove html in angular js

To do this below is a simple filter you can use : 

You just need to be add this filter in your app.js and change the "yourAppName" with your own.


yourAppName.filter('htmlToPlaintext', function() {
    return function(text) {
      return  text ? String(text).replace(/<[^>]+>/gm, '') : '';
    };
});
Method of calling this filter :

<label style="color: #636363;">{{company.notes | htmlToPlaintext}}</label>

If you like this post don't forgot to leave a comment.


Chears 
Happy Coding :)

Difference between php-4 and php-5

This is a very common interview question. If you are going for the interview then you have to know the difference between these. Below is the basic difference of PHP-4 and PHP-5 -


1- PHP-4 is a procedural language where as PHP-5 is a object oriented language.

2- PHP-4 was powered by zend engine 1.0 where as PHP-5 was powered by zend engine 2.0

3- In PHP-4 everything is passed by value where as In PHP-5 all objects are passed by refference.

4- PHP-5 introduce a number of new magic function like _CALL, _GET, _SET and _TOSTRING

5- In PHP-5 it is possible you can declare a class as Abstract.

6- PHP-5 introduce a special function called _autoload.

7- PHP-5 removed register_global(), magic quotes and safe mode. 
This was due to the fact that register_global had opened security holes by allowing data injection.

8- PHP-5 introduce a new mysql extention named MYSQLI for developer in Mysql 4.1 and later version.


Chears 
Happy Coding :)

What is InnoDB storage engine

The InnoDB storage engine provides secure transaction capability. A transaction is a logical groping of statements that is handled by the database server as a single unit.  Either all the statements execute successfully to completion or all modification made by the statements are discarded if an error occurs. 
Transaction system often are described as ACID complient :

ATOMIC - All the statements execute successfully or are canceled as a unit.

CONSISTENT - A database that is in a consistent state when a transaction begins is left in a consistent state by the transaction.

ISOLATED - One transaction does not affected to another transaction.

DURABLE - All the changes made by a transaction that completes successfully are stored properly in the database. Changes are not lost.

Features of InnoDB storage engine:
  1. Provides Full transaction capability with full ACID (Atomic, Consistency, Isolated, and Durabe) compliance.
  2. It has row level locking. By supporting row level locking, you can add data to an InnoDB table without the engine locking the table with each insert and this speeds up both the recovery and storage of information in the database.
  3. The key to the InnoDB system is a database, caching and indexing structure where both indexes and data are cached in memory as well as being stored on disk This enables very fast recovery, and works even on very large data sets.
  4. InnoDB supports foreign key constraints
  5. InnoDB supports automatic crash recovery.
  6. InnoDB supports table compression (read/write)
  7. InnoDB supports spatial data types (no spatial indexes)
  8. Innodb support non-locking ANALYZE TABLE and is only required when the server has been running for a long time since it dives into the index statistics and gets the index information when the table opens.
  9. Innodb does not have separate index files so they do not have to be opened.
  10. Innodb builds its indexes one row at a time in primary key order (after an ALTER), which means index trees aren't built in optimal order and are fragmented.There is currently no way to defragment InnoDB indexes, as 
  11. InnoDB can't build indexes by sorting in MySQL 5.0. Even dropping and recreating InnoDB indexes may result in fragmented indexes, depending on the data.
  12. A table can contain a maximum of 1000 columns.
  13. The InnoDB internal maximum key length is 3500 bytes, but MySQL itself restricts this to 3072 bytes. (1024 bytes for non-64-bit builds before MySQL 5.0.17, and for all builds before 5.0.15.)
  14. The default database page size in InnoDB is 16KB. By recompiling the code, you can set it to values ranging from 8KB to 64KB. You must update the values of UNIV_PAGE_SIZE and UNIV_PAGE_SIZE_SHIFT in the univ.i source file.
  15. InnoDB tables do not support FULLTEXT indexes.
If you like this don't forget to leave a comment below.

Chears 
Happy Coding:)

ERROR 1267 (HY000): Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (latin1_general_ci,IMPLICIT) for operation '='

Today i have encountered a problem when i run a select query after joining two tables i.e "ERROR 1267 (HY000): Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (latin1_general_ci,IMPLICIT) for operation '='" . 
This is happen because the collection type is different of each table.

Solution :

1) - First of all check the collection type of each table by running below query :

SELECT table_schema, table_name, column_name, character_set_name, collation_name

FROM information_schema.columns

WHERE collation_name = 'latin1_general_ci'

ORDER BY table_schema, table_name,ordinal_position;
2) - Second one is update the collection type of that table those collection type is different by running below query :

ALTER TABLE tbl_name CONVERT TO CHARACTER SET latin1 COLLATE 'latin1_swedish_ci';
Don't forget to leave a comment if you like this post.

Chears
Happy Coding :)

How to fixed header after scrolling in angular js

Suppose you have a large number of data in your listing and when you are going to scroll up into the listing then you list heading is move up and you didn't showing it and sometime its a complicated to determine that which column data is specify which column heading. To solve this problem you can do to freeze the heading at specific point (like top of the screen) when listing scroll up. To solve this problem in angular js here is a very simple directive you can use-

Below is the directive :


.directive('fixedTableHeaders', ['$timeout', function fixedTableHeaders($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs){
$timeout(function () {
  element.stickyTableHeaders();
}, 0);
}
    };
}]);


How to use : You have to call the above directive in your main div or table like below -

This is my html code of listing :


<table ng-table="tableParams" class="table table-striped table-bordered"  data-fixed-table-headers>
<tr ng-repeat="user in $data">
<td data-title="'Name'" data-sortable="'first_name'">{{user.first_name}} {{user.last_name}}</td>
<td data-title="'Phone'" data-sortable="'private_phone'">{{user.private_phone}}</td>
<td data-title="'Email'" data-sortable="'email'">{{user.email}}</td>
<td data-title="'Designation'" data-sortable="'designation'"><div ng-repeat="(key, value) in desig" ng-if="key==user.designation">{{value}}</div></td>
<td data-title="'Type'" data-sortable="'user_type'">{{(user.user_type ==3) ? "Employee" : (user.user_type ==2) ? "Employer" : "Lender"}}</td>
<td data-title="'Status'" data-sortable="'status'">{{(user.status ==1) ? "Active" : "Inactive"}}</td>
<td class="td-actions">
<a class="btn-small" href="/#/admin/setting/users/edituser/{{user._id}}"><img src="../../../images/editicon.png" /></a>
<a class="btn-small" ng-click="deleteUser(user._id, user.company_id,user.designation,user.user_type)"><img src="../../../images/cuticon.png" /></a>
</td>
</tr>
</table>

Output :
Fixed header after scroll up in angular js



If you having problem while using this code so please leave a comment i will defenatily reply you back.

Chears
Happy coding :)

How to Remove the "#" Sign from AngularJS URLs

By default, AngularJS will route URLs with a hashtag like below-

For Example:


http://example.com/
http://example.com/#/about
http://example.com/#/contact

It is very easy to get clean URLs and remove the hash tag from the URL.

There are 2 steps to remove "#" sign from the url -

Step (1) - Suppose we have a "DemoApp" app like below. Now we remove the "#" sign by just enabling the HTML5 routing mode like below-


var app = angular.module('DemoApp', ['ngRoute']);
app.config(function ($routeProvider,$locationProvider) {
$routeProvider.when("/home", {
templateUrl: "templates/index.html",
controller: "MainController"
}).when("/employees/", {
templateUrl: "templates/employees.html",
controller: "employeesController"
}).when("/departments/", {
templateUrl: "templates/departments.html",
controller: "departmentsController"
}).otherwise({redirectTo: "/home"});
$locationProvider.html5Mode(true);
});
Step (2) - Now we need to set the base tag to the relative path that tells angular, when it parses the URLs, where to start parsing from like below -

<!doctype html>
<html ng-app="DemoApp">
<head>
    <base href="/"/>
</head>
<body ng-cloak>
<h2>demo app</h2>
<div ng-view></div>
Don't forget to post a comment below if you like this post.

Chears
Happy Coding :)

How to create country state dropdown in angularjs

Today i have requirement in my angular js project to list the country and there corresponding state. When user selected any country then there state should be listed in the next dropdown. I did googling alot but i did't get any proper solution of it. Then i create a directive of it. I can't list the complete country code here so i just listed the code only for two countries "Afghanistan" and "Albania" .But you can download the complete code from HERE.

Code start here :



(function() {
 "use strict";
    var app = angular.module('angularCountryState', []);
}());

(function(window) {

    "use strict"; 
 
    var template = '<div class="control-group">';
 
    template += '<label for="country" class="col-md-3 col-sm-3 col-xs-12 field-name text-padding">{{stateLabel}}</label>';
 
    template += '<div class="col-md-9 col-sm-8 col-xs-12">';
 
    template += '<select id="county" class="span4" name="state" ng-model="ngModel.county" ng-disabled="!ngModel.country" class="form-control">';
 
    template += '<option value="">Select County</option>';
 
    template +='<option ng-repeat="optStates in states track by $index">{{optStates}}</option>';
 
    template +='</select>';
 
    template +='</div>';
 
    template +='</div>'; 
 
    template += '<div class="control-group">'
 
    template += '<label for="country" class="col-md-3 col-sm-3 col-xs-12 field-name text-padding">{{countryLabel}}</label>';
 
    template += '<div class="col-md-9 col-sm-8 col-xs-12" val="{{ngModel.country}}">';
 
    template += '<select class="span4" name="country" ng-change="selectCountry()" ng-model="ngModel.country" required  class="form-control">';
 
    template += '<option value="">Select Country</option>';
 
    template +='<option ng-repeat="theCountry in countries track by $index" >{{theCountry}}</option>';
 
    template +='</select>';
 
    template +='</div>';
 
    template +='</div>';
 
 angular.module("angularCountryState").directive("countryStateSelect", [ function () {
  return {
  
   restrict: "E",
   
   template: template,
   
   scope: { country: "=?", countryState: "=?state", ngModel: '='},
   
   link: function (scope, element, attrs) {
   
    scope.countryLabel = "Country";
    
    scope.stateLabel = "County";   

    if(typeof attrs.countryLabel != 'undefined'){
    
     scope.countryLabel = attrs.countryLabel;
     
    }
    
    if(typeof attrs.stateLabel != 'undefined'){
    
     scope.stateLabel = attrs.stateLabel; 
    }
    
    scope.countries = new Array("Afghanistan", "Albania");
         
    scope.state = new Array();
    
    scope.state[1]="Badakhshan|Badghis|Baghlan|Balkh|Bamian|Farah|Faryab|Ghazni|Ghowr|Helmand|Herat|Jowzjan|Kabol|Kandahar|Kapisa|Konar|Kondoz|Laghman|Lowgar|Nangarhar|Nimruz|Oruzgan|Paktia|Paktika|Parvan|Samangan|Sar-e Pol|Takhar|Vardak|Zabol";
    
    scope.state[2]="Berat|Bulqize|Delvine|Devoll (Bilisht)|Diber (Peshkopi)|Durres|Elbasan|Fier|Gjirokaster|Gramsh|Has (Krume)|Kavaje|Kolonje (Erseke)|Korce|Kruje|Kucove|Kukes|Kurbin|Lezhe|Librazhd|Lushnje|Malesi e Madhe (Koplik)|Mallakaster (Ballsh)|Mat (Burrel)|Mirdite (Rreshen)|Peqin|Permet|Pogradec|Puke|Sarande|Shkoder|Skrapar (Corovode)|Tepelene|Tirane (Tirana)|Tirane (Tirana)|Tropoje (Bajram Curri)|Vlore";
    
    //This Function Is Call On Country Drop Down Change.
    
    scope.selectCountry = function(){
    
     var selectedCountry = scope.ngModel.country;
     
     var indexCountry = scope.countries.indexOf(selectedCountry)+1; 

     scope.states = scope.state[indexCountry].split("|");  
     
     scope.countryState = '';
     
     if(scope.states.length == 1){
     
      scope.states = new Array(selectedCountry);  
      
     }
     
     //indexCountry correspond to the "Select" label
     
     if(indexCountry == 0){
     
      scope.states = new Array("");
      
     }
     
    }
        

    //This Function Is Use To Load Seleted Country State On Edit Page.
    
    scope.$watch('ngModel',function(){
    
     if(typeof scope.ngModel!="undefined"){
     
      var selectedCountry = scope.ngModel.country;
      
      var indexCountry = scope.countries.indexOf(selectedCountry)+1;
      
      if(indexCountry >0){
       scope.states = scope.state[indexCountry].split("|");
       
       if(scope.states.length == 1){
        scope.states = new Array(selectedCountry); 
       }      


       if(indexCountry == 0){
        scope.states = new Array("");
       }
       
      }
      
     }
     
    }); 

   }
   
  };
  
 }]);
}());


 



How to use this code:

Step 1- First of all you have to download and include this js file on you index page like below
<script src="js/angular-country-state.js"></script>

Step 2- Then you have to call this directive on your html page like below
<country-state-select ng-model="company"></country-state-select>

Note : I am passing the object company in ng-model. You can pass your own object. Now when you submiting your form then you will get the selected country name in company.country variable and your state is in company.state You can change the name of these inputs country and state from the html of code.

If you like this post or having any problem while using this code please comment below i will reply you back with the solution of your problem.

Chears 
Happy Coding :)

Jquery form validation script fully customize


If you want to validate your form using jquery then below is a fully customize and very clear jquery validation script.

Preview :

 

What you have to do : If you have internet connection on your computer then you just need to be copy the entire below code and paste it into an html file and run on your borwser to test jquery validation. 


Below is my entire form html code with jquery validation :

---------------------x------------------------My Code Start Here---------------------x--------------------------------x


<html>
<title>php sollution form validation script</title>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<style>
.error{color:red;}
.success{color:green;}
</style>
</head>
<body>
<td valign="top">   
      <table width="100%" border="0" cellpadding="0" cellspacing="10">
        <tr>
          <td align="center" style="font-size:25px; padding:7px;">
<div style="width:550px;">Sign Up User Form</div>
          </td>
        </tr>
    </table>
<!--<form action="fwd.php?a=review" method="post"> -->

<form  method="post" action="signup.php" name="create_account" id="frmid">
<input type="hidden" value="a977610c21b9741b1339847c2eda12ba" name="formid">
<input type="hidden" value="process" name="action">
<table width="100%" border="0" cellspacing="10" cellpadding="10">
  <tr>
    <td style="width:50%;" align="right">First Name:</td>
    <td>
    <input name="firstname" type="text" id="firstname"  size="40" /><span class="inputRequirement">*</span>
    <div id="firsterror"></div>
    </td>
  
  </tr>
  <tr>
   <td style="width:50%;" align="right">Middle Name:</td>
    <td><input name="middlename" type="text" size="40" /></td>
  </tr>
  <tr>
     <td style="width:50%;" align="right">Last Name:</td>
    <td><input name="lastname" type="text" id="lastname" size="40" /><span class="inputRequirement">*</span>
    <div id="lastnameerror"></div>
    </td>
    </tr>
   <tr>
    <td align="right">Date of Birth:</td>
    <td><input id="dob" type="text" onblur="checkDate()" name="dob" size="13" /><span class="inputRequirement">*(eg. 05/21/1970)</span>
    <div id="doberror"></div>
    </td>
  </tr>
  <tr>
    <td align="right">Primary Contact:</td>
    <td><input name="phone1" type="text" id="phone1" size="40"/><span class="inputRequirement">*</span>
    <div id="phone1error"></div>
    </td>
  </tr>
  <tr>
    <td align="right">Secondary Contact:</td>
    <td><input name="phone2" type="text" size="40" /></td>
  </tr>
  <tr>
    <td align="right">E-mail Address:</td>
    <td><input  type="text"  id="emailId" onblur ="checkEmail()"name="email_address" size="40"/><span class="inputRequirement">*</span>
    <div id="emailIderror"></div>
    </td>
  </tr>
  <tr>
    <td align="right">Package:</td>
    <td><select name="package1" style="width:150px; font-size:12;">
    <option style="width:100px; font-size:12;" value="">-- Please Select --</option>
    <option style="width:100px; font-size:12;" value="10000"> Premier </option>
    <option style="width:100px; font-size:12;" value="20000"> Silver </option>
    <option style="width:100px; font-size:12;" value="30000"> Gold </option>
  
    </select><span class="inputRequirement">*</span></td>
  </tr>
 
 <tr>
    <td align="right">User Name:</td>
    <td><input name="username" type="text" id="username" size="40" /><span class="inputRequirement">*</span>
    <div id="usernameerror"></div></td>
  </tr>
  <tr>
    <td align="right">Password:</td>
    <td><input  name="password" type="password" id="password" maxlength="40" size="40" /><span class="inputRequirement">*</span>
    <div id="passworderror"></div></td>
  </tr>
 <tr>
    <td align="right">Confirm Password:</td>
    <td><input type="password" maxlength="40" id="confirmation" name="confirmation" size="40"/><span class="inputRequirement">*</span>
    <div id="confirmationerror"></div></td>
  </tr>

  <tr>
    <td colspan="2" align="center"><br /><input class="button" type="submit" value="Sign Up" name="create" /><br /><br /></td>
    </tr>
</table>
</form>
        &nbsp;&nbsp;<br>
    &nbsp;<br></td>
</body>
</html>

<script>
 $(document).ready(function(){
    //global vars
    var form = $("#frmid");
  
    var firstname = $("#firstname");
    var firsterror=$("#firsterror");
  
    var lastname = $("#lastname");
    var lastnameerror=$("#lastnameerror");
  
    var dob = $("#dob");
    var doberror=$("#doberror");
  
    var phone1 = $("#phone1");
    var phone1error=$("#phone1error");
  
    var emailId = $("#emailId");
    var emailIderror=$("#emailIderror");
  
    var username = $("#username");
    var usernameerror=$("#usernameerror");
  
    var password = $("#password");
    var passworderror=$("#passworderror");
  
    var confirmation = $("#confirmation");
    var confirmationerror=$("#confirmationerror");
  
    var captcha = $("#captcha");
    var captchaerror=$("#captchaerror");
  
  
  
    firstname.blur(validatefirstname);
    lastname.blur(validateLastName);
    dob.blur(validateDoB);
    phone1.blur(validatePhone1);
    emailId.blur(validateEmail);
    username.blur(validateUserName);
    password.blur(validatePassword);
    confirmation.blur(validateConPassword);
    captcha.blur(validateCaptcha);
  
 
    //On Submitting
    form.submit(function(){
        if(validatefirstname() & validateLastName() & validateDoB()& validatePhone1() & validateEmail() & validateUserName() &  validatePassword() & validateConPassword() & validateCaptcha())
            return true;
        else
            return false;
    });
 
    function validatefirstname(){
        //if it's NOT valid
        if(firstname.val() == ""){
            firsterror.text("Please Enter Firstname");
            firsterror.addClass("error");
            return false;
        }
        //if it's valid
        else{
            firsterror.text("");
            firstname.addClass("success");
            return true;
        }
    }
   function validateLastName(){
        //if it's NOT valid
        if(lastname.val() == ""){
            lastnameerror.text("Please Enter Lastname");
            lastnameerror.addClass("error");
            return false;
        }
        //if it's valid
        else{
            lastnameerror.text("");
            lastname.addClass("success");
            return true;
        }
    }
     function validateDoB(){
        //if it's NOT valid
        if(dob.val() == ""){
            doberror.text("Please Enter Date of Birth");
            doberror.addClass("error");
            return false;
        }
        //if it's valid
        else{
            doberror.text("");
            dob.addClass("success");
            return true;
        }
    }
    function validatePhone1(){
        //if it's NOT valid
        if(phone1.val() == ""){
            phone1error.text("Please Enter Primary Contact No");
            phone1error.addClass("error");
            return false;
        }
        //if it's valid
        else{
            phone1error.text("");
            phone1.addClass("success");
            return true;
        }
    }
  
      
  
    function validateEmail(){
         //if it's NOT valid
        var a = $("#emailId").val();
        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
        if(emailId.val() == ""){
            emailIderror.text("Please Enter Email Address");
            emailIderror.addClass("error");
            return false;
        }else if(filter.test(a)==false){
            emailIderror.text("Please enter Valid email address");
            emailIderror.addClass("error");
            return false;
      
        }else{
            emailIderror.text("");
            emailId.addClass("success");
            return true;
        }
      
    }
  
  
    function validateUserName(){
        //if it's NOT valid
        if(username.val() == ""){
            usernameerror.text("Please Enter User Name");
            usernameerror.addClass("error");
            return false;
        }
        //if it's valid
        else{
            usernameerror.text("");
            username.addClass("success");
            return true;
        }
    }
  
    function validatePassword(){
        //if it's NOT valid
        if(password.val() == ""){
            passworderror.text("Please Enter Password");
            passworderror.addClass("error");
            return false;
        }
        //if it's valid
        else{
            passworderror.text("");
            password.addClass("success");
            return true;
        }
    }
 
     function validateConPassword(){
        //if it's NOT valid
        if(confirmation.val() == ""){
            confirmationerror.text("Please Enter Confirm Password");
            confirmationerror.addClass("error");
            return false;
        }
        //if it's valid
        else{
            confirmationerror.text("");
            confirmation.addClass("success");
            return true;
        }
    }
      function validateCaptcha(){
        //if it's NOT valid
        if(captcha.val() == ""){
            captchaerror.text("Please Enter Confirm Password");
            captchaerror.addClass("error");
            return false;
        }
        //if it's valid
        else{
            captchaerror.text("");
            captcha.addClass("success");
            return true;
        }
    }  
     
});
</script>

------------------------x--------------------------------End here---------------------x-----------------------------------x

If you guy are having problem during implementation then you can contact me for instant reply. I am happy to help you ...


Happy coding guys :)

How to Export and Import database using MONGO DB

Exporting from MongoDB :

To export the database, simply tell mongodump which database (or collection) you want to export, and where to export it to. Mine was the fairquid database, so my command looks like this:

mongodump -d fairquid -o fairquidbackup

This dumps the fairquid database into the fairquidbackup directory. Take a look at what we have in that directory now:

fairquid
├── users.metadata.json
└── users.bson
└── products.metadata.json
└── products.bson
└── companies.metadata.json
└── companies.bson
└── system.indexes.bson

0 directories, 2 files

Some of the collection in my fairquid database are users, products, companies etc, however you'll see a .bson and .json file for each collection in your database, plus the system indexes collection. It is up to you whether you want to take individual collections, or a whole database, but bear in mind that your choice will dictate whether you get information about indexes etc when you import the data elsewhere.

Importing to MongoDB :

To import, simply use the mongorestore command, which accepts either a single .bson file representing a collection, or a directory containing multiple files. Here's my example:

mongorestore -d fairquid /path/to/fairquid

You can specify any database name and path to files you like, so for taking backups or restoring additional copies of a database, this can be really handy. The mongo commands are well-documented and I found them easy to work with.
Hopefully this helps you work with them too!



Please don't forgot to leave a comment if you like this post.

Chears :)
Happy Coding

Password Match form validation in AngularJS

I am stuck in a form validation to change password where i need to take a specific length of password (like combination of special characters, alphabets and numbers) from user and confirm it by re-enter password. Actually i am using the ng-pattern property of angular js to match the password of both input boxes but the problem is ng-pattern is only match if your are passing simple string. It don't work to match the string with the special charecters. See below example-

Not Working :

<input type="password" name="password" class="span4" ng-model="user.password" ng-pattern="/^(?=(?:[^A-Z]*[A-Z]){2})(?=[^!@#$&*\%\^\)\(]*[!@#$&*\%\^\)\(])(?=(?:[^0-9]*[0-9]){2}).{8,}$/">

<input type="password" name="password2" class="span4" ng-model="user.password2" ng-pattern="user.password">

Working :

<input type="password" id="password" name="password" ng-model="user.password" ng-pattern="/^(?=(?:[^A-Z]*[A-Z]){2})(?=[^!@#$&*\%\^\)\(]*[!@#$&*\%\^\)\(])(?=(?:[^0-9]*[0-9]){2}).{8,}$/">

<input type="password" name="password2" class="span4" ng-model="user.password2" pw-check="password">

So to match the password of both text boxes input i created a simple directive (pwCheck) below is my compleate code :

Below is my directive :

.directive('pwCheck', [function () {
 return {
   require: 'ngModel',
   link: function (scope, elem, attrs, ctrl) {
  var firstPassword = '#' + attrs.pwCheck;
  elem.add(firstPassword).on('keyup', function () {
    scope.$apply(function () {
   var v = elem.val()===$(firstPassword).val();
   ctrl.$setValidity('pwmatch', v);
    });
  });
   }
 }
}]);

Below is my html code :

<form name="registerForm" id="registerForm" ng-submit="editAccountPassword(user, registerForm)" class="form-horizontal" novalidate>
 <div class="modal-body">
  <div class="col-md-12">
  <span class="alert alert-danger ng-cloak" ng-show="registerForm.password2.$error.pwmatch && !registerForm.password.$error.pattern">Passwords should match !!</span>
  </div>
  <div class="col-md-12">
  <span class="alert alert-danger ng-cloak" ng-show="registerForm.password.$error.pattern">Password should be minimum 8 character long and it should contain 2 upper case letters, 1 special character, 2 digits & 1 lower case letter</span>
  </div>
  
  <div class="widget-content">  
   <div class="control-group">           
    <label for="password" class="col-md-4 col-sm-4 col-xs-12 field-name text-padding">New Password</label>
    <div class="col-md-8 col-sm-8 col-xs-12">
     <input type="password" id="password" name="password" class="span4" ng-model="user.password" required="" ng-pattern="/^(?=(?:[^A-Z]*[A-Z]){2})(?=[^!@#$&*\)\(]*[!@#$&*\)\(])(?=(?:[^0-9]*[0-9]){2}).{8,}$/">
    </div>   
   </div>
   
   <div class="control-group" ng-class="{'has-error': registerForm.password2.$invalid && registerForm.password2.$dirty}">           
    <label for="password" class="col-md-4 col-sm-4 col-xs-12 field-name text-padding">{{'Retype New Password' | translate}}</label>
    <div class="col-md-8 col-sm-8 col-xs-12">
     <input type="password" name="password2" class="span4" ng-model="user.password2"  required="" pw-check="password">
      </div>
    </div>   
   </div>
  </div>
 </div>
</form>
Preview :




If you like this post please leave a comment.

Chears 
Happy Coding :)

How to write data in existing excel using NODE.JS

Today i finally solve a big problem in my current node js project. Actually i have a requirement to write data in existing excel document. I already have an excel so i just need to open it and write some data and then save it. But unfortunately i unable to find a way to do this from a long time. After googling a lot i found a node module "xlsx-populate". Its fulfill my requirement. You can check the more detail about it from git hub link https://github.com/dtjohnson/xlsx-populate

Below is my server code of nodeJS  :


app.post('/writeEmployeeDataExcel',function(req,res){
 if(req.body.length>0){console.log('here');
  var data = req.body;
  var index = ['title', 'first_name', 'last_name', 'email', 'dateofbirth', 'hire_date'];
  var filename = "newemployeesheet.xlsx";
  var workbook = Workbook.fromFile("../client/app/downloads/employeeTemp.xlsx", function (err, workbook){
   if (err) return res.status(500).send(err);
   var sheet = workbook.getSheet(0);
   var i=0;
   for (var rowNum = 2; rowNum < parseInt(data.length)+2; rowNum++){
    var row = sheet.getRow(rowNum);
    for (var colNum = 1; colNum < parseInt(index.length)+1; colNum++) {
     var cell = row.getCell(colNum);
     var exceldata = '';
     if((index[colNum-1]=='dateofbirth' || index[colNum-1]=='hire_date') && typeof data[i][index[colNum-1]]!='undefined'){
      var dateNow = new Date(data[i][index[colNum-1]]);
      var dd = dateNow.getDate() < 10 ? '0' + dateNow.getDate() : dateNow.getDate();
      var monthSingleDigit = dateNow.getMonth() + 1;
      var mm = monthSingleDigit < 10 ? '0' + monthSingleDigit : monthSingleDigit;
      var yy = dateNow.getFullYear().toString();
      exceldata = date = dd+'/'+mm+'/'+yy;
     }else{
      exceldata = data[i][index[colNum-1]];
     }
     
     cell.setValue(exceldata);
    }
    i++;
   }
   
   workbook.toFileSync("../client/app/downloads/"+filename);
   res.status(200).send({'name':filename});
   fs.exists("../client/app/downloads/"+filename, function(exists) {
    if (exists) {
     fs.unlink("../client/app/downloads/"+filename);
    }
    workbook.toFileSync("../client/app/downloads/"+filename);
    res.status(200).send({'name':filename});
    
   });
   
  });
 }
});

Preview :


If you like this post don't forgot to leave a comment..

Chears :)
Happy coding..

How to deteact INTERNET EXPLORER (IE) browser and its version using ANGULAR.JS

I need to deteact if my website user are using internet explorer browser and its version is less than 10 then i need to a message to my site visitors that "You are using unsupported browser version and the site may not function correctly" like below screen shot in angular js :



Below is my code that i write in my main file app.js :

var app = angular.module('clientApp', ['ngRoute', 'ngCookies']).run(function($rootScope,Restangular) {

var isIE = false || !!document.documentMode;

if(isIE && document.documentMode<10){
    $rootScope.iemsg = 'You are on an unsupported browser version and the site may not function correctly. Our site works best on IE10/FF/Safari/Chrome";
}

});

Below is my html code to display warning message using bootstrap:

<div class="alert alert-error" ng-if="iemsg"><i class="btn-icon-only icon-warning-sign"></i>{{iemsg}}</div>

Don't forgot to leave a comment if you like this post or having any trouble while using this code.



Chears :)
Happy Coding..